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): make OAuth refresh-token rotation atomic under concurrent refreshes (#15632)

goingforstudying-ctrl775dbc7f66e6
diff --git a/autogpt_platform/backend/backend/api/features/oauth_test.py b/autogpt_platform/backend/backend/api/features/oauth_test.py
index c1aaeb8583..3e3ec63ede 100644
--- a/autogpt_platform/backend/backend/api/features/oauth_test.py
+++ b/autogpt_platform/backend/backend/api/features/oauth_test.py
@@ -30,8 +30,14 @@ from prisma.models import OAuthApplication as PrismaOAuthApplication
from prisma.models import OAuthAuthorizationCode as PrismaOAuthAuthorizationCode
from prisma.models import OAuthRefreshToken as PrismaOAuthRefreshToken
from prisma.models import User as PrismaUser
+from pytest_mock import MockerFixture
from backend.api.rest_api import app
+from backend.data.auth.oauth import (
+ InvalidGrantError,
+ create_refresh_token,
+ refresh_tokens,
+)
from backend.data.user import is_user_banned
keysmith = APIKeySmith()
@@ -1179,6 +1185,79 @@ async def test_token_refresh_wrong_application(
assert "does not belong" in response.json()["detail"].lower()
[email protected](loop_scope="session")
+async def test_refresh_token_concurrent_refresh_succeeds_once(
+ mocker: MockerFixture,
+ test_user: str,
+ test_oauth_app: dict,
+):
+ """Two refreshes of one token that both pass the checks before either
+ revokes it must not both mint a token pair (#15288)."""
+ refresh_token = await create_refresh_token(
+ test_oauth_app["id"], test_user, [APIKeyPermission.EXECUTE_GRAPH]
+ )
+ _hold_refreshes_after_their_checks(mocker, parties=2)
+
+ results = await asyncio.gather(
+ *(
+ refresh_tokens(refresh_token.token.get_secret_value(), test_oauth_app["id"])
+ for _ in range(2)
+ ),
+ return_exceptions=True,
+ )
+
+ minted = [r for r in results if isinstance(r, tuple)]
+ refused = [r for r in results if isinstance(r, InvalidGrantError)]
+ assert (len(minted), len(refused)) == (1, 1), results
+ assert "revoked" in str(refused[0])
+
+
[email protected](loop_scope="session")
+async def test_token_endpoint_concurrent_refresh_issues_one_token_pair(
+ client: httpx.AsyncClient,
+ mocker: MockerFixture,
+ test_user: str,
+ test_oauth_app: dict,
+):
+ """Concurrent refresh grants with one token: one gets new tokens, the rest
+ get invalid_grant, and the database holds a single live pair."""
+ refresh_token = await create_refresh_token(
+ test_oauth_app["id"], test_user, [APIKeyPermission.EXECUTE_GRAPH]
+ )
+ _hold_refreshes_after_their_checks(mocker, parties=3)
+ grant = {
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token.token.get_secret_value(),
+ "client_id": test_oauth_app["client_id"],
+ "client_secret": test_oauth_app["client_secret"],
+ }
+
+ responses = await asyncio.gather(
+ *(client.post("/api/oauth/token", json=grant) for _ in range(3))
+ )
+
+ statuses = sorted(r.status_code for r in responses)
+ assert statuses == [200, 400, 400], [r.text for r in responses]
+ refusals = [r.json()["detail"] for r in responses if r.status_code == 400]
+ assert all("revoked" in detail for detail in refusals), refusals
+ live = {"applicationId": test_oauth_app["id"], "revokedAt": None}
+ assert await PrismaOAuthRefreshToken.prisma().count(where=live) == 1
+ assert await PrismaOAuthAccessToken.prisma().count(where=live) == 1
+
+
+def _hold_refreshes_after_their_checks(mocker: MockerFixture, parties: int) -> None:
+ """Hold each refresh at its ban check, the last check before it revokes the
+ old token, until `parties` refreshes have reached it. All of them then
+ claim the token at once, which is the race in #15288."""
+ checks_passed = asyncio.Barrier(parties)
+
+ async def not_banned(user_id: str) -> bool:
+ await asyncio.wait_for(checks_passed.wait(), timeout=10)
+ return False
+
+ mocker.patch("backend.data.auth.oauth.is_user_banned", new=not_banned)
+
+
# ============================================================================
# Token Introspection Integration Tests
# ============================================================================
diff --git a/autogpt_platform/backend/backend/data/auth/oauth.py b/autogpt_platform/backend/backend/data/auth/oauth.py
index 631b6da0ef..0da186f8c9 100644
--- a/autogpt_platform/backend/backend/data/auth/oauth.py
+++ b/autogpt_platform/backend/backend/data/auth/oauth.py
@@ -658,11 +658,15 @@ async def refresh_tokens(
if await is_user_banned(rt.userId):
raise InvalidGrantError("the account this token belongs to is banned")
- # Revoke old refresh token
- await PrismaOAuthRefreshToken.prisma().update(
- where={"token": token_hash},
+ # Revoke the old token atomically: the checks above read a snapshot, so two
+ # concurrent refreshes can both pass them. Only the request whose
+ # conditional write flips revokedAt from NULL may mint new tokens.
+ revoked = await PrismaOAuthRefreshToken.prisma().update_many(
+ where={"token": token_hash, "revokedAt": None},
data={"revokedAt": now},
)
+ if revoked != 1:
+ raise InvalidGrantError("refresh token has been revoked")
# Create new access and refresh tokens with same scopes
scopes = [APIPermission(s) for s in rt.scopes]