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): resolve autopilot beta blockers (SECRT-2266/2267/2268/2269) (#12874)

Nicholas Tindle10e421cd3eb4
diff --git a/autogpt_platform/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py b/autogpt_platform/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py
index 04c6fa2a77..eb69ab2fac 100644
--- a/autogpt_platform/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py
+++ b/autogpt_platform/autogpt_libs/autogpt_libs/supabase_integration_credentials_store/types.py
@@ -59,6 +59,8 @@ class OAuthState(BaseModel):
code_verifier: Optional[str] = None
scopes: list[str]
"""Unix timestamp (seconds) indicating when this OAuth state expires"""
+ credential_id: Optional[str] = None
+ """If set, this OAuth flow upgrades an existing credential's scopes."""
class UserMetadata(BaseModel):
diff --git a/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py b/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py
new file mode 100644
index 0000000000..352f14df5a
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/integrations/incremental_oauth_test.py
@@ -0,0 +1,1130 @@
+"""Tests for incremental OAuth authorization (scope upgrade)."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import fastapi
+import fastapi.testclient
+import pytest
+from pydantic import SecretStr
+
+from backend.api.features.integrations.router import router
+from backend.data.model import APIKeyCredentials, OAuth2Credentials, OAuthState
+
+app = fastapi.FastAPI()
+app.include_router(router)
+client = fastapi.testclient.TestClient(app)
+
+TEST_USER_ID = "test-user-id"
+
+
+def _make_google_oauth2_cred(
+ cred_id: str = "google-cred-1",
+ scopes: list[str] | None = None,
+ username: str = "[email protected]",
+ title: str = "My Google",
+) -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id=cred_id,
+ provider="google",
+ title=title,
+ access_token=SecretStr("ya29.access-token"),
+ refresh_token=SecretStr("1//refresh-token"),
+ scopes=(
+ scopes
+ if scopes is not None
+ else ["https://www.googleapis.com/auth/gmail.readonly"]
+ ),
+ username=username,
+ access_token_expires_at=9999999999,
+ )
+
+
+def _make_github_oauth2_cred(
+ cred_id: str = "github-cred-1",
+ scopes: list[str] | None = None,
+ username: str = "alice",
+ title: str = "My GitHub",
+) -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id=cred_id,
+ provider="github",
+ title=title,
+ access_token=SecretStr("ghp_access_token"),
+ refresh_token=SecretStr("ghp_refresh_token"),
+ scopes=scopes if scopes is not None else ["repo"],
+ username=username,
+ )
+
+
[email protected](autouse=True)
+def setup_auth(mock_jwt_user):
+ from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+# ==================== OAuthState model tests ==================== #
+
+
+class TestOAuthStateCredentialId:
+ """OAuthState model should support a credential_id field for upgrades."""
+
+ def test_oauth_state_accepts_credential_id(self):
+ state = OAuthState(
+ token="abc",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["openid"],
+ credential_id="existing-cred-id",
+ )
+ assert state.credential_id == "existing-cred-id"
+
+ def test_oauth_state_defaults_credential_id_none(self):
+ state = OAuthState(
+ token="abc",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["openid"],
+ )
+ assert state.credential_id is None
+
+
+# ==================== Login endpoint tests ==================== #
+
+
+class TestIncrementalOAuthLogin:
+ """Tests for the login endpoint with credential_id parameter."""
+
+ def test_login_with_credential_id_stores_in_state(self):
+ """Login with credential_id should pass it through to store_state_token."""
+ existing = _make_google_oauth2_cred()
+ handler = MagicMock()
+ handler.get_login_url.return_value = "https://accounts.google.com/auth"
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.store.store_state_token = AsyncMock(
+ return_value=("state-token", "code-challenge")
+ )
+
+ resp = client.get(
+ "/google/login",
+ params={
+ "scopes": "https://www.googleapis.com/auth/calendar.readonly",
+ "credential_id": "google-cred-1",
+ },
+ )
+
+ assert resp.status_code == 200
+ # Verify store_state_token was called with credential_id
+ call_kwargs = mock_mgr.store.store_state_token.call_args
+ assert call_kwargs.kwargs.get("credential_id") == "google-cred-1" or (
+ len(call_kwargs.args) > 3 and call_kwargs.args[3] == "google-cred-1"
+ )
+
+ def test_login_github_unions_scopes_for_upgrade(self):
+ """For GitHub, login should request union of existing + new scopes."""
+ existing = _make_github_oauth2_cred(scopes=["repo"])
+ handler = MagicMock()
+ handler.get_login_url.return_value = "https://github.com/login/oauth/authorize"
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.store.store_state_token = AsyncMock(
+ return_value=("state-token", "code-challenge")
+ )
+
+ resp = client.get(
+ "/github/login",
+ params={
+ "scopes": "read:org",
+ "credential_id": "github-cred-1",
+ },
+ )
+
+ assert resp.status_code == 200
+ # The scopes passed to get_login_url should be the union
+ login_scopes = handler.get_login_url.call_args[0][0]
+ assert set(login_scopes) == {"repo", "read:org"}
+
+ def test_login_google_keeps_requested_scopes_only(self):
+ """For Google, login should use only the new scopes (include_granted_scopes handles merging)."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"]
+ )
+ handler = MagicMock()
+ handler.get_login_url.return_value = "https://accounts.google.com/auth"
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.store.store_state_token = AsyncMock(
+ return_value=("state-token", "code-challenge")
+ )
+
+ resp = client.get(
+ "/google/login",
+ params={
+ "scopes": "https://www.googleapis.com/auth/calendar.readonly",
+ "credential_id": "google-cred-1",
+ },
+ )
+
+ assert resp.status_code == 200
+ login_scopes = handler.get_login_url.call_args[0][0]
+ # Google should NOT union scopes in the login URL
+ assert "https://www.googleapis.com/auth/calendar.readonly" in login_scopes
+ assert "https://www.googleapis.com/auth/gmail.readonly" not in login_scopes
+ # Verify credential_id was passed through to store_state_token
+ call_kwargs = mock_mgr.store.store_state_token.call_args
+ assert call_kwargs.kwargs.get("credential_id") == "google-cred-1"
+
+ def test_login_credential_not_found_returns_404(self):
+ handler = MagicMock()
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=None)
+
+ resp = client.get(
+ "/google/login",
+ params={
+ "scopes": "openid",
+ "credential_id": "nonexistent",
+ },
+ )
+
+ assert resp.status_code == 404
+
+ def test_login_credential_provider_mismatch_returns_400(self):
+ """credential_id pointing to a Google cred when URL says github -> 400."""
+ google_cred = _make_google_oauth2_cred()
+ handler = MagicMock()
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=google_cred)
+
+ resp = client.get(
+ "/github/login",
+ params={
+ "scopes": "repo",
+ "credential_id": "google-cred-1",
+ },
+ )
+
+ assert resp.status_code == 400
+
+ def test_login_non_oauth2_credential_returns_400(self):
+ """credential_id pointing to an API key credential -> 400."""
+ api_key_cred = APIKeyCredentials(
+ id="apikey-1",
+ provider="github",
+ title="API Key",
+ api_key=SecretStr("ghp_key"),
+ )
+ handler = MagicMock()
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=api_key_cred)
+
+ resp = client.get(
+ "/github/login",
+ params={
+ "scopes": "repo",
+ "credential_id": "apikey-1",
+ },
+ )
+
+ assert resp.status_code == 400
+
+
+# ==================== Callback endpoint tests ==================== #
+
+
+class TestIncrementalOAuthCallback:
+ """Tests for the callback endpoint when upgrading credentials."""
+
+ def _make_state_with_credential_id(
+ self,
+ credential_id: str,
+ scopes: list[str] | None = None,
+ provider: str = "google",
+ ) -> OAuthState:
+ return OAuthState(
+ token="state-token",
+ provider=provider,
+ expires_at=9999999999,
+ scopes=(
+ scopes
+ if scopes is not None
+ else ["https://www.googleapis.com/auth/calendar.readonly"]
+ ),
+ credential_id=credential_id,
+ )
+
+ def test_callback_upgrades_existing_credential(self):
+ """When state has credential_id, should update existing credential."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"]
+ )
+ new_cred = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ]
+ )
+ state = self._make_state_with_credential_id("google-cred-1")
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+ mock_mgr.create = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ # Should call update, not create
+ mock_mgr.update.assert_called_once()
+ mock_mgr.create.assert_not_called()
+
+ def test_callback_upgrade_merges_scopes(self):
+ """Upgraded credential should have union of old + new scopes."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"]
+ )
+ new_cred = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ]
+ )
+ state = self._make_state_with_credential_id("google-cred-1")
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ data = resp.json()
+ assert set(data["scopes"]) == {
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ }
+
+ def test_callback_upgrade_preserves_id_and_title(self):
+ """Upgraded credential should keep its original ID and title."""
+ existing = _make_google_oauth2_cred(
+ cred_id="original-id", title="My Work Google"
+ )
+ new_cred = _make_google_oauth2_cred(cred_id="new-id-from-exchange")
+ state = self._make_state_with_credential_id("original-id")
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["id"] == "original-id"
+ assert data["title"] == "My Work Google"
+
+ def test_callback_upgrade_rejects_username_mismatch(self):
+ """Should reject if the new auth returns a different username."""
+ existing = _make_google_oauth2_cred(username="[email protected]")
+ new_cred = _make_google_oauth2_cred(username="[email protected]")
+ state = self._make_state_with_credential_id("google-cred-1")
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 400
+ assert "username" in resp.json()["detail"].lower()
+
+ def test_callback_implicit_merge_same_provider_username(self):
+ """Without credential_id, should auto-merge when same provider+username exists."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"]
+ )
+ new_cred = _make_google_oauth2_cred(
+ cred_id="new-cred-id",
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ],
+ username="[email protected]",
+ )
+ # State WITHOUT credential_id
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/calendar.readonly"],
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[existing])
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+ mock_mgr.create = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ # Should update the existing credential, not create a new one
+ mock_mgr.update.assert_called_once()
+ mock_mgr.create.assert_not_called()
+ # The returned ID should be the existing credential's ID
+ data = resp.json()
+ assert data["id"] == "google-cred-1"
+
+ def test_callback_no_implicit_merge_different_username(self):
+ """Without credential_id, different username should create new credential."""
+ existing = _make_google_oauth2_cred(username="[email protected]")
+ new_cred = _make_google_oauth2_cred(
+ cred_id="new-cred-id",
+ username="[email protected]",
+ )
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[existing])
+ mock_mgr.create = AsyncMock()
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ mock_mgr.create.assert_called_once()
+ mock_mgr.update.assert_not_called()
+ # Verify the implicit merge lookup was attempted
+ mock_mgr.store.get_creds_by_provider.assert_called_once()
+
+ def test_callback_creates_new_when_no_existing(self):
+ """Without credential_id and no matching credential, creates new."""
+ new_cred = _make_google_oauth2_cred()
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[])
+ mock_mgr.create = AsyncMock()
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ mock_mgr.create.assert_called_once()
+ mock_mgr.update.assert_not_called()
+ # Verify the implicit merge lookup was attempted
+ mock_mgr.store.get_creds_by_provider.assert_called_once()
+
+
+# ==================== Round 2: Review feedback tests ==================== #
+
+
+class TestManagedCredentialProtection:
+ """Managed/system credentials must not be upgradeable."""
+
+ def test_login_rejects_managed_credential_id(self):
+ """Explicit credential_id pointing to a managed credential -> 400."""
+ managed = _make_google_oauth2_cred(cred_id="managed-1")
+ managed.is_managed = True
+ handler = MagicMock()
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=managed)
+
+ resp = client.get(
+ "/google/login",
+ params={
+ "scopes": "https://www.googleapis.com/auth/calendar.readonly",
+ "credential_id": "managed-1",
+ },
+ )
+
+ assert resp.status_code == 400
+
+ def test_callback_rejects_upgrade_of_managed_credential(self):
+ """Callback with credential_id for a managed credential -> 400."""
+ managed = _make_google_oauth2_cred(cred_id="managed-1")
+ managed.is_managed = True
+ new_cred = _make_google_oauth2_cred()
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/calendar.readonly"],
+ credential_id="managed-1",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=managed)
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 400
+
+
+class TestMetadataNoneGuard:
+ """Metadata merge must handle None values."""
+
+ def test_callback_upgrade_handles_none_metadata(self):
+ """Upgrading credential with metadata=None should not crash."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"]
+ )
+ existing.metadata = None # type: ignore[assignment]
+ new_cred = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ]
+ )
+ new_cred.metadata = None # type: ignore[assignment]
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/calendar.readonly"],
+ credential_id="google-cred-1",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+
+
+class TestStateHelperScopesPattern:
+ """Test helper should handle empty scopes correctly."""
+
+ def test_make_state_preserves_empty_scopes(self):
+ """_make_state_with_credential_id([]) should keep empty list."""
+ state_maker = TestIncrementalOAuthCallback()
+ state = state_maker._make_state_with_credential_id("cred-1", scopes=[])
+ assert state.scopes == []
+
+
+class TestSystemCredentialProtection:
+ """Platform-owned system credentials must never be upgraded."""
+
+ def test_login_rejects_system_credential_id(self):
+ """Explicit credential_id pointing to a system credential -> 400."""
+ handler = MagicMock()
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch(
+ "backend.api.features.integrations.router.is_system_credential",
+ return_value=True,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock()
+
+ resp = client.get(
+ "/google/login",
+ params={
+ "scopes": "https://www.googleapis.com/auth/calendar.readonly",
+ "credential_id": "system-cred-id",
+ },
+ )
+
+ assert resp.status_code == 400
+ assert "system credentials" in resp.json()["detail"].lower()
+ # The store lookup must never happen for system credentials.
+ mock_mgr.store.get_creds_by_id.assert_not_called()
+
+ def test_callback_rejects_upgrade_of_system_credential(self):
+ """Defense-in-depth: even if a stale login state points at a system
+ credential, the callback-time `_upgrade_existing_credential` must
+ reject it before persisting anything."""
+ existing = _make_google_oauth2_cred(cred_id="sys-cred-id")
+ new_cred = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ]
+ )
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/calendar.readonly"],
+ credential_id="sys-cred-id",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ # is_system_credential returns True only when asked about "sys-cred-id"
+ # — emulating the real predicate that recognises platform-reserved IDs.
+ def _is_system(cred_id):
+ return cred_id == "sys-cred-id"
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch(
+ "backend.api.features.integrations.router.is_system_credential",
+ side_effect=_is_system,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 400
+ assert "system credentials" in resp.json()["detail"].lower()
+ # No write must have happened for the system credential.
+ mock_mgr.update.assert_not_called()
+
+ def test_implicit_merge_skips_system_credentials(self):
+ """The implicit (provider+username) merge filter must exclude system
+ credentials so a user login cannot accidentally overwrite one."""
+ system_match = _make_google_oauth2_cred(
+ cred_id="sys-cred-id", username="[email protected]"
+ )
+ new_cred = _make_google_oauth2_cred(
+ cred_id="new-cred-id",
+ scopes=system_match.scopes,
+ username="[email protected]",
+ )
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=system_match.scopes,
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ def _is_system(cred_id):
+ return cred_id == "sys-cred-id"
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch(
+ "backend.api.features.integrations.router.is_system_credential",
+ side_effect=_is_system,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(
+ return_value=[system_match]
+ )
+ mock_mgr.create = AsyncMock()
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ # Since the only provider+username match is a system credential, the
+ # callback must create a new credential rather than overwriting it.
+ mock_mgr.create.assert_called_once()
+ mock_mgr.update.assert_not_called()
+
+ def test_upgrade_rejects_provider_mismatch(self):
+ """Defense-in-depth: if a stale login somehow passed validation but the
+ stored credential's provider no longer matches the new token's
+ provider, the write-path must refuse to overwrite it."""
+ existing = _make_google_oauth2_cred(cred_id="mixed-up-cred")
+ # Simulate a provider drift: the new credential exchange returned a
+ # different provider than what's stored on disk.
+ new_cred = _make_github_oauth2_cred(cred_id="mixed-up-cred")
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ credential_id="mixed-up-cred",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 400
+ assert "provider" in resp.json()["detail"].lower()
+ mock_mgr.update.assert_not_called()
+
+
+class TestPreserveRefreshTokenAndUsername:
+ """Incremental callbacks must not silently drop refresh_token/username."""
+
+ def test_upgrade_preserves_existing_refresh_token_when_new_is_empty(self):
+ """If the new token response omits refresh_token, keep the existing one."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ )
+ existing.refresh_token = SecretStr("original-refresh")
+ # Google may omit refresh_token on incremental re-authorization.
+ new_cred = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ],
+ )
+ new_cred.refresh_token = None # type: ignore[assignment]
+
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=["https://www.googleapis.com/auth/calendar.readonly"],
+ credential_id="google-cred-1",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ captured: dict[str, OAuth2Credentials] = {}
+
+ async def _capture_update(_user_id, creds):
+ captured["creds"] = creds
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock(side_effect=_capture_update)
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ updated = captured["creds"]
+ assert updated.refresh_token is not None
+ assert updated.refresh_token.get_secret_value() == "original-refresh"
+
+ def test_upgrade_preserves_existing_username_when_new_is_empty(self):
+ """If the new response lacks username, keep the existing one."""
+ existing = _make_google_oauth2_cred(username="[email protected]")
+ new_cred = _make_google_oauth2_cred(scopes=existing.scopes)
+ new_cred.username = None
+
+ state = OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=existing.scopes,
+ credential_id="google-cred-1",
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ captured: dict[str, OAuth2Credentials] = {}
+
+ async def _capture_update(_user_id, creds):
+ captured["creds"] = creds
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock(side_effect=_capture_update)
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ assert captured["creds"].username == "[email protected]"
+
+
+class TestImplicitMergeScopeGuard:
+ """Implicit (provider+username) merge must not advertise scopes wider than
+ the freshly-minted token actually grants."""
+
+ def _build_state(self, scopes: list[str]) -> OAuthState:
+ return OAuthState(
+ token="state-token",
+ provider="google",
+ expires_at=9999999999,
+ scopes=scopes,
+ )
+
+ def test_implicit_merge_skipped_when_new_scopes_narrower(self):
+ """If the new token doesn't cover all existing scopes, create a
+ fresh credential instead of overwriting the existing one."""
+ existing = _make_google_oauth2_cred(
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ],
+ )
+ # New login only requested gmail — narrower than existing.
+ new_cred = _make_google_oauth2_cred(
+ cred_id="new-cred-id",
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ )
+ state = self._build_state(["https://www.googleapis.com/auth/gmail.readonly"])
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[existing])
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.create = AsyncMock()
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ mock_mgr.create.assert_called_once()
+ mock_mgr.update.assert_not_called()
+
+ def test_implicit_merge_allowed_when_new_scopes_are_superset(self):
+ """If the new token covers every existing scope, the implicit merge
+ path can proceed as before."""
+ existing = _make_google_oauth2_cred(
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ )
+ new_cred = _make_google_oauth2_cred(
+ cred_id="new-cred-id",
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ],
+ )
+ state = self._build_state(
+ [
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ]
+ )
+ handler = MagicMock()
+ handler.exchange_code_for_tokens = AsyncMock(return_value=new_cred)
+ handler.handle_default_scopes.return_value = state.scopes
+
+ with (
+ patch(
+ "backend.api.features.integrations.router._get_provider_oauth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[existing])
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.create = AsyncMock()
+ mock_mgr.update = AsyncMock()
+
+ resp = client.post(
+ "/google/callback",
+ json={"code": "auth-code", "state_token": "state-token"},
+ )
+
+ assert resp.status_code == 200
+ mock_mgr.update.assert_called_once()
+ mock_mgr.create.assert_not_called()
+
+
+class TestUpgradeExistingCredentialDoesNotMutateCaller:
+ """Cursor Low (thread PRRT_kwDOJKSTjM58rern): ``_upgrade_existing_credential``
+ used to mutate the caller's ``new_credentials`` object in-place
+ (overwriting id/title/scopes/metadata/refresh_token/username). Safe
+ today because all callers immediately replace their reference, but
+ fragile — a future reader of ``credentials`` after the call would
+ silently see overwritten values. Pin the contract so the caller's
+ object stays intact."""
+
+ @pytest.mark.asyncio
+ async def test_caller_credentials_object_is_unchanged_after_upgrade(self):
+ from backend.api.features.integrations.router import (
+ _upgrade_existing_credential,
+ )
+
+ existing = _make_google_oauth2_cred(
+ cred_id="existing-cred-id",
+ scopes=["https://www.googleapis.com/auth/gmail.readonly"],
+ username="[email protected]",
+ title="Existing title",
+ )
+ new_credentials = _make_google_oauth2_cred(
+ cred_id="new-cred-id-from-exchange",
+ scopes=[
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ ],
+ username="[email protected]",
+ title="New title from exchange",
+ )
+
+ # Snapshot the caller's object BEFORE the call so we can detect
+ # any in-place mutation by comparing afterwards.
+ snapshot = new_credentials.model_copy(deep=True)
+
+ with (
+ patch(
+ "backend.api.features.integrations.router.is_system_credential",
+ return_value=False,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.get_creds_by_id = AsyncMock(return_value=existing)
+ mock_mgr.update = AsyncMock()
+
+ returned = await _upgrade_existing_credential(
+ TEST_USER_ID, existing.id, new_credentials
+ )
+
+ # Caller's object must not have been touched — no id/title/scopes
+ # rewrite, no refresh_token/username/metadata mutation.
+ assert new_credentials.id == snapshot.id
+ assert new_credentials.title == snapshot.title
+ assert new_credentials.scopes == snapshot.scopes
+ assert new_credentials.metadata == snapshot.metadata
+ assert new_credentials.username == snapshot.username
+ assert (
+ new_credentials.refresh_token.get_secret_value()
+ if new_credentials.refresh_token
+ else None
+ ) == (
+ snapshot.refresh_token.get_secret_value()
+ if snapshot.refresh_token
+ else None
+ )
+
+ # The returned object carries the merged state, and is persisted.
+ assert returned.id == existing.id
+ assert set(returned.scopes) == {
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar.readonly",
+ }
+ mock_mgr.update.assert_called_once()
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index 1f97b5a987..ee88cdd1bd 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -87,14 +87,23 @@ async def login(
scopes: Annotated[
str, Query(title="Comma-separated list of authorization scopes")
] = "",
+ credential_id: Annotated[
+ str | None,
+ Query(title="ID of existing credential to upgrade scopes for"),
+ ] = None,
) -> LoginResponse:
handler = _get_provider_oauth_handler(request, provider)
requested_scopes = scopes.split(",") if scopes else []
+ if credential_id:
+ requested_scopes = await _prepare_scope_upgrade(
+ user_id, provider, credential_id, requested_scopes
+ )
+
# Generate and store a secure random state token along with the scopes
state_token, code_challenge = await creds_manager.store.store_state_token(
- user_id, provider, requested_scopes
+ user_id, provider, requested_scopes, credential_id=credential_id
)
login_url = handler.get_login_url(
requested_scopes, state_token, code_challenge=code_challenge
@@ -216,7 +225,9 @@ async def callback(
)
# TODO: Allow specifying `title` to set on `credentials`
- await creds_manager.create(user_id, credentials)
+ credentials = await _merge_or_create_credential(
+ user_id, provider, credentials, valid_state.credential_id
+ )
logger.debug(
f"Successfully processed OAuth callback for user {user_id} "
@@ -281,6 +292,115 @@ async def get_credential(
return to_meta_response(credential)
+class PickerTokenResponse(BaseModel):
+ """Short-lived OAuth access token shipped to the browser for rendering a
+ provider-hosted picker UI (e.g. Google Drive Picker). Deliberately narrow:
+ only the fields the client needs to initialize the picker widget. Issued
+ from the user's own stored credential so ownership and scope gating are
+ enforced by the credential lookup."""
+
+ access_token: str = Field(
+ description="OAuth access token suitable for the picker SDK call."
+ )
+ access_token_expires_at: int | None = Field(
+ default=None,
+ description="Unix timestamp at which the access token expires, if known.",
+ )
+
+
+# Allowlist of (provider, scopes) tuples that may mint picker tokens. Only
+# Drive-picker-capable scopes qualify so a caller can't use this endpoint to
+# extract a GitHub / other-provider OAuth token for unrelated purposes. If a
+# future provider integrates a hosted picker that needs a raw access token,
+# add its specific picker-relevant scopes here.
+_PICKER_TOKEN_ALLOWED_SCOPES: dict[ProviderName, frozenset[str]] = {
+ ProviderName.GOOGLE: frozenset(
+ [
+ "https://www.googleapis.com/auth/drive.file",
+ "https://www.googleapis.com/auth/drive.readonly",
+ "https://www.googleapis.com/auth/drive",
+ ]
+ ),
+}
+
+
+ "/{provider}/credentials/{cred_id}/picker-token",
+ summary="Issue a short-lived access token for a provider-hosted picker",
+ operation_id="postV1GetPickerToken",
+)
+async def get_picker_token(
+ provider: Annotated[
+ ProviderName, Path(title="The provider that owns the credentials")
+ ],
+ cred_id: Annotated[
+ str, Path(title="The ID of the OAuth2 credentials to mint a token from")
+ ],
+ user_id: Annotated[str, Security(get_user_id)],
+) -> PickerTokenResponse:
+ """Return the raw access token for an OAuth2 credential so the frontend
+ can initialize a provider-hosted picker (e.g. Google Drive Picker).
+
+ `GET /{provider}/credentials/{cred_id}` deliberately strips secrets (see
+ `CredentialsMetaResponse` + `TestGetCredentialReturnsMetaOnly` in
+ `router_test.py`). That hardening broke the Drive picker, which needs the
+ raw access token to call `google.picker.Builder.setOAuthToken(...)`. This
+ endpoint carves a narrow, explicit hole: the caller must own the
+ credential, it must be OAuth2, and the endpoint returns only the access
+ token + its expiry — nothing else about the credential. SDK-default
+ credentials are excluded for the same reason as `get_credential`.
+ """
+ if is_sdk_default(cred_id):
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="Credentials not found"
+ )
+
+ credential = await creds_manager.get(user_id, cred_id)
+ if not credential:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="Credentials not found"
+ )
+ if not provider_matches(credential.provider, provider):
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="Credentials not found"
+ )
+ if not isinstance(credential, OAuth2Credentials):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Picker tokens are only available for OAuth2 credentials",
+ )
+ if not credential.access_token:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Credential has no access token; reconnect the account",
+ )
+
+ # Gate on provider+scope: only credentials that actually grant access to
+ # a provider-hosted picker flow may mint a token through this endpoint.
+ # Prevents using this path to extract bearer tokens for unrelated OAuth
+ # integrations (e.g. GitHub) that happen to be stored under the same user.
+ allowed_scopes = _PICKER_TOKEN_ALLOWED_SCOPES.get(provider)
+ if not allowed_scopes:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(f"Picker tokens are not available for provider '{provider.value}'"),
+ )
+ cred_scopes = set(credential.scopes or [])
+ if cred_scopes.isdisjoint(allowed_scopes):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "Credential does not grant any scope eligible for the picker. "
+ "Reconnect with the appropriate scope."
+ ),
+ )
+
+ return PickerTokenResponse(
+ access_token=credential.access_token.get_secret_value(),
+ access_token_expires_at=credential.access_token_expires_at,
+ )
+
+
@router.post("/{provider}/credentials", status_code=201, summary="Create Credentials")
async def create_credentials(
user_id: Annotated[str, Security(get_user_id)],
@@ -574,6 +694,186 @@ async def _execute_webhook_preset_trigger(
# Continue processing - webhook should be resilient to individual failures
+# -------------------- INCREMENTAL AUTH HELPERS -------------------- #
+
+
+async def _prepare_scope_upgrade(
+ user_id: str,
+ provider: ProviderName,
+ credential_id: str,
+ requested_scopes: list[str],
+) -> list[str]:
+ """Validate an existing credential for scope upgrade and compute scopes.
+
+ For providers without native incremental auth (e.g. GitHub), returns the
+ union of existing + requested scopes. For providers that handle merging
+ server-side (e.g. Google with ``include_granted_scopes``), returns the
+ requested scopes unchanged.
+
+ Raises HTTPException on validation failure.
+ """
+ # Platform-owned system credentials must never be upgraded — scope
+ # changes here would leak across every user that shares them.
+ if is_system_credential(credential_id):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="System credentials cannot be upgraded",
+ )
+
+ existing = await creds_manager.store.get_creds_by_id(user_id, credential_id)
+ if not existing:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="Credential to upgrade not found",
+ )
+ if not isinstance(existing, OAuth2Credentials):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Only OAuth2 credentials can be upgraded",
+ )
+ if not provider_matches(existing.provider, provider.value):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Credential provider does not match the requested provider",
+ )
+ if existing.is_managed:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Managed credentials cannot be upgraded",
+ )
+
+ # Google handles scope merging via include_granted_scopes; others need
+ # the union of existing + new scopes in the login URL.
+ if provider != ProviderName.GOOGLE:
+ requested_scopes = list(set(requested_scopes) | set(existing.scopes))
+
+ return requested_scopes
+
+
+async def _merge_or_create_credential(
+ user_id: str,
+ provider: ProviderName,
+ credentials: OAuth2Credentials,
+ credential_id: str | None,
+) -> OAuth2Credentials:
+ """Either upgrade an existing credential or create a new one.
+
+ When *credential_id* is set (explicit upgrade), merges scopes and updates
+ the existing credential. Otherwise, checks for an implicit merge (same
+ provider + username) before falling back to creating a new credential.
+ """
+ if credential_id:
+ return await _upgrade_existing_credential(user_id, credential_id, credentials)
+
+ # Implicit merge: check for existing credential with same provider+username.
+ # Skip managed/system credentials and require a non-None username on both
+ # sides so we never accidentally merge unrelated credentials.
+ if credentials.username is None:
+ await creds_manager.create(user_id, credentials)
+ return credentials
+
+ existing_creds = await creds_manager.store.get_creds_by_provider(user_id, provider)
+ matching = next(
+ (
+ c
+ for c in existing_creds
+ if isinstance(c, OAuth2Credentials)
+ and not c.is_managed
+ and not is_system_credential(c.id)
+ and c.username is not None
+ and c.username == credentials.username
+ ),
+ None,
+ )
+ if matching:
+ # Only merge into the existing credential when the new token
+ # already covers every scope we're about to advertise on it.
+ # Without this guard we'd overwrite ``matching.access_token`` with
+ # a narrower token while storing a wider ``scopes`` list — the
+ # record would claim authorizations the token does not grant, and
+ # blocks using the lost scopes would fail with opaque 401/403s
+ # until the user hits re-auth. On a narrowing login, keep the
+ # two credentials separate instead.
+ if set(credentials.scopes).issuperset(set(matching.scopes)):
+ return await _upgrade_existing_credential(user_id, matching.id, credentials)
+
+ await creds_manager.create(user_id, credentials)
+ return credentials
+
+
+async def _upgrade_existing_credential(
+ user_id: str,
+ existing_cred_id: str,
+ new_credentials: OAuth2Credentials,
+) -> OAuth2Credentials:
+ """Merge scopes from *new_credentials* into an existing credential."""
+ # Defense-in-depth: re-check system and provider invariants right before
+ # the write. The login-time check in `_prepare_scope_upgrade` can go stale
+ # by the time the callback runs, and the implicit-merge path bypasses
+ # login-time validation entirely, so every write-path must enforce these
+ # on its own.
+ if is_system_credential(existing_cred_id):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="System credentials cannot be upgraded",
+ )
+ existing = await creds_manager.store.get_creds_by_id(user_id, existing_cred_id)
+ if not existing or not isinstance(existing, OAuth2Credentials):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Credential to upgrade not found",
+ )
+ if existing.is_managed:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Managed credentials cannot be upgraded",
+ )
+ if not provider_matches(existing.provider, new_credentials.provider):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Credential provider does not match the requested provider",
+ )
+
+ if (
+ existing.username
+ and new_credentials.username
+ and existing.username != new_credentials.username
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Username mismatch: authenticated as a different user",
+ )
+
+ # Operate on a copy so the caller's ``new_credentials`` object is not
+ # mutated out from under them. Every caller today immediately discards
+ # or replaces its reference, but the implicit-merge path in
+ # ``_merge_or_create_credential`` reads ``credentials.scopes`` before
+ # calling into us — a future reader after the call would otherwise
+ # silently see the overwritten values.
+ merged = new_credentials.model_copy(deep=True)
+ merged.id = existing.id
+ merged.title = existing.title
+ merged.scopes = list(set(existing.scopes) | set(new_credentials.scopes))
+ merged.metadata = {
+ **(existing.metadata or {}),
+ **(new_credentials.metadata or {}),
+ }
+ # Preserve the existing refresh_token and username if the incremental
+ # response doesn't carry them. Providers like Google only return a
+ # refresh_token on first authorization — dropping it here would orphan
+ # the credential on the next access-token expiry, forcing the user to
+ # re-auth from scratch. Username is similarly sticky: if we've already
+ # resolved it for this credential, keep it rather than silently
+ # blanking it on an incremental upgrade.
+ if not merged.refresh_token and existing.refresh_token:
+ merged.refresh_token = existing.refresh_token
+ merged.refresh_token_expires_at = existing.refresh_token_expires_at
+ if not merged.username and existing.username:
+ merged.username = existing.username
+ await creds_manager.update(user_id, merged)
+ return merged
+
+
# --------------------------- UTILITIES ---------------------------- #
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 47f8b7a770..dc66e2c6ea 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
@@ -568,3 +568,181 @@ class TestCleanupManagedCredentials:
_PROVIDERS.update(saved)
# No exception raised — cleanup failure is swallowed.
+
+
+class TestGetPickerToken:
+ """POST /{provider}/credentials/{cred_id}/picker-token must:
+ 1. Return the access token for OAuth2 creds the caller owns.
+ 2. 404 for non-owned, non-existent, or wrong-provider creds.
+ 3. 400 for non-OAuth2 creds (API key, host-scoped, user/password).
+ 4. 404 for SDK default creds (same hardening as get_credential).
+ 5. Preserve the `TestGetCredentialReturnsMetaOnly` contract — the
+ existing meta-only endpoint must still strip secrets even after
+ this picker-token endpoint exists."""
+
+ def test_oauth2_owner_gets_access_token(self):
+ # Use a Google cred with a drive.file scope — only picker-eligible
+ # (provider, scope) pairs can mint a token. GitHub-style creds are
+ # explicitly rejected; see `test_non_picker_provider_rejected_as_400`.
+ cred = _make_oauth2_cred(
+ cred_id="cred-gdrive",
+ provider="google",
+ )
+ cred.scopes = ["https://www.googleapis.com/auth/drive.file"]
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/google/credentials/cred-gdrive/picker-token")
+
+ assert resp.status_code == 200
+ data = resp.json()
+ # The whole point of this endpoint: the access token IS returned here.
+ assert data["access_token"] == "ghp_secret_token"
+ # Only the two declared fields come back — nothing else leaks.
+ assert set(data.keys()) <= {"access_token", "access_token_expires_at"}
+
+ def test_non_picker_provider_rejected_as_400(self):
+ """Provider allowlist: even with a valid OAuth2 credential, a
+ non-picker provider (GitHub, etc.) cannot mint a picker token.
+ Stops this endpoint from being used as a generic bearer-token
+ extraction path for any stored OAuth cred under the same user."""
+ cred = _make_oauth2_cred(provider="github")
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/github/credentials/cred-456/picker-token")
+
+ assert resp.status_code == 400
+ assert "not available for provider" in resp.json()["detail"]
+ assert "ghp_secret_token" not in str(resp.json())
+
+ def test_google_oauth_without_drive_scope_rejected(self):
+ """Scope allowlist: a Google OAuth2 cred that only carries non-picker
+ scopes (e.g. gmail.readonly, calendar) cannot mint a picker token.
+ Forces the frontend to reconnect with a Drive scope before the
+ picker is available."""
+ cred = _make_oauth2_cred(provider="google")
+ cred.scopes = [
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/calendar",
+ ]
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/google/credentials/cred-456/picker-token")
+
+ assert resp.status_code == 400
+ assert "picker" in resp.json()["detail"].lower()
+
+ def test_api_key_credential_rejected_as_400(self):
+ cred = _make_api_key_cred()
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/openai/credentials/cred-123/picker-token")
+
+ assert resp.status_code == 400
+ # API keys must not silently fall through to a 200 response of some
+ # other shape — the client should see a clear shape rejection.
+ body = str(resp.json())
+ assert "sk-secret-key-value" not in body
+
+ def test_user_password_credential_rejected_as_400(self):
+ cred = _make_user_password_cred()
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/openai/credentials/cred-789/picker-token")
+
+ assert resp.status_code == 400
+ body = str(resp.json())
+ assert "s3cret-pass" not in body
+ assert "admin" not in body
+
+ def test_host_scoped_credential_rejected_as_400(self):
+ cred = _make_host_scoped_cred()
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/openai/credentials/cred-host/picker-token")
+
+ assert resp.status_code == 400
+ assert "top-secret" not in str(resp.json())
+
+ def test_missing_credential_returns_404(self):
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=None)
+ resp = client.post("/github/credentials/nonexistent/picker-token")
+
+ assert resp.status_code == 404
+ assert resp.json()["detail"] == "Credentials not found"
+
+ def test_wrong_provider_returns_404(self):
+ """Symmetric with get_credential: provider mismatch is a generic
+ 404, not a 400, so we don't leak existence of a credential the
+ caller doesn't own on that provider."""
+ cred = _make_oauth2_cred(provider="github")
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/google/credentials/cred-456/picker-token")
+
+ assert resp.status_code == 404
+ assert resp.json()["detail"] == "Credentials not found"
+
+ def test_sdk_default_returns_404(self):
+ """SDK defaults are invisible to the user-facing API — picker-token
+ must not mint a token for them either."""
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock()
+ resp = client.post("/openai/credentials/openai-default/picker-token")
+
+ assert resp.status_code == 404
+ mock_mgr.get.assert_not_called()
+
+ def test_oauth2_without_access_token_returns_400(self):
+ """A stored OAuth2 cred whose access_token is missing can't satisfy
+ a picker init. Surface a clear reconnect instruction rather than
+ returning an empty string."""
+ cred = _make_oauth2_cred()
+ # Simulate a cred that lost its access token
+ object.__setattr__(cred, "access_token", None)
+
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.post("/github/credentials/cred-456/picker-token")
+
+ assert resp.status_code == 400
+ assert "reconnect" in resp.json()["detail"].lower()
+
+ def test_meta_only_endpoint_still_strips_access_token(self):
+ """Regression guard for the coexistence contract: the new
+ picker-token endpoint must NOT accidentally leak the token through
+ the meta-only GET endpoint. TestGetCredentialReturnsMetaOnly
+ covers this more broadly; this is a fast sanity check co-located
+ with the new endpoint's tests."""
+ cred = _make_oauth2_cred()
+ with patch(
+ "backend.api.features.integrations.router.creds_manager"
+ ) as mock_mgr:
+ mock_mgr.get = AsyncMock(return_value=cred)
+ resp = client.get("/github/credentials/cred-456")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert "access_token" not in body
+ assert "refresh_token" not in body
+ assert "ghp_secret_token" not in str(body)
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index 0743b461c6..0e21edf061 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -1804,7 +1804,7 @@ async def create_preset_from_graph_execution(
raise NotFoundError(
f"Graph #{graph_execution.graph_id} not found or accessible"
)
- elif len(graph.aggregate_credentials_inputs()) > 0:
+ elif len(graph.regular_credentials_inputs) > 0:
raise ValueError(
f"Graph execution #{graph_exec_id} can't be turned into a preset "
"because it was run before this feature existed "
diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.py
index 1cc29bd6d4..dc503c7ae1 100644
--- a/autogpt_platform/backend/backend/blocks/_base.py
+++ b/autogpt_platform/backend/backend/blocks/_base.py
@@ -333,6 +333,8 @@ class BlockSchema(BaseModel):
"credentials_provider": [config.get("provider", "google")],
"credentials_types": [config.get("type", "oauth2")],
"credentials_scopes": config.get("scopes"),
+ "is_auto_credential": True,
+ "input_field_name": info["field_name"],
}
result[kwarg_name] = CredentialsFieldInfo.model_validate(
auto_schema, by_alias=True
@@ -762,6 +764,61 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):
block_id=self.id,
)
+ # Ensure auto-credential kwargs are present before we hand off to
+ # run(). A missing auto-credential means the upstream field (e.g.
+ # a Google Drive picker) didn't embed a _credentials_id, or the
+ # executor couldn't resolve it. Without this guard, run() would
+ # crash with a TypeError (missing required kwarg) or an opaque
+ # AttributeError deep inside the provider SDK.
+ #
+ # Only raise when the field is ALSO not populated in input_data.
+ # ``_acquire_auto_credentials`` intentionally skips setting the
+ # kwarg in two legitimate cases — ``_credentials_id`` is ``None``
+ # (chained from upstream) or the field is missing from
+ # ``input_data`` at prep time (connected from upstream block).
+ # In both cases the upstream block is expected to populate the
+ # field value by execute time; raising here would break the
+ # documented ``AgentGoogleDriveFileInputBlock`` chaining pattern.
+ # Dry-run skips because the executor intentionally runs blocks
+ # without resolved creds for schema validation.
+ if not is_dry_run:
+ for (
+ kwarg_name,
+ info,
+ ) in self.input_schema.get_auto_credentials_fields().items():
+ kwargs.setdefault(kwarg_name, None)
+ if kwargs[kwarg_name] is not None:
+ continue
+ # Upstream-chained pattern: the field was populated by a
+ # prior node (e.g. AgentGoogleDriveFileInputBlock) whose
+ # output carries a resolved ``_credentials_id``.
+ # ``_acquire_auto_credentials`` deliberately doesn't set
+ # the kwarg in that case because the value isn't available
+ # at prep time; the executor fills it in before we reach
+ # ``_execute``. Trust it if the ``_credentials_id`` KEY
+ # is present — its value may be explicitly ``None`` in
+ # the chained case (see sentry thread
+ # PRRT_kwDOJKSTjM58sJfA). Checking truthiness here would
+ # falsely preempt run() for every valid chained graph
+ # that ships ``_credentials_id=None`` in the picker
+ # object. Mirror ``_acquire_auto_credentials``'s own
+ # skip rule, which treats ``cred_id is None`` as a
+ # chained-skip signal.
+ field_name = info["field_name"]
+ field_value = input_data.get(field_name)
+ if isinstance(field_value, dict) and "_credentials_id" in field_value:
+ continue
+ raise BlockExecutionError(
+ message=(
+ f"Missing credentials for '{kwarg_name}'. "
+ "Select a file via the picker (which carries "
+ "its credentials), or connect credentials for "
+ "this block."
+ ),
+ block_name=self.name,
+ block_id=self.id,
+ )
+
# Use the validated input data
async for output_name, output_data in self.run(
self.input_schema(**{k: v for k, v in input_data.items() if v is not None}),
diff --git a/autogpt_platform/backend/backend/blocks/google/__init__.py b/autogpt_platform/backend/backend/blocks/google/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/blocks/google/sheets_test.py b/autogpt_platform/backend/backend/blocks/google/sheets_test.py
new file mode 100644
index 0000000000..40a28f3cc7
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/google/sheets_test.py
@@ -0,0 +1,129 @@
+"""Edge-case tests for Google Sheets block credential handling.
+
+These pin the contract for the systemic auto-credential None-guard in
+``Block._execute()``: any block with an auto-credential field (via
+``GoogleDriveFileField`` etc.) that's called without resolved
+credentials must surface a clean, user-facing ``BlockExecutionError``
+— never a wrapped ``TypeError`` (missing required kwarg) or
+``AttributeError`` deep in the provider SDK.
+"""
+
+import pytest
+
+from backend.blocks.google.sheets import GoogleSheetsReadBlock
+from backend.util.exceptions import BlockExecutionError
+
+
+async def test_sheets_read_missing_credentials_yields_clean_error():
+ """Valid spreadsheet but no resolved credentials -> the systemic
+ None-guard in ``Block._execute()`` yields a ``Missing credentials``
+ error before ``run()`` is entered."""
+ block = GoogleSheetsReadBlock()
+ input_data = {
+ "spreadsheet": {
+ "id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "name": "Test Spreadsheet",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ "range": "Sheet1!A1:B2",
+ }
+
+ with pytest.raises(BlockExecutionError, match="Missing credentials"):
+ async for _ in block.execute(input_data):
+ pass
+
+
+async def test_sheets_read_no_spreadsheet_still_hits_credentials_guard():
+ """When neither spreadsheet nor credentials are present, the
+ credentials guard fires first (it runs before we hand off to
+ ``run()``). The user-facing message should still be the clean
+ ``Missing credentials`` one, not an opaque ``TypeError``."""
+ block = GoogleSheetsReadBlock()
+ input_data = {"range": "Sheet1!A1:B2"} # no spreadsheet, no credentials
+
+ with pytest.raises(BlockExecutionError, match="Missing credentials"):
+ async for _ in block.execute(input_data):
+ pass
+
+
+async def test_sheets_read_upstream_chained_value_skips_guard(mocker):
+ """A spreadsheet value chained in from an upstream input block (e.g.
+ ``AgentGoogleDriveFileInputBlock``) carries a resolved
+ ``_credentials_id`` that ``_acquire_auto_credentials`` didn't have
+ visibility into at prep time. The systemic None-guard must NOT
+ preempt run() in that case — otherwise every chained Drive-picker
+ pattern crashes with a bogus ``Missing credentials`` error.
+
+ We short-circuit past the guard by patching the Google API client
+ build; any error that escapes from run() is fine as long as the
+ ``Missing credentials`` message never surfaces."""
+ # Patch out the real Google Sheets client build so we don't hit the
+ # network and can detect we reached the provider SDK.
+ mocker.patch(
+ "backend.blocks.google.sheets.build",
+ side_effect=RuntimeError("api-boundary-reached"),
+ )
+
+ block = GoogleSheetsReadBlock()
+ input_data = {
+ "spreadsheet": {
+ "_credentials_id": "upstream-chained-cred-id",
+ "id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "name": "Upstream-chained sheet",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ "range": "Sheet1!A1:B2",
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ async for _ in block.execute(input_data):
+ pass
+
+ # The guard should skip (chained data present) and let us reach run(),
+ # which then hits the patched provider-SDK boundary. A "Missing
+ # credentials" error here would mean the None-guard broke the
+ # documented AgentGoogleDriveFileInputBlock chaining pattern.
+ assert "Missing credentials" not in str(exc_info.value)
+
+
+async def test_sheets_read_upstream_chained_with_explicit_none_cred_id_skips_guard(
+ mocker,
+):
+ """Sentry HIGH regression (thread PRRT_kwDOJKSTjM58sJfA): the
+ documented chained-upstream pattern ships the spreadsheet dict with
+ ``_credentials_id=None`` — the executor fills in the resolved id
+ between prep time and ``run()``. The previous ``_base.py`` guard
+ used ``field_value.get("_credentials_id")`` and treated the falsy
+ ``None`` value as "missing", raising ``BlockExecutionError`` on
+ every chained graph.
+
+ Pin the contract: the presence of the ``_credentials_id`` key — not
+ its truthiness — is what signals "trust the skip". A dict with
+ ``_credentials_id: None`` must not preempt run()."""
+ mocker.patch(
+ "backend.blocks.google.sheets.build",
+ side_effect=RuntimeError("api-boundary-reached"),
+ )
+
+ block = GoogleSheetsReadBlock()
+ input_data = {
+ "spreadsheet": {
+ "_credentials_id": None, # explicit None — chained-upstream shape
+ "id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
+ "name": "Upstream-chained sheet (None cred_id)",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ "range": "Sheet1!A1:B2",
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ async for _ in block.execute(input_data):
+ pass
+
+ # The guard must not raise "Missing credentials" for this shape.
+ # We expect to reach run() and hit the patched provider-SDK boundary.
+ assert "Missing credentials" not in str(exc_info.value)
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.py
index ad3836e937..cb5270291a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py
@@ -151,7 +151,7 @@ def build_missing_credentials_from_graph(
preserving all supported credential types for each field.
"""
matched_keys = set(matched_credentials.keys()) if matched_credentials else set()
- aggregated_fields = graph.aggregate_credentials_inputs()
+ aggregated_fields = graph.regular_credentials_inputs
return {
field_key: _serialize_missing_credential(field_key, field_info)
@@ -371,7 +371,7 @@ async def match_user_credentials_to_graph(
missing_creds: list[str] = []
# Get aggregated credentials requirements from the graph
- aggregated_creds = graph.aggregate_credentials_inputs()
+ aggregated_creds = graph.regular_credentials_inputs
logger.debug(
f"Matching credentials for graph {graph.id}: {len(aggregated_creds)} required"
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
new file mode 100644
index 0000000000..971b3da973
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
@@ -0,0 +1,76 @@
+"""Tests for chat tools utility functions."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.data.model import CredentialsFieldInfo
+
+
+def _make_regular_field() -> CredentialsFieldInfo:
+ return CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ },
+ by_alias=True,
+ )
+
+
+def test_build_missing_credentials_excludes_auto_creds():
+ """
+ build_missing_credentials_from_graph() should use regular_credentials_inputs
+ and thus exclude auto_credentials from the "missing" set.
+ """
+ from backend.copilot.tools.utils import build_missing_credentials_from_graph
+
+ regular_field = _make_regular_field()
+
+ mock_graph = MagicMock()
+ # regular_credentials_inputs should only return the non-auto field
+ mock_graph.regular_credentials_inputs = {
+ "github_api_key": (regular_field, {("node-1", "credentials")}, True),
+ }
+
+ result = build_missing_credentials_from_graph(mock_graph, matched_credentials=None)
+
+ # Should include the regular credential
+ assert "github_api_key" in result
+ # Should NOT include the auto_credential (not in regular_credentials_inputs)
+ assert "google_oauth2" not in result
+
+
+async def test_match_user_credentials_excludes_auto_creds():
+ """
+ match_user_credentials_to_graph() should use regular_credentials_inputs
+ and thus exclude auto_credentials from matching.
+ """
+ from backend.copilot.tools.utils import match_user_credentials_to_graph
+
+ regular_field = _make_regular_field()
+
+ mock_graph = MagicMock()
+ mock_graph.id = "test-graph"
+ # regular_credentials_inputs returns only non-auto fields
+ mock_graph.regular_credentials_inputs = {
+ "github_api_key": (regular_field, {("node-1", "credentials")}, True),
+ }
+
+ # Mock the credentials manager to return no credentials
+ with patch(
+ "backend.copilot.tools.utils.IntegrationCredentialsManager"
+ ) as MockCredsMgr:
+ mock_store = AsyncMock()
+ mock_store.get_all_creds.return_value = []
+ MockCredsMgr.return_value.store = mock_store
+
+ matched, missing = await match_user_credentials_to_graph(
+ user_id="test-user", graph=mock_graph
+ )
+
+ # No credentials available, so github should be missing
+ assert len(matched) == 0
+ assert len(missing) == 1
+ assert "github_api_key" in missing[0]
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.py
index a140f3ec84..6b25a2792c 100644
--- a/autogpt_platform/backend/backend/data/graph.py
+++ b/autogpt_platform/backend/backend/data/graph.py
@@ -440,8 +440,7 @@ class GraphModel(Graph, GraphMeta):
@computed_field
@property
def credentials_input_schema(self) -> dict[str, Any]:
- graph_credentials_inputs = self.aggregate_credentials_inputs()
-
+ graph_credentials_inputs = self.regular_credentials_inputs
logger.debug(
f"Combined credentials input fields for graph #{self.id} ({self.name}): "
f"{graph_credentials_inputs}"
@@ -620,6 +619,28 @@ class GraphModel(Graph, GraphMeta):
for key, (field_info, node_field_pairs) in combined.items()
}
+ @property
+ def regular_credentials_inputs(
+ self,
+ ) -> dict[str, tuple[CredentialsFieldInfo, set[tuple[str, str]], bool]]:
+ """Credentials that need explicit user mapping (CredentialsMetaInput fields)."""
+ return {
+ k: v
+ for k, v in self.aggregate_credentials_inputs().items()
+ if not v[0].is_auto_credential
+ }
+
+ @property
+ def auto_credentials_inputs(
+ self,
+ ) -> dict[str, tuple[CredentialsFieldInfo, set[tuple[str, str]], bool]]:
+ """Credentials embedded in file fields (_credentials_id), resolved at execution time."""
+ return {
+ k: v
+ for k, v in self.aggregate_credentials_inputs().items()
+ if v[0].is_auto_credential
+ }
+
def reassign_ids(self, user_id: str, reassign_graph_id: bool = False):
"""
Reassigns all IDs in the graph to new UUIDs.
@@ -670,6 +691,21 @@ class GraphModel(Graph, GraphMeta):
) and graph_id in graph_id_map:
node.input_default["graph_id"] = graph_id_map[graph_id]
+ # Clear auto-credentials references (e.g., _credentials_id in
+ # GoogleDriveFile fields) so the new user must re-authenticate
+ # with their own account. We null the entire field rather than
+ # just the _credentials_id key — a partial object (e.g. a bare
+ # {"id": "...", "name": "..."} left over after stripping) would
+ # be rejected by the auto-credentials validator added below,
+ # breaking fork_graph() for agents that previously had a
+ # picker-selected Drive file.
+ for node in graph.nodes:
+ if not node.input_default:
+ continue
+ for key, value in list(node.input_default.items()):
+ if isinstance(value, dict) and "_credentials_id" in value:
+ node.input_default[key] = None
+
def validate_graph(
self,
for_run: bool = False,
@@ -836,6 +872,90 @@ class GraphModel(Graph, GraphMeta):
)
)
+ # Validate auto-credentials fields (e.g. GoogleDriveFileField).
+ # Blocks with auto-credentials fields expect an *object* whose
+ # embedded `_credentials_id` carries the user's credential at
+ # run time — that field is only populated by a provider-specific
+ # picker (e.g. the Google Drive picker for google-drive-picker
+ # format). Hardcoding a bare ID or a partial object into
+ # `input_default` produces an agent that either fails save-time
+ # schema validation (bare string rejected by pydantic) or passes
+ # it but crashes at execution time because
+ # `_acquire_auto_credentials` has no `_credentials_id` to resolve.
+ # Catch the anti-pattern for any auto-credentials field; tailor
+ # the remediation text to whichever format is declared so that
+ # future auto-credentials pickers don't inherit a stale hint.
+ for kwarg_name, info in InputSchema.get_auto_credentials_fields().items():
+ field_name = info["field_name"]
+ field_schema = InputSchema.get_field_schema(field_name)
+
+ # An upstream link will supply the value at run time — fine.
+ has_incoming = any(
+ sanitize_pin_name(link.sink_name) == sanitize_pin_name(field_name)
+ for link in input_links.get(node.id, [])
+ )
+ if has_incoming:
+ continue
+
+ value = node.input_default.get(field_name)
+ if value is None or value == "":
+ # Nothing set and nothing linked. Existing required-field
+ # check above already handles the "required but missing"
+ # case; we don't double-report here.
+ continue
+
+ picker_format = field_schema.get("format")
+ if picker_format == "google-drive-picker":
+ remediation = (
+ f"Add an AgentGoogleDriveFileInputBlock node to the "
+ f"graph and link its 'result' output to "
+ f"{field_name!r} instead. That block renders a "
+ f"Google Drive picker at run time so whoever runs "
+ f"the agent supplies their own credentials via the "
+ f"picked file."
+ )
+ else:
+ # Generic fallback for any future auto-credentials format
+ # we haven't written specific guidance for yet.
+ remediation = (
+ f"This field expects a picker-populated object "
+ f"containing a '_credentials_id'. Wire the matching "
+ f"input block for this provider into {field_name!r} "
+ f"so whoever runs the agent supplies their own "
+ f"credentials at run time."
+ )
+
+ if isinstance(value, str):
+ node_errors[node.id][field_name] = (
+ f"{field_name!r} was set to a bare string ID. This "
+ f"field expects an object carrying the user's "
+ f"credentials; a hardcoded ID can't authenticate. "
+ f"{remediation}"
+ )
+ continue
+
+ if isinstance(value, dict) and not value.get("_credentials_id"):
+ node_errors[node.id][field_name] = (
+ f"{field_name!r} is hardcoded without credentials "
+ f"(no '_credentials_id'). This field needs the "
+ f"user's OAuth credential, which is only populated "
+ f"by the picker. {remediation}"
+ )
+ continue
+
+ # Catch-all: any other type (int, bool, list, ...) falls
+ # through both isinstance checks today and reaches
+ # `_acquire_auto_credentials` at execute time, where
+ # ``.get("_credentials_id")`` on a non-dict raises
+ # AttributeError. Surface a clean error here instead.
+ if not isinstance(value, (str, dict)):
+ node_errors[node.id][field_name] = (
+ f"{field_name!r} is set to a {type(value).__name__} "
+ f"value ({value!r}). This field expects an object "
+ f"carrying the user's credentials. {remediation}"
+ )
+ continue
+
# Validate dependencies between fields
for field_name in input_fields.keys():
field_json_schema = InputSchema.get_field_schema(field_name)
diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.py
index 3c4ad15c2b..fa985385e5 100644
--- a/autogpt_platform/backend/backend/data/graph_test.py
+++ b/autogpt_platform/backend/backend/data/graph_test.py
@@ -39,6 +39,22 @@ def mock_embedding_functions():
yield
[email protected](autouse=True)
+def _enable_google_blocks_for_auto_cred_tests(request, monkeypatch):
+ # The Google Sheets / Gmail blocks auto-disable when OAuth client
+ # env vars are unset — which is the case in CI. The graph validator
+ # short-circuits disabled blocks at graph.py:798 before reaching the
+ # auto-credentials branch we want to exercise. Flip the disable
+ # flags for the ``test_auto_credentials_*`` group so the validator
+ # actually runs the new anti-pattern check; other tests in this
+ # file are unaffected.
+ if not request.node.name.startswith("test_auto_credentials_"):
+ return
+ monkeypatch.setattr("backend.blocks.google.sheets.GOOGLE_SHEETS_DISABLED", False)
+ monkeypatch.setattr("backend.blocks.google.gmail.GOOGLE_OAUTH_IS_CONFIGURED", True)
+ monkeypatch.setattr("backend.blocks.google._auth.GOOGLE_OAUTH_IS_CONFIGURED", True)
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_graph_creation(server: SpinTestServer, snapshot: Snapshot):
"""
@@ -488,6 +504,332 @@ def test_node_credentials_optional_with_other_metadata():
assert node.metadata["customized_name"] == "My Custom Node"
+# ============================================================================
+# Tests for CredentialsFieldInfo.combine() field propagation
+def test_combine_preserves_is_auto_credential_flag():
+ """
+ CredentialsFieldInfo.combine() must propagate is_auto_credential and
+ input_field_name to the combined result. Regression test for reviewer
+ finding that combine() dropped these fields.
+ """
+ from backend.data.model import CredentialsFieldInfo
+
+ auto_field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["google"],
+ "credentials_types": ["oauth2"],
+ "credentials_scopes": ["drive.readonly"],
+ "is_auto_credential": True,
+ "input_field_name": "spreadsheet",
+ },
+ by_alias=True,
+ )
+
+ # combine() takes *args of (field_info, key) tuples
+ combined = CredentialsFieldInfo.combine(
+ (auto_field, ("node-1", "credentials")),
+ (auto_field, ("node-2", "credentials")),
+ )
+
+ assert len(combined) == 1
+ group_key = next(iter(combined))
+ combined_info, combined_keys = combined[group_key]
+
+ assert combined_info.is_auto_credential is True
+ assert combined_info.input_field_name == "spreadsheet"
+ assert combined_keys == {("node-1", "credentials"), ("node-2", "credentials")}
+
+
+def test_combine_preserves_regular_credential_defaults():
+ """Regular credentials should have is_auto_credential=False after combine()."""
+ from backend.data.model import CredentialsFieldInfo
+
+ regular_field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ },
+ by_alias=True,
+ )
+
+ combined = CredentialsFieldInfo.combine(
+ (regular_field, ("node-1", "credentials")),
+ )
+
+ group_key = next(iter(combined))
+ combined_info, _ = combined[group_key]
+
+ assert combined_info.is_auto_credential is False
+ assert combined_info.input_field_name is None
+
+
+# ============================================================================
+# Tests for _reassign_ids credential clearing (Fix 3: SECRT-1772)
+
+
+def test_reassign_ids_clears_credentials_id():
+ """
+ [SECRT-1772] _reassign_ids should null out the entire
+ GoogleDriveFile-style input_default field so forked agents
+ don't retain the original creator's credential references AND
+ don't leave a partial file object (which would be rejected by
+ the auto-credentials validator).
+ """
+ from backend.data.graph import GraphModel
+
+ node = Node(
+ id="node-1",
+ block_id=StoreValueBlock().id,
+ input_default={
+ "spreadsheet": {
+ "_credentials_id": "original-cred-id",
+ "id": "file-123",
+ "name": "test.xlsx",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ "url": "https://docs.google.com/spreadsheets/d/file-123",
+ },
+ },
+ )
+
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})
+
+ # The entire field is nulled — leaving a partial file object behind
+ # would be rejected by the auto-credentials validator, breaking
+ # fork_graph() for agents that previously had a picker-selected file.
+ assert graph.nodes[0].input_default["spreadsheet"] is None
+
+
+def test_reassign_ids_preserves_non_credential_fields():
+ """
+ Regression guard: _reassign_ids should NOT null fields that don't
+ carry a _credentials_id (e.g., plain user-entered values).
+ """
+ from backend.data.graph import GraphModel
+
+ node = Node(
+ id="node-1",
+ block_id=StoreValueBlock().id,
+ input_default={
+ # No _credentials_id — a plain dict that should be preserved
+ "config": {
+ "id": "file-123",
+ "name": "test.xlsx",
+ },
+ },
+ )
+
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})
+
+ field = graph.nodes[0].input_default["config"]
+ assert field == {"id": "file-123", "name": "test.xlsx"}
+
+
+def test_reassign_ids_handles_no_credentials():
+ """
+ Regression guard: _reassign_ids should not error when input_default
+ has no dict fields with _credentials_id.
+ """
+ from backend.data.graph import GraphModel
+
+ node = Node(
+ id="node-1",
+ block_id=StoreValueBlock().id,
+ input_default={
+ "input": "some value",
+ "another_input": 42,
+ },
+ )
+
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})
+
+ # Should not error, fields unchanged
+ assert graph.nodes[0].input_default["input"] == "some value"
+ assert graph.nodes[0].input_default["another_input"] == 42
+
+
+def test_reassign_ids_handles_multiple_credential_fields():
+ """
+ [SECRT-1772] When a node has multiple dict fields with _credentials_id,
+ ALL of them should be cleared.
+ """
+ from backend.data.graph import GraphModel
+
+ node = Node(
+ id="node-1",
+ block_id=StoreValueBlock().id,
+ input_default={
+ "spreadsheet": {
+ "_credentials_id": "cred-1",
+ "id": "file-1",
+ "name": "file1.xlsx",
+ },
+ "doc_file": {
+ "_credentials_id": "cred-2",
+ "id": "file-2",
+ "name": "file2.docx",
+ },
+ "plain_input": "not a dict",
+ },
+ )
+
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})
+
+ # Each auto-credential field is nulled entirely — not just the id key —
+ # so the validator accepts the forked graph.
+ assert graph.nodes[0].input_default["spreadsheet"] is None
+ assert graph.nodes[0].input_default["doc_file"] is None
+ assert graph.nodes[0].input_default["plain_input"] == "not a dict"
+
+
+# ============================================================================
+# Tests for discriminate() field propagation
+def test_discriminate_preserves_is_auto_credential_flag():
+ """
+ CredentialsFieldInfo.discriminate() must propagate is_auto_credential and
+ input_field_name to the discriminated result. Regression test for
+ discriminate() dropping these fields (same class of bug as combine()).
+ """
+ from backend.data.model import CredentialsFieldInfo
+
+ auto_field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["google", "openai"],
+ "credentials_types": ["oauth2"],
+ "credentials_scopes": ["drive.readonly"],
+ "is_auto_credential": True,
+ "input_field_name": "spreadsheet",
+ "discriminator": "model",
+ "discriminator_mapping": {"gpt-4": "openai", "gemini": "google"},
+ },
+ by_alias=True,
+ )
+
+ discriminated = auto_field.discriminate("gemini")
+
+ assert discriminated.is_auto_credential is True
+ assert discriminated.input_field_name == "spreadsheet"
+ assert discriminated.provider == frozenset(["google"])
+
+
+def test_discriminate_preserves_regular_credential_defaults():
+ """Regular credentials should have is_auto_credential=False after discriminate()."""
+ from backend.data.model import CredentialsFieldInfo
+
+ regular_field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["google", "openai"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ "discriminator": "model",
+ "discriminator_mapping": {"gpt-4": "openai", "gemini": "google"},
+ },
+ by_alias=True,
+ )
+
+ discriminated = regular_field.discriminate("gpt-4")
+
+ assert discriminated.is_auto_credential is False
+ assert discriminated.input_field_name is None
+ assert discriminated.provider == frozenset(["openai"])
+
+
+# ============================================================================
+# Tests for credentials_input_schema excluding auto_credentials
+def test_credentials_input_schema_excludes_auto_creds():
+ """
+ GraphModel.credentials_input_schema should exclude auto_credentials
+ (is_auto_credential=True) from the schema. Auto_credentials are
+ transparently resolved at execution time via file picker data.
+ """
+ from datetime import datetime, timezone
+ from unittest.mock import PropertyMock, patch
+
+ from backend.data.graph import GraphModel, NodeModel
+ from backend.data.model import CredentialsFieldInfo
+
+ regular_field_info = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ },
+ by_alias=True,
+ )
+
+ graph = GraphModel(
+ id="test-graph",
+ version=1,
+ name="Test",
+ description="Test",
+ user_id="test-user",
+ created_at=datetime.now(timezone.utc),
+ nodes=[
+ NodeModel(
+ id="node-1",
+ block_id=StoreValueBlock().id,
+ input_default={},
+ graph_id="test-graph",
+ graph_version=1,
+ ),
+ ],
+ links=[],
+ )
+
+ # Mock regular_credentials_inputs to return only the non-auto field (3-tuple)
+ regular_only = {
+ "github_credentials": (
+ regular_field_info,
+ {("node-1", "credentials")},
+ True,
+ ),
+ }
+
+ with patch.object(
+ type(graph),
+ "regular_credentials_inputs",
+ new_callable=PropertyMock,
+ return_value=regular_only,
+ ):
+ schema = graph.credentials_input_schema
+ field_names = set(schema.get("properties", {}).keys())
+ # Should include regular credential but NOT auto_credential
+ assert "github_credentials" in field_names
+ assert "google_credentials" not in field_names
+
+
# ============================================================================
# Tests for MCP Credential Deduplication
# ============================================================================
@@ -1479,3 +1821,356 @@ def test_generate_schema_raises_value_error_when_name_missing():
"""
with pytest.raises(ValueError):
GraphModel._generate_schema((AgentInputBlock.Input, {}))
+
+
+# ============================================================================
+# Tests for the auto-credentials hardcoded-input anti-pattern validator
+# (catches what Mehmet's agent-builder session produced: CoPilot hardcoded
+# file IDs into GoogleSheetsReadBlock.constantInput.spreadsheet across 13
+# save attempts instead of wiring an AgentGoogleDriveFileInputBlock).
+# ============================================================================
+
+
+def _sheets_graph(spreadsheet_value: Any) -> Graph:
+ """Build a 1-node graph with a GoogleSheetsReadBlock whose `spreadsheet`
+ input_default is whatever the test wants to pin. No incoming links."""
+ from backend.blocks.google.sheets import GoogleSheetsReadBlock
+
+ node = Node(
+ id="00000000-0000-0000-0000-000000000001",
+ block_id=GoogleSheetsReadBlock().id,
+ input_default={
+ "spreadsheet": spreadsheet_value,
+ "range": "Sheet1!A1:B2",
+ },
+ )
+ return Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+
+def test_auto_credentials_bare_string_real_id_rejected():
+ """Mehmet's v7-v10 shape: CoPilot stuffed the bare Drive ID into
+ constantInput.spreadsheet. Pydantic already rejects this at schema
+ validation, but the Node model stores whatever dict the caller gave —
+ so the graph validator is the last line of defence when code paths
+ bypass that (e.g. raw API callers). Must emit a clean error naming
+ AgentGoogleDriveFileInputBlock."""
+ graph = _sheets_graph("1KAv8hhChef7a5ycn6Al1M4DdkiG_PVcKQ_tYkRpGA-I")
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors, errors
+ msg = errors[graph.nodes[0].id]["spreadsheet"]
+ assert "bare string" in msg
+ assert "AgentGoogleDriveFileInputBlock" in msg
+ assert "'result'" in msg
+
+
+def test_auto_credentials_placeholder_string_rejected():
+ """Mehmet's v4-v6 shape: a non-ID placeholder the LLM made up
+ ("SHEETS_ID_BURAYA"). Same anti-pattern, same error — we don't try
+ to distinguish "looks like a Drive ID" from "obvious placeholder";
+ any bare string here is wrong."""
+ graph = _sheets_graph("SHEETS_ID_BURAYA")
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors
+ msg = errors[graph.nodes[0].id]["spreadsheet"]
+ assert "bare string" in msg
+ assert "AgentGoogleDriveFileInputBlock" in msg
+
+
+def test_auto_credentials_partial_object_missing_cred_id_rejected():
+ """Mehmet's v11-v13 shape: CoPilot finally learned to wrap the ID in
+ an object (`{"id": "..."}`), so pydantic's `GoogleDriveFile` schema
+ accepts it — but there's still no `_credentials_id`, so
+ `_acquire_auto_credentials` in the executor would raise
+ "Authentication missing" at run time. Validator must catch this
+ before save and tell the author to use the input block."""
+ graph = _sheets_graph({"id": "1KAv8hhChef7a5ycn6Al1M4DdkiG_PVcKQ_tYkRpGA-I"})
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors
+ msg = errors[graph.nodes[0].id]["spreadsheet"]
+ assert "_credentials_id" in msg
+ assert "AgentGoogleDriveFileInputBlock" in msg
+
+
+def test_auto_credentials_empty_credentials_id_rejected():
+ """An empty-string `_credentials_id` has the same runtime effect as
+ no `_credentials_id` at all — `_acquire_auto_credentials` treats
+ falsy cred_id as missing. Validator must reject this too."""
+ graph = _sheets_graph(
+ {
+ "id": "1KAv8hhChef7a5ycn6Al1M4DdkiG_PVcKQ_tYkRpGA-I",
+ "_credentials_id": "",
+ }
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors
+ assert "_credentials_id" in errors[graph.nodes[0].id]["spreadsheet"]
+
+
+def test_auto_credentials_fully_hydrated_object_accepted():
+ """Author pre-selected a file via the builder's Drive picker: the
+ object carries a real `_credentials_id` plus metadata. Validator
+ must NOT flag this — it's the legitimate author-flow shape and
+ forking clears `_credentials_id` separately via `_reassign_ids`."""
+ graph = _sheets_graph(
+ {
+ "_credentials_id": "cred-abc-def",
+ "id": "1KAv8hhChef7a5ycn6Al1M4DdkiG_PVcKQ_tYkRpGA-I",
+ "name": "Q4 Budget",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ "url": "https://docs.google.com/spreadsheets/d/1KAv8…",
+ }
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert (
+ graph.nodes[0].id not in errors
+ or "spreadsheet" not in errors[graph.nodes[0].id]
+ ), errors
+
+
+def test_auto_credentials_with_upstream_link_accepted():
+ """The correct pattern: an AgentGoogleDriveFileInputBlock feeds its
+ `result` output into `GoogleSheetsReadBlock.spreadsheet`. Even with
+ no `input_default.spreadsheet`, validator must pass — because the
+ link guarantees the value (with `_credentials_id`) arrives at run
+ time."""
+ from backend.blocks.google.sheets import GoogleSheetsReadBlock
+ from backend.blocks.io import AgentGoogleDriveFileInputBlock
+
+ drive_input_node = Node(
+ id="00000000-0000-0000-0000-000000000001",
+ block_id=AgentGoogleDriveFileInputBlock().id,
+ input_default={
+ "name": "spreadsheet_input",
+ "title": "Select Spreadsheet",
+ "allowed_views": ["SPREADSHEETS"],
+ },
+ )
+ sheets_node = Node(
+ id="00000000-0000-0000-0000-000000000002",
+ block_id=GoogleSheetsReadBlock().id,
+ input_default={"range": "Sheet1!A1:B2"}, # spreadsheet omitted on purpose
+ )
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[drive_input_node, sheets_node],
+ links=[
+ Link(
+ source_id=drive_input_node.id,
+ source_name="result",
+ sink_id=sheets_node.id,
+ sink_name="spreadsheet",
+ )
+ ],
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert (
+ sheets_node.id not in errors or "spreadsheet" not in errors[sheets_node.id]
+ ), errors
+
+
+def test_auto_credentials_unset_does_not_emit_double_error():
+ """If the field is missing AND not linked, the existing required-field
+ check — not our new rule — owns the error. Drive fields default to
+ None so they aren't required, meaning validator should simply emit
+ nothing for `spreadsheet` here."""
+ from backend.blocks.google.sheets import GoogleSheetsReadBlock
+
+ node = Node(
+ id="00000000-0000-0000-0000-000000000001",
+ block_id=GoogleSheetsReadBlock().id,
+ input_default={"range": "Sheet1!A1:B2"},
+ )
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert node.id not in errors or "spreadsheet" not in errors[node.id], errors
+
+
+def test_auto_credentials_bare_string_does_not_over_match_non_auto_fields():
+ """Sanity: a non-auto-credential field on the same node with a bare
+ string value must NOT be flagged by the auto-credentials rule. The
+ `range` field is a plain string — validator should leave it alone."""
+ graph = _sheets_graph(
+ {
+ "_credentials_id": "cred-abc",
+ "id": "file-id",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ }
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ # spreadsheet is fine (fully hydrated), range is a plain string (fine)
+ assert graph.nodes[0].id not in errors, errors
+
+
+def test_auto_credentials_error_on_every_bad_node_independently():
+ """Mehmet's real graph had THREE Drive-consuming blocks in one graph,
+ each with the same anti-pattern (Sheets x2, Docs, SheetsUpdate in
+ v13 — actually 3 Sheets-family nodes + Docs). The validator must
+ flag each separately; it must not stop at the first bad one."""
+ from backend.blocks.google.sheets import (
+ GoogleSheetsReadBlock,
+ GoogleSheetsUpdateCellBlock,
+ )
+
+ bad1 = Node(
+ id="00000000-0000-0000-0000-000000000001",
+ block_id=GoogleSheetsReadBlock().id,
+ input_default={
+ "spreadsheet": "bare-id-1",
+ "range": "Sheet1!A1",
+ },
+ )
+ bad2 = Node(
+ id="00000000-0000-0000-0000-000000000002",
+ block_id=GoogleSheetsUpdateCellBlock().id,
+ input_default={
+ "spreadsheet": {"id": "partial-object-only"},
+ "cell": "A1",
+ "value_input_option": "RAW",
+ },
+ )
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[bad1, bad2],
+ links=[],
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert bad1.id in errors, errors
+ assert "bare string" in errors[bad1.id]["spreadsheet"]
+ assert bad2.id in errors
+ assert "_credentials_id" in errors[bad2.id]["spreadsheet"]
+
+
+def test_auto_credentials_non_picker_format_gets_generic_remediation():
+ """Defence against future regression: if a block ever exposes an
+ auto-credentials field whose `format` isn't `google-drive-picker`,
+ the validator must still flag the same bad shapes but the error
+ text must NOT reference AgentGoogleDriveFileInputBlock (which is
+ Drive-specific). Otherwise we'd ship misleading guidance the moment
+ another provider gets its own picker. We simulate the future case
+ by patching get_field_schema on a real block."""
+ from backend.blocks.google.sheets import GoogleSheetsReadBlock
+
+ graph = _sheets_graph({"id": "only-id-no-creds"})
+
+ sheets_schema = GoogleSheetsReadBlock.Input
+ real_get_field_schema = sheets_schema.get_field_schema
+
+ def mock_get_field_schema(name: str):
+ schema = real_get_field_schema(name)
+ if name == "spreadsheet":
+ schema = {**schema, "format": "future-provider-picker"}
+ return schema
+
+ with patch.object(
+ sheets_schema, "get_field_schema", staticmethod(mock_get_field_schema)
+ ):
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors
+ msg = errors[graph.nodes[0].id]["spreadsheet"]
+ # Still catches the missing-creds anti-pattern
+ assert "_credentials_id" in msg
+ # But does NOT mention the Drive-specific block name
+ assert "AgentGoogleDriveFileInputBlock" not in msg
+ assert "Google Drive" not in msg
+
+
+def test_auto_credentials_validator_ignores_regular_credentials_fields():
+ """Regression guard: blocks with regular `credentials: CredentialsMetaInput`
+ fields (GmailSendBlock, AITextGeneratorBlock, etc.) must NOT be
+ flagged by this rule — it applies only to auto-credentials fields
+ derived via `GoogleDriveFileField` (or any future picker-sourced
+ auto-credentials field)."""
+ from backend.blocks.google.gmail import GmailSendBlock
+
+ gmail_block = GmailSendBlock()
+ node = Node(
+ id="00000000-0000-0000-0000-000000000001",
+ block_id=gmail_block.id,
+ input_default={
+ "to": ["[email protected]"],
+ "subject": "hi",
+ "body": "hello",
+ },
+ )
+ graph = Graph(
+ id="test-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ # Gmail's `credentials` field is a regular CredentialsMetaInput, not
+ # an auto-credentials picker field. No auto-credentials error should
+ # be emitted. (Existing credential-availability validation happens
+ # elsewhere in the execution path, not here.)
+ node_err = errors.get(node.id, {})
+ assert "AgentGoogleDriveFileInputBlock" not in " ".join(node_err.values()), (
+ f"Unexpected Drive-picker remediation on a non-auto-credentials "
+ f"block: {node_err}"
+ )
+
+
+ "bad_value",
+ [
+ pytest.param(42, id="int"),
+ pytest.param(True, id="bool"),
+ pytest.param(["1KAv8h", "fileid"], id="list"),
+ ],
+)
+def test_auto_credentials_non_str_non_dict_value_rejected(bad_value):
+ """Cursor Low (thread PRRT_kwDOJKSTjM58r5Vu): the validator's
+ auto-credential anti-pattern branch only covered `isinstance(value,
+ str)` and `isinstance(value, dict)`. Any other type (int, bool,
+ list, ...) fell through silently — which later crashes inside
+ ``_acquire_auto_credentials`` at execute time when it tries to
+ ``.get("_credentials_id")`` on a non-dict.
+
+ Pin the catch-all: any non-str/non-dict value must emit the same
+ re-auth guidance pointing at ``AgentGoogleDriveFileInputBlock``."""
+ graph = _sheets_graph(bad_value)
+
+ errors = GraphModel._validate_graph_get_errors(graph)
+
+ assert graph.nodes[0].id in errors, f"no error emitted for {bad_value!r}"
+ msg = errors[graph.nodes[0].id]["spreadsheet"]
+ # Must point the user at the correct fix (the Drive input block).
+ assert "AgentGoogleDriveFileInputBlock" in msg
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index 09fdaa6cf8..a8cc6e8b16 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -456,6 +456,8 @@ class OAuthState(BaseModel):
code_verifier: Optional[str] = None
"""Unix timestamp (seconds) indicating when this OAuth state expires"""
scopes: list[str]
+ credential_id: Optional[str] = None
+ """If set, this OAuth flow upgrades an existing credential's scopes."""
# Fields for external API OAuth flows
callback_url: Optional[str] = None
"""External app's callback URL for OAuth redirect"""
@@ -607,6 +609,8 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):
discriminator: Optional[str] = None
discriminator_mapping: Optional[dict[str, CP]] = None
discriminator_values: set[Any] = Field(default_factory=set)
+ is_auto_credential: bool = False
+ input_field_name: Optional[str] = None
@classmethod
def combine(
@@ -694,6 +698,9 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):
+ "_credentials"
)
+ # Propagate is_auto_credential from the combined field.
+ # All fields in a group should share the same is_auto_credential
+ # value since auto and regular credentials serve different purposes.
result[group_key] = (
CredentialsFieldInfo[CP, CT](
credentials_provider=combined.provider,
@@ -702,6 +709,8 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):
discriminator=combined.discriminator,
discriminator_mapping=combined.discriminator_mapping,
discriminator_values=set(all_discriminator_values),
+ is_auto_credential=combined.is_auto_credential,
+ input_field_name=combined.input_field_name,
),
combined_keys,
)
@@ -726,7 +735,9 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):
credentials_scopes=self.required_scopes,
discriminator=self.discriminator,
discriminator_mapping=self.discriminator_mapping,
- discriminator_values=set(self.discriminator_values), # defensive copy
+ discriminator_values=set(self.discriminator_values),
+ is_auto_credential=self.is_auto_credential,
+ input_field_name=self.input_field_name,
)
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 0cf0ea0936..ce198b972c 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -138,6 +138,123 @@ def execute_graph(
T = TypeVar("T")
+async def _acquire_auto_credentials(
+ input_model: type[BlockSchema],
+ input_data: dict[str, Any],
+ creds_manager: "IntegrationCredentialsManager",
+ user_id: str,
+) -> tuple[dict[str, Any], list[AsyncRedisLock]]:
+ """
+ Resolve auto_credentials from GoogleDriveFileField-style inputs.
+
+ Returns:
+ (extra_exec_kwargs, locks): kwargs to inject into block execution, and
+ credential locks to release after execution completes.
+ """
+ extra_exec_kwargs: dict[str, Any] = {}
+ locks: list[AsyncRedisLock] = []
+
+ try:
+ for kwarg_name, info in input_model.get_auto_credentials_fields().items():
+ field_name = info["field_name"]
+ field_data = input_data.get(field_name)
+
+ if field_data and isinstance(field_data, dict):
+ # Check if _credentials_id key exists in the field data
+ if "_credentials_id" in field_data:
+ cred_id = field_data["_credentials_id"]
+ if cred_id is None:
+ # Explicitly None means the value is being chained in
+ # at execution time from an upstream block — skip.
+ continue
+ if not isinstance(cred_id, str) or not cred_id.strip():
+ # Non-string or empty string is corrupted state.
+ # Fail loudly so the user re-authenticates rather
+ # than silently running with no creds.
+ provider = info.get("config", {}).get(
+ "provider", "external service"
+ )
+ file_name = field_data.get("name", "selected file")
+ raise ValueError(
+ f"{provider.capitalize()} credential id for "
+ f"'{file_name}' in field '{field_name}' is empty "
+ f"or invalid. Please open the agent in the "
+ f"builder and re-select the file."
+ )
+ # Credential ID provided - acquire credentials
+ provider = info.get("config", {}).get(
+ "provider", "external service"
+ )
+ file_name = field_data.get("name", "selected file")
+ try:
+ credentials, lock = await creds_manager.acquire(
+ user_id, cred_id
+ )
+ locks.append(lock)
+ extra_exec_kwargs[kwarg_name] = credentials
+ except ValueError:
+ raise ValueError(
+ f"{provider.capitalize()} credentials for "
+ f"'{file_name}' in field '{field_name}' are not "
+ f"available in your account. "
+ f"This can happen if the agent was created by another "
+ f"user or the credentials were deleted. "
+ f"Please open the agent in the builder and re-select "
+ f"the file to authenticate with your own account."
+ )
+ else:
+ # _credentials_id key missing entirely - this is an error
+ provider = info.get("config", {}).get(
+ "provider", "external service"
+ )
+ file_name = field_data.get("name", "selected file")
+ raise ValueError(
+ f"Authentication missing for '{file_name}' in field "
+ f"'{field_name}'. Please re-select the file to authenticate "
+ f"with {provider.capitalize()}."
+ )
+ elif field_data is None and field_name not in input_data:
+ # Field not in input_data at all = connected from upstream block, skip
+ pass
+ elif field_data is None or field_data == "":
+ # field_data is None/empty but key IS in input_data = user didn't select
+ provider = info.get("config", {}).get("provider", "external service")
+ raise ValueError(
+ f"No file selected for '{field_name}'. "
+ f"Please select a file to provide "
+ f"{provider.capitalize()} authentication."
+ )
+ else:
+ # field_data is truthy but NOT a dict (e.g. bare Drive ID
+ # string, int, list). The graph validator catches this at
+ # save time, but API callers / legacy graphs can still
+ # reach here — surface what the value actually is instead
+ # of the misleading "No file selected" message.
+ provider = info.get("config", {}).get("provider", "external service")
+ raise ValueError(
+ f"Invalid {type(field_data).__name__} value for "
+ f"'{field_name}': this field expects a picker-populated "
+ f"object carrying the user's credentials, not a bare "
+ f"value. Please re-select the file via the picker to "
+ f"provide {provider.capitalize()} authentication."
+ )
+ except BaseException:
+ # Release any locks already acquired so failures on later fields
+ # don't strand earlier credentials until Redis TTL expires them.
+ for lock in locks:
+ try:
+ await lock.release()
+ except Exception as release_exc:
+ _logger.warning(
+ "Failed to release auto-credential lock after acquisition "
+ "error: %s",
+ release_exc,
+ )
+ raise
+
+ return extra_exec_kwargs, locks
+
+
async def execute_node(
node: Node,
data: NodeExecutionEntry,
@@ -310,41 +427,14 @@ async def execute_node(
extra_exec_kwargs[field_name] = credentials
# Handle auto-generated credentials (e.g., from GoogleDriveFileInput)
- for kwarg_name, info in input_model.get_auto_credentials_fields().items():
- field_name = info["field_name"]
- field_data = input_data.get(field_name)
- if field_data and isinstance(field_data, dict):
- # Check if _credentials_id key exists in the field data
- if "_credentials_id" in field_data:
- cred_id = field_data["_credentials_id"]
- if cred_id:
- # Credential ID provided - acquire credentials
- provider = info.get("config", {}).get(
- "provider", "external service"
- )
- file_name = field_data.get("name", "selected file")
- try:
- credentials, lock = await creds_manager.acquire(
- user_id, cred_id
- )
- creds_locks.append(lock)
- extra_exec_kwargs[kwarg_name] = credentials
- except ValueError:
- # Credential was deleted or doesn't exist
- raise ValueError(
- f"Authentication expired for '{file_name}' in field '{field_name}'. "
- f"The saved {provider.capitalize()} credentials no longer exist. "
- f"Please re-select the file to re-authenticate."
- )
- # else: _credentials_id is explicitly None, skip credentials (for chained data)
- else:
- # _credentials_id key missing entirely - this is an error
- provider = info.get("config", {}).get("provider", "external service")
- file_name = field_data.get("name", "selected file")
- raise ValueError(
- f"Authentication missing for '{file_name}' in field '{field_name}'. "
- f"Please re-select the file to authenticate with {provider.capitalize()}."
- )
+ auto_extra_kwargs, auto_locks = await _acquire_auto_credentials(
+ input_model=input_model,
+ input_data=input_data,
+ creds_manager=creds_manager,
+ user_id=user_id,
+ )
+ extra_exec_kwargs.update(auto_extra_kwargs)
+ creds_locks.extend(auto_locks)
output_size = 0
diff --git a/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py b/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py
new file mode 100644
index 0000000000..62f58cfa59
--- /dev/null
+++ b/autogpt_platform/backend/backend/executor/manager_auto_credentials_test.py
@@ -0,0 +1,471 @@
+"""
+Tests for auto_credentials handling in execute_node().
+
+These test the _acquire_auto_credentials() helper function extracted from
+execute_node() (manager.py lines 273-308).
+"""
+
+import pytest
+from pytest_mock import MockerFixture
+
+
+def google_drive_file_data():
+ return {
+ "valid": {
+ "_credentials_id": "cred-id-123",
+ "id": "file-123",
+ "name": "test.xlsx",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ "chained": {
+ "_credentials_id": None,
+ "id": "file-456",
+ "name": "chained.xlsx",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ "missing_key": {
+ "id": "file-789",
+ "name": "bad.xlsx",
+ "mimeType": "application/vnd.google-apps.spreadsheet",
+ },
+ }
+
+
+def mock_input_model(mocker: MockerFixture):
+ """Create a mock input model with get_auto_credentials_fields() returning one field."""
+ input_model = mocker.MagicMock()
+ input_model.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {
+ "provider": "google",
+ "type": "oauth2",
+ "scopes": ["https://www.googleapis.com/auth/drive.readonly"],
+ },
+ }
+ }
+ return input_model
+
+
+def mock_creds_manager(mocker: MockerFixture):
+ manager = mocker.AsyncMock()
+ mock_lock = mocker.AsyncMock()
+ mock_creds = mocker.MagicMock()
+ mock_creds.id = "cred-id-123"
+ mock_creds.provider = "google"
+ manager.acquire.return_value = (mock_creds, mock_lock)
+ return manager, mock_creds, mock_lock
+
+
+async def test_auto_credentials_happy_path(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """When field_data has a valid _credentials_id, credentials should be acquired."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, mock_creds, mock_lock = mock_creds_manager
+ input_data = {"spreadsheet": google_drive_file_data["valid"]}
+
+ extra_kwargs, locks = await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ manager.acquire.assert_called_once_with("user-1", "cred-id-123")
+ assert extra_kwargs["credentials"] == mock_creds
+ assert mock_lock in locks
+
+
+async def test_auto_credentials_field_none_static_raises(
+ mocker: MockerFixture,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ [THE BUG FIX TEST — OPEN-2895]
+ When field_data is None and the key IS in input_data (user didn't select a file),
+ should raise ValueError instead of silently skipping.
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ # Key is present but value is None = user didn't select a file
+ input_data = {"spreadsheet": None}
+
+ with pytest.raises(ValueError, match="No file selected"):
+ await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+
+async def test_auto_credentials_field_absent_skips(
+ mocker: MockerFixture,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ When the field key is NOT in input_data at all (upstream connection),
+ should skip without error.
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ # Key not present = connected from upstream block
+ input_data = {}
+
+ extra_kwargs, locks = await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ manager.acquire.assert_not_called()
+ assert "credentials" not in extra_kwargs
+ assert locks == []
+
+
+async def test_auto_credentials_chained_cred_id_none(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ When _credentials_id is explicitly None (chained data from upstream),
+ should skip credential acquisition.
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ input_data = {"spreadsheet": google_drive_file_data["chained"]}
+
+ extra_kwargs, locks = await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ manager.acquire.assert_not_called()
+ assert "credentials" not in extra_kwargs
+
+
+async def test_auto_credentials_missing_cred_id_key_raises(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ When _credentials_id key is missing entirely from field_data dict,
+ should raise ValueError.
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ input_data = {"spreadsheet": google_drive_file_data["missing_key"]}
+
+ with pytest.raises(ValueError, match="Authentication missing"):
+ await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+
+async def test_auto_credentials_ownership_mismatch_error(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ [SECRT-1772] When acquire() raises ValueError (credential belongs to another user),
+ the error message should mention 'not available' (not 'expired').
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ manager.acquire.side_effect = ValueError(
+ "Credentials #cred-id-123 for user #user-2 not found"
+ )
+ input_data = {"spreadsheet": google_drive_file_data["valid"]}
+
+ with pytest.raises(ValueError, match="not available in your account"):
+ await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-2",
+ )
+
+
+async def test_auto_credentials_deleted_credential_error(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """
+ [SECRT-1772] When acquire() raises ValueError (credential was deleted),
+ the error message should mention 'not available' (not 'expired').
+ """
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, _ = mock_creds_manager
+ manager.acquire.side_effect = ValueError(
+ "Credentials #cred-id-123 for user #user-1 not found"
+ )
+ input_data = {"spreadsheet": google_drive_file_data["valid"]}
+
+ with pytest.raises(ValueError, match="not available in your account"):
+ await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+
+async def test_auto_credentials_lock_appended(
+ mocker: MockerFixture,
+ google_drive_file_data,
+ mock_input_model,
+ mock_creds_manager,
+):
+ """Lock from acquire() should be included in returned locks list."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, _, mock_lock = mock_creds_manager
+ input_data = {"spreadsheet": google_drive_file_data["valid"]}
+
+ extra_kwargs, locks = await _acquire_auto_credentials(
+ input_model=mock_input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ assert len(locks) == 1
+ assert locks[0] is mock_lock
+
+
+async def test_auto_credentials_multiple_fields(
+ mocker: MockerFixture,
+ mock_creds_manager,
+):
+ """When there are multiple auto_credentials fields, only valid ones should acquire."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager, mock_creds, mock_lock = mock_creds_manager
+
+ input_model = mocker.MagicMock()
+ input_model.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ },
+ "credentials2": {
+ "field_name": "doc_file",
+ "config": {"provider": "google", "type": "oauth2"},
+ },
+ }
+
+ input_data = {
+ "spreadsheet": {
+ "_credentials_id": "cred-id-123",
+ "id": "file-1",
+ "name": "file1.xlsx",
+ },
+ "doc_file": {
+ "_credentials_id": None,
+ "id": "file-2",
+ "name": "chained.doc",
+ },
+ }
+
+ extra_kwargs, locks = await _acquire_auto_credentials(
+ input_model=input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ # Only the first field should have acquired credentials
+ manager.acquire.assert_called_once_with("user-1", "cred-id-123")
+ assert "credentials" in extra_kwargs
+ assert "credentials2" not in extra_kwargs
+
+
+async def test_acquire_auto_credentials_releases_partial_locks_on_failure(
+ mocker: MockerFixture,
+):
+ """When acquiring a later auto-credential field raises, any locks
+ already taken for earlier fields must be released — otherwise they'd
+ sit until Redis TTL expires, blocking the next execution."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager = mocker.AsyncMock()
+ good_creds = mocker.MagicMock()
+ good_creds.id = "cred-id-good"
+ good_lock = mocker.AsyncMock()
+
+ async def _acquire(_user_id, cred_id):
+ if cred_id == "cred-id-good":
+ return (good_creds, good_lock)
+ raise ValueError(f"bad cred {cred_id}")
+
+ manager.acquire.side_effect = _acquire
+
+ input_model = mocker.MagicMock()
+ input_model.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ },
+ "credentials2": {
+ "field_name": "doc_file",
+ "config": {"provider": "google", "type": "oauth2"},
+ },
+ }
+
+ input_data = {
+ "spreadsheet": {
+ "_credentials_id": "cred-id-good",
+ "id": "file-1",
+ "name": "file1.xlsx",
+ },
+ "doc_file": {
+ "_credentials_id": "cred-id-broken",
+ "id": "file-2",
+ "name": "file2.doc",
+ },
+ }
+
+ with pytest.raises(ValueError):
+ await _acquire_auto_credentials(
+ input_model=input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ good_lock.release.assert_awaited_once()
+
+
+async def test_acquire_auto_credentials_rejects_empty_string_credential_id(
+ mocker: MockerFixture,
+):
+ """Corrupted state: ``_credentials_id`` set to an empty string used to
+ slip through ``if cred_id:`` and run without injecting credentials.
+ Now it raises so the user re-authenticates rather than executing a
+ block that silently has no creds."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager = mocker.AsyncMock()
+
+ input_model = mocker.MagicMock()
+ input_model.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+
+ input_data = {
+ "spreadsheet": {
+ "_credentials_id": "", # corrupted empty string
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ with pytest.raises(ValueError, match="empty or invalid"):
+ await _acquire_auto_credentials(
+ input_model=input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ # Never tried to acquire the (empty) credential.
+ manager.acquire.assert_not_called()
+
+
+ "bad_value",
+ [
+ pytest.param("1KAv8hhChef7a5ycn6Al1M4DdkiG_PVcKQ_tYkRpGA-I", id="bare-string"),
+ pytest.param(42, id="int"),
+ pytest.param(True, id="bool"),
+ pytest.param(["a", "b"], id="list"),
+ ],
+)
+async def test_acquire_auto_credentials_rejects_non_dict_value_with_type_message(
+ mocker: MockerFixture,
+ bad_value,
+):
+ """Cursor Medium (thread PRRT_kwDOJKSTjM58sEDl): the ``else`` branch
+ in ``_acquire_auto_credentials`` used to raise "No file selected"
+ for ANY truthy non-dict ``field_data`` (e.g. a bare Drive ID
+ string). That message is misleading when the value *was*
+ supplied — it's just the wrong shape. The graph validator catches
+ bare strings at save time, but API callers / legacy graphs can
+ still reach the runtime.
+
+ Pin the tighter contract: a non-dict value must raise an error
+ that names both the field *and* the type it received."""
+ from backend.executor.manager import _acquire_auto_credentials
+
+ manager = mocker.AsyncMock()
+ input_model = mocker.MagicMock()
+ input_model.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+
+ input_data = {"spreadsheet": bad_value}
+
+ with pytest.raises(ValueError) as exc_info:
+ await _acquire_auto_credentials(
+ input_model=input_model,
+ input_data=input_data,
+ creds_manager=manager,
+ user_id="user-1",
+ )
+
+ msg = str(exc_info.value)
+ # Must mention the field name.
+ assert "spreadsheet" in msg
+ # Must describe the actual type rather than the misleading
+ # "No file selected" — anchor on the type name so the fix
+ # can't silently regress to the old generic message.
+ assert type(bad_value).__name__ in msg
+ manager.acquire.assert_not_called()
diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.py
index 24da0b3c7b..497565ab13 100644
--- a/autogpt_platform/backend/backend/executor/utils.py
+++ b/autogpt_platform/backend/backend/executor/utils.py
@@ -331,12 +331,30 @@ async def _validate_node_input_credentials(
# Find any fields of type CredentialsMetaInput
credentials_fields = block.input_schema.get_credentials_fields()
- if not credentials_fields:
+ auto_credentials_fields = block.input_schema.get_auto_credentials_fields()
+ if not credentials_fields and not auto_credentials_fields:
continue
# Track if any credential field is missing for this node
has_missing_credentials = False
+ # Local helper: mark the node as skippable when a per-field branch
+ # decides the field is optional-and-missing. We add to
+ # `nodes_to_skip` here rather than relying on the post-loop
+ # guard — that guard only fires when the NODE-level
+ # ``is_creds_optional`` is True. For auto-credential fields the
+ # optionality is usually field-level (``field_name not in
+ # required_fields`` because the schema default is None), so
+ # deferring would let the node silently pass validation and then
+ # crash in ``_acquire_auto_credentials`` at runtime. See Cursor
+ # thread PRRT_kwDOJKSTjM58r_37. Defined once per node (not per
+ # field) to avoid redefining the closure each inner-loop
+ # iteration — see Cursor thread PRRT_kwDOJKSTjM58sEDe.
+ def _mark_optional_skip() -> None:
+ nonlocal has_missing_credentials
+ has_missing_credentials = True
+ nodes_to_skip.add(node.id)
+
# A credential field is optional if the node metadata says so, or if
# the block schema declares a default for the field.
required_fields = block.input_schema.get_required_fields()
@@ -415,17 +433,127 @@ async def _validate_node_input_credentials(
credential_errors[node.id][field_name] = CRED_ERR_INVALID_TYPE_MISMATCH
continue
- # If node has optional credentials and any are missing, allow running without.
- # The executor will pass credentials=None to the block's run().
+ # Validate auto-credentials (GoogleDriveFileField-based)
+ # These have _credentials_id embedded in the file field data
+ if auto_credentials_fields:
+ for _kwarg_name, info in auto_credentials_fields.items():
+ field_name = info["field_name"]
+ field_is_optional = (
+ is_creds_optional or field_name not in required_fields
+ )
+ # Check input_default and nodes_input_masks for the field value
+ field_value = node.input_default.get(field_name)
+ if nodes_input_masks and node.id in nodes_input_masks:
+ field_value = nodes_input_masks[node.id].get(
+ field_name, field_value
+ )
+
+ if field_value is None:
+ # Sentry HIGH: an explicitly-None value (e.g. cleared by
+ # `_reassign_ids` on fork, or nulled by a mask) means
+ # credentials were there and are now gone. Treat as
+ # missing so optional fields hit `nodes_to_skip` and
+ # required fields surface a clean re-auth message —
+ # don't silently fall through to `_acquire_auto_credentials`
+ # which would then crash with ValueError at runtime.
+ # NOTE: this branch only fires when the key is
+ # explicitly `None`. If the field is absent from
+ # `input_default` altogether (chained from upstream
+ # via `input_links`), `.get()` also returns None — but
+ # that path is handled at execute time by
+ # `_acquire_auto_credentials` skipping fields not in
+ # `input_data`. To keep this validator from over-reaching
+ # in that case, callers set the field explicitly to
+ # `None` only for the cleared-fork scenario.
+ field_is_explicitly_none = field_name in node.input_default or (
+ nodes_input_masks
+ and node.id in nodes_input_masks
+ and field_name in nodes_input_masks[node.id]
+ )
+ if not field_is_explicitly_none:
+ continue
+ if field_is_optional:
+ _mark_optional_skip()
+ continue
+ has_missing_credentials = True
+ credential_errors[node.id][field_name] = (
+ f"{CRED_ERR_NOT_AVAILABLE_PREFIX} no file selected "
+ "for this field. Please select a file via the "
+ "picker to authenticate."
+ )
+ continue
+
+ if field_value and isinstance(field_value, dict):
+ if "_credentials_id" not in field_value:
+ # Key removed (e.g., on fork) — needs re-auth. Use the
+ # CRED_ERR_NOT_AVAILABLE_PREFIX marker so the copilot
+ # credential-race fallback recognises this as a
+ # credentials gate failure.
+ if field_is_optional:
+ _mark_optional_skip()
+ continue
+ has_missing_credentials = True
+ credential_errors[node.id][field_name] = (
+ f"{CRED_ERR_NOT_AVAILABLE_PREFIX} authentication "
+ "missing for the selected file. Please re-select "
+ "the file to authenticate with your own account."
+ )
+ continue
+ cred_id = field_value.get("_credentials_id")
+ if cred_id is None:
+ # Explicitly None means the value is being chained in
+ # at execution time from an upstream block — skip.
+ continue
+ if not isinstance(cred_id, str) or not cred_id.strip():
+ # Non-string or empty string is a corrupted state —
+ # treat it like a missing credential so the user
+ # re-authenticates rather than silently running with
+ # no creds.
+ if field_is_optional:
+ _mark_optional_skip()
+ continue
+ has_missing_credentials = True
+ credential_errors[node.id][field_name] = (
+ f"{CRED_ERR_NOT_AVAILABLE_PREFIX} credential id "
+ "on the selected file is empty or invalid. "
+ "Please re-select the file."
+ )
+ continue
+ try:
+ creds_store = get_integration_credentials_store()
+ creds = await creds_store.get_creds_by_id(user_id, cred_id)
+ except Exception as e:
+ if field_is_optional:
+ _mark_optional_skip()
+ continue
+ has_missing_credentials = True
+ credential_errors[node.id][
+ field_name
+ ] = f"{CRED_ERR_NOT_AVAILABLE_PREFIX} {e}"
+ continue
+ if not creds:
+ if field_is_optional:
+ _mark_optional_skip()
+ continue
+ has_missing_credentials = True
+ credential_errors[node.id][
+ field_name
+ ] = f"{CRED_ERR_UNKNOWN_PREFIX}{cred_id}"
+
+ # If node has optional credentials and any are missing, skip the
+ # node so the executor doesn't try to execute it with None creds.
+ # The per-field loops above deliberately didn't record an error for
+ # the optional case — the "will be marked for skip after loop"
+ # contract lives here.
if (
has_missing_credentials
and is_creds_optional
and node.id not in credential_errors
):
logger.info(
- f"Node #{node.id}: optional credentials not configured, "
- "running without"
+ f"Node #{node.id}: optional credentials not configured, " "skipping"
)
+ nodes_to_skip.add(node.id)
return credential_errors, nodes_to_skip
@@ -446,8 +574,9 @@ def make_node_credentials_input_map(
"""
result: dict[str, dict[str, JsonValue]] = {}
- # Get aggregated credentials fields for the graph
- graph_cred_inputs = graph.aggregate_credentials_inputs()
+ # Only map regular credentials (not auto_credentials, which are resolved
+ # at execution time from _credentials_id in file field data)
+ graph_cred_inputs = graph.regular_credentials_inputs
for graph_input_name, (_, compatible_node_fields, _) in graph_cred_inputs.items():
# Best-effort map: skip missing items
diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.py
index 4b88cf9825..9b87a8886f 100644
--- a/autogpt_platform/backend/backend/executor/utils_test.py
+++ b/autogpt_platform/backend/backend/executor/utils_test.py
@@ -623,8 +623,11 @@ async def test_validate_node_input_credentials_returns_nodes_to_skip(
nodes_input_masks=None,
)
- # Node should NOT be in nodes_to_skip (runs without credentials) and not in errors
- assert mock_node.id not in nodes_to_skip
+ # Optional-creds + missing => skip the node (don't run it with None creds)
+ # and don't record an error. This contract is relied on by the executor
+ # which would otherwise try to run a block whose credentials never
+ # arrived.
+ assert mock_node.id in nodes_to_skip
assert mock_node.id not in errors
@@ -1100,3 +1103,635 @@ def test_non_credential_errors_are_not_matched():
assert not is_credential_validation_error_message(
"Block configuration says credentials are fine"
)
+
+
+# ============================================================================
+# Tests for auto_credentials validation in _validate_node_input_credentials
+# (Fix 3: SECRT-1772 + Fix 4: Path 4)
+# ============================================================================
+
+
+async def test_validate_node_input_credentials_auto_creds_valid(
+ mocker: MockerFixture,
+):
+ """
+ [SECRT-1772] When a node has auto_credentials with a valid _credentials_id
+ that exists in the store, validation should pass without errors.
+ """
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-with-auto-creds"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {
+ "spreadsheet": {
+ "_credentials_id": "valid-cred-id",
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ # No regular credentials fields
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ # Has auto_credentials fields
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ # Mock the credentials store to return valid credentials
+ mock_store = mocker.MagicMock()
+ mock_creds = mocker.MagicMock()
+ mock_creds.id = "valid-cred-id"
+ mock_store.get_creds_by_id = mocker.AsyncMock(return_value=mock_creds)
+ mocker.patch(
+ "backend.executor.utils.get_integration_credentials_store",
+ return_value=mock_store,
+ )
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="test-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id not in errors
+ assert mock_node.id not in nodes_to_skip
+
+
+async def test_validate_node_input_credentials_auto_creds_missing(
+ mocker: MockerFixture,
+):
+ """
+ [SECRT-1772] When a node has auto_credentials with a _credentials_id
+ that doesn't exist for the current user, validation should report an error.
+ """
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-with-bad-auto-creds"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {
+ "spreadsheet": {
+ "_credentials_id": "other-users-cred-id",
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ # The auto-credentials validator respects optional fields — mark the
+ # spreadsheet field as required so the missing-cred error is recorded.
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ # Mock the credentials store to return None (cred not found for this user)
+ mock_store = mocker.MagicMock()
+ mock_store.get_creds_by_id = mocker.AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.executor.utils.get_integration_credentials_store",
+ return_value=mock_store,
+ )
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="different-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id in errors
+ assert "spreadsheet" in errors[mock_node.id]
+ # Error message uses the CRED_ERR_UNKNOWN_PREFIX marker so the copilot
+ # credential-race fallback recognises it as a credentials gate failure.
+ assert (
+ errors[mock_node.id]["spreadsheet"].lower().startswith("unknown credentials #")
+ )
+
+
+async def test_validate_node_input_credentials_both_regular_and_auto(
+ mocker: MockerFixture,
+):
+ """
+ [SECRT-1772] A node that has BOTH regular credentials AND auto_credentials
+ should have both validated.
+ """
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-with-both-creds"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {
+ "credentials": {
+ "id": "regular-cred-id",
+ "provider": "github",
+ "type": "api_key",
+ },
+ "spreadsheet": {
+ "_credentials_id": "auto-cred-id",
+ "id": "file-123",
+ "name": "test.xlsx",
+ },
+ }
+
+ mock_credentials_field_type = mocker.MagicMock()
+ mock_credentials_meta = mocker.MagicMock()
+ mock_credentials_meta.id = "regular-cred-id"
+ mock_credentials_meta.provider = "github"
+ mock_credentials_meta.type = "api_key"
+ mock_credentials_field_type.model_validate.return_value = mock_credentials_meta
+
+ mock_block = mocker.MagicMock()
+ # Regular credentials field
+ mock_block.input_schema.get_credentials_fields.return_value = {
+ "credentials": mock_credentials_field_type,
+ }
+ # Auto-credentials field
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "auto_credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ # Mock the credentials store to return valid credentials for both
+ mock_store = mocker.MagicMock()
+ mock_regular_creds = mocker.MagicMock()
+ mock_regular_creds.id = "regular-cred-id"
+ mock_regular_creds.provider = "github"
+ mock_regular_creds.type = "api_key"
+
+ mock_auto_creds = mocker.MagicMock()
+ mock_auto_creds.id = "auto-cred-id"
+
+ def get_creds_side_effect(user_id, cred_id):
+ if cred_id == "regular-cred-id":
+ return mock_regular_creds
+ elif cred_id == "auto-cred-id":
+ return mock_auto_creds
+ return None
+
+ mock_store.get_creds_by_id = mocker.AsyncMock(side_effect=get_creds_side_effect)
+ mocker.patch(
+ "backend.executor.utils.get_integration_credentials_store",
+ return_value=mock_store,
+ )
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="test-user",
+ nodes_input_masks=None,
+ )
+
+ # Both should validate successfully - no errors
+ assert mock_node.id not in errors
+ assert mock_node.id not in nodes_to_skip
+
+
+async def test_validate_node_input_credentials_auto_creds_optional_missing(
+ mocker: MockerFixture,
+):
+ """When a node marks credentials optional and the auto-credential is
+ missing, validation should not record an error — the node is simply
+ marked for skip or runs without credentials."""
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-optional-auto-creds"
+ mock_node.credentials_optional = True
+ mock_node.input_default = {
+ "spreadsheet": {
+ "_credentials_id": "other-users-cred-id",
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ mock_store = mocker.MagicMock()
+ mock_store.get_creds_by_id = mocker.AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.executor.utils.get_integration_credentials_store",
+ return_value=mock_store,
+ )
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="different-user",
+ nodes_input_masks=None,
+ )
+
+ # Optional auto-credential that's missing must NOT error — instead the
+ # node lands in nodes_to_skip so the executor doesn't try to run it.
+ assert mock_node.id not in errors
+ assert mock_node.id in nodes_to_skip
+
+
+async def test_validate_node_input_credentials_auto_creds_uses_marker_prefix(
+ mocker: MockerFixture,
+):
+ """Auto-credential errors must use ``CRED_ERR_*`` prefixes so the copilot
+ credential-race fallback recognises them — otherwise dry runs fail
+ before the user gets a chance to re-auth."""
+ from backend.executor.utils import (
+ _validate_node_input_credentials,
+ is_credential_validation_error_message,
+ )
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-missing-auto-creds-key"
+ mock_node.credentials_optional = False
+ # Missing _credentials_id entirely — e.g. after a fork.
+ mock_node.input_default = {
+ "spreadsheet": {
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, _ = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="some-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id in errors
+ message = errors[mock_node.id]["spreadsheet"]
+ assert is_credential_validation_error_message(message)
+
+
+async def test_validate_node_input_credentials_auto_creds_empty_string_id(
+ mocker: MockerFixture,
+):
+ """A ``_credentials_id`` set to an empty string is a corrupted state —
+ the validator must treat it like a missing credential, not silently
+ pass. Without this guard, ``if cred_id and isinstance(cred_id, str)``
+ evaluated to False and the node ran with no credentials injected."""
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-with-empty-string-cred"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {
+ "spreadsheet": {
+ "_credentials_id": "", # corrupted
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, _ = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="some-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id in errors
+ assert "spreadsheet" in errors[mock_node.id]
+
+
+async def test_validate_node_input_credentials_auto_creds_skipped_when_none(
+ mocker: MockerFixture,
+):
+ """
+ When a node has auto_credentials but the field value has _credentials_id=None
+ (e.g., from upstream connection), validation should skip it without error.
+ """
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-with-chained-auto-creds"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {
+ "spreadsheet": {
+ "_credentials_id": None,
+ "id": "file-123",
+ "name": "test.xlsx",
+ }
+ }
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="test-user",
+ nodes_input_masks=None,
+ )
+
+ # No error - chained data with None cred_id is valid
+ assert mock_node.id not in errors
+
+
+async def test_validate_node_input_credentials_auto_creds_optional_none_value_skips(
+ mocker: MockerFixture,
+):
+ """Sentry HIGH regression: if input_default[field_name] is explicitly
+ ``None`` (e.g. cleared by ``_reassign_ids`` on fork) and the field is
+ optional, the validator previously silently skipped the whole
+ auto-credentials block — ``has_missing_credentials`` never flipped
+ true and the node never landed in ``nodes_to_skip``. Then
+ ``_acquire_auto_credentials`` would hit ``field_data is None`` at
+ runtime and raise ``ValueError`` instead of cleanly skipping.
+
+ The validator must treat an explicitly-None value as a missing
+ credential and, for optional fields, add the node to
+ ``nodes_to_skip`` instead."""
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-cleared-on-fork"
+ mock_node.credentials_optional = True
+ # input_default has the field but its value was cleared to None
+ mock_node.input_default = {"spreadsheet": None}
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="some-user",
+ nodes_input_masks=None,
+ )
+
+ # Optional + missing → node MUST land in nodes_to_skip so the executor
+ # never enters a run that would crash in `_acquire_auto_credentials`.
+ assert mock_node.id not in errors
+ assert mock_node.id in nodes_to_skip
+
+
+async def test_validate_node_input_credentials_field_level_optional_none_value_skips(
+ mocker: MockerFixture,
+):
+ """Cursor Medium (thread PRRT_kwDOJKSTjM58r_37): a node with
+ ``credentials_optional=False`` (the default) but whose auto-credential
+ field is NOT in ``required_fields`` (typical — the ``spreadsheet``
+ field on Google Sheets blocks defaults to None, so pydantic marks it
+ non-required at the schema level). The per-field check correctly
+ flags ``field_is_optional=True`` via ``field_name not in
+ required_fields``, but the POST-LOOP guard used ``is_creds_optional``
+ (the node-level flag) only — so the node silently passed validation
+ and crashed at runtime inside ``_acquire_auto_credentials`` with
+ ``ValueError('No file selected')``.
+
+ Pin the contract: when ANY per-field branch decides the field is
+ optional and missing, the node must land in ``nodes_to_skip``
+ regardless of the node-level ``credentials_optional`` flag."""
+ from backend.executor.utils import _validate_node_input_credentials
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-field-optional-cleared"
+ # Node-level flag is False (the common case) — the field is only
+ # field-level optional because it's absent from required_fields.
+ mock_node.credentials_optional = False
+ mock_node.input_default = {"spreadsheet": None}
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ # Field-level optional: `spreadsheet` is NOT in required_fields because
+ # its pydantic default is None.
+ mock_block.input_schema.get_required_fields.return_value = []
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, nodes_to_skip = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="some-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id not in errors
+ assert mock_node.id in nodes_to_skip
+
+
+async def test_validate_node_input_credentials_auto_creds_required_none_value_errors(
+ mocker: MockerFixture,
+):
+ """Sentry HIGH regression, required-field variant. If
+ ``input_default[field_name]`` is explicitly ``None`` and the field is
+ required, the validator must surface a
+ ``CRED_ERR_NOT_AVAILABLE_PREFIX`` error so the dry-run gate fires
+ before we enter `run()` — rather than silently letting the node pass
+ validation and crashing inside `_acquire_auto_credentials`."""
+ from backend.executor.utils import (
+ _validate_node_input_credentials,
+ is_credential_validation_error_message,
+ )
+
+ mock_node = mocker.MagicMock()
+ mock_node.id = "node-cleared-on-fork-required"
+ mock_node.credentials_optional = False
+ mock_node.input_default = {"spreadsheet": None}
+
+ mock_block = mocker.MagicMock()
+ mock_block.input_schema.get_credentials_fields.return_value = {}
+ mock_block.input_schema.get_auto_credentials_fields.return_value = {
+ "credentials": {
+ "field_name": "spreadsheet",
+ "config": {"provider": "google", "type": "oauth2"},
+ }
+ }
+ mock_block.input_schema.get_required_fields.return_value = ["spreadsheet"]
+ mock_node.block = mock_block
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.nodes = [mock_node]
+
+ errors, _ = await _validate_node_input_credentials(
+ graph=mock_graph,
+ user_id="some-user",
+ nodes_input_masks=None,
+ )
+
+ assert mock_node.id in errors
+ assert "spreadsheet" in errors[mock_node.id]
+ assert is_credential_validation_error_message(errors[mock_node.id]["spreadsheet"])
+
+
+# ============================================================================
+# Tests for CredentialsFieldInfo auto_credential tag (Fix 4: Path 4)
+# ============================================================================
+
+
+def test_credentials_field_info_auto_credential_tag():
+ """
+ [Path 4] CredentialsFieldInfo should support is_auto_credential and
+ input_field_name fields for distinguishing auto from regular credentials.
+ """
+ from backend.data.model import CredentialsFieldInfo
+
+ # Regular credential should have is_auto_credential=False by default
+ regular = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["api_key"],
+ },
+ by_alias=True,
+ )
+ assert regular.is_auto_credential is False
+ assert regular.input_field_name is None
+
+ # Auto credential should have is_auto_credential=True
+ auto = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["google"],
+ "credentials_types": ["oauth2"],
+ "is_auto_credential": True,
+ "input_field_name": "spreadsheet",
+ },
+ by_alias=True,
+ )
+ assert auto.is_auto_credential is True
+ assert auto.input_field_name == "spreadsheet"
+
+
+def test_make_node_credentials_input_map_excludes_auto_creds(
+ mocker: MockerFixture,
+):
+ """
+ [Path 4] make_node_credentials_input_map should only include regular credentials,
+ not auto_credentials (which are resolved at execution time).
+ """
+ from backend.data.model import CredentialsFieldInfo, CredentialsMetaInput
+ from backend.executor.utils import make_node_credentials_input_map
+ from backend.integrations.providers import ProviderName
+
+ # Create a mock graph with aggregate_credentials_inputs that returns
+ # both regular and auto credentials
+ mock_graph = mocker.MagicMock()
+
+ regular_field_info = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["api_key"],
+ "is_auto_credential": False,
+ },
+ by_alias=True,
+ )
+
+ # Mock regular_credentials_inputs property (auto_credentials are excluded)
+ mock_graph.regular_credentials_inputs = {
+ "github_creds": (regular_field_info, {("node-1", "credentials")}, True),
+ }
+
+ graph_credentials_input = {
+ "github_creds": CredentialsMetaInput(
+ id="cred-123",
+ provider=ProviderName("github"),
+ type="api_key",
+ ),
+ }
+
+ result = make_node_credentials_input_map(mock_graph, graph_credentials_input)
+
+ # Regular credentials should be mapped
+ assert "node-1" in result
+ assert "credentials" in result["node-1"]
+
+ # Auto credentials should NOT appear in the result
+ # (they would have been mapped to the kwarg_name "credentials" not "spreadsheet")
+ for node_id, fields in result.items():
+ for field_name, value in fields.items():
+ # Verify no auto-credential phantom entries
+ if isinstance(value, dict):
+ assert "_credentials_id" not in value
diff --git a/autogpt_platform/backend/backend/integrations/credentials_store.py b/autogpt_platform/backend/backend/integrations/credentials_store.py
index 2cf9f48767..7d0c0a4b7a 100644
--- a/autogpt_platform/backend/backend/integrations/credentials_store.py
+++ b/autogpt_platform/backend/backend/integrations/credentials_store.py
@@ -551,6 +551,7 @@ class IntegrationCredentialsStore:
callback_url: Optional[str] = None,
state_metadata: Optional[dict] = None,
initiated_by_api_key_id: Optional[str] = None,
+ credential_id: Optional[str] = None,
) -> tuple[str, str]:
token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(minutes=10)
@@ -563,6 +564,7 @@ class IntegrationCredentialsStore:
code_verifier=code_verifier,
expires_at=int(expires_at.timestamp()),
scopes=scopes,
+ credential_id=credential_id,
# External API OAuth flow fields
callback_url=callback_url,
state_metadata=state_metadata or {},
diff --git a/autogpt_platform/backend/backend/integrations/oauth/google.py b/autogpt_platform/backend/backend/integrations/oauth/google.py
index bba2bc71c5..a807a8b7d2 100644
--- a/autogpt_platform/backend/backend/integrations/oauth/google.py
+++ b/autogpt_platform/backend/backend/integrations/oauth/google.py
@@ -11,6 +11,7 @@ from pydantic import SecretStr
from backend.data.model import OAuth2Credentials
from backend.integrations.providers import ProviderName
+from backend.util.request import Requests
from .base import BaseOAuthHandler
@@ -107,13 +108,33 @@ class GoogleOAuthHandler(BaseOAuthHandler):
return credentials
async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:
- session = AuthorizedSession(credentials)
- session.post(
+ # Google's revoke endpoint only needs the token in the request body;
+ # it does not need an Authorization header. Previously this used
+ # google-auth's AuthorizedSession, which calls .before_request() on
+ # the credential object — that fails with AttributeError when given
+ # our Pydantic OAuth2Credentials (which isn't a google-auth
+ # Credentials). Switching to the platform's async Requests helper
+ # matches how the other providers (reddit/github/...) do it.
+ if not credentials.access_token:
+ return False
+
+ # raise_for_status=False so a 400 (already-revoked token, malformed
+ # body, rate limit, etc.) flows back as response.ok=False instead of
+ # raising — the caller uses the bool to set the UI `revoked` flag
+ # and does not need to distinguish failure modes.
+ # retry_max_attempts bounds tenacity retries on 429/5xx — without
+ # it `Requests` retries indefinitely with exponential backoff up
+ # to 5 minutes per wait, and a transient Google failure would
+ # hang the credential deletion API call forever.
+ response = await Requests(
+ raise_for_status=False,
+ retry_max_attempts=3,
+ ).post(
self.revoke_uri,
- params={"token": credentials.access_token.get_secret_value()},
- headers={"content-type": "application/x-www-form-urlencoded"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ data={"token": credentials.access_token.get_secret_value()},
)
- return True
+ return response.ok
def _request_email(
self, creds: Credentials | ExternalAccountCredentials
diff --git a/autogpt_platform/backend/backend/integrations/oauth/google_test.py b/autogpt_platform/backend/backend/integrations/oauth/google_test.py
new file mode 100644
index 0000000000..9e69d80048
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/google_test.py
@@ -0,0 +1,137 @@
+"""Regression tests for GoogleOAuthHandler.
+
+Pins the fix for SECRT-2267 / AUTOGPT-SERVER-6HB: calling revoke_tokens
+with our platform OAuth2Credentials must not crash with
+``AttributeError: 'OAuth2Credentials' object has no attribute
+'before_request'``. The old code handed our Pydantic model to
+google-auth's AuthorizedSession, which expected a google-auth
+Credentials and then called .before_request() on it.
+"""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from pydantic import SecretStr
+from pytest_mock import MockerFixture
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.google import GoogleOAuthHandler
+from backend.integrations.providers import ProviderName
+
+
+def _handler() -> GoogleOAuthHandler:
+ return GoogleOAuthHandler(
+ client_id="test-client-id",
+ client_secret="test-client-secret",
+ redirect_uri="https://example.com/callback",
+ )
+
+
+def _creds() -> OAuth2Credentials:
+ return OAuth2Credentials(
+ provider=ProviderName.GOOGLE,
+ title=None,
+ username="[email protected]",
+ access_token=SecretStr("access-token-value"),
+ refresh_token=SecretStr("refresh-token-value"),
+ access_token_expires_at=None,
+ refresh_token_expires_at=None,
+ scopes=["https://www.googleapis.com/auth/userinfo.email"],
+ )
+
+
+async def test_revoke_tokens_does_not_call_before_request(mocker: MockerFixture):
+ """revoke_tokens must not pass our Pydantic credentials into
+ google-auth's AuthorizedSession path. It should POST the token via
+ the platform's async Requests helper instead."""
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_post = AsyncMock(return_value=mock_response)
+ mocker.patch(
+ "backend.integrations.oauth.google.Requests",
+ return_value=MagicMock(post=mock_post),
+ )
+
+ result = await _handler().revoke_tokens(_creds())
+
+ assert result is True
+ mock_post.assert_awaited_once()
+ args, kwargs = mock_post.call_args
+ # URL is positional or first kwarg
+ url = args[0] if args else kwargs.get("url")
+ assert url == "https://oauth2.googleapis.com/revoke"
+ assert kwargs["data"] == {"token": "access-token-value"}
+ assert kwargs["headers"]["Content-Type"] == "application/x-www-form-urlencoded"
+
+
+async def test_revoke_tokens_returns_false_when_no_access_token(
+ mocker: MockerFixture,
+):
+ """If the stored credential somehow lacks an access token, don't
+ crash — return False so the caller can surface a clean deletion
+ outcome."""
+ mock_post = AsyncMock()
+ mocker.patch(
+ "backend.integrations.oauth.google.Requests",
+ return_value=MagicMock(post=mock_post),
+ )
+
+ creds = _creds()
+ # Simulate a credential row that lost its access token
+ object.__setattr__(creds, "access_token", None)
+
+ result = await _handler().revoke_tokens(creds)
+
+ assert result is False
+ mock_post.assert_not_awaited()
+
+
+async def test_revoke_tokens_propagates_http_failure(mocker: MockerFixture):
+ """A non-2xx response from Google's revoke endpoint should surface
+ as False, not True. Deletion callers use this signal to decide
+ whether revocation was actually confirmed upstream."""
+ mock_response = MagicMock()
+ mock_response.ok = False
+ mock_post = AsyncMock(return_value=mock_response)
+ mocker.patch(
+ "backend.integrations.oauth.google.Requests",
+ return_value=MagicMock(post=mock_post),
+ )
+
+ result = await _handler().revoke_tokens(_creds())
+
+ assert result is False
+
+
+async def test_revoke_tokens_uses_bounded_retries(mocker: MockerFixture):
+ """Cursor Medium (thread PRRT_kwDOJKSTjM58rtx1): the platform's
+ ``Requests`` helper retries *indefinitely* on 429/5xx by default
+ (no ``stop`` condition in tenacity unless ``retry_max_attempts`` is
+ passed). If Google's revoke endpoint transiently returns a 429 or
+ 5xx, ``revoke_tokens`` would hang forever and block the credential
+ deletion API call.
+
+ Pin the bound: ``Requests`` must be constructed with a finite
+ ``retry_max_attempts`` so revoke always terminates."""
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_post = AsyncMock(return_value=mock_response)
+ mock_requests_cls = mocker.patch(
+ "backend.integrations.oauth.google.Requests",
+ return_value=MagicMock(post=mock_post),
+ )
+
+ await _handler().revoke_tokens(_creds())
+
+ assert mock_requests_cls.call_count == 1
+ _, kwargs = mock_requests_cls.call_args
+ retry_max_attempts = kwargs.get("retry_max_attempts")
+ assert retry_max_attempts is not None, (
+ "Requests was constructed without retry_max_attempts — retries are "
+ "unbounded, and a transient 429/5xx from Google would hang revoke."
+ )
+ assert retry_max_attempts >= 1
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/page.test.tsx
index 310c238dfc..93c0d6aa85 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/page.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/__tests__/page.test.tsx
@@ -1,5 +1,6 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
import { render, screen } from "@/tests/integrations/test-utils";
-import { describe, expect, it, vi } from "vitest";
// Mock withRoleAccess to bypass server-side auth
vi.mock("@/lib/withRoleAccess", () => ({
@@ -9,125 +10,209 @@ vi.mock("@/lib/withRoleAccess", () => ({
),
}));
-// Mock the generated API hooks used by DiagnosticsContent
-vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({
- useGetV2GetExecutionDiagnostics: () => ({
- data: undefined,
- isLoading: true,
- isError: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2GetAgentDiagnostics: () => ({
- data: undefined,
- isLoading: true,
- isError: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2GetScheduleDiagnostics: () => ({
- data: undefined,
- isLoading: true,
- isError: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListRunningExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListOrphanedExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListFailedExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListLongRunningExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListStuckQueuedExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListInvalidExecutions: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- usePostV2StopSingleExecution: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2StopMultipleExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2StopAllLongRunningExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2CleanupOrphanedExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2CleanupAllOrphanedExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2CleanupAllStuckQueuedExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2RequeueStuckExecution: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2RequeueMultipleStuckExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- usePostV2RequeueAllStuckQueuedExecutions: () => ({
- mutateAsync: vi.fn(),
- isPending: false,
- }),
- useGetV2ListAllUserSchedules: () => ({
- data: undefined,
+// `vi.hoisted` so the shared stubs are initialised before the module
+// factory below is evaluated. Individual tests reassign the return
+// values; reset in `beforeEach` so tests don't bleed state into each
+// other.
+const api = vi.hoisted(() => {
+ const defaultQuery = () => ({
+ data: undefined as unknown,
isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- useGetV2ListOrphanedSchedules: () => ({
- data: undefined,
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- }),
- usePostV2CleanupOrphanedSchedules: () => ({
- mutateAsync: vi.fn(),
+ isError: false,
+ error: null as unknown,
+ refetch: () => {},
+ });
+ const defaultMutation = () => ({
+ mutateAsync: async () => {},
isPending: false,
- }),
+ });
+ return {
+ useGetV2GetExecutionDiagnostics: vi.fn(defaultQuery),
+ useGetV2GetAgentDiagnostics: vi.fn(defaultQuery),
+ useGetV2GetScheduleDiagnostics: vi.fn(defaultQuery),
+ useGetV2ListRunningExecutions: vi.fn(defaultQuery),
+ useGetV2ListOrphanedExecutions: vi.fn(defaultQuery),
+ useGetV2ListFailedExecutions: vi.fn(defaultQuery),
+ useGetV2ListLongRunningExecutions: vi.fn(defaultQuery),
+ useGetV2ListStuckQueuedExecutions: vi.fn(defaultQuery),
+ useGetV2ListInvalidExecutions: vi.fn(defaultQuery),
+ usePostV2StopSingleExecution: vi.fn(defaultMutation),
+ usePostV2StopMultipleExecutions: vi.fn(defaultMutation),
+ usePostV2StopAllLongRunningExecutions: vi.fn(defaultMutation),
+ usePostV2CleanupOrphanedExecutions: vi.fn(defaultMutation),
+ usePostV2CleanupAllOrphanedExecutions: vi.fn(defaultMutation),
+ usePostV2CleanupAllStuckQueuedExecutions: vi.fn(defaultMutation),
+ usePostV2RequeueStuckExecution: vi.fn(defaultMutation),
+ usePostV2RequeueMultipleStuckExecutions: vi.fn(defaultMutation),
+ usePostV2RequeueAllStuckQueuedExecutions: vi.fn(defaultMutation),
+ useGetV2ListAllUserSchedules: vi.fn(defaultQuery),
+ useGetV2ListOrphanedSchedules: vi.fn(defaultQuery),
+ usePostV2CleanupOrphanedSchedules: vi.fn(defaultMutation),
+ defaultQuery,
+ defaultMutation,
+ };
+});
+
+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({
+ useGetV2GetExecutionDiagnostics: api.useGetV2GetExecutionDiagnostics,
+ useGetV2GetAgentDiagnostics: api.useGetV2GetAgentDiagnostics,
+ useGetV2GetScheduleDiagnostics: api.useGetV2GetScheduleDiagnostics,
+ useGetV2ListRunningExecutions: api.useGetV2ListRunningExecutions,
+ useGetV2ListOrphanedExecutions: api.useGetV2ListOrphanedExecutions,
+ useGetV2ListFailedExecutions: api.useGetV2ListFailedExecutions,
+ useGetV2ListLongRunningExecutions: api.useGetV2ListLongRunningExecutions,
+ useGetV2ListStuckQueuedExecutions: api.useGetV2ListStuckQueuedExecutions,
+ useGetV2ListInvalidExecutions: api.useGetV2ListInvalidExecutions,
+ usePostV2StopSingleExecution: api.usePostV2StopSingleExecution,
+ usePostV2StopMultipleExecutions: api.usePostV2StopMultipleExecutions,
+ usePostV2StopAllLongRunningExecutions:
+ api.usePostV2StopAllLongRunningExecutions,
+ usePostV2CleanupOrphanedExecutions: api.usePostV2CleanupOrphanedExecutions,
+ usePostV2CleanupAllOrphanedExecutions:
+ api.usePostV2CleanupAllOrphanedExecutions,
+ usePostV2CleanupAllStuckQueuedExecutions:
+ api.usePostV2CleanupAllStuckQueuedExecutions,
+ usePostV2RequeueStuckExecution: api.usePostV2RequeueStuckExecution,
+ usePostV2RequeueMultipleStuckExecutions:
+ api.usePostV2RequeueMultipleStuckExecutions,
+ usePostV2RequeueAllStuckQueuedExecutions:
+ api.usePostV2RequeueAllStuckQueuedExecutions,
+ useGetV2ListAllUserSchedules: api.useGetV2ListAllUserSchedules,
+ useGetV2ListOrphanedSchedules: api.useGetV2ListOrphanedSchedules,
+ usePostV2CleanupOrphanedSchedules: api.usePostV2CleanupOrphanedSchedules,
}));
// Import the inner component directly since the page is async/server
import { DiagnosticsContent } from "../components/DiagnosticsContent";
+function query<T>(data: T) {
+ return {
+ data: { data },
+ isLoading: false,
+ isError: false,
+ error: null,
+ refetch: () => {},
+ };
+}
+
+function emptyExecutionData() {
+ // All-zeros snapshot that still populates every numeric field the UI
+ // reads — lets the happy-path render without tripping on undefined.
+ return {
+ timestamp: "2026-04-22T12:00:00Z",
+ running_executions: 0,
+ queued_executions_db: 0,
+ queued_executions_rabbitmq: 0,
+ cancel_queue_depth: 0,
+ stuck_queued_1h: 0,
+ stuck_running_24h: 0,
+ orphaned_running: 0,
+ orphaned_queued: 0,
+ failed_count_24h: 0,
+ failed_count_1h: 0,
+ failure_rate_24h: 0,
+ completed_24h: 0,
+ completed_1h: 0,
+ throughput_per_hour: 0,
+ invalid_queued_with_start: 0,
+ invalid_running_without_start: 0,
+ oldest_running_hours: null,
+ };
+}
+
describe("AdminDiagnosticsPage", () => {
+ beforeEach(() => {
+ for (const fn of Object.values(api)) {
+ if (typeof fn === "function" && "mockImplementation" in fn) {
+ (fn as ReturnType<typeof vi.fn>).mockImplementation(api.defaultQuery);
+ }
+ }
+ });
+
it("renders DiagnosticsContent in loading state", () => {
+ api.useGetV2GetExecutionDiagnostics.mockImplementation(() => ({
+ ...api.defaultQuery(),
+ isLoading: true,
+ }));
render(<DiagnosticsContent />);
expect(screen.getByText("Loading diagnostics...")).toBeDefined();
});
+
+ it("renders the ErrorCard when a diagnostics query fails", () => {
+ api.useGetV2GetExecutionDiagnostics.mockImplementation(() => ({
+ ...api.defaultQuery(),
+ isError: true,
+ error: { status: 500, message: "boom" },
+ }));
+ render(<DiagnosticsContent />);
+ // ErrorCard is the shared molecule; it renders "Something went
+ // wrong" as its header. Assert on that so this test doesn't break
+ // if the card adopts proper a11y roles later.
+ expect(screen.getByText(/something went wrong/i)).toBeDefined();
+ });
+
+ it("renders the dashboard with zeroed execution data (no alert cards)", () => {
+ api.useGetV2GetExecutionDiagnostics.mockImplementation(() =>
+ query(emptyExecutionData()),
+ );
+ api.useGetV2GetAgentDiagnostics.mockImplementation(() =>
+ query({ total_agents: 0 }),
+ );
+ api.useGetV2GetScheduleDiagnostics.mockImplementation(() =>
+ query({
+ user_schedules: 0,
+ total_orphaned: 0,
+ orphaned_deleted_graph: 0,
+ orphaned_no_library_access: 0,
+ total_runs_next_hour: 0,
+ schedules_next_hour: 0,
+ }),
+ );
+
+ render(<DiagnosticsContent />);
+
+ // Dashboard header is the canonical "we rendered something" signal.
+ expect(screen.getByText("System Diagnostics")).toBeDefined();
+ expect(screen.getByRole("button", { name: /refresh/i })).toBeDefined();
+ // ``Click to view →`` text appears only inside an alert card; its
+ // absence confirms the conditional branches stayed off. (The
+ // card titles themselves also appear in the always-rendered legend,
+ // so asserting on them would produce false positives.)
+ expect(screen.queryByText(/Click to view/i)).toBeNull();
+ });
+
+ it("renders alert cards when there are critical issues", () => {
+ api.useGetV2GetExecutionDiagnostics.mockImplementation(() =>
+ query({
+ ...emptyExecutionData(),
+ orphaned_running: 3,
+ orphaned_queued: 2,
+ failed_count_24h: 11,
+ failed_count_1h: 2,
+ failure_rate_24h: 0.45,
+ stuck_running_24h: 4,
+ oldest_running_hours: 36,
+ invalid_queued_with_start: 1,
+ invalid_running_without_start: 1,
+ }),
+ );
+ api.useGetV2GetScheduleDiagnostics.mockImplementation(() =>
+ query({
+ user_schedules: 10,
+ total_orphaned: 2,
+ orphaned_deleted_graph: 1,
+ orphaned_no_library_access: 1,
+ total_runs_next_hour: 0,
+ schedules_next_hour: 0,
+ }),
+ );
+
+ render(<DiagnosticsContent />);
+
+ expect(screen.getByText("Orphaned Executions")).toBeDefined();
+ expect(screen.getByText("Failed Executions (24h)")).toBeDefined();
+ expect(screen.getByText("Long-Running Executions")).toBeDefined();
+ expect(screen.getByText("Orphaned Schedules")).toBeDefined();
+ expect(screen.getByText("Invalid States (Data Corruption)")).toBeDefined();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.ts
new file mode 100644
index 0000000000..7ec8e58830
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/diagnostics/components/__tests__/useDiagnosticsContent.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderHook } from "@testing-library/react";
+
+// Mock the three generated API hooks this hook composes. The hook under
+// test is intentionally thin — it forwards loading/error from the three
+// children and coalesces them. Stubbing at the module boundary lets us
+// exercise the combine-logic without spinning up MSW.
+const mockExecutions = vi.fn();
+const mockAgents = vi.fn();
+const mockSchedules = vi.fn();
+
+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({
+ useGetV2GetExecutionDiagnostics: (...args: unknown[]) =>
+ mockExecutions(...args),
+ useGetV2GetAgentDiagnostics: (...args: unknown[]) => mockAgents(...args),
+ useGetV2GetScheduleDiagnostics: (...args: unknown[]) =>
+ mockSchedules(...args),
+}));
+
+import { useDiagnosticsContent } from "../useDiagnosticsContent";
+
+function stub(overrides: Record<string, unknown> = {}) {
+ return {
+ data: undefined,
+ isLoading: false,
+ isError: false,
+ error: null,
+ refetch: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe("useDiagnosticsContent", () => {
+ it("is loading when any of the child queries is loading", () => {
+ mockExecutions.mockReturnValue(stub({ isLoading: true }));
+ mockAgents.mockReturnValue(stub());
+ mockSchedules.mockReturnValue(stub());
+
+ const { result } = renderHook(() => useDiagnosticsContent());
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.isError).toBe(false);
+ });
+
+ it("is in error state when any of the child queries errored", () => {
+ const err = new Error("schedule boom");
+ mockExecutions.mockReturnValue(stub());
+ mockAgents.mockReturnValue(stub());
+ mockSchedules.mockReturnValue(stub({ isError: true, error: err }));
+
+ const { result } = renderHook(() => useDiagnosticsContent());
+ expect(result.current.isError).toBe(true);
+ expect(result.current.error).toBe(err);
+ });
+
+ it("unwraps each response's data field into a dedicated return key", () => {
+ mockExecutions.mockReturnValue(
+ stub({ data: { data: { running_executions: 7 } } }),
+ );
+ mockAgents.mockReturnValue(stub({ data: { data: { total_agents: 3 } } }));
+ mockSchedules.mockReturnValue(
+ stub({ data: { data: { user_schedules: 9 } } }),
+ );
+
+ const { result } = renderHook(() => useDiagnosticsContent());
+ expect(result.current.executionData).toEqual({ running_executions: 7 });
+ expect(result.current.agentData).toEqual({ total_agents: 3 });
+ expect(result.current.scheduleData).toEqual({ user_schedules: 9 });
+ });
+
+ it("refresh() invokes refetch on all three child queries", () => {
+ const refetchEx = vi.fn();
+ const refetchAg = vi.fn();
+ const refetchSc = vi.fn();
+ mockExecutions.mockReturnValue(stub({ refetch: refetchEx }));
+ mockAgents.mockReturnValue(stub({ refetch: refetchAg }));
+ mockSchedules.mockReturnValue(stub({ refetch: refetchSc }));
+
+ const { result } = renderHook(() => useDiagnosticsContent());
+ result.current.refresh();
+
+ expect(refetchEx).toHaveBeenCalledTimes(1);
+ expect(refetchAg).toHaveBeenCalledTimes(1);
+ expect(refetchSc).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/components/__tests__/PanelHeader.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/components/__tests__/PanelHeader.test.tsx
new file mode 100644
index 0000000000..7769bb41f6
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/components/__tests__/PanelHeader.test.tsx
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+
+import { PanelHeader } from "../PanelHeader";
+
+describe("PanelHeader", () => {
+ const baseProps = {
+ onClose: () => {},
+ canRevert: false,
+ revertTargetVersion: null as number | null,
+ onRevert: () => {},
+ };
+
+ it("renders the panel title and the close button", () => {
+ render(<PanelHeader {...baseProps} />);
+ expect(screen.getByText("Chat with Builder")).toBeDefined();
+ expect(screen.getByRole("button", { name: /close/i })).toBeDefined();
+ });
+
+ it("omits the revert button when revert is not available", () => {
+ render(<PanelHeader {...baseProps} />);
+ expect(screen.queryByRole("button", { name: /revert/i })).toBeNull();
+ });
+
+ it("shows the revert button with a generic aria-label when no target version is known", () => {
+ render(<PanelHeader {...baseProps} canRevert revertTargetVersion={null} />);
+ expect(
+ screen.getByRole("button", { name: "Revert to previous version" }),
+ ).toBeDefined();
+ });
+
+ it("shows the revert button with a version-specific aria-label when a target version is known", () => {
+ render(<PanelHeader {...baseProps} canRevert revertTargetVersion={7} />);
+ expect(
+ screen.getByRole("button", { name: "Revert to version 7" }),
+ ).toBeDefined();
+ });
+
+ it("invokes the revert and close callbacks on click", () => {
+ const onClose = vi.fn();
+ const onRevert = vi.fn();
+ render(
+ <PanelHeader
+ {...baseProps}
+ canRevert
+ onClose={onClose}
+ onRevert={onRevert}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /revert/i }));
+ fireEvent.click(screen.getByRole("button", { name: /close/i }));
+ expect(onRevert).toHaveBeenCalledTimes(1);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactErrorBoundary.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactErrorBoundary.test.tsx
new file mode 100644
index 0000000000..afe7db36ff
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/components/__tests__/ArtifactErrorBoundary.test.tsx
@@ -0,0 +1,96 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+
+import { ArtifactErrorBoundary } from "../ArtifactErrorBoundary";
+
+// Spy instead of full mock — other code paths in the test harness reach
+// for ``@sentry/nextjs.withServerActionInstrumentation`` (middleware /
+// server-session code), so a blanket mock drops those exports and
+// generates noisy warnings from unrelated modules.
+vi.mock("@sentry/nextjs", async () => {
+ const actual =
+ await vi.importActual<typeof import("@sentry/nextjs")>("@sentry/nextjs");
+ return { ...actual, captureException: vi.fn() };
+});
+
+function Boom({ message = "render failed" }: { message?: string }): never {
+ throw new Error(message);
+}
+
+function Ok() {
+ return <div>child-output</div>;
+}
+
+describe("ArtifactErrorBoundary", () => {
+ const baseProps = {
+ artifactID: "artifact-1",
+ artifactTitle: "My Artifact",
+ artifactType: "markdown",
+ };
+
+ it("renders children when no error is thrown", () => {
+ render(
+ <ArtifactErrorBoundary {...baseProps}>
+ <Ok />
+ </ArtifactErrorBoundary>,
+ );
+ expect(screen.getByText("child-output")).toBeDefined();
+ });
+
+ it("shows the fallback message and the child's error text when a child throws", async () => {
+ // React logs thrown errors to the console during render; silence the
+ // noise so it doesn't drown the test report.
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ render(
+ <ArtifactErrorBoundary {...baseProps}>
+ <Boom message="rendering exploded" />
+ </ArtifactErrorBoundary>,
+ );
+
+ expect(screen.getByText(/couldn.t be rendered/i)).toBeDefined();
+ // The title of the failing artifact is surfaced so the user knows which
+ // artifact to regenerate.
+ expect(screen.getByText("My Artifact")).toBeDefined();
+ // The raw error message from the thrown Error is shown verbatim so the
+ // user can paste it into chat for the agent to act on.
+ expect(screen.getByText("rendering exploded")).toBeDefined();
+ // The copy button is present and clickable.
+ expect(
+ screen.getByRole("button", { name: /copy error details/i }),
+ ).toBeDefined();
+
+ errorSpy.mockRestore();
+ });
+
+ it("copies a structured error report when the copy button is clicked", () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(global.navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+
+ render(
+ <ArtifactErrorBoundary {...baseProps}>
+ <Boom message="copy me" />
+ </ArtifactErrorBoundary>,
+ );
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /copy error details/i }),
+ );
+
+ expect(writeText).toHaveBeenCalledTimes(1);
+ const payload = writeText.mock.calls[0][0] as string;
+ // The serialized report must carry both the identity of the artifact
+ // and the error text — that's what makes it useful for the agent.
+ expect(payload).toContain("Artifact: My Artifact");
+ expect(payload).toContain("ID: artifact-1");
+ expect(payload).toContain("Type: markdown");
+ expect(payload).toContain("Error: copy me");
+
+ errorSpy.mockRestore();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
index f9a7f01cd9..57f3ec844a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
@@ -576,7 +576,10 @@ describe("SubscriptionTierSection", () => {
subscription: makeSubscription({
tier: "BUSINESS",
pendingTier: "FREE",
- pendingTierEffectiveAt: new Date("2026-05-15T00:00:00Z"),
+ // Noon UTC so the local-formatted date lands on the same day
+ // regardless of the runner's timezone (midnight UTC drifts to
+ // the prior day in any timezone west of UTC).
+ pendingTierEffectiveAt: new Date("2026-05-15T12:00:00Z"),
}),
});
render(<SubscriptionTierSection />);
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/__tests__/PendingChangeBanner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/__tests__/PendingChangeBanner.test.tsx
new file mode 100644
index 0000000000..73e044c1fe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/__tests__/PendingChangeBanner.test.tsx
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+
+import { PendingChangeBanner } from "../PendingChangeBanner";
+
+describe("PendingChangeBanner", () => {
+ const baseProps = {
+ currentTier: "PRO",
+ pendingTier: "FREE",
+ // Use noon UTC so the formatted local date lands on the same day
+ // regardless of the host timezone (important for CI runners).
+ pendingEffectiveAt: "2026-05-01T12:00:00Z",
+ onKeepCurrent: () => {},
+ isBusy: false,
+ };
+
+ it("renders nothing when there is no effective date", () => {
+ // Backend invariant: effective date is always set when pending_tier is —
+ // rendering without it would produce a sentence with a missing noun, so
+ // the component must bail rather than show "Scheduled ... on undefined".
+ const { container } = render(
+ <PendingChangeBanner {...baseProps} pendingEffectiveAt={null} />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+
+ it("shows cancellation copy when pending tier is FREE", () => {
+ render(<PendingChangeBanner {...baseProps} />);
+ expect(screen.getByText(/cancel your subscription on/i)).toBeDefined();
+ expect(screen.getByText("May 1, 2026")).toBeDefined();
+ // Button reflects the CURRENT tier, not the pending one.
+ expect(screen.getByRole("button", { name: /keep pro/i })).toBeDefined();
+ });
+
+ it("shows downgrade copy when pending tier is a paid tier", () => {
+ render(
+ <PendingChangeBanner
+ {...baseProps}
+ currentTier="BUSINESS"
+ pendingTier="PRO"
+ />,
+ );
+ expect(screen.getByText(/downgrade to/i)).toBeDefined();
+ expect(screen.getByText("Pro")).toBeDefined();
+ expect(
+ screen.getByRole("button", { name: /keep business/i }),
+ ).toBeDefined();
+ });
+
+ it("invokes onKeepCurrent when the button is clicked", () => {
+ const onKeepCurrent = vi.fn();
+ render(
+ <PendingChangeBanner {...baseProps} onKeepCurrent={onKeepCurrent} />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /keep pro/i }));
+ expect(onKeepCurrent).toHaveBeenCalledTimes(1);
+ });
+
+ it("disables the button and swaps the label while busy", () => {
+ render(<PendingChangeBanner {...baseProps} isBusy />);
+ const button = screen.getByRole("button", { name: /cancelling/i });
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts
new file mode 100644
index 0000000000..ecc020482a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ formatCost,
+ formatPendingDate,
+ getTierLabel,
+ TIERS,
+ TIER_ORDER,
+} from "./helpers";
+
+describe("formatCost", () => {
+ it("returns 'Free' for the FREE tier regardless of cents", () => {
+ expect(formatCost(0, "FREE")).toBe("Free");
+ expect(formatCost(999, "FREE")).toBe("Free");
+ });
+
+ it("returns a placeholder when paid tier has no price yet", () => {
+ expect(formatCost(0, "PRO")).toBe("Pricing available soon");
+ expect(formatCost(0, "BUSINESS")).toBe("Pricing available soon");
+ });
+
+ it("formats cents to a dollars-per-month string for paid tiers", () => {
+ expect(formatCost(999, "PRO")).toBe("$9.99/mo");
+ expect(formatCost(4900, "BUSINESS")).toBe("$49.00/mo");
+ });
+});
+
+describe("getTierLabel", () => {
+ it("returns the canonical label for known tiers", () => {
+ expect(getTierLabel("FREE")).toBe("Free");
+ expect(getTierLabel("PRO")).toBe("Pro");
+ expect(getTierLabel("BUSINESS")).toBe("Business");
+ });
+
+ it("title-cases unknown tier keys as a fallback", () => {
+ // ENTERPRISE is in TIER_ORDER but intentionally not in TIERS — it still
+ // needs a readable label so the pending-change sentence reads cleanly.
+ expect(getTierLabel("ENTERPRISE")).toBe("Enterprise");
+ expect(getTierLabel("CUSTOM_TIER")).toBe("Custom_tier");
+ });
+});
+
+describe("formatPendingDate", () => {
+ it("formats a Date into a stable en-US string", () => {
+ const d = new Date("2026-03-15T12:00:00Z");
+ // en-US pinned to avoid SSR/CSR hydration mismatch, so the output must
+ // match regardless of the host locale.
+ expect(formatPendingDate(d)).toBe("Mar 15, 2026");
+ });
+
+ it("accepts an ISO string and produces the same output as a Date", () => {
+ expect(formatPendingDate("2026-03-15T12:00:00Z")).toBe("Mar 15, 2026");
+ });
+});
+
+describe("TIERS / TIER_ORDER", () => {
+ it("every entry in TIERS has a key that appears in TIER_ORDER", () => {
+ for (const tier of TIERS) {
+ expect(TIER_ORDER).toContain(tier.key);
+ }
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 780285b0a1..43861d98a2 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -4981,6 +4981,57 @@
}
}
},
+ "/api/integrations/{provider}/credentials/{cred_id}/picker-token": {
+ "post": {
+ "tags": ["v1", "integrations"],
+ "summary": "Issue a short-lived access token for a provider-hosted picker",
+ "description": "Return the raw access token for an OAuth2 credential so the frontend\ncan initialize a provider-hosted picker (e.g. Google Drive Picker).\n\n`GET /{provider}/credentials/{cred_id}` deliberately strips secrets (see\n`CredentialsMetaResponse` + `TestGetCredentialReturnsMetaOnly` in\n`router_test.py`). That hardening broke the Drive picker, which needs the\nraw access token to call `google.picker.Builder.setOAuthToken(...)`. This\nendpoint carves a narrow, explicit hole: the caller must own the\ncredential, it must be OAuth2, and the endpoint returns only the access\ntoken + its expiry — nothing else about the credential. SDK-default\ncredentials are excluded for the same reason as `get_credential`.",
+ "operationId": "postV1GetPickerToken",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "provider",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "The provider that owns the credentials",
+ "description": "Provider name for integrations. Can be any string value, including custom provider names."
+ }
+ },
+ {
+ "name": "cred_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "The ID of the OAuth2 credentials to mint a token from"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/PickerTokenResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/integrations/{provider}/login": {
"get": {
"tags": ["v1", "integrations"],
@@ -5007,6 +5058,15 @@
"title": "Comma-separated list of authorization scopes",
"default": ""
}
+ },
+ {
+ "name": "credential_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "ID of existing credential to upgrade scopes for"
+ }
}
],
"responses": {
@@ -13749,6 +13809,24 @@
"title": "PendingHumanReviewModel",
"description": "Response model for pending human review data.\n\nRepresents a human review request that is awaiting user action.\nContains all necessary information for a user to review and approve\nor reject data from a Human-in-the-Loop block execution.\n\nAttributes:\n id: Unique identifier for the review record\n user_id: ID of the user who must perform the review\n node_exec_id: ID of the node execution that created this review\n node_id: ID of the node definition (for grouping reviews from same node)\n graph_exec_id: ID of the graph execution containing the node\n graph_id: ID of the graph template being executed\n graph_version: Version number of the graph template\n payload: The actual data payload awaiting review\n instructions: Instructions or message for the reviewer\n editable: Whether the reviewer can edit the data\n status: Current review status (WAITING, APPROVED, or REJECTED)\n review_message: Optional message from the reviewer\n created_at: Timestamp when review was created\n updated_at: Timestamp when review was last modified\n reviewed_at: Timestamp when review was completed (if applicable)"
},
+ "PickerTokenResponse": {
+ "properties": {
+ "access_token": {
+ "type": "string",
+ "title": "Access Token",
+ "description": "OAuth access token suitable for the picker SDK call."
+ },
+ "access_token_expires_at": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Access Token Expires At",
+ "description": "Unix timestamp at which the access token expires, if known."
+ }
+ },
+ "type": "object",
+ "required": ["access_token"],
+ "title": "PickerTokenResponse",
+ "description": "Short-lived OAuth access token shipped to the browser for rendering a\nprovider-hosted picker UI (e.g. Google Drive Picker). Deliberately narrow:\nonly the fields the client needs to initialize the picker widget. Issued\nfrom the user's own stored credential so ownership and scope gating are\nenforced by the credential lookup."
+ },
"PlatformCostDashboard": {
"properties": {
"by_provider": {
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.ts
new file mode 100644
index 0000000000..d604daf2b5
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/useCredentialsInput.test.ts
@@ -0,0 +1,220 @@
+import { renderHook, act } from "@testing-library/react";
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import type {
+ BlockIOCredentialsSubSchema,
+ CredentialsMetaResponse,
+} from "@/lib/autogpt-server-api";
+
+vi.mock("@/hooks/useCredentials", () => ({ default: vi.fn() }));
+vi.mock("@/lib/autogpt-server-api/context", () => ({
+ useBackendAPI: vi.fn(),
+}));
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: vi.fn(),
+}));
+vi.mock("@/lib/oauth-popup", () => ({
+ openOAuthPopup: vi.fn(),
+ OAUTH_ERROR_WINDOW_CLOSED: "Sign-in window was closed",
+ OAUTH_ERROR_FLOW_CANCELED: "OAuth flow was canceled",
+ OAUTH_ERROR_FLOW_TIMED_OUT: "OAuth flow timed out",
+}));
+vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),
+}));
+
+import useCredentials from "@/hooks/useCredentials";
+import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { openOAuthPopup } from "@/lib/oauth-popup";
+import { useCredentialsInput } from "../useCredentialsInput";
+
+const mockUseCredentials = useCredentials as unknown as ReturnType<
+ typeof vi.fn
+>;
+const mockUseBackendAPI = useBackendAPI as unknown as ReturnType<typeof vi.fn>;
+const mockOpenOAuthPopup = openOAuthPopup as unknown as ReturnType<
+ typeof vi.fn
+>;
+
+function makeCred(
+ partial: Partial<CredentialsMetaResponse>,
+): CredentialsMetaResponse {
+ return {
+ id: "cred-id",
+ provider: "google",
+ type: "oauth2",
+ title: "Test",
+ scopes: [],
+ ...partial,
+ } as CredentialsMetaResponse;
+}
+
+const baseSchema: BlockIOCredentialsSubSchema = {
+ credentials_provider: ["google"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: ["drive.file", "drive.metadata"],
+} as BlockIOCredentialsSubSchema;
+
+function makeCredentialsReturn(overrides: Record<string, any> = {}) {
+ return {
+ provider: "google",
+ providerName: "Google",
+ savedCredentials: [],
+ upgradeableCredentials: [],
+ supportsApiKey: false,
+ supportsOAuth2: true,
+ supportsUserPassword: false,
+ supportsHostScoped: false,
+ isLoading: false,
+ isSystemProvider: false,
+ schema: baseSchema,
+ oAuthCallback: vi.fn().mockResolvedValue(makeCred({ id: "new-cred" })),
+ mcpOAuthCallback: vi.fn(),
+ createAPIKeyCredentials: vi.fn(),
+ createUserPasswordCredentials: vi.fn(),
+ createHostScopedCredentials: vi.fn(),
+ deleteCredentials: vi.fn(),
+ discriminatorValue: undefined,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseBackendAPI.mockReturnValue({
+ oAuthLogin: vi.fn().mockResolvedValue({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-123",
+ }),
+ });
+});
+
+describe("useCredentialsInput – upgradeableCredentials", () => {
+ it("exposes userUpgradeableCredentials filtered from upgradeableCredentials", () => {
+ const upgradeable = makeCred({
+ id: "narrow",
+ title: "Narrow Cred",
+ scopes: ["drive.file"],
+ });
+ const systemUpgradeable = makeCred({
+ id: "sys",
+ title: "Use credits for Google",
+ scopes: ["drive.file"],
+ is_system: true,
+ });
+
+ mockUseCredentials.mockReturnValue(
+ makeCredentialsReturn({
+ savedCredentials: [],
+ upgradeableCredentials: [upgradeable, systemUpgradeable],
+ }),
+ );
+
+ const onSelect = vi.fn();
+ const { result } = renderHook(() =>
+ useCredentialsInput({
+ schema: baseSchema,
+ onSelectCredential: onSelect,
+ }),
+ );
+
+ expect(result.current.isLoading).toBe(false);
+ if (result.current.isLoading) return;
+
+ // System credentials should be filtered out
+ expect(result.current.userUpgradeableCredentials).toHaveLength(1);
+ expect(result.current.userUpgradeableCredentials![0].id).toBe("narrow");
+ });
+});
+
+describe("useCredentialsInput – handleScopeUpgrade", () => {
+ it("passes credentialID through executeOAuthFlow to oAuthLogin", async () => {
+ const oAuthLoginMock = vi.fn().mockResolvedValue({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-abc",
+ });
+ mockUseBackendAPI.mockReturnValue({ oAuthLogin: oAuthLoginMock });
+
+ const oAuthCallback = vi.fn().mockResolvedValue(
+ makeCred({
+ id: "upgraded-cred",
+ scopes: ["drive.file", "drive.metadata"],
+ }),
+ );
+
+ mockUseCredentials.mockReturnValue(
+ makeCredentialsReturn({ oAuthCallback }),
+ );
+
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: Promise.resolve({ code: "auth-code", state: "state-abc" }),
+ cleanup: { abort: vi.fn() },
+ });
+
+ const onSelect = vi.fn();
+ const { result } = renderHook(() =>
+ useCredentialsInput({
+ schema: baseSchema,
+ onSelectCredential: onSelect,
+ }),
+ );
+
+ expect(result.current.isLoading).toBe(false);
+ if (result.current.isLoading) return;
+
+ await act(async () => {
+ await result.current.handleScopeUpgrade!("existing-cred-id");
+ });
+
+ expect(oAuthLoginMock).toHaveBeenCalledWith(
+ "google",
+ ["drive.file", "drive.metadata"],
+ "existing-cred-id",
+ );
+ });
+
+ it("handleOAuthLogin calls executeOAuthFlow without credentialID", async () => {
+ const oAuthLoginMock = vi.fn().mockResolvedValue({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-xyz",
+ });
+ mockUseBackendAPI.mockReturnValue({ oAuthLogin: oAuthLoginMock });
+
+ const oAuthCallback = vi.fn().mockResolvedValue(
+ makeCred({
+ id: "new-cred",
+ scopes: ["drive.file", "drive.metadata"],
+ }),
+ );
+
+ mockUseCredentials.mockReturnValue(
+ makeCredentialsReturn({ oAuthCallback }),
+ );
+
+ mockOpenOAuthPopup.mockReturnValue({
+ promise: Promise.resolve({ code: "code-2", state: "state-xyz" }),
+ cleanup: { abort: vi.fn() },
+ });
+
+ const onSelect = vi.fn();
+ const { result } = renderHook(() =>
+ useCredentialsInput({
+ schema: baseSchema,
+ onSelectCredential: onSelect,
+ }),
+ );
+
+ expect(result.current.isLoading).toBe(false);
+ if (result.current.isLoading) return;
+
+ await act(async () => {
+ await result.current.handleOAuthLogin!();
+ });
+
+ // credentialID should be undefined (not passed)
+ expect(oAuthLoginMock).toHaveBeenCalledWith(
+ "google",
+ ["drive.file", "drive.metadata"],
+ undefined,
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
index a124566c84..0f63d4237a 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
@@ -154,6 +154,7 @@ export function useCredentialsInput({
supportsUserPassword,
supportsHostScoped,
savedCredentials,
+ upgradeableCredentials,
oAuthCallback,
mcpOAuthCallback,
isSystemProvider,
@@ -163,8 +164,11 @@ export function useCredentialsInput({
// Split credentials into user and system
const userCredentials = filterSystemCredentials(savedCredentials);
const systemCredentials = getSystemCredentials(savedCredentials);
+ const userUpgradeableCredentials = filterSystemCredentials(
+ upgradeableCredentials,
+ );
- async function handleOAuthLogin() {
+ async function executeOAuthFlow(credentialID?: string) {
setOAuthError(null);
// Abort any previous OAuth flow
@@ -187,6 +191,7 @@ export function useCredentialsInput({
({ login_url, state_token } = await api.oAuthLogin(
provider,
schema.credentials_scopes,
+ credentialID,
));
}
@@ -253,6 +258,14 @@ export function useCredentialsInput({
}
}
+ async function handleOAuthLogin() {
+ return executeOAuthFlow();
+ }
+
+ async function handleScopeUpgrade(credentialID: string) {
+ return executeOAuthFlow(credentialID);
+ }
+
const hasMultipleCredentialTypes =
countSupportedTypes(
supportsOAuth2,
@@ -393,6 +406,8 @@ export function useCredentialsInput({
handleDeleteCredential,
handleDeleteConfirm,
handleOAuthLogin,
+ handleScopeUpgrade,
+ userUpgradeableCredentials,
onSelectCredential,
schema,
siblingInputs,
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/fetchPickerAccessToken.test.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/fetchPickerAccessToken.test.ts
new file mode 100644
index 0000000000..cfcd351d29
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/fetchPickerAccessToken.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
+ postV1GetPickerToken: vi.fn(),
+ getGetV1GetSpecificCredentialByIdQueryOptions: vi.fn(),
+}));
+
+import { postV1GetPickerToken } from "@/app/api/__generated__/endpoints/integrations/integrations";
+import { fetchPickerAccessToken } from "../useGoogleDrivePicker";
+
+// Keep the cast rather than `vi.mocked(postV1GetPickerToken)` so the
+// intentionally-malformed mock responses below (missing `headers`, empty
+// `data`, non-200 status) don't have to satisfy the generated
+// `postV1GetPickerTokenResponse` union — these tests exercise defensive
+// paths against misshapen server responses.
+const mockPost = postV1GetPickerToken as unknown as ReturnType<typeof vi.fn>;
+
+afterEach(() => {
+ mockPost.mockReset();
+});
+
+describe("fetchPickerAccessToken", () => {
+ it("returns the access token when the picker-token endpoint succeeds", async () => {
+ // Backend `POST /api/integrations/google/credentials/{id}/picker-token`
+ // returns { access_token, access_token_expires_at } on success. The hook
+ // only needs the access_token; `access_token_expires_at` is informational.
+ mockPost.mockResolvedValue({
+ status: 200,
+ data: {
+ access_token: "ya29.real-token-value",
+ access_token_expires_at: 1776834363,
+ },
+ });
+
+ await expect(fetchPickerAccessToken("cred-123")).resolves.toBe(
+ "ya29.real-token-value",
+ );
+ expect(mockPost).toHaveBeenCalledWith("google", "cred-123");
+ });
+
+ it("throws when the server returns a non-200 response", async () => {
+ // Backend returns 400/404 for non-OAuth2 creds, missing creds, or creds
+ // without an access_token. `okData` treats anything !== 200 as undefined,
+ // so we should surface a distinct error rather than silently passing an
+ // empty string to the Google Picker.
+ mockPost.mockResolvedValue({
+ status: 400,
+ data: {
+ detail: "Picker tokens are only available for OAuth2 credentials",
+ },
+ });
+
+ await expect(fetchPickerAccessToken("cred-456")).rejects.toThrow(
+ /did not return an access token/i,
+ );
+ });
+
+ it("throws when the 200 response is missing access_token", async () => {
+ // Regression guard for the pre-PR-#12874 shape: the meta-only endpoint
+ // used to satisfy the picker query but never included access_token —
+ // the hook silently entered the "Failed to retrieve" fallback path.
+ // If the server ever responds with an empty `data` again, we want a
+ // loud throw, not a silent fallback, so reviewers see the mismatch.
+ mockPost.mockResolvedValue({ status: 200, data: {} });
+
+ await expect(fetchPickerAccessToken("cred-789")).rejects.toThrow(
+ /did not return an access token/i,
+ );
+ });
+
+ it("throws when the 200 response has an empty-string access_token", async () => {
+ // Defence against a misconfigured or stripped server response. An empty
+ // string would pass `response.data.access_token` presence checks in some
+ // implementations; make sure falsy-but-present also trips the guard.
+ mockPost.mockResolvedValue({
+ status: 200,
+ data: { access_token: "", access_token_expires_at: null },
+ });
+
+ await expect(fetchPickerAccessToken("cred-empty")).rejects.toThrow(
+ /did not return an access token/i,
+ );
+ });
+
+ it("propagates thrown errors from the underlying fetch", async () => {
+ // Network failure / proxy 415 / JSON parse error surfaces as a thrown
+ // error from the generated mutator. Don't swallow it — the caller
+ // (`useGoogleDrivePicker.openPicker()`) has its own try/catch that
+ // surfaces an "Authentication Error" toast, which relies on this
+ // propagation.
+ mockPost.mockRejectedValue(new Error("network boom"));
+
+ await expect(fetchPickerAccessToken("cred-boom")).rejects.toThrow(
+ "network boom",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/hasAllRequiredScopes.test.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/hasAllRequiredScopes.test.ts
new file mode 100644
index 0000000000..bf0b1ba536
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/hasAllRequiredScopes.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { hasAllRequiredScopes } from "../useGoogleDrivePicker";
+
+describe("hasAllRequiredScopes", () => {
+ it("returns true when no scopes are required", () => {
+ expect(hasAllRequiredScopes([], undefined)).toBe(true);
+ expect(hasAllRequiredScopes(["drive.file"], undefined)).toBe(true);
+ expect(hasAllRequiredScopes([], [])).toBe(true);
+ });
+
+ it("returns true when granted scopes are a superset of required", () => {
+ expect(
+ hasAllRequiredScopes(
+ ["drive.file", "drive.metadata", "drive.readonly"],
+ ["drive.file", "drive.metadata"],
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when granted scopes exactly match required", () => {
+ expect(
+ hasAllRequiredScopes(
+ ["drive.file", "drive.metadata"],
+ ["drive.file", "drive.metadata"],
+ ),
+ ).toBe(true);
+ });
+
+ it("returns false when even one required scope is missing", () => {
+ // Regression: the picker must gate on EVERY required scope being
+ // present. Prior to the fix the check used
+ // `Set.prototype.isSupersetOf` — which is ES2025 and not yet in
+ // the supported browser baseline — so the check silently ran as
+ // `undefined` and never failed closed.
+ expect(
+ hasAllRequiredScopes(["drive.file"], ["drive.file", "drive.metadata"]),
+ ).toBe(false);
+ });
+
+ it("returns false when granted scopes are empty but required is non-empty", () => {
+ expect(hasAllRequiredScopes([], ["drive.file"])).toBe(false);
+ });
+
+ it("tolerates null / undefined granted scopes", () => {
+ // Shape from the API: `oauth2` credentials sometimes store `scopes`
+ // as null. We should treat null/undefined as "no scopes granted",
+ // not crash.
+ expect(hasAllRequiredScopes(null, ["drive.file"])).toBe(false);
+ expect(hasAllRequiredScopes(undefined, ["drive.file"])).toBe(false);
+ expect(hasAllRequiredScopes(null, [])).toBe(true);
+ expect(hasAllRequiredScopes(null, undefined)).toBe(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..c4ca0e645b
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/helpers.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/services/scripts/scripts", () => ({
+ loadScript: vi.fn(),
+}));
+
+import { loadScript } from "@/services/scripts/scripts";
+import { loadGoogleAPIPicker, loadGoogleIdentityServices } from "../helpers";
+
+const mockLoadScript = loadScript as unknown as ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ mockLoadScript.mockReset();
+ // Simulate an immediate successful script load so the helpers can
+ // proceed past the `loadScript` await.
+ mockLoadScript.mockResolvedValue(undefined);
+
+ // Provide a minimal stub for the Google global so the downstream
+ // checks (`window.gapi`, `window.google`) pass.
+ (window as any).gapi = {
+ load: (_name: string, opts: { callback: () => void }) => {
+ opts.callback();
+ },
+ };
+ (window as any).google = {
+ accounts: { oauth2: {} },
+ };
+});
+
+afterEach(() => {
+ delete (window as any).gapi;
+ delete (window as any).google;
+});
+
+describe("loadGoogleAPIPicker", () => {
+ it("loads api.js with the no-referrer-when-downgrade policy", async () => {
+ // Firefox respects the default strict-origin-when-cross-origin
+ // policy and strips the Referer header on cross-site navigation —
+ // Google's api.js issues a picker-token request that fails without
+ // a Referer. Passing `referrerPolicy: "no-referrer-when-downgrade"`
+ // keeps the header intact for cross-site same-scheme requests.
+ // Pin that policy so a future cleanup doesn't silently drop it.
+ await loadGoogleAPIPicker();
+
+ expect(mockLoadScript).toHaveBeenCalledTimes(1);
+ const [url, opts] = mockLoadScript.mock.calls[0];
+ expect(url).toBe("https://apis.google.com/js/api.js");
+ expect(opts).toEqual({ referrerPolicy: "no-referrer-when-downgrade" });
+ });
+
+ it("throws if window.gapi is missing after the script loads", async () => {
+ delete (window as any).gapi;
+
+ await expect(loadGoogleAPIPicker()).rejects.toThrow(/Google AIP/);
+ });
+});
+
+describe("loadGoogleIdentityServices", () => {
+ it("loads gsi/client with the no-referrer-when-downgrade policy", async () => {
+ await loadGoogleIdentityServices();
+
+ expect(mockLoadScript).toHaveBeenCalledTimes(1);
+ const [url, opts] = mockLoadScript.mock.calls[0];
+ expect(url).toBe("https://accounts.google.com/gsi/client");
+ expect(opts).toEqual({ referrerPolicy: "no-referrer-when-downgrade" });
+ });
+
+ it("throws if google.accounts.oauth2 is missing after the script loads", async () => {
+ (window as any).google = {};
+
+ await expect(loadGoogleIdentityServices()).rejects.toThrow(
+ /Google Identity Services not available/,
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.ts
new file mode 100644
index 0000000000..bf31d6ab46
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/__tests__/useGoogleDrivePicker.test.ts
@@ -0,0 +1,333 @@
+import { renderHook, act } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/hooks/useCredentials", () => ({ default: vi.fn() }));
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: vi.fn(),
+}));
+vi.mock("@/services/scripts/scripts", () => ({
+ loadScript: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
+ getGetV1GetSpecificCredentialByIdQueryOptions: vi.fn(),
+ postV1GetPickerToken: vi.fn(),
+}));
+vi.mock("@/app/api/helpers", () => ({
+ okData: vi.fn((resp: any) => (resp?.status === 200 ? resp.data : undefined)),
+}));
+
+import useCredentials from "@/hooks/useCredentials";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ getGetV1GetSpecificCredentialByIdQueryOptions,
+ postV1GetPickerToken,
+} from "@/app/api/__generated__/endpoints/integrations/integrations";
+import { useGoogleDrivePicker } from "../useGoogleDrivePicker";
+import type { CredentialsMetaResponse } from "@/lib/autogpt-server-api";
+
+const mockUseCredentials = useCredentials as unknown as ReturnType<
+ typeof vi.fn
+>;
+const mockUseToast = useToast as unknown as ReturnType<typeof vi.fn>;
+const mockPostPickerToken = postV1GetPickerToken as unknown as ReturnType<
+ typeof vi.fn
+>;
+const mockGetQueryOptions =
+ getGetV1GetSpecificCredentialByIdQueryOptions as unknown as ReturnType<
+ typeof vi.fn
+ >;
+
+function makeCred(
+ partial: Partial<CredentialsMetaResponse>,
+): CredentialsMetaResponse {
+ return {
+ id: "cred-id",
+ provider: "google",
+ type: "oauth2",
+ title: "Test",
+ scopes: [],
+ ...partial,
+ } as CredentialsMetaResponse;
+}
+
+// Minimal react-query QueryClient mock
+const mockFetchQuery = vi.fn();
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ fetchQuery: mockFetchQuery }),
+}));
+
+// Mock Google globals for ensureLoaded + buildAndShowPicker
+function setupGoogleGlobals() {
+ const setOAuthToken = vi.fn();
+ const setDeveloperKey = vi.fn();
+ const setAppId = vi.fn();
+ const setCallback = vi.fn();
+ const enableFeature = vi.fn();
+ const addView = vi.fn();
+ const build = vi.fn().mockReturnValue({ setVisible: vi.fn() });
+
+ // Use a class so `new PickerBuilder()` works properly in vitest 4.x
+ class MockPickerBuilder {
+ setOAuthToken = (...args: any[]) => {
+ setOAuthToken(...args);
+ return this;
+ };
+ setDeveloperKey = (...args: any[]) => {
+ setDeveloperKey(...args);
+ return this;
+ };
+ setAppId = (...args: any[]) => {
+ setAppId(...args);
+ return this;
+ };
+ setCallback = (...args: any[]) => {
+ setCallback(...args);
+ return this;
+ };
+ enableFeature = (...args: any[]) => {
+ enableFeature(...args);
+ return this;
+ };
+ addView = (...args: any[]) => {
+ addView(...args);
+ return this;
+ };
+ build = (...args: any[]) => build(...args);
+ }
+
+ class MockDocsView {
+ setMode = vi.fn();
+ constructor(_viewId?: any) {}
+ }
+
+ (window as any).gapi = {
+ load: (_name: string, opts: { callback: () => void }) => opts.callback(),
+ };
+ (window as any).google = {
+ accounts: {
+ oauth2: {
+ initTokenClient: vi.fn().mockReturnValue({
+ requestAccessToken: vi.fn(),
+ }),
+ },
+ },
+ picker: {
+ PickerBuilder: MockPickerBuilder,
+ DocsView: MockDocsView,
+ DocsViewMode: { LIST: "LIST" },
+ Feature: { NAV_HIDDEN: "NAV_HIDDEN", MULTISELECT_ENABLED: "MULTI" },
+ ViewId: {
+ DOCS: "DOCS",
+ DOCUMENTS: "DOCUMENTS",
+ SPREADSHEETS: "SPREADSHEETS",
+ },
+ Response: { ACTION: "action", DOCUMENTS: "documents" },
+ Action: { PICKED: "picked" },
+ Document: {
+ ID: "id",
+ NAME: "name",
+ MIME_TYPE: "mimeType",
+ URL: "url",
+ ICON_URL: "iconUrl",
+ },
+ },
+ };
+
+ return { build, setOAuthToken };
+}
+
+const toastMock = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseToast.mockReturnValue({ toast: toastMock });
+ mockGetQueryOptions.mockReturnValue({ queryKey: ["cred"], queryFn: vi.fn() });
+});
+
+afterEach(() => {
+ delete (window as any).gapi;
+ delete (window as any).google;
+});
+
+describe("useGoogleDrivePicker – openPicker saved-credential flow", () => {
+ it("shows insufficient scopes toast when credential lacks required scopes", async () => {
+ const { build } = setupGoogleGlobals();
+
+ const savedCred = makeCred({
+ id: "narrow-cred",
+ scopes: ["drive.file"],
+ });
+
+ mockUseCredentials.mockReturnValue({
+ provider: "google",
+ providerName: "Google",
+ savedCredentials: [savedCred],
+ upgradeableCredentials: [],
+ supportsOAuth2: true,
+ supportsApiKey: false,
+ supportsUserPassword: false,
+ supportsHostScoped: false,
+ isLoading: false,
+ isSystemProvider: false,
+ });
+
+ // The credential returned by fetchQuery lacks the required scopes
+ mockFetchQuery.mockResolvedValue({
+ status: 200,
+ data: {
+ id: "narrow-cred",
+ type: "oauth2",
+ scopes: ["drive.file"],
+ },
+ });
+
+ const onError = vi.fn();
+ const onPicked = vi.fn();
+ const onCanceled = vi.fn();
+
+ const { result } = renderHook(() =>
+ useGoogleDrivePicker({
+ scopes: ["drive.file", "drive.metadata"],
+ developerKey: "dev-key",
+ clientId: "client-id",
+ appId: "app-id",
+ onPicked,
+ onCanceled,
+ onError,
+ }),
+ );
+
+ await act(async () => {
+ await result.current.handleOpenPicker();
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Insufficient Permissions",
+ variant: "destructive",
+ }),
+ );
+ expect(onError).toHaveBeenCalledWith(expect.any(Error));
+ // Picker should NOT have been built
+ expect(build).not.toHaveBeenCalled();
+ });
+
+ it("fetches picker token and builds picker when scopes are sufficient", async () => {
+ const { build, setOAuthToken } = setupGoogleGlobals();
+
+ const savedCred = makeCred({
+ id: "full-cred",
+ scopes: ["drive.file", "drive.metadata"],
+ });
+
+ mockUseCredentials.mockReturnValue({
+ provider: "google",
+ providerName: "Google",
+ savedCredentials: [savedCred],
+ upgradeableCredentials: [],
+ supportsOAuth2: true,
+ supportsApiKey: false,
+ supportsUserPassword: false,
+ supportsHostScoped: false,
+ isLoading: false,
+ isSystemProvider: false,
+ });
+
+ // fetchQuery returns oauth2 credential with all scopes
+ mockFetchQuery.mockResolvedValue({
+ status: 200,
+ data: {
+ id: "full-cred",
+ type: "oauth2",
+ scopes: ["drive.file", "drive.metadata"],
+ },
+ });
+
+ // Mock picker token endpoint
+ mockPostPickerToken.mockResolvedValue({
+ status: 200,
+ data: { access_token: "ya29.picker-token" },
+ });
+
+ const onError = vi.fn();
+ const onPicked = vi.fn();
+ const onCanceled = vi.fn();
+
+ const { result } = renderHook(() =>
+ useGoogleDrivePicker({
+ scopes: ["drive.file", "drive.metadata"],
+ developerKey: "dev-key",
+ clientId: "client-id",
+ appId: "app-id",
+ onPicked,
+ onCanceled,
+ onError,
+ }),
+ );
+
+ await act(async () => {
+ await result.current.handleOpenPicker();
+ });
+
+ // Should have fetched a picker token
+ expect(mockPostPickerToken).toHaveBeenCalledWith("google", "full-cred");
+ // Picker should have been built with the token
+ expect(build).toHaveBeenCalled();
+ expect(setOAuthToken).toHaveBeenCalledWith("ya29.picker-token");
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it("calls onError when credential is not oauth2", async () => {
+ setupGoogleGlobals();
+
+ const savedCred = makeCred({
+ id: "api-key-cred",
+ type: "api_key",
+ scopes: [],
+ });
+
+ mockUseCredentials.mockReturnValue({
+ provider: "google",
+ providerName: "Google",
+ savedCredentials: [savedCred],
+ upgradeableCredentials: [],
+ supportsOAuth2: true,
+ supportsApiKey: true,
+ supportsUserPassword: false,
+ supportsHostScoped: false,
+ isLoading: false,
+ isSystemProvider: false,
+ });
+
+ mockFetchQuery.mockResolvedValue({
+ status: 200,
+ data: { id: "api-key-cred", type: "api_key" },
+ });
+
+ const onError = vi.fn();
+ const onPicked = vi.fn();
+ const onCanceled = vi.fn();
+
+ const { result } = renderHook(() =>
+ useGoogleDrivePicker({
+ scopes: ["drive.file"],
+ developerKey: "dev-key",
+ clientId: "client-id",
+ appId: "app-id",
+ onPicked,
+ onCanceled,
+ onError,
+ }),
+ );
+
+ await act(async () => {
+ await result.current.handleOpenPicker();
+ });
+
+ expect(onError).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining("Failed to retrieve"),
+ }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/helpers.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/helpers.ts
index 05b591ebf6..ab7b92c20b 100644
--- a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/helpers.ts
@@ -4,7 +4,9 @@ import { loadScript } from "@/services/scripts/scripts";
export async function loadGoogleAPIPicker(): Promise<void> {
validateWindow();
- await loadScript("https://apis.google.com/js/api.js");
+ await loadScript("https://apis.google.com/js/api.js", {
+ referrerPolicy: "no-referrer-when-downgrade",
+ });
const googleAPI = window.gapi;
if (!googleAPI) {
@@ -27,7 +29,9 @@ export async function loadGoogleIdentityServices(): Promise<void> {
throw new Error("Google Identity Services cannot load on server");
}
- await loadScript("https://accounts.google.com/gsi/client");
+ await loadScript("https://accounts.google.com/gsi/client", {
+ referrerPolicy: "no-referrer-when-downgrade",
+ });
const google = window.google;
if (!google?.accounts?.oauth2) {
diff --git a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/useGoogleDrivePicker.ts b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/useGoogleDrivePicker.ts
index f6478f6c2b..fd9b0f6bbb 100644
--- a/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/useGoogleDrivePicker.ts
+++ b/autogpt_platform/frontend/src/components/contextual/GoogleDrivePicker/useGoogleDrivePicker.ts
@@ -1,5 +1,7 @@
-import { getGetV1GetSpecificCredentialByIdQueryOptions } from "@/app/api/__generated__/endpoints/integrations/integrations";
-import type { OAuth2Credentials } from "@/app/api/__generated__/models/oAuth2Credentials";
+import {
+ getGetV1GetSpecificCredentialByIdQueryOptions,
+ postV1GetPickerToken,
+} from "@/app/api/__generated__/endpoints/integrations/integrations";
import { useToast } from "@/components/molecules/Toast/use-toast";
import useCredentials from "@/hooks/useCredentials";
import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
@@ -17,6 +19,35 @@ import {
} from "./helpers";
import { okData } from "@/app/api/helpers";
+export async function fetchPickerAccessToken(
+ credentialId: string,
+): Promise<string> {
+ const response = await postV1GetPickerToken("google", credentialId);
+ const token = okData(response)?.access_token;
+ if (!token) {
+ throw new Error(
+ "Server did not return an access token for the Google Drive picker.",
+ );
+ }
+ return token;
+}
+
+/**
+ * Whether a saved credential's granted scopes cover every scope the picker
+ * is asking for. Pulled out of openPicker() so the scope-gate can be
+ * exercised directly — the hook flow around it needs a browser env and
+ * is hard to test in isolation. `undefined` required-scopes is treated
+ * as "no scope requirement".
+ */
+export function hasAllRequiredScopes(
+ credentialScopes: readonly string[] | null | undefined,
+ requiredScopes: readonly string[] | null | undefined,
+): boolean {
+ if (!requiredScopes || requiredScopes.length === 0) return true;
+ const granted = new Set(credentialScopes || []);
+ return requiredScopes.every((scope) => granted.has(scope));
+}
+
const defaultScopes = ["https://www.googleapis.com/auth/drive.file"];
type TokenClient = {
@@ -129,35 +160,29 @@ export function useGoogleDrivePicker(options: Props) {
const response = await queryClient.fetchQuery(queryOptions);
const cred = okData(response);
- if (cred) {
- if (cred.type === "oauth2") {
- const oauthCred = cred as OAuth2Credentials;
- if (oauthCred.access_token) {
- const credentialScopes = new Set(oauthCred.scopes || []);
- const requiredScopesSet = new Set(requestedScopes);
- const hasRequiredScopes = Array.from(requiredScopesSet).every(
- (scope) => credentialScopes.has(scope),
- );
-
- if (!hasRequiredScopes) {
- const error = new Error(
- "The saved Google OAuth credentials do not have the required permissions. Please sign in again with the correct permissions.",
- );
- toast({
- title: "Insufficient Permissions",
- description: error.message,
- variant: "destructive",
- });
- setHasInsufficientScopes(true);
- if (onError) onError(error);
- return;
- }
-
- accessTokenRef.current = oauthCred.access_token;
- buildAndShowPicker(oauthCred.access_token);
- return;
- }
+ if (cred && cred.type === "oauth2") {
+ if (!hasAllRequiredScopes(cred.scopes, requestedScopes)) {
+ const error = new Error(
+ "The saved Google OAuth credentials do not have the required permissions. Please sign in again with the correct permissions.",
+ );
+ toast({
+ title: "Insufficient Permissions",
+ description: error.message,
+ variant: "destructive",
+ });
+ setHasInsufficientScopes(true);
+ if (onError) onError(error);
+ return;
}
+
+ // The meta endpoint (used above for the scope check) deliberately
+ // strips `access_token` — see TestGetCredentialReturnsMetaOnly in
+ // backend/api/features/integrations/router_test.py. Mint a fresh
+ // access token via the dedicated picker-token endpoint instead.
+ const accessToken = await fetchPickerAccessToken(credentialId);
+ accessTokenRef.current = accessToken;
+ buildAndShowPicker(accessToken);
+ return;
}
const error = new Error(
diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.test.ts b/autogpt_platform/frontend/src/hooks/useCredentials.test.ts
new file mode 100644
index 0000000000..c015949a9b
--- /dev/null
+++ b/autogpt_platform/frontend/src/hooks/useCredentials.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it } from "vitest";
+import { renderHook } from "@testing-library/react";
+import React from "react";
+import { classifyCredentials } from "./useCredentials";
+import useCredentials from "./useCredentials";
+import type {
+ BlockIOCredentialsSubSchema,
+ CredentialsMetaResponse,
+} from "@/lib/autogpt-server-api";
+import {
+ CredentialsProvidersContext,
+ type CredentialsProvidersContextType,
+} from "@/providers/agent-credentials/credentials-provider";
+
+function makeSchema(
+ partial: Partial<BlockIOCredentialsSubSchema> = {},
+): BlockIOCredentialsSubSchema {
+ return {
+ credentials_provider: ["google"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: [],
+ ...partial,
+ } as BlockIOCredentialsSubSchema;
+}
+
+function makeCred(
+ partial: Partial<CredentialsMetaResponse>,
+): CredentialsMetaResponse {
+ return {
+ id: "cred-id",
+ provider: "google",
+ type: "oauth2",
+ title: "Test Credential",
+ scopes: [],
+ ...partial,
+ } as CredentialsMetaResponse;
+}
+
+describe("classifyCredentials", () => {
+ it("drops credentials of unsupported types", () => {
+ const schema = makeSchema({ credentials_types: ["oauth2"] });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [
+ makeCred({ id: "a", type: "api_key" }),
+ makeCred({ id: "b", type: "oauth2" }),
+ ],
+ schema,
+ undefined,
+ );
+
+ expect(savedCredentials.map((c) => c.id)).toEqual(["b"]);
+ expect(upgradeableCredentials).toEqual([]);
+ });
+
+ it("classifies OAuth2 creds with all required scopes as saved", () => {
+ const schema = makeSchema({
+ credentials_scopes: ["drive.file", "drive.metadata"],
+ });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [
+ makeCred({
+ id: "full",
+ scopes: ["drive.file", "drive.metadata", "drive.readonly"],
+ }),
+ ],
+ schema,
+ undefined,
+ );
+
+ expect(savedCredentials.map((c) => c.id)).toEqual(["full"]);
+ expect(upgradeableCredentials).toEqual([]);
+ });
+
+ it("classifies OAuth2 creds missing a scope as upgradeable (not discarded)", () => {
+ // Regression coverage for the incremental-OAuth flow: a credential
+ // that's missing only one scope must land in upgradeableCredentials so
+ // the UI can offer the user a scope-upgrade flow rather than force
+ // them to create a whole new credential from scratch.
+ const schema = makeSchema({
+ credentials_scopes: ["drive.file", "drive.metadata"],
+ });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [makeCred({ id: "narrow", scopes: ["drive.file"] })],
+ schema,
+ undefined,
+ );
+
+ expect(savedCredentials).toEqual([]);
+ expect(upgradeableCredentials.map((c) => c.id)).toEqual(["narrow"]);
+ });
+
+ it("treats schemas without credentials_scopes as no-scope-required", () => {
+ const schema = makeSchema({ credentials_scopes: undefined });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [makeCred({ id: "anything", scopes: [] })],
+ schema,
+ undefined,
+ );
+
+ expect(savedCredentials.map((c) => c.id)).toEqual(["anything"]);
+ expect(upgradeableCredentials).toEqual([]);
+ });
+
+ it("filters MCP OAuth2 credentials by host (discriminator) and never upgrades them", () => {
+ const schema = makeSchema({
+ credentials_provider: ["mcp"],
+ credentials_types: ["oauth2"],
+ });
+ const creds = [
+ makeCred({ id: "match", provider: "mcp", host: "https://mcp.example" }),
+ makeCred({
+ id: "different-host",
+ provider: "mcp",
+ host: "https://other.example",
+ }),
+ ];
+
+ const matchingDiscriminator = classifyCredentials(
+ creds,
+ schema,
+ "https://mcp.example",
+ );
+ expect(matchingDiscriminator.savedCredentials.map((c) => c.id)).toEqual([
+ "match",
+ ]);
+ expect(matchingDiscriminator.upgradeableCredentials).toEqual([]);
+
+ // A missing discriminator must drop all MCP creds (not upgrade them).
+ const noDiscriminator = classifyCredentials(creds, schema, undefined);
+ expect(noDiscriminator.savedCredentials).toEqual([]);
+ expect(noDiscriminator.upgradeableCredentials).toEqual([]);
+ });
+
+ it("host_scoped credentials: discriminator URL is hostname-compared to c.host", () => {
+ const schema = makeSchema({ credentials_types: ["host_scoped"] });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [
+ makeCred({
+ id: "match",
+ type: "host_scoped",
+ host: "api.example.com",
+ }),
+ makeCred({
+ id: "mismatch",
+ type: "host_scoped",
+ host: "other.example.com",
+ }),
+ ],
+ schema,
+ "https://api.example.com/something",
+ );
+
+ expect(savedCredentials.map((c) => c.id)).toEqual(["match"]);
+ expect(upgradeableCredentials).toEqual([]);
+ });
+
+ it("includes api_key and user_password credentials unconditionally when type is supported", () => {
+ const schema = makeSchema({
+ credentials_types: ["api_key", "user_password"],
+ });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ [
+ makeCred({ id: "k", type: "api_key" }),
+ makeCred({ id: "p", type: "user_password" }),
+ ],
+ schema,
+ undefined,
+ );
+
+ expect(savedCredentials.map((c) => c.id).sort()).toEqual(["k", "p"]);
+ expect(upgradeableCredentials).toEqual([]);
+ });
+});
+
+function makeProviderMap(
+ saved: CredentialsMetaResponse[],
+): CredentialsProvidersContextType {
+ return {
+ google: {
+ provider: "google",
+ providerName: "Google",
+ savedCredentials: saved,
+ isSystemProvider: false,
+ oAuthCallback: async () => makeCred({}),
+ mcpOAuthCallback: async () => makeCred({}),
+ createAPIKeyCredentials: async () => makeCred({}),
+ createUserPasswordCredentials: async () => makeCred({}),
+ createHostScopedCredentials: async () => makeCred({}),
+ deleteCredentials: async () => ({ deleted: true, revoked: true }),
+ },
+ };
+}
+
+describe("useCredentials (hook)", () => {
+ it("returns upgradeableCredentials for OAuth2 creds missing scopes", () => {
+ const schema = makeSchema({
+ credentials_provider: ["google"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: ["drive.file", "drive.metadata"],
+ });
+
+ const full = makeCred({
+ id: "full",
+ scopes: ["drive.file", "drive.metadata"],
+ });
+ const narrow = makeCred({ id: "narrow", scopes: ["drive.file"] });
+ const providers = makeProviderMap([full, narrow]);
+
+ function Wrapper({ children }: { children: React.ReactNode }) {
+ return React.createElement(
+ CredentialsProvidersContext.Provider,
+ { value: providers },
+ children,
+ );
+ }
+
+ const { result } = renderHook(() => useCredentials(schema), {
+ wrapper: Wrapper,
+ });
+
+ expect(result.current).not.toBeNull();
+ const data = result.current!;
+ expect(data.isLoading).toBe(false);
+ if (data.isLoading) return;
+
+ expect(data.savedCredentials.map((c) => c.id)).toEqual(["full"]);
+ expect(data.upgradeableCredentials.map((c) => c.id)).toEqual(["narrow"]);
+ });
+
+ it("returns empty upgradeableCredentials when all scopes match", () => {
+ const schema = makeSchema({
+ credentials_provider: ["google"],
+ credentials_types: ["oauth2"],
+ credentials_scopes: ["drive.file"],
+ });
+
+ const cred = makeCred({ id: "ok", scopes: ["drive.file", "drive.meta"] });
+ const providers = makeProviderMap([cred]);
+
+ function Wrapper({ children }: { children: React.ReactNode }) {
+ return React.createElement(
+ CredentialsProvidersContext.Provider,
+ { value: providers },
+ children,
+ );
+ }
+
+ const { result } = renderHook(() => useCredentials(schema), {
+ wrapper: Wrapper,
+ });
+
+ expect(result.current).not.toBeNull();
+ const data = result.current!;
+ expect(data.isLoading).toBe(false);
+ if (data.isLoading) return;
+
+ expect(data.savedCredentials.map((c) => c.id)).toEqual(["ok"]);
+ expect(data.upgradeableCredentials).toEqual([]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.ts b/autogpt_platform/frontend/src/hooks/useCredentials.ts
index 9a78e5b8f4..21c0e425ad 100644
--- a/autogpt_platform/frontend/src/hooks/useCredentials.ts
+++ b/autogpt_platform/frontend/src/hooks/useCredentials.ts
@@ -7,10 +7,63 @@ import {
} from "@/providers/agent-credentials/credentials-provider";
import {
BlockIOCredentialsSubSchema,
+ CredentialsMetaResponse,
CredentialsProviderName,
} from "@/lib/autogpt-server-api";
import { getHostFromUrl } from "@/lib/utils/url";
+export function classifyCredentials(
+ allSaved: readonly CredentialsMetaResponse[],
+ credsInputSchema: BlockIOCredentialsSubSchema,
+ discriminatorValue: string | undefined,
+): {
+ savedCredentials: CredentialsMetaResponse[];
+ upgradeableCredentials: CredentialsMetaResponse[];
+} {
+ const savedCredentials: CredentialsMetaResponse[] = [];
+ const upgradeableCredentials: CredentialsMetaResponse[] = [];
+ const supportedTypes = credsInputSchema.credentials_types;
+
+ for (const c of allSaved) {
+ if (!supportedTypes.includes(c.type)) continue;
+
+ // MCP OAuth2 credentials filter by server URL — not upgradeable
+ if (c.type === "oauth2" && c.provider === "mcp") {
+ if (discriminatorValue != null && c.host === discriminatorValue) {
+ savedCredentials.push(c);
+ }
+ continue;
+ }
+
+ if (c.type === "oauth2") {
+ const requiredScopes = credsInputSchema.credentials_scopes;
+ // Set.prototype.isSupersetOf is ES2025 and this project targets
+ // ES2022 — fall back to an array every() check so the picker's
+ // scope filter runs cleanly on current Node/browser baselines.
+ const credScopes = new Set(c.scopes);
+ const hasAllScopes =
+ !requiredScopes || requiredScopes.every((s) => credScopes.has(s));
+ if (hasAllScopes) {
+ savedCredentials.push(c);
+ } else {
+ upgradeableCredentials.push(c);
+ }
+ continue;
+ }
+
+ if (c.type === "host_scoped") {
+ if (discriminatorValue && getHostFromUrl(discriminatorValue) == c.host) {
+ savedCredentials.push(c);
+ }
+ continue;
+ }
+
+ savedCredentials.push(c);
+ }
+
+ return { savedCredentials, upgradeableCredentials };
+}
+
export type CredentialsData =
| {
provider: string;
@@ -30,6 +83,7 @@ export type CredentialsData =
supportsHostScoped: boolean;
isLoading: false;
discriminatorValue?: string;
+ upgradeableCredentials: CredentialsMetaResponse[];
});
export default function useCredentials(
@@ -83,45 +137,14 @@ export default function useCredentials(
// No provider means maybe it's still loading
if (!provider) {
- // return {
- // provider: credsInputSchema.credentials_provider,
- // schema: credsInputSchema,
- // supportsApiKey,
- // supportsOAuth2,
- // isLoading: true,
- // };
return null;
}
- const savedCredentials = provider.savedCredentials.filter((c) => {
- // First, check if the credential type is supported by this block
- const supportedTypes = credsInputSchema.credentials_types;
- if (!supportedTypes.includes(c.type)) {
- return false;
- }
-
- // Filter MCP OAuth2 credentials by server URL matching
- if (c.type === "oauth2" && c.provider === "mcp") {
- return discriminatorValue != null && c.host === discriminatorValue;
- }
-
- // Filter by OAuth credentials that have sufficient scopes for this block
- if (c.type === "oauth2") {
- const requiredScopes = credsInputSchema.credentials_scopes;
- return (
- !requiredScopes ||
- new Set(c.scopes).isSupersetOf(new Set(requiredScopes))
- );
- }
-
- // Filter host_scoped credentials by host matching
- if (c.type === "host_scoped") {
- return discriminatorValue && getHostFromUrl(discriminatorValue) == c.host;
- }
-
- // Include all other credential types that passed the type check
- return true;
- });
+ const { savedCredentials, upgradeableCredentials } = classifyCredentials(
+ provider.savedCredentials,
+ credsInputSchema,
+ discriminatorValue,
+ );
return {
...provider,
@@ -132,6 +155,7 @@ export default function useCredentials(
supportsUserPassword,
supportsHostScoped,
savedCredentials,
+ upgradeableCredentials,
discriminatorValue,
isLoading: false,
};
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.ts
new file mode 100644
index 0000000000..5baa78e4c0
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from "vitest";
+import BackendAPI, { buildOAuthLoginQuery } from "./client";
+
+describe("BackendAPI.oAuthLogin", () => {
+ it("passes credentialID through to buildOAuthLoginQuery", async () => {
+ const api = new BackendAPI("http://test", "ws://test");
+ const spy = vi.spyOn(api as any, "_get").mockResolvedValue({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-abc",
+ });
+
+ const result = await api.oAuthLogin("google", ["drive.file"], "cred-1");
+
+ expect(spy).toHaveBeenCalledWith("/integrations/google/login", {
+ scopes: "drive.file",
+ credential_id: "cred-1",
+ });
+ expect(result).toEqual({
+ login_url: "https://accounts.google.com/o/oauth2/auth",
+ state_token: "state-abc",
+ });
+ });
+
+ it("omits query when no scopes or credentialID", async () => {
+ const api = new BackendAPI("http://test", "ws://test");
+ const spy = vi
+ .spyOn(api as any, "_get")
+ .mockResolvedValue({ login_url: "url", state_token: "tok" });
+
+ await api.oAuthLogin("github");
+
+ expect(spy).toHaveBeenCalledWith("/integrations/github/login", undefined);
+ });
+});
+
+describe("buildOAuthLoginQuery", () => {
+ it("returns undefined when called with no args", () => {
+ expect(buildOAuthLoginQuery()).toBeUndefined();
+ });
+
+ it("returns undefined when scopes is empty and credentialID is absent", () => {
+ // Old behavior sent `{scopes: ""}` for an empty array, which the
+ // backend rejects. Pin the tighter contract.
+ expect(buildOAuthLoginQuery([])).toBeUndefined();
+ });
+
+ it("joins scopes with a comma", () => {
+ expect(buildOAuthLoginQuery(["drive.file", "drive.metadata"])).toEqual({
+ scopes: "drive.file,drive.metadata",
+ });
+ });
+
+ it("includes credential_id when provided", () => {
+ expect(buildOAuthLoginQuery(undefined, "cred-1")).toEqual({
+ credential_id: "cred-1",
+ });
+ });
+
+ it("includes both scopes and credential_id when both are provided", () => {
+ // The incremental-OAuth flow sends both: the scopes the block needs,
+ // plus the credential to merge them into.
+ expect(buildOAuthLoginQuery(["drive.file"], "cred-1")).toEqual({
+ scopes: "drive.file",
+ credential_id: "cred-1",
+ });
+ });
+
+ it("ignores an empty credentialID", () => {
+ expect(buildOAuthLoginQuery(["drive.file"], "")).toEqual({
+ scopes: "drive.file",
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 961776e79e..f10f6be545 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -71,6 +71,24 @@ export class LogoutInterruptError extends Error {
}
}
+/**
+ * Build the query object for `oAuthLogin`. Kept as a named helper so the
+ * shape — scopes-only vs credential_id-only vs both vs neither — can be
+ * pinned in tests without mocking the whole BackendAPI request layer.
+ *
+ * Returns `undefined` when neither argument is provided so callers can
+ * omit the query string entirely.
+ */
+export function buildOAuthLoginQuery(
+ scopes?: string[],
+ credentialID?: string,
+): Record<string, string> | undefined {
+ const query: Record<string, string> = {};
+ if (scopes && scopes.length > 0) query.scopes = scopes.join(",");
+ if (credentialID) query.credential_id = credentialID;
+ return Object.keys(query).length > 0 ? query : undefined;
+}
+
export default class BackendAPI {
private baseUrl: string;
private wsUrl: string;
@@ -305,9 +323,12 @@ export default class BackendAPI {
oAuthLogin(
provider: string,
scopes?: string[],
+ credentialID?: string,
): Promise<{ login_url: string; state_token: string }> {
- const query = scopes ? { scopes: scopes.join(",") } : undefined;
- return this._get(`/integrations/${provider}/login`, query);
+ return this._get(
+ `/integrations/${provider}/login`,
+ buildOAuthLoginQuery(scopes, credentialID),
+ );
}
oAuthCallback(
diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.ts b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.ts
new file mode 100644
index 0000000000..ee31e4a976
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vitest";
+import type {
+ CredentialsMetaResponse,
+ CredentialsProviderName,
+} from "@/lib/autogpt-server-api";
+import {
+ upsertProviderCredentials,
+ type CredentialsProvidersContextType,
+} from "./credentials-provider";
+
+function makeCred(
+ partial: Partial<CredentialsMetaResponse>,
+): CredentialsMetaResponse {
+ return {
+ id: "cred-id",
+ provider: "google" as CredentialsProviderName,
+ type: "oauth2",
+ title: "Test Credential",
+ scopes: [],
+ ...partial,
+ } as CredentialsMetaResponse;
+}
+
+function makeProviderMap(
+ initial: Partial<
+ Record<CredentialsProviderName, CredentialsMetaResponse[]>
+ > = {},
+): CredentialsProvidersContextType {
+ const out: CredentialsProvidersContextType = {};
+ for (const [provider, saved] of Object.entries(initial)) {
+ out[provider as CredentialsProviderName] = {
+ provider: provider as CredentialsProviderName,
+ providerName: provider,
+ savedCredentials: saved ?? [],
+ isSystemProvider: false,
+ oAuthCallback: async () => makeCred({}),
+ mcpOAuthCallback: async () => makeCred({}),
+ createAPIKeyCredentials: async () => makeCred({}),
+ createUserPasswordCredentials: async () => makeCred({}),
+ createHostScopedCredentials: async () => makeCred({}),
+ deleteCredentials: async () => ({ deleted: true, revoked: true }),
+ };
+ }
+ return out;
+}
+
+describe("upsertProviderCredentials", () => {
+ it("returns prev as-is when the provider isn't in the map", () => {
+ const prev = makeProviderMap({ google: [] });
+ const result = upsertProviderCredentials(
+ prev,
+ "github" as CredentialsProviderName,
+ makeCred({ id: "new-gh" }),
+ );
+ expect(result).toBe(prev);
+ });
+
+ it("returns prev as-is when prev is null", () => {
+ const result = upsertProviderCredentials(
+ null,
+ "google" as CredentialsProviderName,
+ makeCred({ id: "anything" }),
+ );
+ expect(result).toBeNull();
+ });
+
+ it("appends a credential that isn't already in the list", () => {
+ const prev = makeProviderMap({ google: [makeCred({ id: "existing" })] });
+ const result = upsertProviderCredentials(
+ prev,
+ "google" as CredentialsProviderName,
+ makeCred({ id: "new" }),
+ );
+ expect(result?.google?.savedCredentials.map((c) => c.id).sort()).toEqual([
+ "existing",
+ "new",
+ ]);
+ });
+
+ it("replaces an existing credential with the same id (no duplication)", () => {
+ // Regression coverage for the scope-upgrade path: after the callback
+ // returns the upgraded credential, we must REPLACE the existing entry
+ // in the sidebar — not append a second row with the same id.
+ const prev = makeProviderMap({
+ google: [
+ makeCred({
+ id: "cred-1",
+ title: "Old",
+ scopes: ["drive.file"],
+ }),
+ ],
+ });
+ const upgraded = makeCred({
+ id: "cred-1",
+ title: "Upgraded",
+ scopes: ["drive.file", "drive.metadata"],
+ });
+
+ const result = upsertProviderCredentials(
+ prev,
+ "google" as CredentialsProviderName,
+ upgraded,
+ );
+ const saved = result?.google?.savedCredentials;
+ expect(saved?.length).toBe(1);
+ expect(saved?.[0].title).toBe("Upgraded");
+ expect(saved?.[0].scopes).toEqual(["drive.file", "drive.metadata"]);
+ });
+
+ it("returns a new top-level object (doesn't mutate prev)", () => {
+ const prev = makeProviderMap({ google: [] });
+ const snapshot = prev.google?.savedCredentials;
+ const result = upsertProviderCredentials(
+ prev,
+ "google" as CredentialsProviderName,
+ makeCred({ id: "x" }),
+ );
+ expect(result).not.toBe(prev);
+ expect(result?.google?.savedCredentials).not.toBe(snapshot);
+ // snapshot of the old list must still be empty
+ expect(prev.google?.savedCredentials).toEqual([]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx
index a426d8f667..856626dc37 100644
--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx
@@ -68,6 +68,36 @@ export type CredentialsProvidersContextType = {
export const CredentialsProvidersContext =
createContext<CredentialsProvidersContextType | null>(null);
+/**
+ * Replace an existing credential entry (matched by id) or append a new one,
+ * producing a fresh providers map. Used by both OAuth callback paths and
+ * the "create credential" flows so a scope upgrade doesn't duplicate rows
+ * in the sidebar. Pure so it can be exercised directly in tests without
+ * dragging in React state machinery.
+ */
+export function upsertProviderCredentials(
+ prev: CredentialsProvidersContextType | null,
+ provider: CredentialsProviderName,
+ credentials: CredentialsMetaResponse,
+): CredentialsProvidersContextType | null {
+ if (!prev || !prev[provider]) return prev;
+
+ const existing = prev[provider].savedCredentials;
+ const idx = existing.findIndex((c) => c.id === credentials.id);
+ const updated =
+ idx >= 0
+ ? existing.map((c, i) => (i === idx ? credentials : c))
+ : [...existing, credentials];
+
+ return {
+ ...prev,
+ [provider]: {
+ ...prev[provider],
+ savedCredentials: updated,
+ },
+ };
+}
+
export default function CredentialsProvider({
children,
}: {
@@ -83,22 +113,14 @@ export default function CredentialsProvider({
const api = useBackendAPI();
const onFailToast = useToastOnFail();
- const addCredentials = useCallback(
+ const upsertCredentials = useCallback(
(
provider: CredentialsProviderName,
credentials: CredentialsMetaResponse,
) => {
- setProviders((prev) => {
- if (!prev || !prev[provider]) return prev;
-
- return {
- ...prev,
- [provider]: {
- ...prev[provider],
- savedCredentials: [...prev[provider].savedCredentials, credentials],
- },
- };
- });
+ setProviders((prev) =>
+ upsertProviderCredentials(prev, provider, credentials),
+ );
},
[setProviders],
);
@@ -111,19 +133,15 @@ export default function CredentialsProvider({
state_token: string,
): Promise<CredentialsMetaResponse> => {
try {
- const credsMeta = await api.oAuthCallback(
- provider as string,
- code,
- state_token,
- );
- addCredentials(provider as string, credsMeta);
+ const credsMeta = await api.oAuthCallback(provider, code, state_token);
+ upsertCredentials(provider, credsMeta);
return credsMeta;
} catch (error) {
onFailToast("complete OAuth authentication")(error);
throw error;
}
},
- [api, addCredentials, onFailToast],
+ [api, upsertCredentials, onFailToast],
);
/** Exchanges an MCP OAuth code for tokens and adds the result to the internal credentials store. */
@@ -145,14 +163,14 @@ export default function CredentialsProvider({
username: response.data.username ?? undefined,
host: response.data.host ?? undefined,
};
- addCredentials("mcp", credsMeta);
+ upsertCredentials("mcp", credsMeta);
return credsMeta;
} catch (error) {
onFailToast("complete MCP OAuth authentication")(error);
throw error;
}
},
- [addCredentials, onFailToast],
+ [upsertCredentials, onFailToast],
);
/** Wraps `BackendAPI.createAPIKeyCredentials`, and adds the result to the internal credentials store. */
@@ -166,14 +184,14 @@ export default function CredentialsProvider({
provider,
...credentials,
});
- addCredentials(provider, credsMeta);
+ upsertCredentials(provider, credsMeta);
return credsMeta;
} catch (error) {
onFailToast("create API key credentials")(error);
throw error;
}
},
- [api, addCredentials, onFailToast],
+ [api, upsertCredentials, onFailToast],
);
/** Wraps `BackendAPI.createUserPasswordCredentials`, and adds the result to the internal credentials store. */
@@ -187,14 +205,14 @@ export default function CredentialsProvider({
provider,
...credentials,
});
- addCredentials(provider, credsMeta);
+ upsertCredentials(provider, credsMeta);
return credsMeta;
} catch (error) {
onFailToast("create user/password credentials")(error);
throw error;
}
},
- [api, addCredentials, onFailToast],
+ [api, upsertCredentials, onFailToast],
);
/** Wraps `BackendAPI.createHostScopedCredentials`, and adds the result to the internal credentials store. */
@@ -208,14 +226,14 @@ export default function CredentialsProvider({
provider,
...credentials,
});
- addCredentials(provider, credsMeta);
+ upsertCredentials(provider, credsMeta);
return credsMeta;
} catch (error) {
onFailToast("create host-scoped credentials")(error);
throw error;
}
},
- [api, addCredentials, onFailToast],
+ [api, upsertCredentials, onFailToast],
);
/** Wraps `BackendAPI.deleteCredentials`, and removes the credentials from the internal store. */
@@ -228,11 +246,7 @@ export default function CredentialsProvider({
CredentialsDeleteResponse | CredentialsDeleteNeedConfirmationResponse
> => {
try {
- const result = await api.deleteCredentials(
- provider as string,
- id,
- force,
- );
+ const result = await api.deleteCredentials(provider, id, force);
if (!result.deleted) {
return result;
}
@@ -288,7 +302,7 @@ export default function CredentialsProvider({
provider,
{
provider,
- providerName: toDisplayName(provider as string),
+ providerName: toDisplayName(provider),
savedCredentials: providerCredentials,
isSystemProvider: systemProviders.has(provider),
oAuthCallback: (code: string, state_token: string) =>