From de9c5d095b185b04713e7f3c26e125733736e4bc Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:14:16 -0800 Subject: [PATCH 1/3] Raise PyDrive2's RefreshError when a refresh during a request fails When Drive answered 401 to a token that had not expired by the clock, google-auth refreshed it inside the request. If that refresh failed, its own RefreshError reached the caller, with the whole token response in its text. Requests now raise PyDrive2's RefreshError with the same message as Refresh(). Co-Authored-By: Claude Opus 5.5 --- pydrive2/drive.py | 5 ++- pydrive2/files.py | 10 +++++- pydrive2/test/test_auth_flows.py | 60 +++++++++++++++++++++++++++++++- 3 files changed, 72 insertions(+), 3 deletions(-) diff --git a/pydrive2/drive.py b/pydrive2/drive.py index 65a2daf0..32ea7ba8 100644 --- a/pydrive2/drive.py +++ b/pydrive2/drive.py @@ -1,7 +1,8 @@ +from google.auth.exceptions import RefreshError as GoogleRefreshError from googleapiclient import errors from .apiattr import ApiAttributeMixin -from .auth import LoadAuth +from .auth import LoadAuth, RefreshError, _refresh_failure from .files import ApiRequestError, GoogleDriveFile, GoogleDriveFileList @@ -66,3 +67,5 @@ def _Execute(self, request): return request.execute(http=self.auth.thread_local.http) except errors.HttpError as error: raise ApiRequestError(error) from error + except GoogleRefreshError as error: + raise RefreshError(_refresh_failure(error)) from error diff --git a/pydrive2/files.py b/pydrive2/files.py index a1766669..f3c4533b 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -4,6 +4,7 @@ import mimetypes import os +from google.auth.exceptions import RefreshError as GoogleRefreshError from googleapiclient import errors from googleapiclient.http import ( DEFAULT_CHUNK_SIZE, @@ -17,7 +18,7 @@ ApiResource, ApiResourceList, ) -from .auth import LoadAuth +from .auth import LoadAuth, RefreshError, _refresh_failure FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" DEFAULT_FILE_FIELDS = ( @@ -181,6 +182,9 @@ def _GetList(self): ) except errors.HttpError as error: raise ApiRequestError(error) + except GoogleRefreshError as error: + # google-auth refreshed the token during the request and failed. + raise RefreshError(_refresh_failure(error)) from error return self.metadata.get("files", []) @@ -246,6 +250,8 @@ def _next_chunk(self): status, self.done = self.downloader.next_chunk() except errors.HttpError as error: raise ApiRequestError(error) from error + except GoogleRefreshError as error: + raise RefreshError(_refresh_failure(error)) from error self.size = status.total_size self.progress = status.resumable_progress return self._fd.read() @@ -833,6 +839,8 @@ def _Execute(self, request): return self._AddResourceKeyHeaders(request).execute(http=self.http) except errors.HttpError as error: raise ApiRequestError(error) from error + except GoogleRefreshError as error: + raise RefreshError(_refresh_failure(error)) from error def _WrapRequest(self, request): """Replaces request.http with self.http. diff --git a/pydrive2/test/test_auth_flows.py b/pydrive2/test/test_auth_flows.py index d506e730..8340a19a 100644 --- a/pydrive2/test/test_auth_flows.py +++ b/pydrive2/test/test_auth_flows.py @@ -11,7 +11,7 @@ from base64 import urlsafe_b64encode from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager -from datetime import datetime +from datetime import UTC, datetime, timedelta from hashlib import sha256 from http.client import HTTPConnection from pathlib import Path @@ -300,6 +300,64 @@ def test_refresh_after_google_refuses_the_client_reports_its_oauth_error(): assert "{" not in message +@pytest.fixture +def login_drive_rejects(): + """A login whose token Drive rejects and whose refresh Google refuses. + + The token has not expired by the clock, so no refresh happens before + a request: google-auth refreshes after Drive answers 401. + """ + auth = GoogleAuth(settings_file=None) + auth.credentials = Credentials( + "made-up-token", + refresh_token="made-up-refresh-token", + client_id="000000000000-made-up.apps.googleusercontent.com", + client_secret="made-up-secret", + token_uri=TOKEN_URI, + expiry=datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1), + ) + return auth + + +@pytest.mark.drive +@pytest.mark.parametrize( + "request_drive", + [ + pytest.param( + lambda auth: ( + GoogleDrive(auth).CreateFile({"id": "root"}).FetchMetadata() + ), + id="file-metadata", + ), + pytest.param( + lambda auth: GoogleDrive(auth).ListFile().GetList(), + id="file-list", + ), + pytest.param( + lambda auth: ( + GoogleDrive(auth) + .CreateFile({"id": "root"}) + .GetContentIOBuffer() + ), + id="download", + ), + pytest.param(lambda auth: GoogleDrive(auth).GetAbout(), id="about"), + pytest.param( + lambda auth: GDriveFileSystem("root", auth).ls("root"), + id="filesystem", + ), + ], +) +def test_request_whose_token_refresh_fails_raises_refresh_error( + login_drive_rejects, request_drive +): + with pytest.raises(RefreshError) as error: + request_drive(login_drive_rejects) + message = str(error.value) + assert message.startswith("Access token refresh failed: (invalid_client) ") + assert "{" not in message + + @pytest.mark.drive def test_service_auth_after_google_refuses_the_account_reports_its_oauth_error( service_info, From 4b3ae32c02695a9d6bac74fb06ed234745a52fd5 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:08:14 -0800 Subject: [PATCH 2/3] Translate request errors in one place Co-Authored-By: Claude Opus 5.5 --- pydrive2/auth.py | 15 ++++++++++---- pydrive2/drive.py | 15 ++++---------- pydrive2/files.py | 34 +++++++++++++++----------------- pydrive2/test/test_auth_flows.py | 20 +++---------------- 4 files changed, 34 insertions(+), 50 deletions(-) diff --git a/pydrive2/auth.py b/pydrive2/auth.py index 1c7450dd..9b37162a 100644 --- a/pydrive2/auth.py +++ b/pydrive2/auth.py @@ -4,7 +4,7 @@ import os import threading import webbrowser -from contextlib import suppress +from contextlib import contextmanager, suppress from functools import wraps from inspect import signature from pathlib import Path @@ -75,6 +75,15 @@ def _refresh_failure(exc): return f"Access token refresh failed: ({code}) {description}" +@contextmanager +def _refresh_errors(): + """Raise PyDrive2's RefreshError when google-auth cannot refresh.""" + try: + yield + except GoogleRefreshError as exc: + raise RefreshError(_refresh_failure(exc)) from exc + + _auth_creation_lock = threading.Lock() @@ -745,10 +754,8 @@ def Refresh(self): if isinstance(self.http, AuthorizedHttp) else self.http ) - try: + with _refresh_errors(): self.credentials.refresh(Request(http)) - except GoogleRefreshError as exc: - raise RefreshError(_refresh_failure(exc)) from exc if ( user and self.settings.get("save_credentials") diff --git a/pydrive2/drive.py b/pydrive2/drive.py index 32ea7ba8..c3bfd22f 100644 --- a/pydrive2/drive.py +++ b/pydrive2/drive.py @@ -1,9 +1,6 @@ -from google.auth.exceptions import RefreshError as GoogleRefreshError -from googleapiclient import errors - from .apiattr import ApiAttributeMixin -from .auth import LoadAuth, RefreshError, _refresh_failure -from .files import ApiRequestError, GoogleDriveFile, GoogleDriveFileList +from .auth import LoadAuth +from .files import GoogleDriveFile, GoogleDriveFileList, _request_errors class GoogleDrive(ApiAttributeMixin): @@ -62,10 +59,6 @@ def GetAbout(self, fields="*"): return self._Execute(request) def _Execute(self, request): - try: - # Threads share this object, so self.http may be another thread's. + # Threads share this object, so self.http may be another thread's. + with _request_errors(): return request.execute(http=self.auth.thread_local.http) - except errors.HttpError as error: - raise ApiRequestError(error) from error - except GoogleRefreshError as error: - raise RefreshError(_refresh_failure(error)) from error diff --git a/pydrive2/files.py b/pydrive2/files.py index f3c4533b..42b3548a 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -3,8 +3,8 @@ import json import mimetypes import os +from contextlib import contextmanager -from google.auth.exceptions import RefreshError as GoogleRefreshError from googleapiclient import errors from googleapiclient.http import ( DEFAULT_CHUNK_SIZE, @@ -18,7 +18,7 @@ ApiResource, ApiResourceList, ) -from .auth import LoadAuth, RefreshError, _refresh_failure +from .auth import LoadAuth, _refresh_errors FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" DEFAULT_FILE_FIELDS = ( @@ -159,6 +159,17 @@ def GetField(self, field): return details[0].get(field, "") +@contextmanager +def _request_errors(): + """Raise PyDrive2's errors for a failed Drive request.""" + # google-auth can refresh the token during the request and fail. + with _refresh_errors(): + try: + yield + except errors.HttpError as error: + raise ApiRequestError(error) from error + + class FileNotDownloadableError(RuntimeError): """Error trying to download file that is not downloadable.""" @@ -174,17 +185,12 @@ def _GetList(self): fields = params.get("fields") or f"files({DEFAULT_FILE_FIELDS})" # Keep the cursor even when the caller selects only file fields. params["fields"] = _ensure_field(fields, "nextPageToken") - try: + with _request_errors(): self.metadata = ( self.auth.service.files() .list(**params) .execute(http=self.http) ) - except errors.HttpError as error: - raise ApiRequestError(error) - except GoogleRefreshError as error: - # google-auth refreshed the token during the request and failed. - raise RefreshError(_refresh_failure(error)) from error return self.metadata.get("files", []) @@ -246,12 +252,8 @@ def __init__( self._buffer = self._read_chunk() if pre_buffer else None def _next_chunk(self): - try: + with _request_errors(): status, self.done = self.downloader.next_chunk() - except errors.HttpError as error: - raise ApiRequestError(error) from error - except GoogleRefreshError as error: - raise RefreshError(_refresh_failure(error)) from error self.size = status.total_size self.progress = status.resumable_progress return self._fd.read() @@ -835,12 +837,8 @@ def _FileId(self): return file_id def _Execute(self, request): - try: + with _request_errors(): return self._AddResourceKeyHeaders(request).execute(http=self.http) - except errors.HttpError as error: - raise ApiRequestError(error) from error - except GoogleRefreshError as error: - raise RefreshError(_refresh_failure(error)) from error def _WrapRequest(self, request): """Replaces request.http with self.http. diff --git a/pydrive2/test/test_auth_flows.py b/pydrive2/test/test_auth_flows.py index 8340a19a..37f7978a 100644 --- a/pydrive2/test/test_auth_flows.py +++ b/pydrive2/test/test_auth_flows.py @@ -27,6 +27,7 @@ from cryptography.hazmat.primitives.serialization import pkcs12 from filelock import Timeout from google.auth import jwt +from google.auth.exceptions import RefreshError as GoogleRefreshError from google.oauth2.credentials import Credentials from google_auth_httplib2 import AuthorizedHttp, Request @@ -283,23 +284,6 @@ def request(http, uri, method="GET", body=None, **kwargs): assert str(error.value) == message -@pytest.mark.drive -def test_refresh_after_google_refuses_the_client_reports_its_oauth_error(): - auth = GoogleAuth(settings_file=None) - auth.credentials = Credentials( - "made-up-token", - refresh_token="made-up-refresh-token", - client_id="000000000000-made-up.apps.googleusercontent.com", - client_secret="made-up-secret", - token_uri=TOKEN_URI, - ) - with pytest.raises(RefreshError) as error: - auth.Refresh() - message = str(error.value) - assert message.startswith("Access token refresh failed: (invalid_client) ") - assert "{" not in message - - @pytest.fixture def login_drive_rejects(): """A login whose token Drive rejects and whose refresh Google refuses. @@ -323,6 +307,7 @@ def login_drive_rejects(): @pytest.mark.parametrize( "request_drive", [ + pytest.param(lambda auth: auth.Refresh(), id="refresh"), pytest.param( lambda auth: ( GoogleDrive(auth).CreateFile({"id": "root"}).FetchMetadata() @@ -356,6 +341,7 @@ def test_request_whose_token_refresh_fails_raises_refresh_error( message = str(error.value) assert message.startswith("Access token refresh failed: (invalid_client) ") assert "{" not in message + assert isinstance(error.value.__cause__, GoogleRefreshError) @pytest.mark.drive From 99bb045149fc47e5d2a562708c1bf41159e6580e Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 12:20:40 -0800 Subject: [PATCH 3/3] Test a refresh that fails between download chunks Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_auth_flows.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pydrive2/test/test_auth_flows.py b/pydrive2/test/test_auth_flows.py index 37f7978a..1876e930 100644 --- a/pydrive2/test/test_auth_flows.py +++ b/pydrive2/test/test_auth_flows.py @@ -7,6 +7,7 @@ import subprocess import sys import traceback +import uuid import webbrowser from base64 import urlsafe_b64encode from concurrent.futures import ThreadPoolExecutor @@ -42,6 +43,7 @@ from pydrive2.fs import GDriveFileSystem from pydrive2.fs.spec import GDriveAuthError, _client_auth from pydrive2.settings import InvalidConfigError, SettingsError +from pydrive2.test.test_util import pydrive_retry TOKEN_URI = "https://oauth2.googleapis.com/token" EMAIL = "service@example.test" @@ -344,6 +346,36 @@ def test_request_whose_token_refresh_fails_raises_refresh_error( assert isinstance(error.value.__cause__, GoogleRefreshError) +@pytest.mark.drive +def test_download_whose_refresh_fails_after_the_first_chunk_raises_refresh_error( + service_auth, request, monkeypatch +): + drive = GoogleDrive(service_auth) + file = drive.CreateFile({"name": uuid.uuid4().hex}) + file.SetContentString("x" * 2048) + pydrive_retry(file.Upload) + request.addfinalizer(lambda: pydrive_retry(file.Delete)) + reader = drive.CreateFile({"id": file["id"]}) + stream = reader.GetContentIOBuffer(chunksize=1024) + assert stream.read() == b"x" * 1024 + + # The login expires between chunks, and Google refuses to refresh it. + expired = Credentials( + "made-up-token", + refresh_token="made-up-refresh-token", + client_id="000000000000-made-up.apps.googleusercontent.com", + client_secret="made-up-secret", + token_uri=TOKEN_URI, + expiry=datetime.now(UTC).replace(tzinfo=None) - timedelta(hours=1), + ) + monkeypatch.setattr(reader.http, "credentials", expired) + with pytest.raises(RefreshError) as error: + stream.read() + message = str(error.value) + assert message.startswith("Access token refresh failed: (invalid_client) ") + assert isinstance(error.value.__cause__, GoogleRefreshError) + + @pytest.mark.drive def test_service_auth_after_google_refuses_the_account_reports_its_oauth_error( service_info,