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.

refactor(backend/integrations): clearer naming + docs for managed-cred sweep (#12908)

Zamil Majdyab88d03b13b1
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index 3f6da3e748..2ac9f8cabe 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -1139,7 +1139,7 @@ async def get_ayrshare_sso_url(
)
# On-demand provisioning: AyrshareManagedProvider opts out of the
- # startup sweep (profile quota is per-user subscription-bound). This
+ # credentials sweep (profile quota is per-user subscription-bound). This
# endpoint is the only trigger that provisions a profile — one Ayrshare
# profile per user who actually opens the connect flow, not one per
# every authenticated user.
diff --git a/autogpt_platform/backend/backend/integrations/managed_credentials.py b/autogpt_platform/backend/backend/integrations/managed_credentials.py
index cfe7f24168..8ca2f2ff93 100644
--- a/autogpt_platform/backend/backend/integrations/managed_credentials.py
+++ b/autogpt_platform/backend/backend/integrations/managed_credentials.py
@@ -1,14 +1,24 @@
"""Generic infrastructure for system-provided, per-user managed credentials.
Managed credentials are provisioned automatically by the platform (e.g. an
-AgentMail pod-scoped API key) and stored alongside regular user credentials
-with ``is_managed=True``. Users cannot update or delete them.
-
-New integrations register a :class:`ManagedCredentialProvider` at import time;
-the two entry-points consumed by the rest of the application are:
-
-* :func:`ensure_managed_credentials` – fired as a background task from the
- credential-listing endpoints (non-blocking).
+AgentMail pod-scoped API key, or an Ayrshare profile key) and stored
+alongside regular user credentials with ``is_managed=True``. Users cannot
+update or delete them.
+
+New integrations register a :class:`ManagedCredentialProvider` at import
+time; the three entry-points consumed by the rest of the application are:
+
+* :func:`ensure_managed_credentials` – the credentials sweep, called from
+ the credential-listing endpoints (``/credentials``,
+ ``/{provider}/credentials``). Iterates every registered provider and
+ ensures the provider's managed credential has been provisioned for the
+ user, gated by ``auto_provision`` and ``is_available`` (see
+ :class:`ManagedCredentialProvider`).
+* :func:`ensure_managed_credential` (singular) – on-demand provisioning
+ for a specific provider; called when a user-triggered action (e.g. the
+ Ayrshare SSO flow) must guarantee the managed credential exists.
+ Bypasses the ``auto_provision`` gate — callers must check
+ ``is_available`` themselves.
* :func:`cleanup_managed_credentials` – called during account deletion to
revoke external resources (API keys, pods, etc.).
"""
@@ -34,7 +44,24 @@ logger = logging.getLogger(__name__)
class ManagedCredentialProvider(ABC):
- """Base class for integrations that auto-provision per-user credentials."""
+ """Base class for integrations that auto-provision per-user credentials.
+
+ **Two gates decide whether provisioning runs during the credentials
+ sweep** (:func:`ensure_managed_credentials`, fired from ``/credentials``
+ fetches — see that function's docstring for full details):
+
+ 1. :attr:`auto_provision` — does this provider participate in the
+ sweep at all? Opt out here if provisioning has per-user upstream
+ cost that shouldn't fire for every logged-in user.
+ 2. :meth:`is_available` — for providers that DO participate in the
+ sweep, have we been configured with the env vars / secrets needed
+ to call the upstream service?
+
+ Gate 1 is checked first; if it's off, Gate 2 is never consulted. A
+ provider opted out of Gate 1 is still registered here so
+ :func:`cleanup_managed_credentials` and on-demand
+ :func:`ensure_managed_credential` callers can find it.
+ """
provider_name: str
"""Must match the ``provider`` field on the resulting credential."""
@@ -43,22 +70,30 @@ class ManagedCredentialProvider(ABC):
"""Whether :func:`ensure_managed_credentials` should provision this on
credential-list load.
- Default ``True`` matches the AgentMail contract: cheap provisioning that
- is safe to run for every user on first visit. Set to ``False`` when
- provisioning has per-user upstream cost (e.g. Ayrshare's profile quota);
- such providers still register here so account-deletion cleanup works,
- but only run via an explicit :func:`ensure_managed_credential` call
- from a user-triggered endpoint.
+ Default ``True`` matches the AgentMail contract: cheap provisioning
+ (one API key creation) that is safe to run for every user on first
+ visit. Set to ``False`` when provisioning has per-user upstream cost
+ (e.g. Ayrshare's profile quota); such providers skip the sweep
+ entirely and only run via an explicit
+ :func:`ensure_managed_credential` call from a user-triggered endpoint.
"""
@abstractmethod
async def is_available(self) -> bool:
"""Return ``True`` when the org-level configuration is present.
- Used by :func:`ensure_managed_credentials` to skip providers whose
- config is missing (e.g. missing env vars). Independent of
- :attr:`auto_provision` — a provider can be available yet opt out
- of the startup sweep.
+ **What this checks:** are the env vars / secrets this provider
+ needs in order to talk to its upstream (AgentMail API key,
+ Ayrshare API key + JWT key, etc.) actually set?
+
+ **What this does NOT check:** runtime upstream health — no
+ network call is made. A provider that returns ``True`` here may
+ still fail at ``provision()`` time if the upstream is unreachable
+ or the key is rejected.
+
+ Only consulted by the credentials sweep when
+ :attr:`auto_provision` is ``True``. Opt-out providers never hit
+ this check (they bypass the sweep entirely).
"""
@abstractmethod
@@ -221,7 +256,7 @@ async def ensure_managed_credential(
Bypasses the provider's ``is_available()`` gate — callers are expected to
have validated org-level config themselves (e.g. the Ayrshare SSO-URL
endpoint checks its secrets before invoking this). Use for providers
- that opt out of the ``ensure_managed_credentials`` startup sweep because
+ that opt out of the ``ensure_managed_credentials`` credentials sweep because
provisioning has per-user cost or quota implications.
Returns ``True`` on success, ``False`` on transient failure.
@@ -244,15 +279,33 @@ async def ensure_managed_credentials(
user_id: str,
store: IntegrationCredentialsStore,
) -> None:
- """Provision missing managed credentials for *user_id*.
-
- Fired as a non-blocking background task from the credential-listing
- endpoints. Failures are logged but never propagated — the user simply
- will not see the managed credential until the next page load.
-
- Skips entirely if this user has already been checked during the current
- process lifetime (in-memory cache). Resets on restart — just a
- performance optimisation, not a correctness guarantee.
+ """Run the credentials sweep for *user_id*.
+
+ "Credentials sweep" = iterate every registered
+ :class:`ManagedCredentialProvider` and ensure the provider's managed
+ credential has been provisioned for this user. Each provider is
+ gated twice (see the class docstring): by :attr:`auto_provision`
+ (is it in the sweep at all?) and :meth:`is_available` (are we
+ configured to call upstream?). Providers that clear both gates get
+ :func:`_provision_under_lock`'d.
+
+ **When it runs:** triggered from the ``/credentials`` and
+ ``/{provider}/credentials`` GET endpoints — i.e. the first time the
+ frontend asks for the user's credentials on a fresh pod. It's NOT an
+ app-startup hook.
+
+ **Caching:** once the sweep has succeeded for a user on this pod,
+ ``_provisioned_users`` short-circuits subsequent calls. In-memory, so
+ it resets when the pod restarts. Performance optimisation, not a
+ correctness guarantee — a second call while the cache is cold just
+ re-runs the sweep, which is idempotent via
+ ``store.has_managed_credential`` checks inside
+ :func:`_provision_under_lock`.
+
+ **Failure handling:** any per-provider failure is caught in
+ :func:`_ensure_one`; we only cache the user as "provisioned" when
+ every provider either succeeded or was intentionally skipped.
+ Transient failures get retried on the next fetch.
Providers are checked concurrently via ``asyncio.gather``.
"""
diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py
index 603fc45d4b..ce94f70ed1 100644
--- a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py
+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare.py
@@ -49,20 +49,21 @@ logger = logging.getLogger(__name__)
class AyrshareManagedProvider(ManagedCredentialProvider):
provider_name = "ayrshare"
- # Opt out of the startup sweep — each Ayrshare profile counts against
- # our subscription quota, so we only provision when the user actually
- # opens a block that needs it (triggered by the builder's per-provider
- # ``GET /{provider}/credentials`` call).
+ # Opt out of the credentials sweep — each Ayrshare profile counts
+ # against our subscription quota, so we only provision when the user
+ # explicitly triggers the SSO flow from a block. See
+ # ``ManagedCredentialProvider.auto_provision`` for the gate semantics.
auto_provision = False
async def is_available(self) -> bool:
- """Both Ayrshare org-level secrets must be configured."""
+ """True when both ``AYRSHARE_API_KEY`` and ``AYRSHARE_JWT_KEY`` are
+ configured. Pure env-var check — does NOT ping Ayrshare."""
return settings_available()
async def provision(
self, user_id: str, store: IntegrationCredentialsStore
) -> Credentials:
- profile_key = await _read_or_create_profile_key(user_id, store)
+ profile_key = await _migrate_legacy_or_create_profile_key(user_id, store)
return APIKeyCredentials(
provider=self.provider_name,
title="Ayrshare (managed by AutoGPT)",
@@ -115,12 +116,17 @@ def _profile_title(user_id: str) -> str:
return f"User {user_id}-{secrets.token_hex(3)}"
-async def _read_or_create_profile_key(
+async def _migrate_legacy_or_create_profile_key(
user_id: str, store: IntegrationCredentialsStore
) -> str:
- """Return the Ayrshare profile key for *user_id*, creating one if needed.
+ """Return an Ayrshare profile key for *user_id*.
- **Resolution order — idempotent, retry-safe:**
+ Only called from :meth:`AyrshareManagedProvider.provision`, which is
+ itself only reached when the outer
+ :func:`~backend.integrations.managed_credentials._provision_under_lock`
+ has already confirmed via ``has_managed_credential`` that this user has
+ no managed Ayrshare credential yet. So this function does NOT re-check
+ the managed credential — it only has to decide between:
1. **Legacy side channel.** If
``UserIntegrations.managed_credentials.ayrshare_profile_key`` is set
@@ -137,10 +143,9 @@ async def _read_or_create_profile_key(
path). Orphans stick around in Ayrshare's dashboard until cleaned
up manually — acceptable cost for unblocking the user.
- The outer :func:`~backend.integrations.managed_credentials._provision_under_lock`
- holds a distributed Redis lock on ``(user, provider)`` across this whole
- function *and* the subsequent ``add_managed_credential`` call, so
- concurrent workers cannot race and create duplicates.
+ ``_provision_under_lock`` also holds the distributed Redis lock across
+ this whole function *and* the subsequent ``add_managed_credential``
+ call, so concurrent workers cannot race and create duplicates.
"""
user_integrations = await store.get_user_integrations(user_id)
legacy_key = user_integrations.managed_credentials.ayrshare_profile_key
diff --git a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py
index 2e08d94452..aab97bd55d 100644
--- a/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py
+++ b/autogpt_platform/backend/backend/integrations/managed_providers/ayrshare_test.py
@@ -8,7 +8,7 @@ from pydantic import SecretStr
from backend.data.model import APIKeyCredentials
from backend.integrations.managed_providers.ayrshare import (
AyrshareManagedProvider,
- _read_or_create_profile_key,
+ _migrate_legacy_or_create_profile_key,
settings_available,
)
@@ -44,7 +44,7 @@ class TestIsAvailable:
assert await AyrshareManagedProvider().is_available() is False
def test_auto_provision_opt_out(self):
- """Ayrshare opts out of the startup sweep — per-user Ayrshare profiles
+ """Ayrshare opts out of the credentials sweep — per-user Ayrshare profiles
count against our subscription quota, so we only provision when the
user explicitly clicks the builder's SSO flow."""
assert AyrshareManagedProvider.auto_provision is False
@@ -105,7 +105,7 @@ class TestReadOrCreateProfileKey:
async def test_reuses_legacy_key_without_clearing(self):
"""Legacy field is NOT cleared here — that happens in post_provision.
- If `_read_or_create_profile_key` cleared eagerly and the subsequent
+ If `_migrate_legacy_or_create_profile_key` cleared eagerly and the subsequent
`add_managed_credential` failed, a retry would see an empty legacy
field and create a fresh Ayrshare profile, orphaning the user's
linked social accounts.
@@ -116,7 +116,7 @@ class TestReadOrCreateProfileKey:
with patch(
"backend.integrations.managed_providers.ayrshare.AyrshareClient"
) as mock_client:
- result = await _read_or_create_profile_key(_USER_ID, store)
+ result = await _migrate_legacy_or_create_profile_key(_USER_ID, store)
assert result == "legacy-profile-key"
# create_profile must NOT be called — we reuse the existing one.
@@ -137,7 +137,7 @@ class TestReadOrCreateProfileKey:
"backend.integrations.managed_providers.ayrshare.AyrshareClient",
return_value=client_instance,
):
- result = await _read_or_create_profile_key(_USER_ID, store)
+ result = await _migrate_legacy_or_create_profile_key(_USER_ID, store)
assert result == "fresh-profile-key"
client_instance.create_profile.assert_awaited_once()
@@ -226,7 +226,7 @@ class TestProvision:
store = MagicMock()
with patch(
"backend.integrations.managed_providers.ayrshare."
- "_read_or_create_profile_key",
+ "_migrate_legacy_or_create_profile_key",
new=AsyncMock(return_value="profile-key-xyz"),
) as read_mock:
creds = await AyrshareManagedProvider().provision(_USER_ID, store)