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.

feat(backend): cleanup expired PlatformLinkTokens (#13022)

Devendra Reddy Pennabadic7210ba799ce
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 23e060f077..348066af2b 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -377,6 +377,9 @@ class DatabaseManager(AppService):
list_user_links = _(platform_linking_db.list_user_links)
delete_server_link = _(platform_linking_db.delete_server_link)
delete_user_link = _(platform_linking_db.delete_user_link)
+ cleanup_expired_platform_link_tokens = _(
+ platform_linking_db.cleanup_expired_platform_link_tokens
+ )
# ============ CoPilot Chat Sessions ============ #
# NOTE: no eager-load `get_chat_session` here — callers go through
@@ -615,6 +618,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
list_user_links = d.list_user_links
delete_server_link = d.delete_server_link
delete_user_link = d.delete_user_link
+ cleanup_expired_platform_link_tokens = d.cleanup_expired_platform_link_tokens
# ============ CoPilot Chat Sessions ============ #
get_chat_session_metadata = d.get_chat_session_metadata
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 890061ab3f..89c3d202d6 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -269,6 +269,16 @@ def cleanup_failed_push_subscriptions():
run_async(_cleanup())
+def cleanup_platform_link_tokens():
+ """Delete PlatformLinkToken rows expired beyond the retention window."""
+
+ async def _cleanup():
+ db = get_database_manager_async_client()
+ return await db.cleanup_expired_platform_link_tokens()
+
+ run_async(_cleanup())
+
+
def execution_accuracy_alerts():
"""Check execution accuracy and send alerts if drops are detected."""
return report_execution_accuracy_alerts()
@@ -602,6 +612,16 @@ class Scheduler(AppService):
jobstore=Jobstores.EXECUTION.value,
)
+ # Platform Link Token Cleanup - configurable interval
+ self.scheduler.add_job(
+ cleanup_platform_link_tokens,
+ id="cleanup_platform_link_tokens",
+ trigger="interval",
+ replace_existing=True,
+ seconds=config.platform_link_token_cleanup_interval_hours * 3600,
+ jobstore=Jobstores.EXECUTION.value,
+ )
+
# Execution Accuracy Monitoring - configurable interval
self.scheduler.add_job(
execution_accuracy_alerts,
diff --git a/autogpt_platform/backend/backend/platform_linking/db.py b/autogpt_platform/backend/backend/platform_linking/db.py
index 8e419fba72..cdc6bc6247 100644
--- a/autogpt_platform/backend/backend/platform_linking/db.py
+++ b/autogpt_platform/backend/backend/platform_linking/db.py
@@ -426,3 +426,20 @@ async def delete_user_link(link_id: str, user_id: str) -> DeleteLinkResponse:
await PlatformUserLink.prisma().delete(where={"id": link_id})
logger.info("Unlinked %s DMs from AutoGPT user ...%s", link.platform, user_id[-8:])
return DeleteLinkResponse(success=True)
+
+
+# ── Cleanup ──────────────────────────────────────────────────────────
+
+# Keep recently-expired rows for debugging.
+LINK_TOKEN_RETENTION_HOURS = 24
+
+
+async def cleanup_expired_platform_link_tokens() -> int:
+ """Delete PlatformLinkToken rows expired beyond the retention window."""
+ cutoff = datetime.now(timezone.utc) - timedelta(hours=LINK_TOKEN_RETENTION_HOURS)
+ deleted = await PlatformLinkToken.prisma().delete_many(
+ where={"expiresAt": {"lt": cutoff}}
+ )
+ if deleted > 0:
+ logger.info("Cleaned up %d expired platform link tokens", deleted)
+ return deleted
diff --git a/autogpt_platform/backend/backend/platform_linking/db_test.py b/autogpt_platform/backend/backend/platform_linking/db_test.py
index b02679103f..6bc260d611 100644
--- a/autogpt_platform/backend/backend/platform_linking/db_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/db_test.py
@@ -15,6 +15,8 @@ from backend.util.exceptions import (
)
from .db import (
+ LINK_TOKEN_RETENTION_HOURS,
+ cleanup_expired_platform_link_tokens,
confirm_server_link,
confirm_user_link,
create_server_link_token,
@@ -479,3 +481,33 @@ class TestDeleteLinks:
mock_model.prisma.return_value.find_unique = AsyncMock(return_value=link)
with pytest.raises(NotAuthorizedError):
await delete_user_link("x", "u-other")
+
+
+# ── Cleanup ──────────────────────────────────────────────────────────
+
+
+class TestCleanupExpired:
+ @pytest.mark.asyncio
+ async def test_deletes_with_retention_window_cutoff(self):
+ with patch("backend.platform_linking.db.PlatformLinkToken") as mock_model:
+ mock_model.prisma.return_value.delete_many = AsyncMock(return_value=7)
+ count = await cleanup_expired_platform_link_tokens()
+
+ assert count == 7
+ mock_model.prisma.return_value.delete_many.assert_awaited_once()
+ where = mock_model.prisma.return_value.delete_many.await_args.kwargs["where"]
+ assert "expiresAt" in where and "lt" in where["expiresAt"]
+ cutoff = where["expiresAt"]["lt"]
+ delta = datetime.now(timezone.utc) - cutoff
+ assert (
+ timedelta(hours=LINK_TOKEN_RETENTION_HOURS - 1)
+ < delta
+ < timedelta(hours=LINK_TOKEN_RETENTION_HOURS + 1)
+ )
+
+ @pytest.mark.asyncio
+ async def test_returns_zero_when_nothing_to_delete(self):
+ with patch("backend.platform_linking.db.PlatformLinkToken") as mock_model:
+ mock_model.prisma.return_value.delete_many = AsyncMock(return_value=0)
+ count = await cleanup_expired_platform_link_tokens()
+ assert count == 0
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 8a21ba8160..dacfcf8f6e 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -446,6 +446,13 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="Hours between failed push subscription cleanup runs (1-168 hours)",
)
+ platform_link_token_cleanup_interval_hours: int = Field(
+ default=6,
+ ge=1,
+ le=24,
+ description="Hours between platform link token cleanup runs (1-24 hours)",
+ )
+
upload_file_size_limit_mb: int = Field(
default=256,
ge=1,