Skip to content

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): let device-code providers connect from copilot chat (#14095)

Nicholas Tindleb8554633fc72
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index d7408f7dd6..cfc9ac04ab 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -1736,6 +1736,20 @@ def _get_provider_oauth_handler(
key = provider_key(provider_name)
if key not in HANDLERS_BY_NAME:
+ if key in DEVICE_HANDLERS_BY_NAME:
+ # A device-code provider is a public client with no client secret,
+ # so there is no authorization-code flow to start. Point the caller
+ # at the device-auth endpoint rather than reporting "does not
+ # support OAuth". The detail is shown to end users verbatim.
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ f"Provider '{key}' connects with a device code, not an "
+ "OAuth redirect. Connect it through the device-code flow "
+ f"instead (API: POST /api/integrations/{key}"
+ "/device-auth/initiate)."
+ ),
+ )
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Provider '{key}' does not support OAuth",
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router_test.py b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
index 2db2d8d9dd..a0c5f1d801 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
@@ -8,7 +8,7 @@ import fastapi.testclient
import pytest
from pydantic import SecretStr
-from backend.api.features.integrations.router import router
+from backend.api.features.integrations.router import _get_provider_oauth_handler, router
from backend.data.integrations import Webhook
from backend.data.model import (
APIKeyCredentials,
@@ -856,6 +856,65 @@ class TestWebhookPingOwnership:
webhook_manager.trigger_ping.assert_awaited_once()
+class TestOAuthHandlerResolutionForDeviceProviders:
+ """A device-code provider has no OAuth handler, but it is not unknown.
+
+ `_get_provider_oauth_handler` must point the caller at the device-auth
+ endpoint (400) rather than reporting "does not support OAuth" (404).
+ """
+
+ # Synthetic keys so both patches are load-bearing. `HANDLERS_BY_NAME` is an
+ # `SDKAwareHandlersDict` whose `__contains__` reads the module-level
+ # `_handlers_dict` and the SDK registry, never its own storage, so
+ # `patch.dict` on the facade is inert: patch the backing dict instead.
+ DEVICE_ONLY_PROVIDER = "test_device_only_provider"
+ UNREGISTERED_PROVIDER = "test_unregistered_provider"
+
+ def test_a_device_code_provider_is_pointed_at_the_device_endpoint(self):
+ with (
+ patch.dict(
+ "backend.integrations.oauth._handlers_dict",
+ {},
+ clear=True,
+ ),
+ patch.dict(
+ "backend.api.features.integrations.router.DEVICE_HANDLERS_BY_NAME",
+ {self.DEVICE_ONLY_PROVIDER: MagicMock()},
+ clear=True,
+ ),
+ pytest.raises(fastapi.HTTPException) as exc,
+ ):
+ _get_provider_oauth_handler(MagicMock(), self.DEVICE_ONLY_PROVIDER)
+
+ assert exc.value.status_code == 400
+ assert "device code" in exc.value.detail
+ # The detail reaches the user verbatim, so the path must be the mounted
+ # one: the router lives under /api/integrations.
+ assert (
+ f"/api/integrations/{self.DEVICE_ONLY_PROVIDER}/device-auth/initiate"
+ in exc.value.detail
+ )
+
+ def test_an_unknown_provider_still_reports_no_oauth_support(self):
+ with (
+ patch.dict(
+ "backend.integrations.oauth._handlers_dict",
+ {},
+ clear=True,
+ ),
+ patch.dict(
+ "backend.api.features.integrations.router.DEVICE_HANDLERS_BY_NAME",
+ {},
+ clear=True,
+ ),
+ pytest.raises(fastapi.HTTPException) as exc,
+ ):
+ _get_provider_oauth_handler(MagicMock(), self.UNREGISTERED_PROVIDER)
+
+ assert exc.value.status_code == 404
+ assert "does not support OAuth" in exc.value.detail
+
+
class TestDeviceAuthEndpoints:
"""POST /{provider}/device-auth/{initiate,poll}.
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.tsx
index 7067b7ed87..a9491e90fa 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
@@ -7,10 +7,10 @@ import { Text } from "@/components/atoms/Text/Text";
import { AuthCard } from "@/components/auth/AuthCard";
import { CredentialsInput } from "@/components/contextual/CredentialsInput/CredentialsInput";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { CREDENTIALS_TYPES } from "@/lib/autogpt-server-api";
import type {
BlockIOCredentialsSubSchema,
CredentialsMetaInput,
- CredentialsType,
} from "@/lib/autogpt-server-api";
import Image from "next/image";
import Link from "next/link";
@@ -19,14 +19,6 @@ import { useMemo, useRef, useState } from "react";
import { CircleIcon, Tick02Icon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
-// All credential types - we accept any type of credential
-const ALL_CREDENTIAL_TYPES: CredentialsType[] = [
- "api_key",
- "oauth2",
- "user_password",
- "host_scoped",
-];
-
/**
* Provider configuration for the setup wizard.
*
@@ -57,7 +49,8 @@ function createSchemaFromProviderConfig(
type: "object",
properties: {},
credentials_provider: [config.provider],
- credentials_types: ALL_CREDENTIAL_TYPES,
+ // Accept any credential type; the shared list is build-time total.
+ credentials_types: [...CREDENTIALS_TYPES],
credentials_scopes: config.scopes,
discriminator: undefined,
discriminator_mapping: undefined,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
index ceba27ed8d..b10ec93c1a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/helpers.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from "vitest";
+import { deriveAuthMethods } from "@/hooks/useCredentials";
+import type { CredentialsType } from "@/lib/autogpt-server-api/types";
import {
coerceCredentialFields,
buildSiblingInputsFromCredentials,
@@ -38,6 +40,43 @@ describe("coerceCredentialFields", () => {
expect(result.requiredCredentials.has("cred1")).toBe(true);
});
+ it("keeps device_code so device-auth providers are connectable", () => {
+ // `deriveAuthMethods` only shadows `oauth2` when `device_code` is present,
+ // and a device-code provider has no authorization-code flow to offer in
+ // its place, so this filter must pass `device_code` through.
+ const input = {
+ stripe_link_credentials: {
+ provider: "stripe_link",
+ types: ["device_code", "oauth2"],
+ },
+ };
+ const result = coerceCredentialFields(input);
+ expect(result.credentialFields).toHaveLength(1);
+ expect(result.credentialFields[0][1]).toMatchObject({
+ credentials_types: ["device_code", "oauth2"],
+ });
+ });
+
+ it("hands the card a payload that resolves to device auth, not OAuth", () => {
+ // Composed with the real `deriveAuthMethods`, no mocks: what this filter
+ // produces has to be what that consumer needs to route to device auth.
+ const { credentialFields } = coerceCredentialFields({
+ stripe_link_credentials: {
+ provider: "stripe_link",
+ type: "device_code",
+ types: ["device_code", "oauth2"],
+ },
+ });
+
+ const schema = credentialFields[0][1] as {
+ credentials_types: CredentialsType[];
+ };
+ const methods = deriveAuthMethods(schema.credentials_types);
+
+ expect(methods.supportsDeviceCode).toBe(true);
+ expect(methods.supportsOAuth2).toBe(false);
+ });
+
it("filters out invalid credential types", () => {
const input = {
cred1: {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
index bc0a353a8d..161e6761e6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
@@ -1,13 +1,12 @@
import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
import type { CredentialRejection } from "@/app/api/__generated__/models/credentialRejection";
import type { RJSFSchema } from "@rjsf/utils";
+import { CREDENTIALS_TYPES } from "@/lib/autogpt-server-api/types";
-const VALID_CREDENTIAL_TYPES = new Set([
- "api_key",
- "oauth2",
- "user_password",
- "host_scoped",
-]);
+// Used as a filter below, so it has to be total: a type missing here is
+// silently unconnectable from the card. `CREDENTIALS_TYPES` is checked against
+// `CredentialsType` at build time, so a new type cannot go missing quietly.
+const VALID_CREDENTIAL_TYPES: ReadonlySet<string> = new Set(CREDENTIALS_TYPES);
export function coerceCredentialFields(rawMissingCredentials: unknown): {
credentialFields: CredentialField[];
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
index 406b00e6d8..5f2af6474f 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
+import { deriveAuthMethods } from "@/hooks/useCredentials";
import {
countSupportedTypes,
getSupportedTypes,
@@ -510,6 +511,25 @@ describe("resolveActionTarget", () => {
);
});
+ // A device-code provider advertises both types: the grant yields an
+ // oauth2-shaped credential, so `oauth2` must stay in the schema for saved
+ // credentials to match. `resolveActionTarget` checks OAuth first, so the
+ // device-code route depends on `deriveAuthMethods` shadowing `oauth2` out.
+ it("routes a provider advertising both types to device auth, not oauth", () => {
+ const methods = deriveAuthMethods(["oauth2", "device_code"]);
+
+ expect(
+ resolveActionTarget(
+ false,
+ methods.supportsOAuth2,
+ methods.supportsApiKey,
+ methods.supportsUserPassword,
+ methods.supportsHostScoped,
+ methods.supportsDeviceCode,
+ ),
+ ).toBe("device_code");
+ });
+
it("returns null when nothing is supported", () => {
expect(resolveActionTarget(false, false, false, false, false)).toBeNull();
});
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index 457a5cb9b6..5b3c9d7621 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -197,6 +197,22 @@ export type CredentialsType =
| "host_scoped"
| "device_code";
+/**
+ * Every credential type the platform can store, as a runtime list.
+ *
+ * Built from a total `Record<CredentialsType, true>` so that extending
+ * `CredentialsType` without updating this list fails the build. Use it
+ * wherever a list of credential types acts as a filter: an omission there
+ * silently removes a connection method rather than mis-ordering it.
+ */
+export const CREDENTIALS_TYPES: readonly CredentialsType[] = Object.keys({
+ api_key: true,
+ oauth2: true,
+ user_password: true,
+ host_scoped: true,
+ device_code: true,
+} satisfies Record<CredentialsType, true>) as CredentialsType[];
+
export type Credentials =
| APIKeyCredentials
| OAuth2Credentials