AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(platform): refuse an unsafe redirect_uri on the integration setup wizard (#15363)
Cabezae14b739c1821
diff --git a/autogpt_platform/backend/backend/api/features/oauth.py b/autogpt_platform/backend/backend/api/features/oauth.pyindex 89fc7b9b70..4397c07f4a 100644--- a/autogpt_platform/backend/backend/api/features/oauth.py+++ b/autogpt_platform/backend/backend/api/features/oauth.py@@ -27,6 +27,7 @@ from fastapi import (Body,Depends,HTTPException,+ Query,Security,UploadFile,status,@@ -107,17 +108,30 @@ class OAuthApplicationPublicInfo(BaseModel):@router.get("/app/{client_id}",responses={+ 400: {"description": "redirect_uri is not registered for the application"},404: {"description": "Application not found or disabled"},},)async def get_oauth_app_info(- client_id: str, user_id: str = Security(get_user_id)+ client_id: str,+ redirect_uri: Optional[str] = Query(+ default=None,+ description=(+ "Where the page will send the user back to. When given, it must be "+ "one of the application's registered redirect URIs."+ ),+ ),+ user_id: str = Security(get_user_id),) -> OAuthApplicationPublicInfo:"""Get public information about an OAuth application.- This endpoint is used by the consent screen to display application details- to the user before they authorize access.+ This endpoint is used by the consent screen and the integration setup+ wizard to display application details to the user before they authorize+ access. The setup wizard sends the `redirect_uri` it was given and sends+ the user back there only once this endpoint accepts it, so it never+ redirects to an address the application did not register (RFC 6749+ 4.1.2.1).Returns:- name: Application name@@ -130,6 +144,11 @@ async def get_oauth_app_info(status_code=status.HTTP_404_NOT_FOUND,detail="Application not found",)+ if redirect_uri is not None and not validate_redirect_uri(app, redirect_uri):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail="redirect_uri is not registered for this application",+ )return OAuthApplicationPublicInfo(name=app.name,diff --git a/autogpt_platform/backend/backend/api/features/oauth_app_info_test.py b/autogpt_platform/backend/backend/api/features/oauth_app_info_test.pynew file mode 100644index 0000000000..164b98a0d5--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/oauth_app_info_test.py@@ -0,0 +1,57 @@+from datetime import UTC, datetime+from unittest.mock import AsyncMock, patch++import pytest+from fastapi import HTTPException+from prisma.enums import APIKeyPermission++from backend.api.features import oauth+from backend.data.auth.oauth import OAuthApplicationInfo++REGISTERED = "https://client.example/callback"++[email protected]("redirect_uri", [REGISTERED, None])+async def test_app_info_answers_for_a_registered_or_absent_redirect_uri(redirect_uri):+ info = await _get_app_info(redirect_uri)++ assert info.name == "Test app"+++ "redirect_uri",+ [+ "https://evil.example/phish",+ f"{REGISTERED}/",+ "javascript:alert(document.domain)//",+ ],+)+async def test_app_info_refuses_a_redirect_uri_the_app_did_not_register(+ redirect_uri,+):+ with pytest.raises(HTTPException) as error:+ await _get_app_info(redirect_uri)++ assert error.value.status_code == 400+++async def _get_app_info(redirect_uri: str | None):+ now = datetime.now(UTC)+ app = OAuthApplicationInfo(+ id="app-123",+ name="Test app",+ client_id="client-123",+ redirect_uris=[REGISTERED],+ grant_types=["authorization_code"],+ scopes=[APIKeyPermission.READ_GRAPH],+ owner_id="owner",+ is_active=True,+ created_at=now,+ updated_at=now,+ )+ with patch.object(oauth, "get_oauth_application", AsyncMock(return_value=app)):+ return await oauth.get_oauth_app_info(+ "client-123", redirect_uri=redirect_uri, user_id="user"+ )diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/authorize/page.tsx b/autogpt_platform/frontend/src/app/(platform)/auth/authorize/page.tsxindex 64a7ac9c61..f857895fdb 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/authorize/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/auth/authorize/page.tsx@@ -53,7 +53,7 @@ export default function AuthorizePage() {isLoading,error,refetch,- } = useGetOauthGetOauthAppInfo(clientID || "", {+ } = useGetOauthGetOauthAppInfo(clientID || "", undefined, {query: {enabled: !!clientID,staleTime: Infinity,diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/__tests__/page.test.tsxnew file mode 100644index 0000000000..e810fea5e8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/__tests__/page.test.tsx@@ -0,0 +1,162 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++import {+ getGetOauthGetOauthAppInfoMockHandler200,+ getGetOauthGetOauthAppInfoMockHandler400,+} from "@/app/api/__generated__/endpoints/oauth/oauth.msw";+import { server } from "@/mocks/mock-server";+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";+import IntegrationSetupWizardPage from "../page";++const mockUseSearchParams = vi.hoisted(() => vi.fn());++vi.mock("next/navigation", () => ({+ usePathname: () => "/auth/integrations/setup-wizard",+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ useSearchParams: mockUseSearchParams,+}));++// The real credential picker needs the integrations API; this stand-in+// connects a provider so Continue can be reached.+vi.mock("@/components/contextual/CredentialsInput/CredentialsInput", () => ({+ CredentialsInput: ({+ onSelectCredentials,+ }: {+ onSelectCredentials: (credential: { id: string }) => void;+ }) => (+ <button type="button" onClick={() => onSelectCredentials({ id: "cred-1" })}>+ connect+ </button>+ ),+}));++const PAGE = "http://localhost/auth/integrations/setup-wizard";+const REGISTERED = "https://app.example.com/callback";++function openWith(params: Record<string, string>) {+ mockUseSearchParams.mockReturnValue(+ new URLSearchParams({+ client_id: "client-1",+ providers: btoa("{}"),+ redirect_uri: REGISTERED,+ state: "state-1",+ ...params,+ }),+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(window, "location", {+ configurable: true,+ value: { href: PAGE },+ });+});++describe("IntegrationSetupWizardPage", () => {+ test("needs a client_id to check the redirect_uri against", () => {+ mockUseSearchParams.mockReturnValue(+ new URLSearchParams({+ providers: btoa("[]"),+ redirect_uri: REGISTERED,+ }),+ );++ render(<IntegrationSetupWizardPage />);++ expect(+ screen.getByText("Missing required parameters: client_id"),+ ).toBeDefined();+ });++ test("offers no way back to a redirect_uri the app did not register", async () => {+ openWith({ redirect_uri: "https://evil.example/collect" });+ server.use(getGetOauthGetOauthAppInfoMockHandler400());++ render(<IntegrationSetupWizardPage />);++ expect(await screen.findByText("Invalid Request")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();+ expect(window.location.href).toBe(PAGE);+ });++ test("cancelling returns the user to the redirect_uri the backend accepted", async () => {+ let requested: URL | undefined;+ openWith({});+ server.use(+ getGetOauthGetOauthAppInfoMockHandler200(({ request }) => {+ requested = new URL(request.url);+ return { name: "Example App", scopes: ["IDENTITY"] };+ }),+ );++ render(<IntegrationSetupWizardPage />);+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));++ expect(requested?.searchParams.get("redirect_uri")).toBe(REGISTERED);+ const sentTo = new URL(window.location.href);+ expect(`${sentTo.origin}${sentTo.pathname}`).toBe(REGISTERED);+ expect(sentTo.searchParams.get("error")).toBe("user_cancelled");+ expect(sentTo.searchParams.get("state")).toBe("state-1");+ });++ test("continuing returns the user to the accepted redirect_uri, once", async () => {+ const sentTo = recordNavigations();+ openWith({ providers: btoa(JSON.stringify([{ provider: "github" }])) });+ server.use(+ getGetOauthGetOauthAppInfoMockHandler200({+ name: "Example App",+ scopes: ["IDENTITY"],+ }),+ );++ render(<IntegrationSetupWizardPage />);+ fireEvent.click(await screen.findByRole("button", { name: "connect" }));+ const continueButton = screen.getByRole("button", { name: "Continue" });+ fireEvent.click(continueButton);+ fireEvent.click(continueButton);++ expect(sentTo).toEqual([`${REGISTERED}?success=true&state=state-1`]);+ });++ test("a second Cancel does not send the user anywhere again", async () => {+ const sentTo = recordNavigations();+ openWith({});+ server.use(+ getGetOauthGetOauthAppInfoMockHandler200({+ name: "Example App",+ scopes: ["IDENTITY"],+ }),+ );++ render(<IntegrationSetupWizardPage />);+ const cancel = await screen.findByRole("button", { name: "Cancel" });+ fireEvent.click(cancel);+ fireEvent.click(cancel);++ expect(sentTo).toHaveLength(1);+ });+});++function recordNavigations() {+ const sentTo: string[] = [];+ Object.defineProperty(window, "location", {+ configurable: true,+ value: {+ get href() {+ return PAGE;+ },+ set href(url: string) {+ sentTo.push(url);+ },+ },+ });+ return sentTo;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/page.tsx b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/page.tsxindex a9491e90fa..62c5cbe732 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/auth/integrations/setup-wizard/page.tsx@@ -3,6 +3,7 @@import { useGetOauthGetOauthAppInfo } from "@/app/api/__generated__/endpoints/oauth/oauth";import { okData } from "@/app/api/helpers";import { Button } from "@/components/atoms/Button/Button";+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { Text } from "@/components/atoms/Text/Text";import { AuthCard } from "@/components/auth/AuthCard";import { CredentialsInput } from "@/components/contextual/CredentialsInput/CredentialsInput";@@ -24,8 +25,9 @@ import { Icon } from "@/components/atoms/Icon/Icon";** Query parameters:* - `providers`: base64-encoded JSON array of { provider, scopes? } objects- * - `app_name`: (optional) Name of the requesting application- * - `redirect_uri`: Where to redirect after completion+ * - `client_id`: The requesting application's OAuth client ID+ * - `redirect_uri`: Where to redirect after completion; must be one of the+ * application's registered redirect URIs* - `state`: Anti-CSRF token** Example `providers` JSON:@@ -35,7 +37,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";* ]** Example URL:- * /auth/integrations/setup-wizard?app_name=My%20App&providers=W3sicHJvdmlkZXIiOiJnb29nbGUifV0=&redirect_uri=...+ * /auth/integrations/setup-wizard?client_id=...&providers=W3sicHJvdmlkZXIiOiJnb29nbGUifV0=&redirect_uri=...*/interface ProviderConfig {provider: string;@@ -99,9 +101,15 @@ export default function IntegrationSetupWizardPage() {const redirectURI = searchParams.get("redirect_uri");const state = searchParams.get("state");- const { data: appInfo } = useGetOauthGetOauthAppInfo(clientID || "", {- query: { enabled: !!clientID, select: okData },- });+ const {+ data: appInfo,+ isLoading,+ error,+ } = useGetOauthGetOauthAppInfo(+ clientID || "",+ { redirect_uri: redirectURI },+ { query: { enabled: !!clientID && !!redirectURI, select: okData } },+ );// Parse providers from base64-encoded JSONconst providerConfigs = useMemo<ProviderConfig[]>(() => {@@ -138,7 +146,7 @@ export default function IntegrationSetupWizardPage() {// Handle completion - redirect back to clientconst handleComplete = () => {- if (!redirectURI || hasRedirectedRef.current) return;+ if (!appInfo || hasRedirectedRef.current) return;hasRedirectedRef.current = true;const params = new URLSearchParams({@@ -153,7 +161,7 @@ export default function IntegrationSetupWizardPage() {// Handle cancel - redirect back to client with errorconst handleCancel = () => {- if (!redirectURI || hasRedirectedRef.current) return;+ if (!appInfo || hasRedirectedRef.current) return;hasRedirectedRef.current = true;const params = new URLSearchParams({@@ -169,6 +177,7 @@ export default function IntegrationSetupWizardPage() {// Validate required parametersconst missingParams: string[] = [];+ if (!clientID) missingParams.push("client_id");if (!providersParam) missingParams.push("providers");if (!redirectURI) missingParams.push("redirect_uri");@@ -189,6 +198,34 @@ export default function IntegrationSetupWizardPage() {);}+ if (isLoading) {+ return (+ <div className="flex h-full min-h-[85vh] flex-col items-center justify-center py-10">+ <AuthCard title="Loading...">+ <div className="flex flex-col items-center gap-4 py-8">+ <LoadingSpinner size="large" />+ </div>+ </AuthCard>+ </div>+ );+ }++ // appInfo loads only once the backend accepts redirectURI for this client+ if (error || !appInfo) {+ return (+ <div className="flex h-full min-h-[85vh] flex-col items-center justify-center py-10">+ <AuthCard title="Invalid Request">+ <ErrorCard+ context="application"+ responseError={error ? error : { message: "Application not found" }}+ hint="Please contact the administrator of the app that sent you here."+ isOurProblem={false}+ />+ </AuthCard>+ </div>+ );+ }+if (providerConfigs.length === 0) {return (<div className="flex h-full min-h-[85vh] flex-col items-center justify-center py-10">@@ -216,14 +253,8 @@ export default function IntegrationSetupWizardPage() {<AuthCard title="Connect Your Accounts"><div className="flex w-full flex-col gap-6"><Text variant="body" className="text-center text-slate-600">- {appInfo ? (- <>- <strong>{appInfo.name}</strong> is requesting you to connect the- following integrations to your AutoGPT account.- </>- ) : (- "Please connect the following integrations to continue."- )}+ <strong>{appInfo.name}</strong> is requesting you to connect the+ following integrations to your AutoGPT account.</Text>{/* Provider credentials list */}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex cfeba72718..7906a5b226 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -12213,7 +12213,7 @@"get": {"tags": ["oauth"],"summary": "Get Oauth App Info",- "description": "Get public information about an OAuth application.\n\nThis endpoint is used by the consent screen to display application details\nto the user before they authorize access.\n\nReturns:\n- name: Application name\n- description: Application description (if provided)\n- scopes: List of scopes the application is allowed to request",+ "description": "Get public information about an OAuth application.\n\nThis endpoint is used by the consent screen and the integration setup\nwizard to display application details to the user before they authorize\naccess. The setup wizard sends the `redirect_uri` it was given and sends\nthe user back there only once this endpoint accepts it, so it never\nredirects to an address the application did not register (RFC 6749\n4.1.2.1).\n\nReturns:\n- name: Application name\n- description: Application description (if provided)\n- scopes: List of scopes the application is allowed to request","operationId": "getOauthGetOauthAppInfo","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -12222,6 +12222,17 @@"in": "path","required": true,"schema": { "type": "string", "title": "Client Id" }+ },+ {+ "name": "redirect_uri",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Where the page will send the user back to. When given, it must be one of the application's registered redirect URIs.",+ "title": "Redirect Uri"+ },+ "description": "Where the page will send the user back to. When given, it must be one of the application's registered redirect URIs."}],"responses": {@@ -12235,6 +12246,9 @@}}},+ "400": {+ "description": "redirect_uri is not registered for the application"+ },"401": {"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},