Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: restore automations login redirects (#15295)

Rohit Malhotra6b670a73524d
diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.py
index 535381dcc5..33af8e9746 100644
--- a/enterprise/server/routes/auth.py
+++ b/enterprise/server/routes/auth.py
@@ -5,7 +5,7 @@ import warnings
from datetime import datetime, timedelta, timezone
from types import MappingProxyType
from typing import Annotated, Optional, cast
-from urllib.parse import parse_qs, quote, urlencode, urlparse
+from urllib.parse import parse_qs, parse_qsl, quote, urlencode, urlparse, urlunparse
from uuid import UUID as parse_uuid
from fastapi import (
@@ -633,6 +633,7 @@ async def keycloak_callback(
redirect_url = f'{redirect_url}&invitation_success=true'
else:
redirect_url = f'{redirect_url}?invitation_success=true'
+ redirect_url = _build_cross_app_redirect_url(redirect_url, web_url)
response = RedirectResponse(redirect_url, status_code=302)
set_response_cookie(
@@ -736,7 +737,8 @@ def _extract_login_inner_return_to(relative_url: str) -> str | None:
The OAuth flow's ``state`` is set to the full URL of the page that
triggered the login (see ``generateAuthUrl`` in the frontend).
For an unauthenticated deep-link visit, that page is itself
- ``/login?returnTo=<actual destination>``, so the OAuth callback's
+ ``/login?returnTo=<actual destination>`` (or legacy
+ ``/login?redirect=<actual destination>``), so the OAuth callback's
``redirect_url`` ends up *wrapping* the user's true destination
inside a login URL. Sending the user back through ``/login`` after
onboarding works in principle (``LoginPage`` re-redirects authed
@@ -751,7 +753,8 @@ def _extract_login_inner_return_to(relative_url: str) -> str | None:
parsed = urlparse(relative_url)
if parsed.path != '/login':
return None
- inner = parse_qs(parsed.query).get('returnTo')
+ query = parse_qs(parsed.query)
+ inner = query.get('returnTo') or query.get('redirect')
if not inner:
return None
value = inner[0]
@@ -760,6 +763,64 @@ def _extract_login_inner_return_to(relative_url: str) -> str | None:
return value
+def _is_cross_app_relative_path(value: str) -> bool:
+ """Return whether ``value`` is a safe same-origin cross-app route."""
+ if not value.startswith('/') or value.startswith('//'):
+ return False
+ parsed = urlparse(value)
+ return parsed.path == '/automations' or parsed.path.startswith('/automations/')
+
+
+def _merge_login_wrapper_query(inner_destination: str, outer_query: str) -> str:
+ """Move non-routing login-wrapper query params onto an unwrapped destination."""
+ extra_params = [
+ (key, value)
+ for key, value in parse_qsl(outer_query, keep_blank_values=True)
+ if key not in ('returnTo', 'redirect')
+ ]
+ if not extra_params:
+ return inner_destination
+
+ parsed_inner = urlparse(inner_destination)
+ query = parse_qsl(parsed_inner.query, keep_blank_values=True) + extra_params
+ return urlunparse(parsed_inner._replace(query=urlencode(query)))
+
+
+def _build_cross_app_redirect_url(redirect_url: str, web_url: str) -> str:
+ """Build a direct server-side redirect for same-origin microservice routes.
+
+ OAuth state often points back at the main app's ``/login`` page with the
+ real destination nested inside ``returnTo`` or the legacy ``redirect`` query
+ parameter. For paths owned by another frontend, such as ``/automations``,
+ sending the browser through the main app SPA first is brittle: any old or
+ already-loaded bundle can client-navigate and show the main app 404 before
+ ingress sees the route.
+
+ Returning a direct ``Location: <web_url>/automations...`` from the backend
+ makes the browser issue a real document request, so ingress routes it to the
+ automation service.
+ """
+ if not redirect_url:
+ return redirect_url
+
+ relative = redirect_url
+ if web_url and redirect_url.startswith(web_url):
+ relative = redirect_url[len(web_url) :] or '/'
+
+ parsed = urlparse(relative)
+ if parsed.path == '/login':
+ query = parse_qs(parsed.query)
+ inner = query.get('returnTo') or query.get('redirect')
+ if inner and _is_cross_app_relative_path(inner[0]):
+ destination = _merge_login_wrapper_query(inner[0], parsed.query)
+ return f'{web_url}{destination}'
+
+ if _is_cross_app_relative_path(relative):
+ return f'{web_url}{relative}'
+
+ return redirect_url
+
+
def _build_onboarding_redirect(original_url: str, web_url: str) -> str:
"""Build the ``/onboarding`` redirect URL preserving ``returnTo``.
@@ -784,7 +845,8 @@ def _build_onboarding_redirect(original_url: str, web_url: str) -> str:
and lets the frontend use ``navigate(returnTo)`` directly.
When ``original_url`` is itself a ``/login?returnTo=...`` URL β€”
- which is the common case for unauthenticated deep-link visits,
+ or a legacy ``/login?redirect=...`` URL β€” which is the common case for
+ unauthenticated deep-link visits,
because the OAuth flow's ``state`` carries the full login page
URL β€” the *inner* ``returnTo`` is extracted so the user lands at
their real destination in a single navigation rather than
@@ -881,7 +943,7 @@ async def _get_post_auth_redirect(
# ``?returnTo=...`` so the frontend ``OnboardingForm`` can
# restore it after the user finishes the form.
return _build_onboarding_redirect(default_url, web_url)
- return default_url
+ return _build_cross_app_redirect_url(default_url, web_url)
@api_router.post('/accept_tos')
diff --git a/enterprise/tests/unit/server/routes/test_auth_onboarding.py b/enterprise/tests/unit/server/routes/test_auth_onboarding.py
index 6421ae6ad8..574490d548 100644
--- a/enterprise/tests/unit/server/routes/test_auth_onboarding.py
+++ b/enterprise/tests/unit/server/routes/test_auth_onboarding.py
@@ -17,6 +17,7 @@ from fastapi.responses import JSONResponse
from server.auth.saas_user_auth import SaasUserAuth
from server.routes.auth import (
OnboardingSubmission,
+ _build_cross_app_redirect_url,
_build_onboarding_redirect,
_get_post_auth_redirect,
_should_redirect_to_onboarding,
@@ -200,6 +201,27 @@ class TestGetPostAuthRedirect:
assert result == 'https://example.com/dashboard'
+ @pytest.mark.asyncio
+ async def test_unwraps_automation_login_redirect_when_onboarding_completed(
+ self, mock_user
+ ):
+ """Automation redirects should bypass the main app login SPA."""
+ mock_user.onboarding_completed = True
+ user_id = str(mock_user.id)
+
+ with patch(
+ 'server.routes.auth.UserStore.get_user_by_id',
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ ):
+ result = await _get_post_auth_redirect(
+ user_id,
+ 'https://example.com/login?redirect=%2Fautomations&login_method=github',
+ 'https://example.com',
+ )
+
+ assert result == 'https://example.com/automations?login_method=github'
+
@pytest.mark.asyncio
async def test_returns_default_url_when_user_not_found(self):
"""Test that default URL is returned when user is not found."""
@@ -300,6 +322,53 @@ class TestGetPostAuthRedirect:
)
+class TestBuildCrossAppRedirectUrl:
+ def test_unwraps_legacy_login_redirect_to_automations(self):
+ result = _build_cross_app_redirect_url(
+ 'https://example.com/login?redirect=%2Fautomations&login_method=github',
+ 'https://example.com',
+ )
+
+ assert result == 'https://example.com/automations?login_method=github'
+
+ def test_unwraps_login_return_to_automation_deep_link(self):
+ result = _build_cross_app_redirect_url(
+ 'https://example.com/login'
+ '?returnTo=%2Fautomations%2Fabc%3Ftab%3Druns'
+ '&login_method=gitlab',
+ 'https://example.com',
+ )
+
+ assert result == (
+ 'https://example.com/automations/abc?tab=runs&login_method=gitlab'
+ )
+
+ def test_direct_automation_path_becomes_same_origin_absolute_url(self):
+ result = _build_cross_app_redirect_url('/automations', 'https://example.com')
+
+ assert result == 'https://example.com/automations'
+
+ def test_non_automation_login_redirect_is_unchanged(self):
+ result = _build_cross_app_redirect_url(
+ 'https://example.com/login?redirect=%2Fsettings&login_method=github',
+ 'https://example.com',
+ )
+
+ assert result == (
+ 'https://example.com/login?redirect=%2Fsettings&login_method=github'
+ )
+
+ def test_rejects_protocol_relative_inner_redirect(self):
+ result = _build_cross_app_redirect_url(
+ 'https://example.com/login?redirect=%2F%2Fevil.example.com%2Fautomations',
+ 'https://example.com',
+ )
+
+ assert result == (
+ 'https://example.com/login?redirect=%2F%2Fevil.example.com%2Fautomations'
+ )
+
+
# --- Tests for _build_onboarding_redirect ---
@@ -377,6 +446,13 @@ class TestBuildOnboardingRedirect:
)
assert result == 'https://example.com/onboarding?returnTo=%2Ffoo'
+ def test_unwraps_legacy_login_redirect_to_inner_destination(self):
+ result = _build_onboarding_redirect(
+ 'https://example.com/login?redirect=%2Fautomations&login_method=github',
+ 'https://example.com',
+ )
+ assert result == 'https://example.com/onboarding?returnTo=%2Fautomations'
+
def test_unwraps_login_returnTo_to_inner_destination(self):
"""Regression: login-wrapped destinations are unwrapped.
diff --git a/frontend/src/hooks/mutation/use-accept-tos.ts b/frontend/src/hooks/mutation/use-accept-tos.ts
index 058cb9a728..021c309674 100644
--- a/frontend/src/hooks/mutation/use-accept-tos.ts
+++ b/frontend/src/hooks/mutation/use-accept-tos.ts
@@ -3,6 +3,7 @@ import { usePostHog } from "posthog-js/react";
import { useNavigate } from "react-router";
import { openHands } from "#/api/open-hands-axios";
import { handleCaptureConsent } from "#/utils/handle-capture-consent";
+import { navigateOrHardRedirect } from "#/utils/cross-app-redirect";
interface AcceptTosVariables {
redirectUrl: string;
@@ -38,8 +39,7 @@ export const useAcceptTos = () => {
// For external URLs, redirect using window.location
window.location.href = finalRedirectUrl;
} else {
- // For internal routes, use navigate
- navigate(finalRedirectUrl);
+ navigateOrHardRedirect(navigate, finalRedirectUrl);
}
},
onError: () => {
diff --git a/frontend/src/hooks/mutation/use-submit-onboarding.ts b/frontend/src/hooks/mutation/use-submit-onboarding.ts
index 6f31311d30..68c97cba77 100644
--- a/frontend/src/hooks/mutation/use-submit-onboarding.ts
+++ b/frontend/src/hooks/mutation/use-submit-onboarding.ts
@@ -3,6 +3,7 @@ import { useNavigate } from "react-router";
import { openHands } from "#/api/open-hands-axios";
import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { navigateOrHardRedirect } from "#/utils/cross-app-redirect";
type SubmitOnboardingArgs = {
selections: Record<string, string | string[]>;
@@ -45,8 +46,7 @@ export const useSubmitOnboarding = () => {
// For external URLs, redirect using window.location
window.location.href = finalRedirectUrl;
} else {
- // For internal routes, use navigate
- navigate(finalRedirectUrl);
+ navigateOrHardRedirect(navigate, finalRedirectUrl);
}
},
onError: (error) => {
diff --git a/frontend/src/hooks/use-auth-callback.ts b/frontend/src/hooks/use-auth-callback.ts
index 8e3b647ed9..2a2d50d695 100644
--- a/frontend/src/hooks/use-auth-callback.ts
+++ b/frontend/src/hooks/use-auth-callback.ts
@@ -3,6 +3,7 @@ import { useLocation, useNavigate } from "react-router";
import { useIsAuthed } from "./query/use-is-authed";
import { LoginMethod, setLoginMethod } from "#/utils/local-storage";
import { useConfig } from "./query/use-config";
+import { navigateOrHardRedirect } from "#/utils/cross-app-redirect";
/**
* Hook to handle authentication callback and set login method after successful authentication
@@ -55,7 +56,7 @@ export const useAuthCallback = () => {
? `${destination}?${remainingParams}`
: destination;
- navigate(finalUrl, { replace: true });
+ navigateOrHardRedirect(navigate, finalUrl, { replace: true });
}
}, [
isAuthed,
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 0f2f60e6f1..6e2f85e2cf 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -9,6 +9,7 @@ export default [
route("login", "routes/login.tsx"),
route("onboarding", "routes/onboarding-form.tsx"),
route("information-request", "routes/information-request.tsx"),
+ route("automations/*", "routes/cross-app-redirect.tsx"),
layout("routes/root-layout.tsx", [
index("routes/home.tsx"),
route("accept-tos", "routes/accept-tos.tsx"),
diff --git a/frontend/src/routes/cross-app-redirect.tsx b/frontend/src/routes/cross-app-redirect.tsx
new file mode 100644
index 0000000000..0361ed5d2a
--- /dev/null
+++ b/frontend/src/routes/cross-app-redirect.tsx
@@ -0,0 +1,58 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+
+const RELOAD_SENTINEL_KEY = "openhands:automations-cross-app-reload";
+
+export default function CrossAppRedirect() {
+ const { t } = useTranslation();
+ const [alreadyReloaded] = React.useState(() => {
+ try {
+ return (
+ sessionStorage.getItem(RELOAD_SENTINEL_KEY) === window.location.href
+ );
+ } catch {
+ return false;
+ }
+ });
+
+ React.useEffect(() => {
+ if (alreadyReloaded) {
+ return;
+ }
+
+ try {
+ sessionStorage.setItem(RELOAD_SENTINEL_KEY, window.location.href);
+ } catch {
+ // Ignore storage failures; the browser should still try the document load.
+ }
+ window.location.replace(window.location.href);
+ }, [alreadyReloaded]);
+
+ if (alreadyReloaded) {
+ return (
+ <div className="min-h-screen flex items-center justify-center bg-base text-white">
+ <div className="max-w-md text-center space-y-4">
+ <h1 className="text-2xl font-semibold">{t(I18nKey.ERROR$GENERIC)}</h1>
+ <p className="text-sm text-neutral-300">{t(I18nKey.ERROR$UNKNOWN)}</p>
+ <button
+ type="button"
+ className="rounded bg-white px-4 py-2 text-sm font-medium text-black"
+ onClick={() => {
+ sessionStorage.removeItem(RELOAD_SENTINEL_KEY);
+ window.location.replace(window.location.href);
+ }}
+ >
+ {t(I18nKey.LAUNCH$TRY_AGAIN)}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-screen flex items-center justify-center bg-base">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white" />
+ </div>
+ );
+}
diff --git a/frontend/src/routes/login.test.ts b/frontend/src/routes/login.test.ts
new file mode 100644
index 0000000000..d4f1e0c724
--- /dev/null
+++ b/frontend/src/routes/login.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { getSafeReturnTo } from "./login";
+
+describe("getSafeReturnTo", () => {
+ it("prefers returnTo when present", () => {
+ const params = new URLSearchParams({
+ returnTo: "/settings",
+ redirect: "/automations",
+ });
+
+ expect(getSafeReturnTo(params)).toBe("/settings");
+ });
+
+ it("accepts legacy redirect for automation login links", () => {
+ const params = new URLSearchParams({ redirect: "/automations?tab=runs" });
+
+ expect(getSafeReturnTo(params)).toBe("/automations?tab=runs");
+ });
+
+ it("rejects absolute redirect targets", () => {
+ expect(
+ getSafeReturnTo(new URLSearchParams({ redirect: "https://example.com" })),
+ ).toBe("/");
+ expect(
+ getSafeReturnTo(new URLSearchParams({ redirect: "//example.com" })),
+ ).toBe("/");
+ });
+});
diff --git a/frontend/src/routes/login.tsx b/frontend/src/routes/login.tsx
index 2227c09eb0..793edbed47 100644
--- a/frontend/src/routes/login.tsx
+++ b/frontend/src/routes/login.tsx
@@ -8,16 +8,26 @@ import { useInvitation } from "#/hooks/use-invitation";
import { LoginContent } from "#/components/features/auth/login-content";
import { EmailVerificationModal } from "#/components/features/waitlist/email-verification-modal";
import { RequestSubmittedModal } from "#/components/features/onboarding/request-submitted-modal";
+import { navigateOrHardRedirect } from "#/utils/cross-app-redirect";
interface LocationState {
showRequestSubmittedModal?: boolean;
}
+export function getSafeReturnTo(searchParams: URLSearchParams): string {
+ const destination =
+ searchParams.get("returnTo") || searchParams.get("redirect") || "/";
+ if (!destination.startsWith("/") || destination.startsWith("//")) {
+ return "/";
+ }
+ return destination;
+}
+
export default function LoginPage() {
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
- const returnTo = searchParams.get("returnTo") || "/";
+ const returnTo = getSafeReturnTo(searchParams);
const locationState = location.state as LocationState | null;
const config = useConfig();
@@ -65,7 +75,7 @@ export default function LoginPage() {
const separator = returnTo.includes("?") ? "&" : "?";
destination = `${returnTo}${separator}login_method=${encodeURIComponent(loginMethod)}`;
}
- navigate(destination, { replace: true });
+ navigateOrHardRedirect(navigate, destination, { replace: true });
}
}, [isAuthed, isAuthLoading, navigate, returnTo, searchParams]);
diff --git a/frontend/src/routes/onboarding-form.tsx b/frontend/src/routes/onboarding-form.tsx
index 880368b009..1f28a880e1 100644
--- a/frontend/src/routes/onboarding-form.tsx
+++ b/frontend/src/routes/onboarding-form.tsx
@@ -25,6 +25,7 @@ import {
} from "#/api/option-service/option.types";
import { queryClient } from "#/query-client-config";
import OptionService from "#/api/option-service/option-service.api";
+import { navigateOrHardRedirect } from "#/utils/cross-app-redirect";
/**
* Sanitize a raw ``returnTo`` value, returning a safe same-origin path.
@@ -153,7 +154,7 @@ function OnboardingForm() {
// stale ``/onboarding`` link still respects their deep-link
// destination. ``returnTo`` is already sanitized above so it is
// always a safe same-origin path.
- navigate(returnTo, { replace: true });
+ navigateOrHardRedirect(navigate, returnTo, { replace: true });
}
}, [
onboardingStatus?.should_complete_onboarding,
diff --git a/frontend/src/utils/cross-app-redirect.test.ts b/frontend/src/utils/cross-app-redirect.test.ts
new file mode 100644
index 0000000000..49b728df81
--- /dev/null
+++ b/frontend/src/utils/cross-app-redirect.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { isCrossAppPath } from "./cross-app-redirect";
+
+describe("isCrossAppPath", () => {
+ it("detects automation app routes", () => {
+ expect(isCrossAppPath("/automations")).toBe(true);
+ expect(isCrossAppPath("/automations?login_method=github")).toBe(true);
+ expect(isCrossAppPath("/automations/abc?tab=runs")).toBe(true);
+ });
+
+ it("does not match similarly-prefixed main app routes", () => {
+ expect(isCrossAppPath("/automation")).toBe(false);
+ expect(isCrossAppPath("/automations-old")).toBe(false);
+ expect(isCrossAppPath("/settings?returnTo=/automations")).toBe(false);
+ });
+
+ it("does not treat off-origin targets as cross-app paths", () => {
+ expect(isCrossAppPath("//evil.com/automations")).toBe(false);
+ expect(isCrossAppPath("https://evil.com/automations")).toBe(false);
+ });
+});
diff --git a/frontend/src/utils/cross-app-redirect.ts b/frontend/src/utils/cross-app-redirect.ts
new file mode 100644
index 0000000000..37d519a274
--- /dev/null
+++ b/frontend/src/utils/cross-app-redirect.ts
@@ -0,0 +1,27 @@
+import type { NavigateFunction, NavigateOptions } from "react-router";
+
+export function isCrossAppPath(destination: string): boolean {
+ if (!destination.startsWith("/") || destination.startsWith("//")) {
+ return false;
+ }
+
+ try {
+ const { pathname } = new URL(destination, window.location.origin);
+ return pathname === "/automations" || pathname.startsWith("/automations/");
+ } catch {
+ return false;
+ }
+}
+
+export function navigateOrHardRedirect(
+ navigate: NavigateFunction,
+ destination: string,
+ options?: NavigateOptions,
+) {
+ if (isCrossAppPath(destination)) {
+ window.location.replace(destination);
+ return;
+ }
+
+ navigate(destination, options);
+}