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(backend/copilot): offer the reconnect card when a credential cannot be refreshed (#14667)

Bently4ba9059c8bf3
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index abe8a47dd5..397dd0176b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -47,6 +47,7 @@ from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.integrations.providers import ProviderName
from backend.util.exceptions import BlockError, InsufficientBalanceError
from backend.util.feature_flag import Flag, is_feature_enabled
+from backend.util.request import HTTPClientError
from backend.util.timezone_utils import get_user_timezone_or_utc
from backend.util.type import coerce_inputs_to_schema
@@ -353,11 +354,40 @@ async def execute_block(
exec_kwargs[field_name] = credentials
continue
- credentials = await creds_manager.get(
- user_id,
- cred_meta.id,
- lock=False,
- )
+ try:
+ credentials = await creds_manager.get(
+ user_id,
+ cred_meta.id,
+ lock=False,
+ )
+ except HTTPClientError as e:
+ # The provider refused the refresh (revoked grant, expired
+ # refresh token). The user can only fix that by
+ # reconnecting, so hand them the card rather than an error.
+ # Anything else (store, config, handler setup) is not
+ # theirs to fix and takes the usual error path below.
+ await _release_credential_leases(credential_leases)
+ return _build_credential_rejected_card(
+ block=block,
+ block_id=block_id,
+ input_data=input_data,
+ matched_credentials={field_name: cred_meta},
+ session_id=session_id,
+ status_code=credential_rejection_status(e),
+ exc=e,
+ )
+ except Exception:
+ # Not the provider's doing (store, config, handler setup),
+ # so not the user's to fix, and its text can name internal
+ # ids: a fixed message, with the detail kept to the log.
+ logger.exception(
+ "Could not load credential for block %s", block.name
+ )
+ await _release_credential_leases(credential_leases)
+ return ErrorResponse(
+ message=f"Failed to retrieve credentials for {field_name}",
+ session_id=session_id,
+ )
if not (
credentials is not None
and provider_matches(credentials.provider, cred_meta.provider)
@@ -607,8 +637,8 @@ def _build_credential_rejected_card(
input_data: dict[str, Any],
matched_credentials: dict[str, CredentialsMetaInput],
session_id: str,
- status_code: int,
- exc: BlockError,
+ status_code: int | None,
+ exc: BaseException,
) -> SetupRequirementsResponse:
"""Setup card for a credential the provider refused mid-execution.
@@ -635,6 +665,9 @@ def _build_credential_rejected_card(
message=(
f"{provider_name} rejected the saved credential{named} "
f"(HTTP {status_code}). Connect or pick a different one, then re-run."
+ if status_code is not None
+ else f"The saved {provider_name} credential{named} could not be "
+ "refreshed. Reconnect it or pick a different one, then re-run."
),
session_id=session_id,
setup_info=SetupInfo(
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index d378630da8..d803360850 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -1393,7 +1393,7 @@ class TestExecuteBlockCredentialRejection:
return block
@staticmethod
- async def _run(exc: Exception):
+ async def _run(exc: Exception, load_error: Exception | None = None):
from backend.copilot.tools.helpers import execute_block
from backend.data.model import CredentialsMetaInput
@@ -1408,7 +1408,7 @@ class TestExecuteBlockCredentialRejection:
stored.type = "api_key"
creds_manager = MagicMock()
- creds_manager.get = AsyncMock(return_value=stored)
+ creds_manager.get = AsyncMock(return_value=stored, side_effect=load_error)
workspace = MagicMock()
workspace.get_or_create_workspace = AsyncMock(return_value=MagicMock(id="ws-1"))
@@ -1439,6 +1439,45 @@ class TestExecuteBlockCredentialRejection:
dry_run=False,
)
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_a_refresh_the_provider_refused_returns_the_card(self, caplog):
+ # The block never runs: loading the credential refreshes it first, and a
+ # revoked grant fails there. Reconnecting is the only way out.
+ from backend.util.request import HTTPClientError
+
+ from .models import SetupRequirementsResponse
+
+ response = await self._run(
+ RuntimeError("the block must not run"),
+ load_error=HTTPClientError("HTTP 400: refresh_token=rt-secret", 400),
+ )
+
+ assert isinstance(response, SetupRequirementsResponse)
+ assert response.rejection is not None
+ assert response.rejection.credential_id == "cred-1"
+ assert response.rejection.status_code is None
+ assert "rt-secret" not in response.rejection.detail
+ assert "rt-secret" not in caplog.text
+ assert "could not be refreshed" in response.message
+ assert "Work Ayrshare key" in response.message
+ assert "credentials" in response.setup_info.user_readiness.missing_credentials
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_a_failure_that_is_not_the_providers_is_not_a_reconnect_card(self):
+ # A store or config error is not fixed by reconnecting, so it must not
+ # be dressed up as one.
+ from .models import ErrorResponse
+
+ response = await self._run(
+ RuntimeError("the block must not run"),
+ load_error=RuntimeError("store down for user u-1 credential cred-1"),
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert response.message == "Failed to retrieve credentials for credentials"
+ # The internal detail stays out of the reply.
+ assert "u-1" not in response.message and "store down" not in response.message
+
@pytest.mark.asyncio(loop_scope="session")
async def test_provider_401_returns_a_card_naming_the_credential(self):
from backend.util.exceptions import BlockUnknownError
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.py
index 45aac6223b..2440d5321d 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py
@@ -606,6 +606,6 @@ _AUTH_HEADER_RE = re.compile(
# Optional quotes around the key and value cover the JSON and dict shapes a
# provider echoes back; without them the quote before the colon defeats the match.
_SECRET_PARAM_RE = re.compile(
- r"(?i)['\"]?\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token"
- r"|secret|password)\b['\"]?\s*[=:]\s*(?:\"[^\"]*\"|'[^']*'|\S+)"
+ r"(?i)['\"]?\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token"
+ r"|client[_-]?secret|token|secret|password)\b['\"]?\s*[=:]\s*(?:\"[^\"]*\"|'[^']*'|\S+)"
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
index d824ab1226..841eac85d8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
@@ -118,6 +118,10 @@ def test_sanitize_provider_message_drops_secrets(raw: str, expected: str):
f"Authorization: Basic {_SECRET}",
f"Authorization: Token {_SECRET}",
f'{{"authorization": "Bearer {_SECRET}"}}',
+ # An OAuth token endpoint's error can quote these back.
+ f"client_secret={_SECRET}",
+ f'{{"client_secret": "{_SECRET}"}}',
+ f'{{"id_token": "{_SECRET}"}}',
],
)
def test_sanitize_provider_message_leaves_no_secret(raw: str):