From 9300f59d9a7e40306a401403aae42cad79a13c5c Mon Sep 17 00:00:00 2001 From: Asad Ali Date: Mon, 10 Aug 2026 14:12:19 +0000 Subject: [PATCH] Fix: Handle expired OpenEdX refresh tokens gracefully --- openedx/api.py | 30 +++++++++++++++++++++--------- openedx/tasks.py | 9 ++++++++- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/openedx/api.py b/openedx/api.py index 75bf9a91c8..0b751750b7 100644 --- a/openedx/api.py +++ b/openedx/api.py @@ -838,15 +838,27 @@ def _refresh_edx_api_auth(auth): updated OpenEdxApiAuth """ # Note: this is subject to thundering herd problems, we should address this at some point - return _create_tokens_and_update_auth( - auth, - dict( # noqa: C408 - refresh_token=auth.refresh_token, - grant_type="refresh_token", - client_id=settings.OPENEDX_API_CLIENT_ID, - client_secret=settings.OPENEDX_API_CLIENT_SECRET, - ), - ) + try: + return _create_tokens_and_update_auth( + auth, + dict( # noqa: C408 + refresh_token=auth.refresh_token, + grant_type="refresh_token", + client_id=settings.OPENEDX_API_CLIENT_ID, + client_secret=settings.OPENEDX_API_CLIENT_SECRET, + ), + ) + except requests.exceptions.HTTPError as exc: + if exc.response is not None and exc.response.status_code == 400: # noqa: PLR2004 + log.warning( + "Refresh token rejected with 400 for user %s; clearing tokens and attempting full re-authorization.", + auth.user, + ) + auth.refresh_token = None + auth.access_token = None + auth.save(update_fields=["refresh_token", "access_token"]) + return create_edx_auth_token(auth.user) + raise def get_edx_api_client(user, ttl_in_seconds=OPENEDX_AUTH_DEFAULT_TTL_IN_SECONDS): diff --git a/openedx/tasks.py b/openedx/tasks.py index 9c14057b18..0f51c4f1dc 100644 --- a/openedx/tasks.py +++ b/openedx/tasks.py @@ -114,7 +114,14 @@ def update_edx_user_profile(user_id): Task to update the edX user profile. This doesn't change the name or email. """ user = User.objects.get(id=user_id) - api.update_edx_user_profile(user) + try: + api.update_edx_user_profile(user) + except Exception: + log.exception( + "Failed to update Open edX user profile for user %s (id=%s); skipping.", + user, + user_id, + ) @app.task(