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 65a2daf0..c3bfd22f 100644 --- a/pydrive2/drive.py +++ b/pydrive2/drive.py @@ -1,8 +1,6 @@ -from googleapiclient import errors - from .apiattr import ApiAttributeMixin from .auth import LoadAuth -from .files import ApiRequestError, GoogleDriveFile, GoogleDriveFileList +from .files import GoogleDriveFile, GoogleDriveFileList, _request_errors class GoogleDrive(ApiAttributeMixin): @@ -61,8 +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 diff --git a/pydrive2/files.py b/pydrive2/files.py index a1766669..42b3548a 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -3,6 +3,7 @@ import json import mimetypes import os +from contextlib import contextmanager from googleapiclient import errors from googleapiclient.http import ( @@ -17,7 +18,7 @@ ApiResource, ApiResourceList, ) -from .auth import LoadAuth +from .auth import LoadAuth, _refresh_errors FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" DEFAULT_FILE_FIELDS = ( @@ -158,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.""" @@ -173,14 +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) return self.metadata.get("files", []) @@ -242,10 +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 self.size = status.total_size self.progress = status.resumable_progress return self._fd.read() @@ -829,10 +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 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..1876e930 100644 --- a/pydrive2/test/test_auth_flows.py +++ b/pydrive2/test/test_auth_flows.py @@ -7,11 +7,12 @@ import subprocess import sys import traceback +import uuid import webbrowser 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 @@ -27,6 +28,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 @@ -41,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" @@ -283,8 +286,13 @@ 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(): +@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", @@ -292,12 +300,80 @@ def test_refresh_after_google_refuses_the_client_reports_its_oauth_error(): 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: auth.Refresh(), id="refresh"), + 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: - auth.Refresh() + request_drive(login_drive_rejects) 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 +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