Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-13244 Select a connected email account as the 2FA identifier (re-land) (#7905)
Suchintan330f1cf00cb5
diff --git a/alembic/versions/2026_07_31_1522-9d85c51a8468_add_oauth_credential_email_addresses.py b/alembic/versions/2026_07_31_1522-9d85c51a8468_add_oauth_credential_email_addresses.pynew file mode 100644index 000000000..cbe8db3fe--- /dev/null+++ b/alembic/versions/2026_07_31_1522-9d85c51a8468_add_oauth_credential_email_addresses.py@@ -0,0 +1,29 @@+"""add oauth credential email addresses++Revision ID: 9d85c51a8468+Revises: 64cbada89956+Create Date: 2026-07-31T15:22:47.853089+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "9d85c51a8468"+down_revision: Union[str, None] = "64cbada89956"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column("google_oauth_credentials", sa.Column("email_address", sa.String(), nullable=True))+ op.add_column("microsoft_oauth_credentials", sa.Column("email_address", sa.String(), nullable=True))+++def downgrade() -> None:+ op.drop_column("microsoft_oauth_credentials", "email_address")+ op.drop_column("google_oauth_credentials", "email_address")diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 7b09c7c5a..233d36b5d 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -361,6 +361,7 @@ export interface GoogleOAuthCredential {id: string;organization_id: string;credential_name: string;+ email_address?: string | null;provider?: string;state?: string;scopes_requested?: string[] | string | null;@@ -425,6 +426,7 @@ export interface MicrosoftOAuthCredential {id: string;organization_id: string;credential_name: string;+ email_address?: string | null;state?: string;scopes_requested?: string[] | string | null;scopes_granted?: string[] | string | null;diff --git a/skyvern-frontend/src/components/ConnectedEmailAccountPicker.test.tsx b/skyvern-frontend/src/components/ConnectedEmailAccountPicker.test.tsxnew file mode 100644index 000000000..2529aa93f--- /dev/null+++ b/skyvern-frontend/src/components/ConnectedEmailAccountPicker.test.tsx@@ -0,0 +1,386 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type {+ GoogleOAuthCredential,+ MicrosoftOAuthCredential,+} from "@/api/types";++const mocks = vi.hoisted(() => ({+ useGoogleOAuthCredentials: vi.fn(),+ useMicrosoftOAuthCredentials: vi.fn(),+}));++vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();+ return {+ ...actual,+ useGoogleOAuthCredentials: mocks.useGoogleOAuthCredentials,+ };+});++vi.mock("@/hooks/useMicrosoftOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useMicrosoftOAuthCredentials")>();+ return {+ ...actual,+ useMicrosoftOAuthCredentials: mocks.useMicrosoftOAuthCredentials,+ };+});++import { ConnectedEmailAccountPicker } from "./ConnectedEmailAccountPicker";++const gmailScope = "https://www.googleapis.com/auth/gmail.readonly";++function googleCredential(+ id: string,+ overrides: Partial<GoogleOAuthCredential> = {},+): GoogleOAuthCredential {+ return {+ id,+ organization_id: "org_1",+ credential_name: "Default",+ state: "active",+ scopes_granted: [gmailScope],+ email_address: `${id}@gmail.test`,+ created_at: "2026-07-30T00:00:00Z",+ modified_at: "2026-07-30T00:00:00Z",+ ...overrides,+ };+}++function microsoftCredential(+ id: string,+ overrides: Partial<MicrosoftOAuthCredential> = {},+): MicrosoftOAuthCredential {+ return {+ id,+ organization_id: "org_1",+ credential_name: "Default",+ state: "active",+ scopes_granted: ["Mail.Read"],+ email_address: `${id}@outlook.test`,+ created_at: "2026-07-30T00:00:00Z",+ modified_at: "2026-07-30T00:00:00Z",+ ...overrides,+ };+}++function installHooks({+ google = [],+ microsoft = [],+ googleIsLoading = false,+ microsoftIsLoading = false,+ googleError = null,+ microsoftError = null,+}: {+ google?: GoogleOAuthCredential[];+ microsoft?: MicrosoftOAuthCredential[];+ googleIsLoading?: boolean;+ microsoftIsLoading?: boolean;+ googleError?: Error | null;+ microsoftError?: Error | null;+} = {}) {+ mocks.useGoogleOAuthCredentials.mockReturnValue({+ credentials: google,+ isLoading: googleIsLoading,+ isFetching: false,+ error: googleError,+ });+ mocks.useMicrosoftOAuthCredentials.mockReturnValue({+ credentials: microsoft,+ isLoading: microsoftIsLoading,+ isFetching: false,+ error: microsoftError,+ });+}++function picker(value = "", onChange = vi.fn()) {+ return (+ <ConnectedEmailAccountPicker+ value={value}+ onChange={onChange}+ renderCustomInput={({ value: customValue, onChange: onCustomChange }) => (+ <input+ aria-label="Custom 2FA identifier"+ value={customValue}+ onChange={(event) => onCustomChange(event.target.value)}+ />+ )}+ />+ );+}++function renderPicker(value = "", onChange = vi.fn()) {+ render(picker(value, onChange));+ return onChange;+}++beforeEach(() => {+ vi.clearAllMocks();+ installHooks();+});++afterEach(() => {+ cleanup();+});++describe("ConnectedEmailAccountPicker", () => {+ it("shows only active, mail-scoped accounts with resolved email addresses", () => {+ installHooks({+ google: [+ googleCredential("gmail-active"),+ googleCredential("gmail-inactive", { state: "error" }),+ googleCredential("gmail-unscoped", {+ scopes_granted: ["https://www.googleapis.com/auth/drive"],+ }),+ googleCredential("gmail-unresolved", { email_address: null }),+ ],+ microsoft: [+ microsoftCredential("outlook-active", {+ credential_name: "Finance",+ }),+ microsoftCredential("outlook-inactive", { state: "error" }),+ microsoftCredential("outlook-unscoped", {+ scopes_granted: ["Files.Read"],+ }),+ ],+ });++ renderPicker();+ fireEvent.click(+ screen.getByRole("combobox", { name: "Connected email account" }),+ );++ expect(screen.getByText("[email protected]")).toBeTruthy();+ expect(screen.getByText("[email protected]")).toBeTruthy();+ expect(screen.getByText("Gmail")).toBeTruthy();+ expect(screen.getByText("Outlook · Finance")).toBeTruthy();+ expect(screen.queryByText("[email protected]")).toBeNull();+ expect(screen.queryByText("[email protected]")).toBeNull();+ expect(screen.queryByText("[email protected]")).toBeNull();+ expect(screen.queryByText("[email protected]")).toBeNull();+ expect(mocks.useGoogleOAuthCredentials).toHaveBeenCalledWith({+ includeEmail: true,+ });+ expect(mocks.useMicrosoftOAuthCredentials).toHaveBeenCalledWith({+ includeEmail: true,+ });+ });++ it("writes the selected account email address", () => {+ installHooks({+ google: [googleCredential("selected")],+ });+ const onChange = renderPicker();++ fireEvent.click(+ screen.getByRole("combobox", { name: "Connected email account" }),+ );+ fireEvent.click(screen.getByText("[email protected]"));++ expect(onChange).toHaveBeenCalledWith("[email protected]");+ });++ it("toggles to the caller-provided custom input", () => {+ installHooks({+ google: [googleCredential("connected")],+ });+ renderPicker();++ fireEvent.click(screen.getByRole("button", { name: "Enter manually" }));++ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Choose connected account" }),+ ).toBeTruthy();+ });++ it("keeps a non-option custom value visible when dropdown mode is requested", () => {+ installHooks({+ google: [googleCredential("connected")],+ });+ renderPicker("[email protected]");++ fireEvent.click(+ screen.getByRole("button", { name: "Choose connected account" }),+ );++ expect(+ (screen.getByLabelText("Custom 2FA identifier") as HTMLInputElement)+ .value,+ ).toBe("[email protected]");+ expect(+ screen.getByRole("button", { name: "Choose connected account" }),+ ).toBeTruthy();+ });++ it("starts a Jinja value in custom mode", () => {+ installHooks({+ google: [googleCredential("connected")],+ });+ renderPicker("{{ inbox_email }}");++ expect(+ (screen.getByLabelText("Custom 2FA identifier") as HTMLInputElement)+ .value,+ ).toBe("{{ inbox_email }}");+ });++ it("stays in custom mode when the custom value is cleared", () => {+ installHooks({+ google: [googleCredential("connected")],+ });+ const onChange = vi.fn();+ const { rerender } = render(+ <ConnectedEmailAccountPicker+ value="{{ inbox_email }}"+ onChange={onChange}+ renderCustomInput={({ value, onChange: onCustomChange }) => (+ <input+ aria-label="Custom 2FA identifier"+ value={value}+ onChange={(event) => onCustomChange(event.target.value)}+ />+ )}+ />,+ );++ fireEvent.change(screen.getByLabelText("Custom 2FA identifier"), {+ target: { value: "" },+ });+ expect(onChange).toHaveBeenCalledWith("");++ rerender(+ <ConnectedEmailAccountPicker+ value=""+ onChange={onChange}+ renderCustomInput={({ value, onChange: onCustomChange }) => (+ <input+ aria-label="Custom 2FA identifier"+ value={value}+ onChange={(event) => onCustomChange(event.target.value)}+ />+ )}+ />,+ );++ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();+ expect(+ screen.getByRole("button", { name: "Choose connected account" }),+ ).toBeTruthy();+ });++ it("links to integrations when there are no connected mail accounts", () => {+ installHooks({+ googleIsLoading: true,+ microsoftIsLoading: true,+ });+ const { rerender } = render(picker());++ installHooks();+ rerender(picker());++ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();+ const link = screen.getByRole("link", {+ name: "Connect Gmail or Outlook to pick an account",+ });+ expect(link.getAttribute("href")).toBe("/integrations");+ });++ it("latches dropdown mode after slow queries resolve to the saved account", () => {+ installHooks({+ googleIsLoading: true,+ microsoftIsLoading: true,+ });+ const { rerender } = render(picker("[email protected]"));++ expect(screen.getByText("Loading connected accounts...")).toBeTruthy();++ installHooks({+ google: [+ googleCredential("saved", { email_address: "[email protected]" }),+ ],+ });+ rerender(picker("[email protected]"));++ expect(screen.queryByLabelText("Custom 2FA identifier")).toBeNull();+ expect(screen.getByText("[email protected]")).toBeTruthy();+ });++ it("switches a settled dropdown to custom when the controlled value no longer matches", () => {+ installHooks({+ google: [+ googleCredential("saved", { email_address: "[email protected]" }),+ ],+ });+ const { rerender } = render(picker("[email protected]"));++ expect(screen.queryByLabelText("Custom 2FA identifier")).toBeNull();++ rerender(picker("seeded-username"));++ expect(+ (screen.getByLabelText("Custom 2FA identifier") as HTMLInputElement)+ .value,+ ).toBe("seeded-username");+ expect(+ screen.getByRole("button", { name: "Choose connected account" }),+ ).toBeTruthy();+ });++ it("switches a settled dropdown to custom when its matching option disappears", () => {+ installHooks({+ google: [+ googleCredential("saved", { email_address: "[email protected]" }),+ ],+ });+ const { rerender } = render(picker("[email protected]"));++ expect(screen.queryByLabelText("Custom 2FA identifier")).toBeNull();++ installHooks();+ rerender(picker("[email protected]"));++ expect(+ (screen.getByLabelText("Custom 2FA identifier") as HTMLInputElement)+ .value,+ ).toBe("[email protected]");+ expect(+ screen.getByRole("button", { name: "Choose connected account" }),+ ).toBeTruthy();+ });++ it("respects a user toggle while connected accounts are loading", () => {+ installHooks({+ googleIsLoading: true,+ microsoftIsLoading: true,+ });+ const { rerender } = render(picker());++ fireEvent.click(screen.getByRole("button", { name: "Enter manually" }));+ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();++ installHooks({ google: [googleCredential("connected")] });+ rerender(picker());++ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();+ });++ it("shows a neutral manual-entry hint when account loading fails", () => {+ installHooks({ googleError: new Error("request failed") });++ renderPicker();++ expect(screen.getByLabelText("Custom 2FA identifier")).toBeTruthy();+ expect(+ screen.getByText(+ "Couldn't load connected accounts — enter the address manually",+ ),+ ).toBeTruthy();+ expect(screen.queryByRole("link")).toBeNull();+ });+});diff --git a/skyvern-frontend/src/components/ConnectedEmailAccountPicker.tsx b/skyvern-frontend/src/components/ConnectedEmailAccountPicker.tsxnew file mode 100644index 000000000..ad5cdcc08--- /dev/null+++ b/skyvern-frontend/src/components/ConnectedEmailAccountPicker.tsx@@ -0,0 +1,289 @@+import { CodeIcon } from "@radix-ui/react-icons";+import { useEffect, useRef, useState } from "react";++import {+ CustomSelectItem,+ Select,+ SelectContent,+ SelectItemText,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import {+ hasGoogleOAuthCredentialScopes,+ isGoogleOAuthCredentialActive,+ useGoogleOAuthCredentials,+} from "@/hooks/useGoogleOAuthCredentials";+import {+ hasMicrosoftOAuthCredentialScopes,+ isMicrosoftOAuthCredentialActive,+ useMicrosoftOAuthCredentials,+} from "@/hooks/useMicrosoftOAuthCredentials";+import { GOOGLE_GMAIL_REQUIRED_SCOPES } from "@/util/googleScopes";+import { MICROSOFT_MAIL_REQUIRED_SCOPES } from "@/util/microsoftScopes";+import { cn } from "@/util/utils";++type ConnectedEmailAccountPickerProps = {+ value: string;+ onChange: (value: string) => void;+ renderCustomInput: (props: {+ value: string;+ onChange: (value: string) => void;+ }) => React.ReactNode;+ disabled?: boolean;+};++type PickerMode = "dropdown" | "custom";++type EmailOption = {+ id: string;+ emailAddress: string;+ provider: "Gmail" | "Outlook";+ credentialName: string;+};++function optionHint(option: EmailOption): string {+ const credentialName = option.credentialName.trim();+ return credentialName.toLowerCase() === "default"+ ? option.provider+ : `${option.provider} · ${credentialName}`;+}++function initialPickerMode(+ value: string,+ valueMatchesOption: boolean,+ optionCount: number,+): PickerMode {+ return (value && !valueMatchesOption) || optionCount === 0+ ? "custom"+ : "dropdown";+}++function ConnectedEmailModeToggle({+ mode,+ disabled,+ onToggle,+}: {+ mode: PickerMode;+ disabled: boolean;+ onToggle: () => void;+}) {+ const label =+ mode === "dropdown" ? "Enter manually" : "Choose connected account";++ return (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ disabled={disabled}+ aria-label={label}+ aria-pressed={mode === "custom"}+ onClick={onToggle}+ className={cn(+ "nopan inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-input transition-colors disabled:cursor-not-allowed disabled:opacity-50",+ mode === "custom"+ ? "bg-muted text-foreground dark:bg-slate-700"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <CodeIcon className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+}++function ConnectedEmailAccountPicker({+ value,+ onChange,+ renderCustomInput,+ disabled = false,+}: ConnectedEmailAccountPickerProps) {+ const google = useGoogleOAuthCredentials({ includeEmail: true });+ const microsoft = useMicrosoftOAuthCredentials({ includeEmail: true });++ const googleCredentials = google.credentials.filter(+ (credential) =>+ isGoogleOAuthCredentialActive(credential) &&+ hasGoogleOAuthCredentialScopes(credential, GOOGLE_GMAIL_REQUIRED_SCOPES),+ );+ const microsoftCredentials = microsoft.credentials.filter(+ (credential) =>+ isMicrosoftOAuthCredentialActive(credential) &&+ hasMicrosoftOAuthCredentialScopes(+ credential,+ MICROSOFT_MAIL_REQUIRED_SCOPES,+ ),+ );+ const options: EmailOption[] = [+ ...googleCredentials.flatMap((credential) => {+ const emailAddress = credential.email_address?.trim();+ return emailAddress+ ? [+ {+ id: `google:${credential.id}`,+ emailAddress,+ provider: "Gmail" as const,+ credentialName: credential.credential_name,+ },+ ]+ : [];+ }),+ ...microsoftCredentials.flatMap((credential) => {+ const emailAddress = credential.email_address?.trim();+ return emailAddress+ ? [+ {+ id: `microsoft:${credential.id}`,+ emailAddress,+ provider: "Outlook" as const,+ credentialName: credential.credential_name,+ },+ ]+ : [];+ }),+ ];+ const isLoading = google.isLoading || microsoft.isLoading;+ const hasLoadError = Boolean(google.error || microsoft.error);+ const valueMatchesOption = options.some(+ (option) => option.emailAddress === value,+ );+ const optionListKey = JSON.stringify(+ options.map((option) => [option.id, option.emailAddress]),+ );+ const [mode, setMode] = useState<PickerMode | null>(() =>+ isLoading+ ? null+ : initialPickerMode(value, valueMatchesOption, options.length),+ );+ const previousValueRef = useRef(value);+ const previousOptionListKeyRef = useRef(optionListKey);+ useEffect(() => {+ const valueChanged = previousValueRef.current !== value;+ const optionListChanged =+ previousOptionListKeyRef.current !== optionListKey;+ previousValueRef.current = value;+ previousOptionListKeyRef.current = optionListKey;+ if (mode === null && !isLoading) {+ setMode(initialPickerMode(value, valueMatchesOption, options.length));+ return;+ }+ if (+ mode === "dropdown" &&+ !isLoading &&+ (valueChanged || optionListChanged) &&+ value &&+ !valueMatchesOption+ ) {+ setMode("custom");+ }+ }, [+ isLoading,+ mode,+ optionListKey,+ options.length,+ value,+ valueMatchesOption,+ ]);+ const renderedMode = mode ?? "dropdown";+ const eligibleAccountCount =+ googleCredentials.length + microsoftCredentials.length;+ const emptyHint =+ options.length === 0 && !isLoading+ ? hasLoadError+ ? "Couldn't load connected accounts — enter the address manually"+ : eligibleAccountCount === 0+ ? "Connect Gmail or Outlook to pick an account"+ : "Reconnect Gmail or Outlook to pick an account"+ : null;++ return (+ <div className="min-w-0 space-y-2">+ <div className="flex justify-end">+ <ConnectedEmailModeToggle+ mode={renderedMode}+ disabled={disabled}+ onToggle={() => {+ if (renderedMode === "dropdown") {+ setMode("custom");+ } else if (!value || valueMatchesOption) {+ setMode("dropdown");+ }+ }}+ />+ </div>+ {renderedMode === "custom" ? (+ renderCustomInput({+ value,+ onChange: disabled ? () => undefined : onChange,+ })+ ) : isLoading || mode === null ? (+ <Select disabled>+ <SelectTrigger+ aria-label="Connected email account"+ className="nopan text-xs"+ >+ <SelectValue placeholder="Loading connected accounts..." />+ </SelectTrigger>+ </Select>+ ) : (+ <Select+ disabled={disabled}+ value={valueMatchesOption ? value : ""}+ onValueChange={onChange}+ >+ <SelectTrigger+ aria-label="Connected email account"+ className="nopan text-xs"+ >+ <SelectValue placeholder="Select a connected account" />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <CustomSelectItem+ key={option.id}+ value={option.emailAddress}+ className="pr-8"+ >+ <div className="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span className="min-w-0 truncate font-medium">+ <SelectItemText>{option.emailAddress}</SelectItemText>+ </span>+ <span className="shrink-0 text-xs text-muted-foreground">+ {optionHint(option)}+ </span>+ </div>+ </CustomSelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ {emptyHint ? (+ <p className="text-xs text-muted-foreground">+ {hasLoadError ? (+ emptyHint+ ) : (+ <a+ href="/integrations"+ className="underline underline-offset-2 hover:text-foreground"+ >+ {emptyHint}+ </a>+ )}+ </p>+ ) : null}+ </div>+ );+}++export { ConnectedEmailAccountPicker, type ConnectedEmailAccountPickerProps };diff --git a/skyvern-frontend/src/hooks/useGoogleOAuthCredentials.ts b/skyvern-frontend/src/hooks/useGoogleOAuthCredentials.tsindex 3598d88c6..a927c1ffa 100644--- a/skyvern-frontend/src/hooks/useGoogleOAuthCredentials.ts+++ b/skyvern-frontend/src/hooks/useGoogleOAuthCredentials.ts@@ -121,7 +121,8 @@ function extractApiErrorMessage(error: unknown, fallback: string): string {export function useGoogleOAuthCredentials({enabled = true,-}: { enabled?: boolean } = {}) {+ includeEmail = false,+}: { enabled?: boolean; includeEmail?: boolean } = {}) {const credentialGetter = useCredentialGetter();const queryClient = useQueryClient();const { toast } = useToast();@@ -143,11 +144,17 @@ export function useGoogleOAuthCredentials({isFetching,error,} = useQuery<GoogleOAuthCredential[]>({- queryKey: ["googleOAuthCredentials"],+ queryKey: includeEmail+ ? ["googleOAuthCredentials", "includeEmail"]+ : ["googleOAuthCredentials"],enabled,queryFn: async () => {const client = await getClient(credentialGetter);- const response = await client.get("/google/oauth/credentials");+ const response = await client.get(+ includeEmail+ ? "/google/oauth/credentials?include_email=true"+ : "/google/oauth/credentials",+ );return (response.data as GoogleOAuthCredentialListResponse).credentials;},// Moderate staleness so multiple GoogleOAuthCredentialSelector instancesdiff --git a/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.ts b/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.tsindex b7dc82fde..773420bde 100644--- a/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.ts+++ b/skyvern-frontend/src/hooks/useMicrosoftOAuthCredentials.ts@@ -127,7 +127,8 @@ function extractApiErrorMessage(error: unknown, fallback: string): string {export function useMicrosoftOAuthCredentials({enabled = true,-}: { enabled?: boolean } = {}) {+ includeEmail = false,+}: { enabled?: boolean; includeEmail?: boolean } = {}) {const credentialGetter = useCredentialGetter();const queryClient = useQueryClient();const { toast } = useToast();@@ -151,11 +152,17 @@ export function useMicrosoftOAuthCredentials({isFetching,error,} = useQuery<MicrosoftOAuthCredential[]>({- queryKey: ["microsoftOAuthCredentials"],+ queryKey: includeEmail+ ? ["microsoftOAuthCredentials", "includeEmail"]+ : ["microsoftOAuthCredentials"],enabled,queryFn: async () => {const client = await getClient(credentialGetter);- const response = await client.get("/microsoft/oauth/credentials");+ const response = await client.get(+ includeEmail+ ? "/microsoft/oauth/credentials?include_email=true"+ : "/microsoft/oauth/credentials",+ );return (response.data as MicrosoftOAuthCredentialListResponse).credentials;},diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsxindex d14ab514b..676740b02 100644--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx@@ -27,6 +27,10 @@ const patchMock = vi.hoisted(() => vi.fn());const deleteMock = vi.hoisted(() => vi.fn());const getMock = vi.hoisted(() => vi.fn());const toastMock = vi.hoisted(() => vi.fn());+const mockEmailCredentials = vi.hoisted(() => ({+ google: vi.fn(),+ microsoft: vi.fn(),+}));vi.mock("@/api/AxiosClient", () => ({getClient: vi.fn(async () => ({@@ -49,6 +53,24 @@ vi.mock("@/hooks/useCustomCredentialServiceConfig", () => ({useCustomCredentialServiceConfig: () => ({ parsedConfig: null }),}));+vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();+ return {+ ...actual,+ useGoogleOAuthCredentials: mockEmailCredentials.google,+ };+});++vi.mock("@/hooks/useMicrosoftOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useMicrosoftOAuthCredentials")>();+ return {+ ...actual,+ useMicrosoftOAuthCredentials: mockEmailCredentials.microsoft,+ };+});+vi.mock("@/routes/workflows/hooks/useCredentialsQuery", () => ({useCredentialsQuery: () => ({ data: [] }),}));@@ -60,6 +82,30 @@ vi.mock("@/hooks/useFeatureFlag", () => ({useFeatureFlag: useFeatureFlagMock,}));+function installEmailCredentialHooks() {+ mockEmailCredentials.google.mockReturnValue({+ credentials: [+ {+ id: "google-mail",+ organization_id: "org_1",+ credential_name: "Default",+ state: "active",+ scopes_granted: ["https://www.googleapis.com/auth/gmail.readonly"],+ email_address: "[email protected]",+ created_at: "2026-07-30T00:00:00Z",+ modified_at: "2026-07-30T00:00:00Z",+ },+ ],+ isLoading: false,+ isFetching: false,+ });+ mockEmailCredentials.microsoft.mockReturnValue({+ credentials: [],+ isLoading: false,+ isFetching: false,+ });+}+function axiosErrorWithDetail(detail: unknown): AxiosError {const error = new AxiosError("Request failed");error.response = {@@ -201,6 +247,10 @@ describe("getAuthenticatorKeyError", () => {});describe("CredentialsModal additional two-factor methods", () => {+ beforeEach(() => {+ installEmailCredentialHooks();+ });+it("validates extension state and runs its post-save callback with the created id", async () => {const onSaved = vi.fn().mockResolvedValue(undefined);const additionalMethod: CredentialAdditionalTwoFactorMethod = {diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsxindex 746c14569..1ecb87719 100644--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.test.tsx@@ -7,14 +7,38 @@ import {render,screen,waitFor,+ within,} from "@testing-library/react";import { useEffect, useState } from "react";import { MemoryRouter } from "react-router-dom";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { CredentialAuthenticatorSupportProvider } from "./CredentialAuthenticatorSupportContext";import { PasswordCredentialContent } from "./PasswordCredentialContent";+const mockEmailCredentials = vi.hoisted(() => ({+ google: vi.fn(),+ microsoft: vi.fn(),+}));++vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();+ return {+ ...actual,+ useGoogleOAuthCredentials: mockEmailCredentials.google,+ };+});++vi.mock("@/hooks/useMicrosoftOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useMicrosoftOAuthCredentials")>();+ return {+ ...actual,+ useMicrosoftOAuthCredentials: mockEmailCredentials.microsoft,+ };+});+type Values = {name: string;username: string;@@ -72,6 +96,30 @@ const ENTERPRISE_APPS = {"Scan the QR as usual - Skyvern detects these setup codes automatically.",};+function installEmailCredentialHooks() {+ mockEmailCredentials.google.mockReturnValue({+ credentials: [+ {+ id: "google-mail",+ organization_id: "org_1",+ credential_name: "Default",+ state: "active",+ scopes_granted: ["https://www.googleapis.com/auth/gmail.readonly"],+ email_address: "[email protected]",+ created_at: "2026-07-30T00:00:00Z",+ modified_at: "2026-07-30T00:00:00Z",+ },+ ],+ isLoading: false,+ isFetching: false,+ });+ mockEmailCredentials.microsoft.mockReturnValue({+ credentials: [],+ isLoading: false,+ isFetching: false,+ });+}+describe("PasswordCredentialContent — additional two-factor methods", () => {const additionalMethod = {value: "security_device",@@ -176,6 +224,10 @@ describe("PasswordCredentialContent — additional two-factor methods", () => {});describe("PasswordCredentialContent — built-in two-factor methods", () => {+ beforeEach(() => {+ installEmailCredentialHooks();+ });+it("exposes every method as a focusable pressed button and updates selection", () => {render(<MemoryRouter>@@ -215,9 +267,11 @@ describe("PasswordCredentialContent — built-in two-factor methods", () => {function ModalLikeHarness({appliedValues,onChangeSpy,+ editingValues = false,}: {appliedValues: Values | null;onChangeSpy: (next: Values) => void;+ editingValues?: boolean;}) {const [values, setValues] = useState<Values>(INITIAL_VALUES);useEffect(() => {@@ -234,13 +288,17 @@ function ModalLikeHarness({setValues(next);}}editMode- editingGroups={{ name: false, values: false }}+ editingGroups={{ name: false, values: editingValues }}/></MemoryRouter>);}describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regression)", () => {+ beforeEach(() => {+ installEmailCredentialHooks();+ });+afterEach(() => {cleanup();vi.unstubAllGlobals();@@ -321,6 +379,83 @@ describe("PasswordCredentialContent — edit-mode hydration (SKY-9864 regressionexpect(autoFillCall).toBeTruthy();});+ it("renders the connected account picker for Email and preserves manual entry", async () => {+ const onChangeSpy = vi.fn();++ render(+ <ModalLikeHarness+ appliedValues={{+ name: "Example Login",+ username: "[email protected]",+ password: "",+ totp: "",+ totp_type: "email",+ totp_identifier: "[email protected]",+ }}+ onChangeSpy={onChangeSpy}+ editingValues+ />,+ );++ expect(+ await screen.findByRole("combobox", {+ name: "Connected email account",+ }),+ ).toBeTruthy();+ const modeToggle = screen.getByRole("button", { name: "Enter manually" });+ fireEvent.click(modeToggle);+ const identifierInput = modeToggle+ .closest(".min-w-0")+ ?.querySelector("input");+ expect(identifierInput).toBeTruthy();+ fireEvent.change(identifierInput as HTMLInputElement, {+ target: { value: "[email protected]" },+ });++ expect(onChangeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ totp_type: "email",+ totp_identifier: "[email protected]",+ }),+ );+ });++ it("enables editing from a locked connected account picker", async () => {+ const onEnableEditValues = vi.fn();++ render(+ <MemoryRouter>+ <PasswordCredentialContent+ values={{+ name: "Example Login",+ username: "[email protected]",+ password: "",+ totp: "",+ totp_type: "email",+ totp_identifier: "[email protected]",+ }}+ onChange={vi.fn()}+ editMode+ editingGroups={{ name: false, values: false }}+ onEnableEditValues={onEnableEditValues}+ />+ </MemoryRouter>,+ );++ const picker = await screen.findByRole("combobox", {+ name: "Connected email account",+ });+ const pickerField = picker.closest(".relative");+ expect(pickerField).toBeTruthy();++ const editButton = within(pickerField as HTMLElement).getByRole("button", {+ name: "Edit credential values",+ });+ fireEvent.click(editButton);++ expect(onEnableEditValues).toHaveBeenCalledOnce();+ });+it("marks Authenticator App as the selected 2FA method when a new credential opens the 2FA section", async () => {const onChangeSpy = vi.fn();diff --git a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsxindex 90cb7f981..9db5ee342 100644--- a/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx+++ b/skyvern-frontend/src/routes/credentials/PasswordCredentialContent.tsx@@ -1,4 +1,5 @@import googleAuthenticatorIcon from "@/assets/authenticators/google-authenticator.jpg";+import { ConnectedEmailAccountPicker } from "@/components/ConnectedEmailAccountPicker";import { QRCodeIcon } from "@/components/icons/QRCodeIcon";import {Accordion,@@ -883,24 +884,73 @@ function PasswordCredentialContent({<div className="w-40 shrink-0"><Label>{totpIdentifierLabel}</Label></div>- <div className="relative w-full">- <Input- value={totp_identifier}- onChange={(e) =>- updateValues({ totp_identifier: e.target.value })- }- readOnly={valuesReadOnly}- className={cn({ "pr-9 opacity-70": valuesReadOnly })}- />- {valuesReadOnly && (- <button- type="button"- className="absolute right-0 top-0 flex size-9 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"- onClick={onEnableEditValues}- aria-label="Edit credential values"+ <div className="w-full">+ {totpMethod === "email" ? (+ <div+ className={cn(+ "relative w-full",+ valuesReadOnly &&+ "[&_[role=combobox]>svg]:hidden [&_[role=combobox]]:pr-9",+ )}>- <Pencil1Icon className="size-4" />- </button>+ <ConnectedEmailAccountPicker+ value={totp_identifier}+ onChange={(value) =>+ updateValues({ totp_identifier: value })+ }+ disabled={valuesReadOnly}+ renderCustomInput={({+ value,+ onChange: onCustomChange,+ }) => (+ <Input+ value={value}+ onChange={(event) =>+ onCustomChange(event.target.value)+ }+ readOnly={valuesReadOnly}+ className={cn({+ "pr-9 opacity-70": valuesReadOnly,+ })}+ />+ )}+ />+ {valuesReadOnly && (+ <button+ type="button"+ className="absolute bottom-0 right-0 flex size-9 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"+ onClick={onEnableEditValues}+ aria-label="Edit credential values"+ >+ <Pencil1Icon className="size-4" />+ </button>+ )}+ </div>+ ) : (+ <div className="relative w-full">+ <Input+ value={totp_identifier}+ onChange={(event) =>+ updateValues({+ totp_identifier: event.target.value,+ })+ }+ readOnly={valuesReadOnly}+ className={cn({+ "pr-9 opacity-70": valuesReadOnly,+ })}+ />+ {valuesReadOnly && (+ <button+ type="button"+ className="absolute right-0 top-0 flex size-9 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"+ onClick={onEnableEditValues}+ aria-label="Edit credential values"+ >+ <Pencil1Icon className="size-4" />+ </button>+ )}+ </div>)}</div></div>diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsxindex 479c42d07..368ca43ce 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx@@ -8,6 +8,7 @@ import {import { useEdges, useNodes, useNodesData } from "@xyflow/react";import { HelpTooltip } from "@/components/HelpTooltip";+import { ConnectedEmailAccountPicker } from "@/components/ConnectedEmailAccountPicker";import {Accordion,AccordionContent,@@ -205,16 +206,23 @@ function LoginEditorBody({content={helpTooltips["login"]["totpIdentifier"]}/></div>- <WorkflowBlockInputTextarea- nodeId={blockId}- onChange={(value) => update({ totpIdentifier: value })}+ <ConnectedEmailAccountPickervalue={data.totpIdentifier ?? ""}- placeholder={- !data.totpIdentifier?.trim() && credentialTotpIdentifier- ? `${credentialTotpIdentifier} (from credential)`- : placeholders["login"]["totpIdentifier"]- }- className="nopan text-xs"+ onChange={(value) => update({ totpIdentifier: value })}+ disabled={!editable}+ renderCustomInput={({ value, onChange }) => (+ <WorkflowBlockInputTextarea+ nodeId={blockId}+ onChange={onChange}+ value={value}+ placeholder={+ !data.totpIdentifier?.trim() && credentialTotpIdentifier+ ? `${credentialTotpIdentifier} (from credential)`+ : placeholders["login"]["totpIdentifier"]+ }+ className="nopan text-xs"+ />+ )}/>{!data.totpIdentifier?.trim() && credentialTotpIdentifier ? (<p className="text-xs text-muted-foreground dark:text-slate-500">diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsxindex cdd2ad377..8d46acf5c 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx@@ -5,6 +5,29 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import type { LoginNode } from "../../nodes/LoginNode/types";+const mockEmailCredentials = vi.hoisted(() => ({+ google: vi.fn(),+ microsoft: vi.fn(),+}));++vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();+ return {+ ...actual,+ useGoogleOAuthCredentials: mockEmailCredentials.google,+ };+});++vi.mock("@/hooks/useMicrosoftOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useMicrosoftOAuthCredentials")>();+ return {+ ...actual,+ useMicrosoftOAuthCredentials: mockEmailCredentials.microsoft,+ };+});+// Heavy subcomponents pull in network/data layers (workflow params store,// credentials query, etc.) that are out of scope for a unit test of the// form's own composition. Replace each with a typed stub that surfaces the@@ -222,6 +245,27 @@ function makeLoginFixture(beforeEach(() => {mockNodeFixtures.clear();mockCredentialTotp.value = null;+ mockEmailCredentials.google.mockReturnValue({+ credentials: [+ {+ id: "google-mail",+ organization_id: "org_1",+ credential_name: "Default",+ state: "active",+ scopes_granted: ["https://www.googleapis.com/auth/gmail.readonly"],+ email_address: "[email protected]",+ created_at: "2026-07-30T00:00:00Z",+ modified_at: "2026-07-30T00:00:00Z",+ },+ ],+ isLoading: false,+ isFetching: false,+ });+ mockEmailCredentials.microsoft.mockReturnValue({+ credentials: [],+ isLoading: false,+ isFetching: false,+ });usePendingCommitsStore.setState({ commits: {} });updateNodeDataMock.mockReset();useDebouncedSidebarSaveMock.mockReset();@@ -272,9 +316,29 @@ describe("LoginBlockForm (SKY-9374)", () => {screen.getByRole("button", { name: "Add two-factor authentication" }),);- expect(screen.getAllByTestId("wbi-textarea")).toHaveLength(4);+ expect(screen.getAllByTestId("wbi-textarea")).toHaveLength(3);expect(screen.getByText("2FA Identifier")).toBeDefined();expect(screen.getByText("2FA Verification URL")).toBeDefined();+ expect(+ screen.getByRole("combobox", { name: "Connected email account" }),+ ).toBeDefined();+ });++ test("picking a connected account updates the block's 2FA identifier", () => {+ mockNodeFixtures.set("b1", makeLoginFixture("b1"));+ render(<LoginBlockForm blockId="b1" />);++ fireEvent.click(+ screen.getByRole("button", { name: "Add two-factor authentication" }),+ );+ fireEvent.click(+ screen.getByRole("combobox", { name: "Connected email account" }),+ );+ fireEvent.click(screen.getByText("[email protected]"));++ expect(updateNodeDataMock).toHaveBeenCalledWith("b1", {+ totpIdentifier: "[email protected]",+ });});test("auto-expands 2FA when the block already has a totp value", () => {diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex c872a3178..40b384e85 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -63,6 +63,7 @@ from skyvern.forge.sdk.trace import tracedfrom skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVarfrom skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestinationfrom skyvern.services.otp_email import EmailOTPSearchError, EmailOTPVerificationContext, build_email_otp_sources+from skyvern.utils.email_validation import normalize_identifier_if_emailfrom skyvern.utils.url_validators import pinned_ip_clientfrom skyvern.webeye.actions.actions import Actionfrom skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelection, resolve_engine_selection_for_task@@ -1756,7 +1757,7 @@ class AgentFunction:# Persist only the resolved OTP value to avoid retaining raw email bodies.await app.DATABASE.otp.create_otp_code(organization_id,- totp_identifier,+ normalize_identifier_if_email(totp_identifier),otp_value.value,otp_value.value,otp_value.get_otp_type(),diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 9aed4999e..5be42f463 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -1926,6 +1926,7 @@ class GoogleOAuthCredentialModel(Base):id = Column(String, primary_key=True, default=generate_google_oauth_credential_id)organization_id = Column(String, ForeignKey("organizations.organization_id"), index=True, nullable=False)credential_name = Column(String, nullable=False, default="Default")+ email_address = Column(String, nullable=True)provider = Column(String, nullable=False, default="google")state = Column(String, nullable=False, default="pending_consent", index=True)scopes_requested = Column(JSON, nullable=False, default=list)@@ -1965,6 +1966,7 @@ class MicrosoftOAuthCredentialModel(Base):id = Column(String, primary_key=True, default=generate_microsoft_oauth_credential_id)organization_id = Column(String, ForeignKey("organizations.organization_id"), index=True, nullable=False)credential_name = Column(String, nullable=False, default="Default")+ email_address = Column(String, nullable=True)state = Column(String, nullable=False, default="pending_consent", index=True)scopes_requested = Column(JSON, nullable=False, default=list)scopes_granted = Column(JSON, nullable=False, default=list)diff --git a/skyvern/forge/sdk/db/repositories/google_oauth.py b/skyvern/forge/sdk/db/repositories/google_oauth.pyindex dbd006da2..183a7ccac 100644--- a/skyvern/forge/sdk/db/repositories/google_oauth.py+++ b/skyvern/forge/sdk/db/repositories/google_oauth.py@@ -273,6 +273,7 @@ class GoogleOAuthRepository(BaseRepository):encrypted_refresh_token=encrypted_refresh_token,encrypted_method=encrypted_method.value,scopes_granted=scopes_granted,+ email_address=None,consent_nonce=None,consent_redirect_uri=None,consent_expires_at=None,@@ -423,6 +424,69 @@ class GoogleOAuthRepository(BaseRepository):await session.commit()return result+ @db_operation("update_active_refresh_token")+ async def update_active_refresh_token(+ self,+ *,+ organization_id: str,+ credential_id: str,+ encrypted_refresh_token: str,+ encrypted_method: EncryptMethod,+ now: datetime.datetime,+ expected_encrypted_refresh_token: str,+ ) -> bool:+ async with self.Session() as session:+ stmt = (+ update(GoogleOAuthCredentialModel)+ .where(+ GoogleOAuthCredentialModel.id == credential_id,+ GoogleOAuthCredentialModel.organization_id == organization_id,+ GoogleOAuthCredentialModel.state == STATE_ACTIVE,+ GoogleOAuthCredentialModel.encrypted_refresh_token == expected_encrypted_refresh_token,+ )+ .values(+ encrypted_refresh_token=encrypted_refresh_token,+ encrypted_method=encrypted_method.value,+ modified_at=now,+ )+ )+ result = await session.execute(stmt)+ await session.commit()+ return result.rowcount > 0++ @db_operation("update_email_address")+ async def update_email_address(+ self,+ *,+ organization_id: str,+ credential_id: str,+ email_address: str,+ only_if_null: bool,+ expected_version: datetime.datetime | None = None,+ ) -> bool:+ async with self.Session() as session:+ filters = [+ GoogleOAuthCredentialModel.id == credential_id,+ GoogleOAuthCredentialModel.organization_id == organization_id,+ GoogleOAuthCredentialModel.state == STATE_ACTIVE,+ ]+ if only_if_null:+ filters.append(GoogleOAuthCredentialModel.email_address.is_(None))+ if expected_version is not None:+ filters.append(GoogleOAuthCredentialModel.modified_at == expected_version)+ # modified_at is the refresh-token optimistic-lock version and email enrichment must not advance it.+ stmt = (+ update(GoogleOAuthCredentialModel)+ .where(*filters)+ .values(+ email_address=email_address,+ modified_at=GoogleOAuthCredentialModel.modified_at,+ )+ )+ result = await session.execute(stmt)+ await session.commit()+ return result.rowcount > 0+@db_operation("mark_revoked_and_scrub")async def mark_revoked_and_scrub(self,@@ -442,6 +506,7 @@ class GoogleOAuthRepository(BaseRepository):state=STATE_REVOKED,encrypted_refresh_token=None,encrypted_method=None,+ email_address=None,consent_nonce=None,consent_redirect_uri=None,consent_expires_at=None,diff --git a/skyvern/forge/sdk/db/repositories/microsoft_oauth.py b/skyvern/forge/sdk/db/repositories/microsoft_oauth.pyindex 2f428defb..3d7e66497 100644--- a/skyvern/forge/sdk/db/repositories/microsoft_oauth.py+++ b/skyvern/forge/sdk/db/repositories/microsoft_oauth.py@@ -294,6 +294,33 @@ class MicrosoftOAuthRepository(BaseRepository):await session.execute(stmt)await session.commit()+ @db_operation("update_email_address")+ async def update_email_address(+ self,+ *,+ organization_id: str,+ credential_id: str,+ email_address: str,+ only_if_null: bool,+ ) -> bool:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ async with self.Session() as session:+ filters = [+ MicrosoftOAuthCredentialModel.id == credential_id,+ MicrosoftOAuthCredentialModel.organization_id == organization_id,+ MicrosoftOAuthCredentialModel.state == STATE_ACTIVE,+ ]+ if only_if_null:+ filters.append(MicrosoftOAuthCredentialModel.email_address.is_(None))+ stmt = (+ update(MicrosoftOAuthCredentialModel)+ .where(*filters)+ .values(email_address=email_address, modified_at=now)+ )+ result = await session.execute(stmt)+ await session.commit()+ return result.rowcount > 0+@db_operation("mark_revoked_and_scrub")async def mark_revoked_and_scrub(self,@@ -313,6 +340,7 @@ class MicrosoftOAuthRepository(BaseRepository):state=STATE_REVOKED,encrypted_refresh_token=None,encrypted_method=None,+ email_address=None,consent_nonce=None,consent_redirect_uri=None,consent_expires_at=None,diff --git a/skyvern/forge/sdk/db/repositories/otp.py b/skyvern/forge/sdk/db/repositories/otp.pyindex 2b34aad0f..5df52b0a1 100644--- a/skyvern/forge/sdk/db/repositories/otp.py+++ b/skyvern/forge/sdk/db/repositories/otp.py@@ -2,13 +2,22 @@ from __future__ import annotationsfrom datetime import datetime, timedelta, timezone-from sqlalchemy import and_, asc, or_, select, update+from sqlalchemy import and_, asc, func, or_, select, update+from sqlalchemy.sql.elements import ColumnElementfrom skyvern.config import settingsfrom skyvern.forge.sdk.db._error_handling import db_operationfrom skyvern.forge.sdk.db.base_repository import BaseRepositoryfrom skyvern.forge.sdk.db.models import TOTPCodeModelfrom skyvern.forge.sdk.schemas.totp_codes import OTPType, RawTOTPCode, TOTPCode+from skyvern.utils.email_validation import SAFE_EMAIL_ADDRESS_PATTERN, normalize_email_address+++def _identifier_filter(totp_identifier: str) -> ColumnElement[bool]:+ stripped_identifier = totp_identifier.strip()+ if SAFE_EMAIL_ADDRESS_PATTERN.fullmatch(stripped_identifier):+ return func.lower(TOTPCodeModel.totp_identifier) == normalize_email_address(totp_identifier)+ return TOTPCodeModel.totp_identifier == totp_identifierclass OTPRepository(BaseRepository):@@ -45,7 +54,7 @@ class OTPRepository(BaseRepository):query = (select(TOTPCodeModel).filter_by(organization_id=organization_id)- .filter_by(totp_identifier=totp_identifier)+ .filter(_identifier_filter(totp_identifier)).filter_by(parse_status="parsed").filter(TOTPCodeModel.created_at > datetime.now(timezone.utc) - timedelta(minutes=valid_lifespan_minutes)@@ -127,7 +136,7 @@ class OTPRepository(BaseRepository):if workflow_run_id is not None:query = query.filter(TOTPCodeModel.workflow_run_id == workflow_run_id)if totp_identifier:- query = query.filter(TOTPCodeModel.totp_identifier == totp_identifier)+ query = query.filter(_identifier_filter(totp_identifier))query = query.order_by(TOTPCodeModel.created_at.desc()).limit(limit)totp_codes = (await session.scalars(query)).all()return [TOTPCode.model_validate(totp_code) for totp_code in totp_codes]@@ -214,9 +223,9 @@ class OTPRepository(BaseRepository):select(TOTPCodeModel).filter_by(organization_id=organization_id,- totp_identifier=totp_identifier,parse_status="raw",)+ .filter(_identifier_filter(totp_identifier)).filter(TOTPCodeModel.created_at > datetime.now(timezone.utc) - timedelta(minutes=valid_lifespan_minutes))diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 8ccd93ff3..1b599a972 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -153,6 +153,7 @@ from skyvern.services.otp_service import (redact_otp_identifier_for_log,)from skyvern.services.run_service import cancel_workflow_run+from skyvern.utils.email_validation import normalize_identifier_if_emailfrom skyvern.utils.url_validators import validate_urlLOG = structlog.get_logger()@@ -446,6 +447,7 @@ async def send_totp_code(data: TOTPCodeCreate,curr_org: Organization = Depends(org_auth_service.get_current_org),) -> TOTPCode:+ totp_identifier = normalize_identifier_if_email(data.totp_identifier)redacted_totp_identifier = redact_otp_identifier_for_log(data.totp_identifier)LOG.info("Saving OTP code",@@ -514,7 +516,7 @@ async def send_totp_code(raise HTTPException(status_code=400, detail="Failed to parse otp login")raw_row = await app.DATABASE.otp.create_raw_otp_code(organization_id=curr_org.organization_id,- totp_identifier=data.totp_identifier,+ totp_identifier=totp_identifier,content=data.content,task_id=data.task_id,workflow_id=data.workflow_id,@@ -536,7 +538,7 @@ async def send_totp_code(return await app.DATABASE.otp.create_otp_code(organization_id=curr_org.organization_id,- totp_identifier=data.totp_identifier,+ totp_identifier=totp_identifier,content=data.content,code=otp_value.value,task_id=data.task_id,diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.pyindex f1e426781..0b9df87ff 100644--- a/skyvern/forge/sdk/routes/google_oauth.py+++ b/skyvern/forge/sdk/routes/google_oauth.py@@ -1,3 +1,6 @@+import asyncio+import random+import timefrom typing import Annotatedimport httpx@@ -13,20 +16,84 @@ from skyvern.forge.sdk.schemas.google_oauth import (GoogleOAuthAuthorizeResponse,GoogleOAuthClientConfig,GoogleOAuthClientConfigResponse,+ GoogleOAuthCredentialBase,GoogleOAuthCredentialListResponse,GoogleOAuthCredentialResponse,UpdateGoogleOAuthClientConfigRequest,UpdateGoogleOAuthCredentialRequest,)from skyvern.forge.sdk.schemas.organizations import Organization-from skyvern.forge.sdk.services import google_oauth_service, org_auth_service+from skyvern.forge.sdk.services import google_gmail_service, google_oauth_service, org_auth_servicefrom skyvern.forge.sdk.services.google_oauth_service import InvalidAppOriginErrorfrom skyvern.forge.sdk.settings_manager import SettingsManager+from skyvern.utils.email_validation import normalize_email_addressLOG = structlog.get_logger()google_oauth_router = APIRouter()+_EMAIL_BACKFILL_FAILURE_TTL_SECONDS = 3600.0+# Per-process cache bounds provider spend, not correctness.+_EMAIL_BACKFILL_FAILURES: dict[str, float] = {}+++async def _backfill_google_email_addresses(+ *,+ organization_id: str,+ credentials: list[GoogleOAuthCredentialBase],+) -> None:+ now = time.monotonic()+ for credential_id, deadline in list(_EMAIL_BACKFILL_FAILURES.items()):+ if deadline <= now:+ _EMAIL_BACKFILL_FAILURES.pop(credential_id, None)+ eligible_candidates = [+ credential+ for credential in credentials+ if credential.email_address is None+ and credential.id not in _EMAIL_BACKFILL_FAILURES+ and credential.state == google_oauth_service.STATE_ACTIVE+ and google_oauth_service.has_required_scopes(+ credential.scopes_granted,+ google_oauth_service.GOOGLE_GMAIL_SCOPES,+ )+ ]+ candidates = random.sample(eligible_candidates, k=min(3, len(eligible_candidates)))+ for credential in candidates:+ try:+ secrets = await google_oauth_service.load_credential_secrets(+ organization_id=organization_id,+ credential_id=credential.id,+ )+ refresh_result = await google_oauth_service.refresh_and_rotate(+ organization_id=organization_id,+ credential_id=credential.id,+ credential_secrets=secrets,+ )+ email_address = await google_gmail_service.fetch_profile_email(access_token=refresh_result.access_token)+ if email_address is None:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ continue+ email_address = normalize_email_address(email_address)+ updated = await google_oauth_service.update_email_address(+ organization_id=organization_id,+ credential_id=credential.id,+ email_address=email_address,+ only_if_null=True,+ expected_version=refresh_result.credential_version,+ )+ if updated:+ credential.email_address = email_address+ except asyncio.CancelledError:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ raise+ except Exception:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ LOG.warning(+ "Failed to backfill Google account email",+ credential_id=credential.id,+ exc_info=True,+ )+def _require_organization_client_config_enabled() -> None:if not SettingsManager.get_settings().ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG:@@ -166,6 +233,33 @@ async def google_oauth_callback(except google_oauth_service.EncryptionNotConfiguredError as exc:raise HTTPException(status_code=503, detail=str(exc))+ try:+ if google_oauth_service.has_required_scopes(+ scopes_granted,+ google_oauth_service.GOOGLE_GMAIL_SCOPES,+ ):+ email_address = await google_gmail_service.fetch_profile_email(+ access_token=token_data["access_token"],+ )+ if email_address is not None:+ email_address = normalize_email_address(email_address)+ updated = await google_oauth_service.update_email_address(+ organization_id=current_org.organization_id,+ credential_id=credential.id,+ email_address=email_address,+ only_if_null=False,+ expected_version=credential.modified_at,+ )+ if updated:+ credential.email_address = email_address+ else:+ LOG.debug(+ "Skipped Google account email update after credential changed",+ credential_id=credential.id,+ )+ except Exception:+ LOG.warning("Failed to resolve Google account email", exc_info=True)+# ``consent_app_origin`` was validated against ``GOOGLE_OAUTH_APP_ORIGINS`` in# ``start_authorization`` before being persisted to the pending row, so reading# it back here is safe. A future refactor that bypasses that pre-storage check@@ -240,11 +334,23 @@ async def delete_google_oauth_client_config(@google_oauth_router.get("/oauth/credentials")async def list_google_oauth_credentials(current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ include_email: bool = False,) -> GoogleOAuthCredentialListResponse:"""Fetch a list of Google OAuth credentials associated with an organization."""credentials = await google_oauth_service.get_visible_credentials_for_org(organization_id=current_org.organization_id,)+ if include_email:+ try:+ async with asyncio.timeout(10):+ await _backfill_google_email_addresses(+ organization_id=current_org.organization_id,+ credentials=credentials,+ )+ except TimeoutError:+ LOG.warning("Timed out backfilling Google account emails")+ except Exception:+ LOG.warning("Failed to backfill Google account emails", exc_info=True)return GoogleOAuthCredentialListResponse(credentials=credentials)diff --git a/skyvern/forge/sdk/routes/microsoft_oauth.py b/skyvern/forge/sdk/routes/microsoft_oauth.pyindex ab9cd58ed..401d4b35b 100644--- a/skyvern/forge/sdk/routes/microsoft_oauth.py+++ b/skyvern/forge/sdk/routes/microsoft_oauth.py@@ -1,3 +1,6 @@+import asyncio+import random+import timefrom typing import Annotatedimport structlog@@ -7,6 +10,7 @@ from skyvern.forge.sdk.schemas.microsoft_oauth import (CreateMicrosoftOAuthAuthorizeRequest,CreateMicrosoftOAuthCallbackRequest,MicrosoftOAuthAuthorizeResponse,+ MicrosoftOAuthCredentialBase,MicrosoftOAuthCredentialListResponse,MicrosoftOAuthCredentialResponse,UpdateMicrosoftOAuthCredentialRequest,@@ -14,11 +18,68 @@ from skyvern.forge.sdk.schemas.microsoft_oauth import (from skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.services import microsoft_oauth_service, org_auth_servicefrom skyvern.forge.sdk.services.microsoft_oauth_service import InvalidAppOriginError+from skyvern.services.email import outlook+from skyvern.utils.email_validation import normalize_email_addressLOG = structlog.get_logger()microsoft_oauth_router = APIRouter()+_EMAIL_BACKFILL_FAILURE_TTL_SECONDS = 3600.0+# Per-process cache bounds provider spend, not correctness.+_EMAIL_BACKFILL_FAILURES: dict[str, float] = {}+++async def _backfill_microsoft_email_addresses(+ *,+ organization_id: str,+ credentials: list[MicrosoftOAuthCredentialBase],+) -> None:+ now = time.monotonic()+ for credential_id, deadline in list(_EMAIL_BACKFILL_FAILURES.items()):+ if deadline <= now:+ _EMAIL_BACKFILL_FAILURES.pop(credential_id, None)+ eligible_candidates = [+ credential+ for credential in credentials+ if credential.email_address is None and credential.id not in _EMAIL_BACKFILL_FAILURES+ ]+ candidates = random.sample(eligible_candidates, k=min(3, len(eligible_candidates)))+ for credential in candidates:+ try:+ secrets = await microsoft_oauth_service.load_credential_secrets(+ organization_id=organization_id,+ credential_id=credential.id,+ )+ access_token = await microsoft_oauth_service.refresh_and_rotate(+ organization_id=organization_id,+ credential_id=credential.id,+ credential_secrets=secrets,+ )+ email_address = await outlook.fetch_primary_account_email(access_token=access_token)+ if email_address is None:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ continue+ email_address = normalize_email_address(email_address)+ updated = await microsoft_oauth_service.update_email_address(+ organization_id=organization_id,+ credential_id=credential.id,+ email_address=email_address,+ only_if_null=True,+ )+ if updated:+ credential.email_address = email_address+ except asyncio.CancelledError:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ raise+ except Exception:+ _EMAIL_BACKFILL_FAILURES[credential.id] = time.monotonic() + _EMAIL_BACKFILL_FAILURE_TTL_SECONDS+ LOG.warning(+ "Failed to backfill Microsoft account email",+ credential_id=credential.id,+ exc_info=True,+ )+def _require_scopes_from_token(token_data: dict) -> list[str]:raw = token_data.get("scope")@@ -136,16 +197,69 @@ async def microsoft_oauth_callback(except microsoft_oauth_service.EncryptionNotConfiguredError as exc:raise HTTPException(status_code=503, detail=str(exc)) from exc+ email_address = None+ should_resolve_email = True+ try:+ email_address = await outlook.fetch_primary_account_email(+ access_token=token_data["access_token"],+ )+ except outlook.OutlookAPIError as exc:+ if 400 <= exc.status < 500 and exc.status not in {401, 408, 429}:+ LOG.warning("Graph mail unavailable; falling back to Microsoft identity claims", exc_info=True)+ else:+ LOG.debug(+ "Skipped Microsoft account email update after transient Graph failure",+ credential_id=credential.id,+ exc_info=True,+ )+ should_resolve_email = False+ except Exception:+ LOG.warning("Failed to resolve Microsoft account email", exc_info=True)+ should_resolve_email = False++ if should_resolve_email:+ try:+ if email_address is None:+ # Claims are safe after Graph definitively returns no mail or a non-transient client error.+ id_token = token_data.get("id_token")+ email_address = (+ microsoft_oauth_service.email_from_id_token(id_token) if isinstance(id_token, str) else None+ )+ if email_address is not None:+ email_address = normalize_email_address(email_address)+ updated = await microsoft_oauth_service.update_email_address(+ organization_id=current_org.organization_id,+ credential_id=credential.id,+ email_address=email_address,+ only_if_null=False,+ )+ if updated:+ credential.email_address = email_address+ except Exception:+ LOG.warning("Failed to resolve Microsoft account email", exc_info=True)+return MicrosoftOAuthCredentialResponse(credential=credential, app_origin=context.consent_app_origin)@microsoft_oauth_router.get("/oauth/credentials")async def list_microsoft_oauth_credentials(current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ include_email: bool = False,) -> MicrosoftOAuthCredentialListResponse:credentials = await microsoft_oauth_service.get_credentials_for_org(organization_id=current_org.organization_id,)+ if include_email:+ try:+ async with asyncio.timeout(10):+ await _backfill_microsoft_email_addresses(+ organization_id=current_org.organization_id,+ credentials=credentials,+ )+ except TimeoutError:+ LOG.warning("Timed out backfilling Microsoft account emails")+ except Exception:+ LOG.warning("Failed to backfill Microsoft account emails", exc_info=True)return MicrosoftOAuthCredentialListResponse(credentials=credentials)diff --git a/skyvern/forge/sdk/schemas/google_oauth.py b/skyvern/forge/sdk/schemas/google_oauth.pyindex 5eb36055a..56d359102 100644--- a/skyvern/forge/sdk/schemas/google_oauth.py+++ b/skyvern/forge/sdk/schemas/google_oauth.py@@ -73,6 +73,7 @@ class GoogleOAuthCredentialBase(BaseModel):id: strorganization_id: strcredential_name: str+ email_address: str | None = Noneprovider: str = "google"state: strscopes_requested: list[str] = Field(default_factory=list)diff --git a/skyvern/forge/sdk/schemas/microsoft_oauth.py b/skyvern/forge/sdk/schemas/microsoft_oauth.pyindex ae6a65894..d430aa172 100644--- a/skyvern/forge/sdk/schemas/microsoft_oauth.py+++ b/skyvern/forge/sdk/schemas/microsoft_oauth.py@@ -8,6 +8,7 @@ class MicrosoftOAuthCredentialBase(BaseModel):id: strorganization_id: strcredential_name: str+ email_address: str | None = Nonestate: strscopes_requested: list[str] = Field(default_factory=list)scopes_granted: list[str] = Field(default_factory=list)diff --git a/skyvern/forge/sdk/services/google_gmail_service.py b/skyvern/forge/sdk/services/google_gmail_service.pyindex 8d90df5b1..b418f6d82 100644--- a/skyvern/forge/sdk/services/google_gmail_service.py+++ b/skyvern/forge/sdk/services/google_gmail_service.py@@ -1,4 +1,3 @@-import refrom dataclasses import dataclassfrom datetime import datetime, timezonefrom math import ceil@@ -9,13 +8,14 @@ import httpximport structlogfrom skyvern.services.email import gmail_client+from skyvern.utils.email_validation import SAFE_EMAIL_ADDRESS_PATTERNGMAIL_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)"-_SAFE_EMAIL_QUERY_IDENTIFIER = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+$")+_SAFE_EMAIL_QUERY_IDENTIFIER = SAFE_EMAIL_ADDRESS_PATTERN_decode = gmail_client.decode_get_json = gmail_client.get_json_payload_text = gmail_client.payload_text@@ -28,6 +28,34 @@ class GmailMessageCandidate:internal_date: datetime | None = None+async def fetch_profile_email(+ *,+ access_token: str,+ client: httpx.AsyncClient | None = None,+) -> str | None:+ async def _fetch(client_: httpx.AsyncClient) -> str | None:+ payload = await _get_json(+ client_,+ f"{GMAIL_API_BASE}/users/me/profile",+ access_token=access_token,+ )+ if not isinstance(payload, dict):+ return None+ value = payload.get("emailAddress")+ if not isinstance(value, str):+ return None+ candidate = value.strip()+ return candidate if _SAFE_EMAIL_QUERY_IDENTIFIER.fullmatch(candidate) else None++ try:+ if client is not None:+ return await _fetch(client)+ async with httpx.AsyncClient(timeout=20.0) as owned_client:+ return await _fetch(owned_client)+ except (GmailAPIError, ValueError):+ return None++def _as_utc(value: datetime) -> datetime:return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.pyindex aee2efc3f..f0c687cc3 100644--- a/skyvern/forge/sdk/services/google_oauth_service.py+++ b/skyvern/forge/sdk/services/google_oauth_service.py@@ -128,6 +128,10 @@ class ExpiredRefreshTokenError(MissingAccessTokenError):(as opposed to a transient transport error)."""+class RotatedRefreshTokenPersistenceError(RuntimeError):+ pass++class CredentialNotReauthorizableError(ValueError):"""Raised when an in-place re-auth targets a credential that does not exist for the org or isnot in a re-authorizable (active/error) state."""@@ -172,6 +176,13 @@ class GoogleCredentialSecrets:scopes: list[str] = field(default_factory=list)client_id: str | None = Nonecredential_version: datetime.datetime | None = None+ encrypted_refresh_token: str | None = None+++@dataclass(frozen=True)+class GoogleRefreshResult:+ access_token: str+ credential_version: datetime.datetime | None@dataclass(frozen=True)@@ -758,6 +769,7 @@ async def load_credential_secrets(scopes=payload.scopes_granted,client_id=payload.client_id,credential_version=payload.credential_version,+ encrypted_refresh_token=payload.encrypted_refresh_token,)@@ -823,6 +835,52 @@ async def credentials_from_secrets(return creds+async def refresh_and_rotate(+ *,+ organization_id: str,+ credential_id: str,+ credential_secrets: GoogleCredentialSecrets,+) -> GoogleRefreshResult:+ creds = await credentials_from_secrets(credential_secrets, organization_id)+ access_token = creds.token+ if not isinstance(access_token, str) or not access_token:+ raise MissingAccessTokenError("Google token response did not include access_token")++ credential_version = credential_secrets.credential_version+ new_refresh_token = creds.refresh_token+ if (+ isinstance(new_refresh_token, str)+ and new_refresh_token+ and new_refresh_token != credential_secrets.refresh_token+ ):+ try:+ if credential_secrets.encrypted_refresh_token is None:+ raise ValueError("Google OAuth credential is missing its encrypted refresh token")+ encrypted_refresh_token = await encryptor.encrypt(new_refresh_token, EncryptMethod.AES)+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ updated = await app.DATABASE.google_oauth.update_active_refresh_token(+ organization_id=organization_id,+ credential_id=credential_id,+ encrypted_refresh_token=encrypted_refresh_token,+ encrypted_method=EncryptMethod.AES,+ now=now,+ expected_encrypted_refresh_token=credential_secrets.encrypted_refresh_token,+ )+ if not updated:+ raise ValueError("Google OAuth credential changed during refresh-token rotation")+ credential_version = now+ except Exception as exc:+ LOG.exception(+ "Failed to persist rotated Google refresh token",+ organization_id=organization_id,+ credential_id=credential_id,+ )+ raise RotatedRefreshTokenPersistenceError(+ "Failed to persist rotated Google refresh token; reconnect the Google account"+ ) from exc+ return GoogleRefreshResult(access_token=access_token, credential_version=credential_version)++async def get_credentials_for_org(organization_id: str) -> list[GoogleOAuthCredentialBase]:"""List all active Google OAuth credentials for an organization (metadata only)."""return await app.DATABASE.google_oauth.list_active_for_org(organization_id=organization_id)@@ -832,6 +890,23 @@ async def get_visible_credentials_for_org(organization_id: str) -> list[GoogleOAreturn await app.DATABASE.google_oauth.list_visible_for_org(organization_id=organization_id)+async def update_email_address(+ *,+ organization_id: str,+ credential_id: str,+ email_address: str,+ only_if_null: bool,+ expected_version: datetime.datetime | None = None,+) -> bool:+ return await app.DATABASE.google_oauth.update_email_address(+ organization_id=organization_id,+ credential_id=credential_id,+ email_address=email_address,+ only_if_null=only_if_null,+ expected_version=expected_version,+ )++# google-auth 2.x has no first-class async revoke helper; keep the 10-line httpx POST.async def _revoke_refresh_token_at_google(refresh_token: str) -> None:"""Best-effort call to Google's revoke endpoint."""diff --git a/skyvern/forge/sdk/services/microsoft_oauth_service.py b/skyvern/forge/sdk/services/microsoft_oauth_service.pyindex 50399dba0..c14ae067c 100644--- a/skyvern/forge/sdk/services/microsoft_oauth_service.py+++ b/skyvern/forge/sdk/services/microsoft_oauth_service.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport base64import datetimeimport hashlib+import jsonimport secretsfrom dataclasses import dataclass, fieldfrom urllib.parse import urlencode, urlparse@@ -24,6 +25,7 @@ from skyvern.forge.sdk.db.repositories.microsoft_oauth import ( # noqa: F401from skyvern.forge.sdk.encrypt import encryptorfrom skyvern.forge.sdk.encrypt.base import EncryptMethodfrom skyvern.forge.sdk.schemas.microsoft_oauth import MicrosoftOAuthCredentialBase+from skyvern.utils.email_validation import SAFE_EMAIL_ADDRESS_PATTERNLOG = structlog.get_logger()@@ -37,6 +39,7 @@ MICROSOFT_OAUTH_SCOPE_PROFILES: dict[str, tuple[str, ...]] = {}CONSENT_TTL_SECONDS = 600+_SAFE_EMAIL_ADDRESS = SAFE_EMAIL_ADDRESS_PATTERNdef microsoft_access_token_cache_key(organization_id: str, credential_id: str) -> str:@@ -133,6 +136,30 @@ def has_required_scopes(return all(_scope_segment(scope) in granted for scope in required_scopes)+def email_from_id_token(id_token: str) -> str | None:+ if not isinstance(id_token, str):+ return None+ segments = id_token.split(".")+ if len(segments) != 3:+ return None+ try:+ payload_segment = segments[1]+ payload_bytes = base64.urlsafe_b64decode(f"{payload_segment}{'=' * (-len(payload_segment) % 4)}")+ # Signature verification is omitted because this token comes directly from Microsoft's token endpoint over TLS.+ payload = json.loads(payload_bytes.decode("utf-8"))+ except (IndexError, UnicodeDecodeError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None+ for claim in ("email", "preferred_username"):+ value = payload.get(claim)+ if isinstance(value, str):+ candidate = value.strip()+ if _SAFE_EMAIL_ADDRESS.fullmatch(candidate):+ return candidate+ return None++_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})@@ -438,6 +465,21 @@ async def get_credentials_for_org(organization_id: str) -> list[MicrosoftOAuthCrreturn await app.DATABASE.microsoft_oauth.list_active_for_org(organization_id=organization_id)+async def update_email_address(+ *,+ organization_id: str,+ credential_id: str,+ email_address: str,+ only_if_null: bool,+) -> bool:+ return await app.DATABASE.microsoft_oauth.update_email_address(+ organization_id=organization_id,+ credential_id=credential_id,+ email_address=email_address,+ only_if_null=only_if_null,+ )++async def rename_credential(organization_id: str,credential_id: str,diff --git a/skyvern/services/email/outlook.py b/skyvern/services/email/outlook.pyindex d814c2bed..9c37b392c 100644--- a/skyvern/services/email/outlook.py+++ b/skyvern/services/email/outlook.py@@ -11,6 +11,7 @@ import httpximport structlogfrom skyvern.services.email.types import EmailAttachment, EmailMessage+from skyvern.utils.email_validation import SAFE_EMAIL_ADDRESS_PATTERNGRAPH_API_BASE = "https://graph.microsoft.com/v1.0"LOG = structlog.get_logger()@@ -34,7 +35,7 @@ _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.-]+$")+_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])",re.IGNORECASE,@@ -134,6 +135,33 @@ async def _get_json(raise OutlookAPIError(status=response.status_code, code=code, message=message)+async def fetch_primary_account_email(+ *,+ access_token: str,+ client: httpx.AsyncClient | None = None,+) -> str | None:+ async def _fetch(client_: httpx.AsyncClient) -> str | None:+ payload = await _get_json(+ client_,+ f"{GRAPH_API_BASE}/me",+ access_token=access_token,+ params={"$select": "mail"},+ )+ if not isinstance(payload, dict):+ return None+ value = payload.get("mail")+ if isinstance(value, str):+ candidate = value.strip()+ if _SAFE_EMAIL_IDENTIFIER.fullmatch(candidate):+ return candidate+ return None++ if client is not None:+ return await _fetch(client)+ async with httpx.AsyncClient(timeout=20.0) as owned_client:+ return await _fetch(owned_client)++def _clamp_max_results(max_results: int) -> int:return max(1, min(max_results, 100))diff --git a/skyvern/utils/email_validation.py b/skyvern/utils/email_validation.pynew file mode 100644index 000000000..1536f3d04--- /dev/null+++ b/skyvern/utils/email_validation.py@@ -0,0 +1,14 @@+import re++SAFE_EMAIL_ADDRESS_PATTERN = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+$")+++def normalize_email_address(value: str) -> str:+ return value.strip().casefold()+++def normalize_identifier_if_email(value: str) -> str:+ stripped_identifier = value.strip()+ if SAFE_EMAIL_ADDRESS_PATTERN.fullmatch(stripped_identifier):+ return normalize_email_address(value)+ return valuediff --git a/tests/unit/forge/sdk/db/test_otp_repository.py b/tests/unit/forge/sdk/db/test_otp_repository.pynew file mode 100644index 000000000..2c120768c--- /dev/null+++ b/tests/unit/forge/sdk/db/test_otp_repository.py@@ -0,0 +1,176 @@+from collections.abc import Sequence+from types import SimpleNamespace+from typing import Literal+from unittest.mock import AsyncMock++import pytest++from skyvern.forge import agent_functions+from skyvern.forge.agent_functions import AgentFunction+from skyvern.forge.sdk.db.agent_db import AgentDB+from skyvern.forge.sdk.db.models import TOTPCodeModel+from skyvern.forge.sdk.schemas.totp_codes import OTPType, RawTOTPCode, TOTPCode+from skyvern.services import otp_service+from skyvern.services.otp_email import EmailOTPCandidate++ReaderName = Literal["get_otp_codes", "get_recent_otp_codes", "get_raw_otp_codes"]+++async def _read_codes(+ agent_db: AgentDB,+ reader_name: ReaderName,+ totp_identifier: str,+) -> Sequence[TOTPCode | RawTOTPCode]:+ if reader_name == "get_otp_codes":+ return await agent_db.otp.get_otp_codes(+ organization_id="o_test",+ totp_identifier=totp_identifier,+ )+ if reader_name == "get_recent_otp_codes":+ return await agent_db.otp.get_recent_otp_codes(+ organization_id="o_test",+ totp_identifier=totp_identifier,+ )+ return await agent_db.otp.get_raw_otp_codes(+ organization_id="o_test",+ totp_identifier=totp_identifier,+ )++[email protected]("reader_name", ["get_otp_codes", "get_recent_otp_codes", "get_raw_otp_codes"])+ ("stored_identifier", "lookup_identifier"),+ [+ pytest.param(+ "[email protected]",+ "[email protected]",+ id="legacy-mixed-case-row",+ ),+ pytest.param(+ "[email protected]",+ "[email protected]",+ id="tenant-cased-lookup",+ ),+ ],+)+async def test_otp_repository_readers_match_email_identifiers_case_insensitively(+ agent_db: AgentDB,+ reader_name: ReaderName,+ stored_identifier: str,+ lookup_identifier: str,+) -> None:+ parse_status = "raw" if reader_name == "get_raw_otp_codes" else "parsed"+ async with agent_db.Session() as session:+ session.add(+ TOTPCodeModel(+ totp_code_id="otp_legacy_case",+ organization_id="o_test",+ totp_identifier=stored_identifier,+ content="123456",+ code=None if parse_status == "raw" else "123456",+ otp_type=None if parse_status == "raw" else "totp",+ parse_status=parse_status,+ )+ )+ await session.commit()++ results = await _read_codes(agent_db, reader_name, lookup_identifier)++ assert [result.totp_code_id for result in results] == ["otp_legacy_case"]++[email protected]("reader_name", ["get_otp_codes", "get_recent_otp_codes", "get_raw_otp_codes"])+async def test_email_poller_persisted_identifier_is_reachable_by_all_readers(+ agent_db: AgentDB,+ reader_name: ReaderName,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ parse_status = "raw" if reader_name == "get_raw_otp_codes" else "parsed"++ async def create_otp_code(+ organization_id: str,+ totp_identifier: str,+ content: str,+ code: str,+ otp_type: OTPType,+ **_kwargs: object,+ ) -> None:+ async with agent_db.Session() as session:+ session.add(+ TOTPCodeModel(+ totp_code_id="otp_poller_identifier",+ organization_id=organization_id,+ totp_identifier=totp_identifier,+ content=content,+ code=None if parse_status == "raw" else code,+ otp_type=None if parse_status == "raw" else otp_type,+ parse_status=parse_status,+ )+ )+ await session.commit()++ source = SimpleNamespace(+ name="probe",+ list_credential_ids=AsyncMock(return_value=["credential"]),+ search_recent_otp_messages=AsyncMock(+ return_value=[EmailOTPCandidate(message_id="message", content="Your code is 123456")]+ ),+ )+ monkeypatch.setattr(agent_functions, "build_email_otp_sources", lambda _agent: [source])+ monkeypatch.setattr(otp_service, "parse_otp_login", AsyncMock(return_value=otp_service.OTPValue(value="123456")))+ monkeypatch.setattr(+ agent_functions.app,+ "DATABASE",+ SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code)),+ )++ result = await AgentFunction().get_otp_value_from_email(+ organization_id="o_test",+ totp_identifier=" [email protected] ",+ )++ assert result == otp_service.OTPValue(value="123456")+ results = await _read_codes(agent_db, reader_name, "[email protected]")+ assert [stored.totp_code_id for stored in results] == ["otp_poller_identifier"]+ assert [stored.totp_identifier for stored in results] == ["[email protected]"]++[email protected]("reader_name", ["get_otp_codes", "get_recent_otp_codes", "get_raw_otp_codes"])+async def test_otp_repository_readers_match_non_email_identifiers_exactly(+ agent_db: AgentDB,+ reader_name: ReaderName,+) -> None:+ parse_status = "raw" if reader_name == "get_raw_otp_codes" else "parsed"+ async with agent_db.Session() as session:+ session.add_all(+ [+ TOTPCodeModel(+ totp_code_id="otp_username_upper",+ organization_id="o_test",+ totp_identifier="UserA",+ content="123456",+ code=None if parse_status == "raw" else "123456",+ otp_type=None if parse_status == "raw" else "totp",+ parse_status=parse_status,+ ),+ TOTPCodeModel(+ totp_code_id="otp_username_lower",+ organization_id="o_test",+ totp_identifier="usera",+ content="654321",+ code=None if parse_status == "raw" else "654321",+ otp_type=None if parse_status == "raw" else "totp",+ parse_status=parse_status,+ ),+ ]+ )+ await session.commit()++ upper_results = await _read_codes(agent_db, reader_name, "UserA")+ lower_results = await _read_codes(agent_db, reader_name, "usera")++ assert [result.totp_code_id for result in upper_results] == ["otp_username_upper"]+ assert [result.totp_code_id for result in lower_results] == ["otp_username_lower"]diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.pyindex 923f74371..b8d3e740e 100644--- a/tests/unit/google/test_google_oauth.py+++ b/tests/unit/google/test_google_oauth.py@@ -2743,6 +2743,7 @@ async def test_load_credential_secrets_decrypts_repo_payload(monkeypatch: pytestassert secrets.scopes == ["https://a", "https://b"]assert secrets.client_id == "client-1"assert secrets.credential_version == credential_version+ assert secrets.encrypted_refresh_token == "ENC::rt"decrypt_mock.assert_awaited_once_with("ENC::rt", EncryptMethod.AES)@@ -2948,6 +2949,128 @@ async def test_access_token_from_secrets_missing_access_token_raises(monkeypatchawait google_oauth_service.access_token_from_secrets(secrets)+async def test_refresh_and_rotate_persists_google_refresh_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ credential_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ secrets = google_oauth_service.GoogleCredentialSecrets(+ refresh_token="rt-original",+ scopes=["https://a"],+ credential_version=credential_version,+ encrypted_refresh_token="encrypted-rt-original",+ )+ monkeypatch.setattr(+ google_oauth_service,+ "credentials_from_secrets",+ AsyncMock(return_value=SimpleNamespace(token="at-refreshed", refresh_token="rt-rotated")),+ )+ update_active_refresh_token = AsyncMock(return_value=True)+ monkeypatch.setattr(+ google_oauth_service.app,+ "DATABASE",+ SimpleNamespace(+ google_oauth=SimpleNamespace(update_active_refresh_token=update_active_refresh_token),+ ),+ raising=False,+ )+ encrypt = AsyncMock(return_value="encrypted-rt-rotated")+ monkeypatch.setattr(google_oauth_service, "encryptor", SimpleNamespace(encrypt=encrypt))++ result = await google_oauth_service.refresh_and_rotate(+ organization_id="org_1",+ credential_id="goac_1",+ credential_secrets=secrets,+ )++ assert result.access_token == "at-refreshed"+ encrypt.assert_awaited_once_with("rt-rotated", EncryptMethod.AES)+ assert update_active_refresh_token.await_args is not None+ assert update_active_refresh_token.await_args.kwargs["expected_encrypted_refresh_token"] == "encrypted-rt-original"+ assert result.credential_version == update_active_refresh_token.await_args.kwargs["now"]+++async def test_refresh_and_rotate_preserves_version_without_refresh_token_rotation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ credential_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ secrets = google_oauth_service.GoogleCredentialSecrets(+ refresh_token="rt-original",+ scopes=["https://a"],+ credential_version=credential_version,+ encrypted_refresh_token="encrypted-rt-original",+ )+ monkeypatch.setattr(+ google_oauth_service,+ "credentials_from_secrets",+ AsyncMock(return_value=SimpleNamespace(token="at-refreshed", refresh_token="rt-original")),+ )+ update_active_refresh_token = AsyncMock(return_value=True)+ monkeypatch.setattr(+ google_oauth_service.app,+ "DATABASE",+ SimpleNamespace(+ google_oauth=SimpleNamespace(update_active_refresh_token=update_active_refresh_token),+ ),+ raising=False,+ )++ result = await google_oauth_service.refresh_and_rotate(+ organization_id="org_1",+ credential_id="goac_1",+ credential_secrets=secrets,+ )++ assert result == google_oauth_service.GoogleRefreshResult(+ access_token="at-refreshed",+ credential_version=credential_version,+ )+ update_active_refresh_token.assert_not_awaited()+++async def test_refresh_and_rotate_rejects_failed_google_token_persistence(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secrets = google_oauth_service.GoogleCredentialSecrets(+ refresh_token="rt-original",+ credential_version=datetime.datetime(2026, 7, 30, 12, 0, 0),+ encrypted_refresh_token="encrypted-rt-original",+ )+ monkeypatch.setattr(+ google_oauth_service,+ "credentials_from_secrets",+ AsyncMock(return_value=SimpleNamespace(token="at-refreshed", refresh_token="rt-rotated")),+ )+ update_active_refresh_token = AsyncMock(return_value=False)+ monkeypatch.setattr(+ google_oauth_service.app,+ "DATABASE",+ SimpleNamespace(+ google_oauth=SimpleNamespace(update_active_refresh_token=update_active_refresh_token),+ ),+ raising=False,+ )+ monkeypatch.setattr(+ google_oauth_service,+ "encryptor",+ SimpleNamespace(encrypt=AsyncMock(return_value="encrypted-rt-rotated")),+ )++ with pytest.raises(+ google_oauth_service.RotatedRefreshTokenPersistenceError,+ match="reconnect the Google account",+ ):+ await google_oauth_service.refresh_and_rotate(+ organization_id="org_1",+ credential_id="goac_1",+ credential_secrets=secrets,+ )++ update_active_refresh_token.assert_awaited_once()++def test_validate_redirect_uri_allowlist(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(google_oauth_service.settings,@@ -3367,6 +3490,324 @@ async def test_google_oauth_callback_allows_matching_or_legacy_client()+async def test_google_oauth_callback_email_capture_is_authoritative(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from skyvern.forge.sdk.db.repositories.google_oauth import PendingConsentContext++ monkeypatch.setattr(+ google_oauth_service.SettingsManager,+ "get_settings",+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),+ )+ gmail_scope = google_oauth_service.GOOGLE_GMAIL_SCOPES[0]+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = GoogleOAuthCredentialBase(+ id="goac_1",+ organization_id="org_1",+ credential_name="Default",+ provider="google",+ state="active",+ scopes_requested=[gmail_scope],+ scopes_granted=[gmail_scope],+ email_address="[email protected]",+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "load_pending_consent_context",+ AsyncMock(+ return_value=PendingConsentContext(+ credential_id=credential.id,+ consent_redirect_uri="https://x/cb",+ consent_code_verifier="verifier",+ )+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "resolve_client_config",+ AsyncMock(+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(+ config=None,+ source="missing",+ )+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "exchange_code_for_tokens",+ AsyncMock(+ return_value={+ "refresh_token": "refresh-token",+ "access_token": "access-token",+ "scope": gmail_scope,+ }+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "promote_pending_credential",+ AsyncMock(return_value=credential),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_gmail_service,+ "fetch_profile_email",+ AsyncMock(return_value="[email protected]"),+ )+ update_email_address = AsyncMock(return_value=True)+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "update_email_address",+ update_email_address,+ )++ response = await google_oauth_routes.google_oauth_callback(+ CreateGoogleOAuthCallbackRequest(code="code", state="nonce"),+ current_org=SimpleNamespace(organization_id="org_1"),+ )++ assert response.credential.email_address == "[email protected]"+ update_email_address.assert_awaited_once_with(+ organization_id="org_1",+ credential_id="goac_1",+ email_address="[email protected]",+ only_if_null=False,+ expected_version=now,+ )+++async def test_google_email_backfill_uses_post_rotation_version_and_normalizes_address(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pre_rotation_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ post_rotation_version = datetime.datetime(2026, 7, 30, 12, 1, 0)+ credential = GoogleOAuthCredentialBase(+ id="goac_rotated",+ organization_id="org_1",+ credential_name="Default",+ provider="google",+ state="active",+ scopes_requested=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ created_at=pre_rotation_version,+ modified_at=pre_rotation_version,+ )+ monkeypatch.setattr(google_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "load_credential_secrets",+ AsyncMock(return_value="secrets"),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "refresh_and_rotate",+ AsyncMock(+ return_value=google_oauth_service.GoogleRefreshResult(+ access_token="access-token",+ credential_version=post_rotation_version,+ )+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_gmail_service,+ "fetch_profile_email",+ AsyncMock(return_value="[email protected]"),+ )+ update_email_address = AsyncMock(return_value=True)+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "update_email_address",+ update_email_address,+ )++ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ update_email_address.assert_awaited_once_with(+ organization_id="org_1",+ credential_id="goac_rotated",+ email_address="[email protected]",+ only_if_null=True,+ expected_version=post_rotation_version,+ )+ assert credential.email_address == "[email protected]"+++async def test_google_email_backfill_randomizes_candidates_and_uses_null_and_version_guards(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credentials = [+ GoogleOAuthCredentialBase(+ id=f"goac_{index}",+ organization_id="org_1",+ credential_name="Default",+ provider="google",+ state="active",+ scopes_requested=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ created_at=now,+ modified_at=now + datetime.timedelta(seconds=index),+ )+ for index in range(5)+ ]+ selected = [credentials[4], credentials[2], credentials[0]]+ sample = MagicMock(return_value=selected)+ monkeypatch.setattr(google_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ monkeypatch.setattr(google_oauth_routes.random, "sample", sample)+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "load_credential_secrets",+ AsyncMock(side_effect=lambda **kwargs: kwargs["credential_id"]),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "refresh_and_rotate",+ AsyncMock(+ side_effect=lambda *, organization_id, credential_id, credential_secrets: (+ google_oauth_service.GoogleRefreshResult(+ access_token=f"token-{credential_secrets}",+ credential_version=next(item.modified_at for item in selected if item.id == credential_id),+ )+ )+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_gmail_service,+ "fetch_profile_email",+ AsyncMock(side_effect=lambda access_token: f"{access_token}@example.test"),+ )+ update_email_address = AsyncMock(side_effect=[True, False, True])+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "update_email_address",+ update_email_address,+ )++ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=credentials,+ )++ sample.assert_called_once_with(credentials, k=3)+ assert [awaited.kwargs["credential_id"] for awaited in update_email_address.await_args_list] == [+ credential.id for credential in selected+ ]+ assert all(awaited.kwargs["only_if_null"] is True for awaited in update_email_address.await_args_list)+ assert [awaited.kwargs["expected_version"] for awaited in update_email_address.await_args_list] == [+ credential.modified_at for credential in selected+ ]+ assert selected[0].email_address == "[email protected]"+ assert selected[1].email_address is None+ assert selected[2].email_address == "[email protected]"+ assert google_oauth_routes._EMAIL_BACKFILL_FAILURES == {}+++async def test_google_email_backfill_does_not_retry_failed_resolution_within_ttl(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = GoogleOAuthCredentialBase(+ id="goac_failed",+ organization_id="org_1",+ credential_name="Default",+ provider="google",+ state="active",+ scopes_requested=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(google_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ monotonic_time = [100.0]+ monkeypatch.setattr(google_oauth_routes.time, "monotonic", lambda: monotonic_time[0])+ load_secrets = AsyncMock(return_value="secrets")+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "load_credential_secrets",+ load_secrets,+ )+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "refresh_and_rotate",+ AsyncMock(+ return_value=google_oauth_service.GoogleRefreshResult(+ access_token="access-token",+ credential_version=now,+ )+ ),+ )+ monkeypatch.setattr(+ google_oauth_routes.google_gmail_service,+ "fetch_profile_email",+ AsyncMock(return_value=None),+ )++ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )+ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ load_secrets.assert_awaited_once()++ monotonic_time[0] = 3701.0+ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ assert load_secrets.await_count == 2+++async def test_google_email_backfill_caches_cancelled_resolution(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = GoogleOAuthCredentialBase(+ id="goac_slow",+ organization_id="org_1",+ credential_name="Default",+ provider="google",+ state="active",+ scopes_requested=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(google_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ load_secrets = AsyncMock(side_effect=asyncio.CancelledError)+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "load_credential_secrets",+ load_secrets,+ )++ with pytest.raises(asyncio.CancelledError):+ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )+ await google_oauth_routes._backfill_google_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ load_secrets.assert_awaited_once()++@pytest.mark.asyncioasync def test_rename_credential_delegates_to_repo(monkeypatch: pytest.MonkeyPatch) -> None:renamed = SimpleNamespace(id="goac_1", credential_name="Personal Gmail")diff --git a/tests/unit/google/test_google_oauth_repository.py b/tests/unit/google/test_google_oauth_repository.pyindex 77a94ea26..3bf001e7b 100644--- a/tests/unit/google/test_google_oauth_repository.py+++ b/tests/unit/google/test_google_oauth_repository.py@@ -773,3 +773,277 @@ async def test_mark_active_mismatched_client_as_error_with_no_new_client_flips_a"gcred_bound_2": STATE_ERROR,"gcred_unbound": STATE_ACTIVE,}+++async def test_update_email_address_only_if_null_does_not_overwrite_existing_address(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ modified_at = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ GoogleOAuthCredentialModel.__table__.insert().values(+ id="gcred_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address="[email protected]",+ created_at=modified_at,+ modified_at=modified_at,+ )+ )++ updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="gcred_email",+ email_address="[email protected]",+ only_if_null=True,+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.email_address,+ GoogleOAuthCredentialModel.modified_at,+ ).where(GoogleOAuthCredentialModel.id == "gcred_email")+ )+ ).one()++ assert stored.email_address == "[email protected]"+ assert stored.modified_at == modified_at+ assert updated is False+++async def test_update_email_address_authoritative_write_preserves_cas_version(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ modified_at = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ GoogleOAuthCredentialModel.__table__.insert().values(+ id="gcred_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address="[email protected]",+ created_at=modified_at,+ modified_at=modified_at,+ )+ )++ updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="gcred_email",+ email_address="[email protected]",+ only_if_null=False,+ expected_version=modified_at,+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.email_address,+ GoogleOAuthCredentialModel.modified_at,+ ).where(GoogleOAuthCredentialModel.id == "gcred_email")+ )+ ).one()++ assert stored.email_address == "[email protected]"+ assert stored.modified_at == modified_at+ assert updated is True+++async def test_update_email_address_backfill_stale_version_is_noop(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ current_version = datetime.datetime(2026, 7, 30, 12, 5, 0)+ stale_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ GoogleOAuthCredentialModel.__table__.insert().values(+ id="gcred_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address=None,+ created_at=stale_version,+ modified_at=current_version,+ )+ )++ updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="gcred_email",+ email_address="[email protected]",+ only_if_null=True,+ expected_version=stale_version,+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.email_address,+ GoogleOAuthCredentialModel.modified_at,+ ).where(GoogleOAuthCredentialModel.id == "gcred_email")+ )+ ).one()++ assert stored.email_address is None+ assert stored.modified_at == current_version+ assert updated is False+++async def test_mark_revoked_and_scrub_clears_email_address(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ await _seed_active_credential(repo, "gcred_revoke_email", "nonce-revoke-email")+ await repo.update_email_address(+ organization_id="o_test",+ credential_id="gcred_revoke_email",+ email_address="[email protected]",+ only_if_null=False,+ )++ await repo.mark_revoked_and_scrub(+ organization_id="o_test",+ credential_id="gcred_revoke_email",+ now=datetime.datetime.utcnow(),+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.state,+ GoogleOAuthCredentialModel.email_address,+ ).where(GoogleOAuthCredentialModel.id == "gcred_revoke_email")+ )+ ).one()++ assert stored.state == STATE_REVOKED+ assert stored.email_address is None+++async def test_update_active_refresh_token_uses_token_identity_guard_across_rename(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ credential_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ rotated_at = datetime.datetime(2026, 7, 30, 12, 5, 0)+ async with engine.begin() as conn:+ await conn.execute(+ GoogleOAuthCredentialModel.__table__.insert().values(+ id="gcred_rotation",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ encrypted_refresh_token="encrypted-old",+ encrypted_method=EncryptMethod.AES.value,+ created_at=credential_version,+ modified_at=credential_version,+ )+ )++ renamed = await repo.rename_active(+ organization_id="o_test",+ credential_id="gcred_rotation",+ credential_name="Renamed",+ now=datetime.datetime(2026, 7, 30, 12, 2, 0),+ )+ updated = await repo.update_active_refresh_token(+ organization_id="o_test",+ credential_id="gcred_rotation",+ encrypted_refresh_token="encrypted-rotated",+ encrypted_method=EncryptMethod.AES,+ now=rotated_at,+ expected_encrypted_refresh_token="encrypted-old",+ )+ stale_update = await repo.update_active_refresh_token(+ organization_id="o_test",+ credential_id="gcred_rotation",+ encrypted_refresh_token="encrypted-stale",+ encrypted_method=EncryptMethod.AES,+ now=datetime.datetime(2026, 7, 30, 12, 10, 0),+ expected_encrypted_refresh_token="encrypted-old",+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.encrypted_refresh_token,+ GoogleOAuthCredentialModel.modified_at,+ ).where(GoogleOAuthCredentialModel.id == "gcred_rotation")+ )+ ).one()++ assert renamed is not None+ assert renamed.credential_name == "Renamed"+ assert updated is True+ assert stale_update is False+ assert stored.encrypted_refresh_token == "encrypted-rotated"+ assert stored.modified_at == rotated_at+++async def test_post_rotation_version_allows_email_backfill(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ credential_version = datetime.datetime(2026, 7, 30, 12, 0, 0)+ rotated_at = datetime.datetime(2026, 7, 30, 12, 5, 0)+ async with engine.begin() as conn:+ await conn.execute(+ GoogleOAuthCredentialModel.__table__.insert().values(+ id="gcred_rotation_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ encrypted_refresh_token="encrypted-old",+ encrypted_method=EncryptMethod.AES.value,+ created_at=credential_version,+ modified_at=credential_version,+ )+ )++ rotated = await repo.update_active_refresh_token(+ organization_id="o_test",+ credential_id="gcred_rotation_email",+ encrypted_refresh_token="encrypted-rotated",+ encrypted_method=EncryptMethod.AES,+ now=rotated_at,+ expected_encrypted_refresh_token="encrypted-old",+ )+ email_updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="gcred_rotation_email",+ email_address="[email protected]",+ only_if_null=True,+ expected_version=rotated_at,+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ GoogleOAuthCredentialModel.email_address,+ GoogleOAuthCredentialModel.modified_at,+ ).where(GoogleOAuthCredentialModel.id == "gcred_rotation_email")+ )+ ).one()++ assert rotated is True+ assert email_updated is True+ assert stored.email_address == "[email protected]"+ assert stored.modified_at == rotated_atdiff --git a/tests/unit/test_credentials_totp_route_logging.py b/tests/unit/test_credentials_totp_route_logging.pyindex f9dc20eda..0272af041 100644--- a/tests/unit/test_credentials_totp_route_logging.py+++ b/tests/unit/test_credentials_totp_route_logging.py@@ -45,10 +45,10 @@ def _assert_raw_values_not_logged(logs: list[dict[str, object]], *raw_values: st@pytest.mark.asyncio-async def test_send_totp_code_save_log_redacts_identifier_but_stores_raw_values(+async def test_send_totp_code_save_log_redacts_identifier_and_normalizes_email_for_storage(monkeypatch: pytest.MonkeyPatch,) -> None:- raw_identifier = "[email protected]"+ raw_identifier = " [email protected] "raw_content = "135790"create_otp_code = AsyncMock(return_value=SimpleNamespace(totp_code_id="otp_1"))monkeypatch.setattr(credentials.app, "DATABASE", _database_with_otp_create(create_otp_code))@@ -66,12 +66,30 @@ async def test_send_totp_code_save_log_redacts_identifier_but_stores_raw_values(_assert_raw_values_not_logged(logs, raw_identifier, raw_content)create_otp_code.assert_awaited_once()+ assert create_otp_code.await_args is not Nonestorage_kwargs = create_otp_code.await_args.kwargs- assert storage_kwargs["totp_identifier"] == raw_identifier+ assert storage_kwargs["totp_identifier"] == "[email protected]"assert storage_kwargs["content"] == raw_contentassert storage_kwargs["code"] == raw_content+async def test_send_totp_code_preserves_phone_identifier_for_storage(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ phone_identifier = "+1 (555) 555-0123"+ create_otp_code = AsyncMock(return_value=SimpleNamespace(totp_code_id="otp_1"))+ monkeypatch.setattr(credentials.app, "DATABASE", _database_with_otp_create(create_otp_code))++ await credentials.send_totp_code(+ TOTPCodeCreate(totp_identifier=phone_identifier, content="135790"),+ curr_org=SimpleNamespace(organization_id="o_test"),+ )++ assert create_otp_code.await_args is not None+ assert create_otp_code.await_args.kwargs["totp_identifier"] == phone_identifier++@pytest.mark.asyncioasync def test_send_totp_code_auto_detects_long_content_despite_submitted_type(monkeypatch: pytest.MonkeyPatch,@@ -102,6 +120,7 @@ async def test_send_totp_code_auto_detects_long_content_despite_submitted_type()assert result.totp_code_id == "otp_1"+ assert create_otp_code.await_args is not Nonestorage_kwargs = create_otp_code.await_args.kwargsassert storage_kwargs["code"] == magic_linkassert storage_kwargs["otp_type"] == OTPType.MAGIC_LINK@@ -124,6 +143,7 @@ async def test_send_totp_code_infers_short_content_type_despite_submitted_type()assert result.totp_code_id == "otp_1"+ assert create_otp_code.await_args is not Nonestorage_kwargs = create_otp_code.await_args.kwargsassert storage_kwargs["code"] == "135790"assert storage_kwargs["otp_type"] == OTPType.TOTPdiff --git a/tests/unit/test_microsoft_oauth_repository.py b/tests/unit/test_microsoft_oauth_repository.pynew file mode 100644index 000000000..e23f70e57--- /dev/null+++ b/tests/unit/test_microsoft_oauth_repository.py@@ -0,0 +1,145 @@+import datetime+from typing import AsyncGenerator++import pytest+import pytest_asyncio+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine++from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB+from skyvern.forge.sdk.db.models import Base, MicrosoftOAuthCredentialModel # noqa: F401 - registers model on Base+from skyvern.forge.sdk.db.repositories.microsoft_oauth import STATE_ACTIVE, STATE_REVOKED, MicrosoftOAuthRepository+++@pytest_asyncio.fixture+async def engine() -> AsyncGenerator[AsyncEngine, None]:+ eng = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with eng.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)+ yield eng+ await eng.dispose()+++@pytest_asyncio.fixture+async def repo(engine: AsyncEngine) -> MicrosoftOAuthRepository:+ db = BaseAlchemyDB(engine)+ return MicrosoftOAuthRepository(db.Session, debug_enabled=False)+++async def test_update_email_address_only_if_null_does_not_overwrite_existing_address(+ repo: MicrosoftOAuthRepository,+ engine: AsyncEngine,+) -> None:+ modified_at = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ MicrosoftOAuthCredentialModel.__table__.insert().values(+ id="msoac_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address="[email protected]",+ created_at=modified_at,+ modified_at=modified_at,+ )+ )++ updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="msoac_email",+ email_address="[email protected]",+ only_if_null=True,+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ MicrosoftOAuthCredentialModel.email_address,+ MicrosoftOAuthCredentialModel.modified_at,+ ).where(MicrosoftOAuthCredentialModel.id == "msoac_email")+ )+ ).one()++ assert stored.email_address == "[email protected]"+ assert stored.modified_at == modified_at+ assert updated is False+++async def test_update_email_address_authoritative_write_updates_address(+ repo: MicrosoftOAuthRepository,+ engine: AsyncEngine,+) -> None:+ modified_at = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ MicrosoftOAuthCredentialModel.__table__.insert().values(+ id="msoac_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address="[email protected]",+ created_at=modified_at,+ modified_at=modified_at,+ )+ )++ updated = await repo.update_email_address(+ organization_id="o_test",+ credential_id="msoac_email",+ email_address="[email protected]",+ only_if_null=False,+ )++ async with engine.connect() as conn:+ stored_address = (+ await conn.execute(+ select(MicrosoftOAuthCredentialModel.email_address).where(+ MicrosoftOAuthCredentialModel.id == "msoac_email"+ )+ )+ ).scalar_one()++ assert stored_address == "[email protected]"+ assert updated is True+++async def test_mark_revoked_and_scrub_clears_email_address(+ repo: MicrosoftOAuthRepository,+ engine: AsyncEngine,+) -> None:+ now = datetime.datetime(2026, 7, 30, 12, 0, 0)+ async with engine.begin() as conn:+ await conn.execute(+ MicrosoftOAuthCredentialModel.__table__.insert().values(+ id="msoac_revoke_email",+ organization_id="o_test",+ credential_name="Default",+ state=STATE_ACTIVE,+ email_address="[email protected]",+ created_at=now,+ modified_at=now,+ )+ )++ await repo.mark_revoked_and_scrub(+ organization_id="o_test",+ credential_id="msoac_revoke_email",+ now=now + datetime.timedelta(minutes=1),+ )++ async with engine.connect() as conn:+ stored = (+ await conn.execute(+ select(+ MicrosoftOAuthCredentialModel.state,+ MicrosoftOAuthCredentialModel.email_address,+ ).where(MicrosoftOAuthCredentialModel.id == "msoac_revoke_email")+ )+ ).one()++ assert stored.state == STATE_REVOKED+ assert stored.email_address is Nonediff --git a/tests/unit/test_microsoft_oauth_service.py b/tests/unit/test_microsoft_oauth_service.pyindex f1d656778..3b4a276f3 100644--- a/tests/unit/test_microsoft_oauth_service.py+++ b/tests/unit/test_microsoft_oauth_service.py@@ -1,7 +1,10 @@+import asyncio+import base64import datetime+import jsonfrom types import SimpleNamespacefrom typing import Any, Awaitable, Callable-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, MagicMockfrom urllib.parse import parse_qs, urlparseimport httpx@@ -10,7 +13,10 @@ from fastapi import HTTPExceptionfrom skyvern.forge.sdk.db.repositories.microsoft_oauth import PendingConsentContextfrom skyvern.forge.sdk.routes import microsoft_oauth as microsoft_oauth_routes-from skyvern.forge.sdk.schemas.microsoft_oauth import CreateMicrosoftOAuthCallbackRequest+from skyvern.forge.sdk.schemas.microsoft_oauth import (+ CreateMicrosoftOAuthCallbackRequest,+ MicrosoftOAuthCredentialBase,+)from skyvern.forge.sdk.services import microsoft_oauth_service@@ -28,6 +34,11 @@ def _install_microsoft_transport(monkeypatch.setattr(microsoft_oauth_service.httpx, "AsyncClient", fake_async_client)+def _unsigned_id_token(payload: dict[str, str]) -> str:+ encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")+ return f"header.{encoded}.signature"++def test_build_authorize_url_includes_required_params(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_ID", "cid", raising=False)monkeypatch.setattr(microsoft_oauth_service.settings, "MICROSOFT_OAUTH_CLIENT_SECRET", "secret", raising=False)@@ -92,6 +103,33 @@ def test_has_required_scopes_matches_trailing_segments() -> None:assert not microsoft_oauth_service.has_required_scopes(["Mail.Read"], ["Mail.Send"])+def test_email_from_id_token_prefers_email_claim() -> None:+ token = _unsigned_id_token(+ {+ "email": "[email protected]",+ "preferred_username": "[email protected]",+ }+ )++ assert microsoft_oauth_service.email_from_id_token(token) == "[email protected]"+++ ("preferred_username", "expected"),+ [+ ("[email protected]", "[email protected]"),+ ("tenant.onmicrosoft.com", None),+ ],+)+def test_email_from_id_token_requires_email_shaped_preferred_username(+ preferred_username: str,+ expected: str | None,+) -> None:+ token = _unsigned_id_token({"preferred_username": preferred_username})++ assert microsoft_oauth_service.email_from_id_token(token) == expected++def test_validate_redirect_uri_allowlist(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(microsoft_oauth_service.settings,@@ -276,6 +314,7 @@ async def test_refresh_and_rotate_persists_rotated_refresh_token(monkeypatch: pyassert access_token == "at-refreshed"encrypt.assert_awaited_once_with("rt-rotated", microsoft_oauth_service.EncryptMethod.AES)update_active_refresh_token.assert_awaited_once()+ assert update_active_refresh_token.await_args is not Nonekwargs = update_active_refresh_token.await_args.kwargsassert kwargs["organization_id"] == "org-1"assert kwargs["credential_id"] == "cred-1"@@ -403,3 +442,485 @@ async def test_callback_rejects_missing_mail_read_before_promoting(monkeypatch:"Microsoft did not grant Mail.Read. Please re-connect and accept all requested permissions.")promote.assert_not_awaited()+++ ("graph_email", "claim_email", "expected_email"),+ [+ (None, "[email protected]", "[email protected]"),+ ],+)+async def test_microsoft_oauth_callback_prefers_graph_mail_then_falls_back_to_claim(+ monkeypatch: pytest.MonkeyPatch,+ graph_email: str | None,+ claim_email: str,+ expected_email: str,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = MicrosoftOAuthCredentialBase(+ id="msoac_1",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ email_address="[email protected]",+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_pending_consent_context",+ AsyncMock(+ return_value=PendingConsentContext(+ credential_id=credential.id,+ consent_redirect_uri="https://app/cb",+ consent_code_verifier="verifier",+ scopes_requested=["Mail.Read", "offline_access"],+ )+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "exchange_code_for_tokens",+ AsyncMock(+ return_value={+ "refresh_token": "refresh-token",+ "access_token": "access-token",+ "scope": "Mail.Read offline_access",+ "id_token": "id-token",+ }+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "promote_pending_credential",+ AsyncMock(return_value=credential),+ )+ email_from_id_token = MagicMock(return_value=claim_email)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "email_from_id_token",+ email_from_id_token,+ )+ fetch_primary_account_email = AsyncMock(return_value=graph_email)+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "fetch_primary_account_email",+ fetch_primary_account_email,+ )+ update_email_address = AsyncMock(return_value=True)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "update_email_address",+ update_email_address,+ )++ response = await microsoft_oauth_routes.microsoft_oauth_callback(+ CreateMicrosoftOAuthCallbackRequest(code="code", state="state"),+ SimpleNamespace(organization_id="org_1"),+ )++ assert response.credential.email_address == expected_email+ fetch_primary_account_email.assert_awaited_once_with(access_token="access-token")+ if graph_email is None:+ email_from_id_token.assert_called_once_with("id-token")+ else:+ email_from_id_token.assert_not_called()+ update_email_address.assert_awaited_once_with(+ organization_id="org_1",+ credential_id="msoac_1",+ email_address=expected_email,+ only_if_null=False,+ )++[email protected]("status", [401, 408, 429, 503])+async def test_microsoft_oauth_callback_preserves_email_on_transient_graph_failure(+ monkeypatch: pytest.MonkeyPatch,+ status: int,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = MicrosoftOAuthCredentialBase(+ id="msoac_1",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ email_address="[email protected]",+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_pending_consent_context",+ AsyncMock(+ return_value=PendingConsentContext(+ credential_id=credential.id,+ consent_redirect_uri="https://app/cb",+ consent_code_verifier="verifier",+ scopes_requested=["Mail.Read", "offline_access"],+ )+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "exchange_code_for_tokens",+ AsyncMock(+ return_value={+ "refresh_token": "refresh-token",+ "access_token": "access-token",+ "scope": "Mail.Read offline_access",+ "id_token": "id-token",+ }+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "promote_pending_credential",+ AsyncMock(return_value=credential),+ )+ email_from_id_token = MagicMock(return_value="[email protected]")+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "email_from_id_token",+ email_from_id_token,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "fetch_primary_account_email",+ AsyncMock(+ side_effect=microsoft_oauth_routes.outlook.OutlookAPIError(+ status=status,+ code="upstream_unavailable",+ message="temporary failure",+ )+ ),+ )+ update_email_address = AsyncMock(return_value=True)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "update_email_address",+ update_email_address,+ )++ response = await microsoft_oauth_routes.microsoft_oauth_callback(+ CreateMicrosoftOAuthCallbackRequest(code="code", state="state"),+ SimpleNamespace(organization_id="org_1"),+ )++ assert response.credential.email_address == "[email protected]"+ email_from_id_token.assert_not_called()+ update_email_address.assert_not_awaited()+++async def test_microsoft_oauth_callback_falls_back_to_claim_on_non_transient_graph_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = MicrosoftOAuthCredentialBase(+ id="msoac_1",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ email_address=None,+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_pending_consent_context",+ AsyncMock(+ return_value=PendingConsentContext(+ credential_id=credential.id,+ consent_redirect_uri="https://app/cb",+ consent_code_verifier="verifier",+ scopes_requested=["Mail.Read", "offline_access"],+ )+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "exchange_code_for_tokens",+ AsyncMock(+ return_value={+ "refresh_token": "refresh-token",+ "access_token": "access-token",+ "scope": "Mail.Read offline_access",+ "id_token": "id-token",+ }+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "promote_pending_credential",+ AsyncMock(return_value=credential),+ )+ email_from_id_token = MagicMock(return_value="[email protected]")+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "email_from_id_token",+ email_from_id_token,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "fetch_primary_account_email",+ AsyncMock(+ side_effect=microsoft_oauth_routes.outlook.OutlookAPIError(+ status=403,+ code="mailbox_not_enabled",+ message="mailbox unavailable",+ )+ ),+ )+ update_email_address = AsyncMock(return_value=True)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "update_email_address",+ update_email_address,+ )++ response = await microsoft_oauth_routes.microsoft_oauth_callback(+ CreateMicrosoftOAuthCallbackRequest(code="code", state="state"),+ SimpleNamespace(organization_id="org_1"),+ )++ assert response.credential.email_address == "[email protected]"+ email_from_id_token.assert_called_once_with("id-token")+ update_email_address.assert_awaited_once_with(+ organization_id="org_1",+ credential_id="msoac_1",+ email_address="[email protected]",+ only_if_null=False,+ )+++async def test_fetch_primary_account_email_raises_transport_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ attempts = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal attempts+ attempts += 1+ raise httpx.ConnectError("connection failed", request=request)++ monkeypatch.setattr(microsoft_oauth_routes.outlook.asyncio, "sleep", AsyncMock())+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:+ with pytest.raises(microsoft_oauth_routes.outlook.OutlookAPIError) as exc_info:+ await microsoft_oauth_routes.outlook.fetch_primary_account_email(+ access_token="access-token",+ client=client,+ )++ assert exc_info.value.status == 503+ assert exc_info.value.code == "upstream_unavailable"+ assert attempts == 3++[email protected]("status", [400, 429, 503])+async def test_fetch_primary_account_email_raises_graph_errors(+ monkeypatch: pytest.MonkeyPatch,+ status: int,+) -> None:+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "_get_json",+ AsyncMock(+ side_effect=microsoft_oauth_routes.outlook.OutlookAPIError(+ status=status,+ code="temporary",+ message="temporary failure",+ )+ ),+ )++ with pytest.raises(microsoft_oauth_routes.outlook.OutlookAPIError):+ await microsoft_oauth_routes.outlook.fetch_primary_account_email(+ access_token="access-token",+ client=AsyncMock(),+ )+++async def test_fetch_primary_account_email_does_not_fall_back_to_upn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ get_json = AsyncMock(+ return_value={+ "mail": None,+ "userPrincipalName": "[email protected]",+ }+ )+ monkeypatch.setattr(microsoft_oauth_routes.outlook, "_get_json", get_json)++ result = await microsoft_oauth_routes.outlook.fetch_primary_account_email(+ access_token="access-token",+ client=AsyncMock(),+ )++ assert result is None+ assert get_json.await_args is not None+ assert get_json.await_args.kwargs["params"] == {"$select": "mail"}+++async def test_microsoft_email_backfill_randomizes_candidates_and_uses_null_guard(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credentials = [+ MicrosoftOAuthCredentialBase(+ id=f"msoac_{index}",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ created_at=now,+ modified_at=now,+ )+ for index in range(5)+ ]+ selected = [credentials[3], credentials[1], credentials[4]]+ sample = MagicMock(return_value=selected)+ monkeypatch.setattr(microsoft_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ monkeypatch.setattr(microsoft_oauth_routes.random, "sample", sample)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_credential_secrets",+ AsyncMock(side_effect=lambda **kwargs: kwargs["credential_id"]),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "refresh_and_rotate",+ AsyncMock(+ side_effect=lambda *, organization_id, credential_id, credential_secrets: f"token-{credential_secrets}"+ ),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "fetch_primary_account_email",+ AsyncMock(side_effect=lambda access_token: f"{access_token}@Example.Test"),+ )+ update_email_address = AsyncMock(side_effect=[True, False, True])+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "update_email_address",+ update_email_address,+ )++ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=credentials,+ )++ sample.assert_called_once_with(credentials, k=3)+ assert [awaited.kwargs["credential_id"] for awaited in update_email_address.await_args_list] == [+ credential.id for credential in selected+ ]+ assert all(awaited.kwargs["only_if_null"] is True for awaited in update_email_address.await_args_list)+ assert selected[0].email_address == "[email protected]"+ assert selected[1].email_address is None+ assert selected[2].email_address == "[email protected]"+ assert microsoft_oauth_routes._EMAIL_BACKFILL_FAILURES == {}+++async def test_microsoft_email_backfill_does_not_retry_failed_resolution_within_ttl(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = MicrosoftOAuthCredentialBase(+ id="msoac_failed",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(microsoft_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ monotonic_time = [100.0]+ monkeypatch.setattr(microsoft_oauth_routes.time, "monotonic", lambda: monotonic_time[0])+ load_secrets = AsyncMock(return_value="secrets")+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_credential_secrets",+ load_secrets,+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "refresh_and_rotate",+ AsyncMock(return_value="access-token"),+ )+ monkeypatch.setattr(+ microsoft_oauth_routes.outlook,+ "fetch_primary_account_email",+ AsyncMock(return_value=None),+ )++ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )+ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ load_secrets.assert_awaited_once()++ monotonic_time[0] = 3701.0+ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ assert load_secrets.await_count == 2+++async def test_microsoft_email_backfill_caches_cancelled_resolution(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ credential = MicrosoftOAuthCredentialBase(+ id="msoac_slow",+ organization_id="org_1",+ credential_name="Default",+ state="active",+ scopes_requested=["Mail.Read"],+ scopes_granted=["Mail.Read"],+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(microsoft_oauth_routes, "_EMAIL_BACKFILL_FAILURES", {})+ load_secrets = AsyncMock(side_effect=asyncio.CancelledError)+ monkeypatch.setattr(+ microsoft_oauth_routes.microsoft_oauth_service,+ "load_credential_secrets",+ load_secrets,+ )++ with pytest.raises(asyncio.CancelledError):+ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )+ await microsoft_oauth_routes._backfill_microsoft_email_addresses(+ organization_id="org_1",+ credentials=[credential],+ )++ load_secrets.assert_awaited_once()