diff --git a/googleapiclient/_auth.py b/googleapiclient/_auth.py index 065b2ecd30..7cf58e40e7 100644 --- a/googleapiclient/_auth.py +++ b/googleapiclient/_auth.py @@ -157,7 +157,7 @@ def is_valid(credentials): def get_credentials_from_http(http): if http is None: return None - elif hasattr(http.request, "credentials"): + elif hasattr(getattr(http, "request", None), "credentials"): return http.request.credentials elif hasattr(http, "credentials") and not isinstance( http.credentials, httplib2.Credentials diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index 52c8566259..aa3e452c56 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -14,13 +14,14 @@ """Universe domain compatibility helpers. -Prefers ``google.api_core.universe.resolve_client_universe`` when available -(>= 2.45.0) and falls back to a local copy for older ``google-api-core`` -releases. +Prefers ``google.api_core.universe`` helpers when available (>= 2.45.0) and +falls back to local copies for older ``google-api-core`` releases. """ import collections.abc import os +import re +import urllib.parse from google.api_core import client_options as client_options_lib from google.auth import credentials as google_auth_credentials @@ -101,6 +102,45 @@ def resolve_client_universe(client_options=None): ) +try: + from google.api_core.universe import is_googleapis_host +except ImportError: + # TODO(https://github.com/googleapis/google-cloud-python/issues/19297): Replace with + # google.api_core.universe.is_googleapis_host once minimum allowed + # google-api-core version exceeds 2.44.0. + _GOOGLEAPIS_HOST_PATTERN = re.compile( + rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE)}$", + re.IGNORECASE, + ) + + def is_googleapis_host(url): + """Return True if an HTTP(S) URL targets ``googleapis.com`` or a subdomain.""" + if ( + not isinstance(url, str) + or not url + or "#" in url + or "\\" in url + or not url.isprintable() + or any(ch.isspace() for ch in url) + ): + return False + try: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("http", "https") or not url[ + len(parsed.scheme) : + ].startswith("://"): + return False + if "@" in parsed.netloc: + return False + _ = parsed.port + host = parsed.hostname or "" + return bool( + host and host.isascii() and _GOOGLEAPIS_HOST_PATTERN.fullmatch(host) + ) + except ValueError: + return False + + def check_api_core_compatible_with_credentials_universe(credentials): """Raise APICoreVersionError if credentials require universe support.""" if not HAS_UNIVERSE: @@ -116,15 +156,27 @@ def validate_request_credentials_universe(client_universe, credentials): skips uncached Compute Engine credentials to avoid metadata server calls during offline client initialization), this validates uncached Compute Engine credentials as well before the outbound request is sent. + + Args: + client_universe: The universe domain the request targets. + credentials: The credentials to check, or ``None`` if none are set. + + Returns: + bool: ``True`` if the request may be sent with these credentials. + + Raises: + UniverseMismatchError: If the credentials belong to another universe. + APICoreVersionError: If google-api-core < 2.18.0 and the credentials + belong to a non-default universe. """ if not HAS_UNIVERSE: # Without google.api_core.universe (< 2.18.0), the client can only # target the default universe; reject non-default credentials. check_api_core_compatible_with_credentials_universe(credentials) - return + return True if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): - return + return True # Intentionally call compare_domains directly rather than # google.api_core.universe.validate_credentials_universe so uncached # Compute Engine credentials are checked before attaching a token. - api_core_universe.compare_domains(client_universe, credentials) + return api_core_universe.compare_domains(client_universe, credentials) diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 6819659968..3a88feae62 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -299,7 +299,7 @@ def build( # document over the network (raises UniverseMismatchError, or # APICoreVersionError when google-api-core < 2.18.0). credentials_to_validate = ( - getattr(http, "credentials", None) if http is not None else credentials + _auth.get_credentials_from_http(http) if http is not None else credentials ) _universe.validate_request_credentials_universe( universe_domain, credentials_to_validate @@ -730,7 +730,7 @@ def build_from_document( base = mtls_endpoint else: # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". - http_credentials = getattr(http, "credentials", None) + http_credentials = _auth.get_credentials_from_http(http) _universe.check_api_core_compatible_with_credentials_universe(http_credentials) if model is None: @@ -1274,7 +1274,7 @@ def method(self, **kwargs): url = _add_query_parameter(url, "uploadType", "multipart") logger.debug("URL being requested: %s %s" % (httpMethod, url)) - return self._requestBuilder( + request = self._requestBuilder( self._http, model.response, url, @@ -1284,6 +1284,9 @@ def method(self, **kwargs): methodId=methodId, resumable=resumable, ) + if isinstance(request, HttpRequest): + request._universe_domain = self._universe_domain or DEFAULT_UNIVERSE + return request docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"] if len(parameters.argmap) > 0: @@ -1534,7 +1537,9 @@ def new_batch_http_request(callback=None): Returns: A BatchHttpRequest object based on the discovery document. """ - return BatchHttpRequest(callback=callback, batch_uri=batch_uri) + batch = BatchHttpRequest(callback=callback, batch_uri=batch_uri) + batch._universe_domain = self._universe_domain or DEFAULT_UNIVERSE + return batch self._set_dynamic_attr("new_batch_http_request", new_batch_http_request) @@ -1635,18 +1640,14 @@ def _validate_credentials(self): Raises: UniverseMismatchError: If the configured universe domain is not valid. """ - credentials = getattr(self._http, "credentials", None) - - self._credentials_validated = ( - ( - self._credentials_validated - or _universe.api_core_universe.compare_domains( - self._universe_domain, credentials + if not self._credentials_validated: + credentials = _auth.get_credentials_from_http(self._http) + self._credentials_validated = ( + _universe.validate_request_credentials_universe( + self._universe_domain, + credentials, ) ) - if _universe.HAS_UNIVERSE - else True - ) return self._credentials_validated diff --git a/googleapiclient/http.py b/googleapiclient/http.py index 5aad076854..9e8249764d 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -52,6 +52,7 @@ from googleapiclient import _auth from googleapiclient import _helpers as util +from googleapiclient import _universe from googleapiclient.errors import ( BatchError, HttpError, @@ -817,6 +818,11 @@ def next_chunk(self, num_retries=0): self._progress + self._chunksize - 1, ) http = self._request.http + request_universe = getattr(self._request, "_universe_domain", None) + if request_universe is not None: + _universe.validate_request_credentials_universe( + request_universe, _auth.get_credentials_from_http(http) + ) resp, content = _retry_request( http, @@ -953,6 +959,15 @@ def __init__( self._rand = random.random self._sleep = time.sleep + # Universe domain attached by the Resource that created this request; + # manually created requests have no universe attached. + self._universe_domain = None + + def __setstate__(self, state): + self.__dict__.update(state) + # Objects pickled by an earlier release have no _universe_domain. + self.__dict__.setdefault("_universe_domain", None) + @util.positional(1) def execute(self, http=None, num_retries=0): """Execute the request. @@ -972,10 +987,18 @@ def execute(self, http=None, num_retries=0): Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occurred. + google.api_core.universe.UniverseMismatchError if the credentials + attached to ``http`` belong to a different universe domain than the + client. """ if http is None: http = self.http + if self._universe_domain is not None: + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) + if self.resumable: body = None while body is None: @@ -1072,6 +1095,11 @@ def next_chunk(self, http=None, num_retries=0): if http is None: http = self.http + if self._universe_domain is not None: + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) + if self.resumable.size() is None: size = "*" else: @@ -1226,7 +1254,7 @@ def from_json(s, http, postproc): d = json.loads(s) if d["resumable"] is not None: d["resumable"] = MediaUpload.new_from_json(d["resumable"]) - return HttpRequest( + req = HttpRequest( http, postproc, uri=d["uri"], @@ -1236,6 +1264,8 @@ def from_json(s, http, postproc): methodId=d["methodId"], resumable=d["resumable"], ) + req._universe_domain = d.get("_universe_domain") + return req @staticmethod def null_postproc(resp, contents): @@ -1326,6 +1356,49 @@ def __init__(self, callback=None, batch_uri=None): # A map of id(Credentials) that have been refreshed. self._refreshed_credentials = {} + # Track the batch's universe domain. Resource.new_batch_http_request() + # stamps its universe domain here; any googleapis.com batch URI targets + # the default universe. Other custom URIs leave this as None. + self._universe_domain = ( + _universe.DEFAULT_UNIVERSE + if _universe.is_googleapis_host(batch_uri) + else None + ) + + def __setstate__(self, state): + self.__dict__.update(state) + # Objects pickled by an earlier release have no _universe_domain. + self.__dict__.setdefault("_universe_domain", None) + + def _validate_http_credentials(self, http): + """Validate outer and per-request credentials before sending the batch.""" + # Collect unique credentials (outer http and per-subrequest http) and + # unique target universes (the batch endpoint and each subrequest) so + # cross-universe batches and mismatched overrides fail before any token + # refresh or network send. + creds_by_id = {} + for transport in (http, *(self._requests[i].http for i in self._order)): + creds = _auth.get_credentials_from_http(transport) + if creds is not None: + creds_by_id[id(creds)] = creds + + # Skip None: a batch or request that was not built by a Resource has no + # universe to check against. + universes = dict.fromkeys( + u + for u in ( + self._universe_domain, + *( + getattr(self._requests[i], "_universe_domain", None) + for i in self._order + ), + ) + if u is not None + ) + for target_universe in universes: + for creds in creds_by_id.values(): + _universe.validate_request_credentials_universe(target_universe, creds) + def _refresh_and_apply_credentials(self, request, http): """Refresh the credentials and apply to the request. @@ -1635,6 +1708,8 @@ def execute(self, http=None): if http is None: raise ValueError("Missing a valid http object.") + self._validate_http_credentials(http) + # Special case for OAuth2Credentials-style objects which have not yet been # refreshed with an initial access_token. creds = _auth.get_credentials_from_http(http) diff --git a/tests/test__auth.py b/tests/test__auth.py index cb70ff3deb..ebeb2b5629 100644 --- a/tests/test__auth.py +++ b/tests/test__auth.py @@ -198,3 +198,8 @@ def test_default_credentials(self): credentials = mock.Mock(spec=google.auth.credentials.Credentials) with self.assertRaises(ValueError): _auth.authorized_http(credentials) + + +class TestGetCredentialsFromHttp(unittest.TestCase): + def test_missing_request_attribute_returns_none(self): + self.assertIsNone(_auth.get_credentials_from_http(object())) diff --git a/tests/test__universe.py b/tests/test__universe.py index 1891c0d1be..f88ed1e4ea 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -97,6 +97,38 @@ def test_prefers_upstream_resolve_client_universe_when_available(self): self.assertIs( _universe.resolve_client_universe, universe.resolve_client_universe ) + if hasattr(universe, "is_googleapis_host"): + self.assertIs(_universe.is_googleapis_host, universe.is_googleapis_host) + + def test_is_googleapis_host(self): + matching = ( + "https://www.googleapis.com/batch", + "https://www.googleapis.com/batch/zoo/v1", + "https://storage.googleapis.com/batch/storage/v1", + "https://googleapis.com/batch", + "http://www.googleapis.com/batch", + ) + non_matching = ( + "https://www.foo.com/batch", + "https://notgoogleapis.com/batch", + "https://www.googleapis.com@evil.com/batch", + "https://www.googleapis.com\\@evil.com/batch", + "https://www.googleapis.com/batch#frag", + "https://www.googleapis.com:99999/batch", + "ftp://www.googleapis.com/batch", + "https:www.googleapis.com/batch", + "https://www.googleapis.com /batch", + "", + None, + ) + for fn in ( + _universe.is_googleapis_host, + self.fallback_universe.is_googleapis_host, + ): + for url in matching: + self.assertTrue(fn(url), msg=url) + for url in non_matching: + self.assertFalse(fn(url), msg=url) @parameterized.expand( [ @@ -197,18 +229,26 @@ def test_resolve_client_universe_invalid_type_raises(self): fn("invalid") def test_validate_request_credentials_universe_accepts_matching_and_exempt(self): - _universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None) - _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials() + self.assertTrue( + _universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None) + ) + self.assertTrue( + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials() + ) ) - _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, _make_credentials(self.FAKE_UNIVERSE) + self.assertTrue( + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, _make_credentials(self.FAKE_UNIVERSE) + ) ) def test_validate_request_credentials_universe_exempts_aio_anonymous(self): aio_credentials = pytest.importorskip("google.auth.aio.credentials") - _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, aio_credentials.AnonymousCredentials() + self.assertTrue( + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, aio_credentials.AnonymousCredentials() + ) ) def test_validate_request_credentials_universe_mismatch_raises(self): @@ -320,6 +360,30 @@ def test_validate_request_credentials_universe_delegates_without_universe_suppor None, _make_credentials(self.FAKE_UNIVERSE) ) + def test_is_googleapis_host_without_universe_support(self): + self.assertTrue( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com/batch/zoo/v1" + ) + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host("https://www.foo.com/batch") + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com@evil.com/batch" + ) + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com:99999/batch" + ) + ) + self.assertFalse(self.legacy_universe.is_googleapis_host("")) + self.assertFalse( + self.legacy_universe.is_googleapis_host("ftp://www.googleapis.com/batch") + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_discovery.py b/tests/test_discovery.py index d2b71e38ce..e9fdd43af9 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -1640,6 +1640,9 @@ def test_http_anonymous_credentials_in_universe(self): ) self.assertEqual(_requested_uris(http_mock), [self.V2_URI]) self.assertEqual(zoo._universe_domain, self.FAKE_UNIVERSE) + self.assertTrue(zoo._validate_credentials()) + request = zoo.animals().list() + self.assertEqual(request._universe_domain, self.FAKE_UNIVERSE) @unittest.skipUnless( hasattr(google.auth.compute_engine.Credentials, "universe_domain"), @@ -3071,9 +3074,10 @@ def test_validate_credentials_with_client_options_without_universe(self): def test_validate_credentials_with_no_universe(self): fake_universe = "foo.com" + creds_without_universe = mock.Mock(spec=[]) http = google_auth_httplib2.AuthorizedHttp( - credentials=None, http=build_http() + credentials=creds_without_universe, http=build_http() ) discovery = read_datafile("zoo.json") service = build_from_document( @@ -3087,7 +3091,7 @@ def test_validate_credentials_with_no_universe(self): assert service._validate_credentials() http = google_auth_httplib2.AuthorizedHttp( - credentials=None, http=build_http() + credentials=creds_without_universe, http=build_http() ) discovery = read_datafile("zoo.json") service = build_from_document( @@ -3101,6 +3105,32 @@ def test_validate_credentials_with_no_universe(self): with self.assertRaises(universe.UniverseMismatchError): service._validate_credentials() + def test_validate_credentials_without_credentials_in_custom_universe(self): + fake_universe = "foo.com" + discovery = read_datafile("zoo.json") + client_options = google.api_core.client_options.ClientOptions( + universe_domain=fake_universe + ) + + service = build_from_document( + discovery, + developerKey="fake-key", + client_options=client_options, + ) + assert service._validate_credentials() + request = service.animals().list() + assert request._universe_domain == fake_universe + + http = google_auth_httplib2.AuthorizedHttp( + credentials=None, http=build_http() + ) + service = build_from_document( + discovery, + http=http, + client_options=client_options, + ) + assert service._validate_credentials() + def test_validate_credentials_with_default_universe(self): fake_universe = "foo.com" diff --git a/tests/test_http.py b/tests/test_http.py index 91f2c7ae52..d7cd7910cd 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -22,6 +22,7 @@ __author__ = "jcgregorio@google.com (Joe Gregorio)" +import importlib.util import io from io import FileIO @@ -29,6 +30,7 @@ import json import logging import os +import pickle import random import socket import ssl @@ -38,9 +40,22 @@ from unittest import mock import urllib +import google.api_core +import google.auth.compute_engine +import google.auth.credentials +import google_auth_httplib2 import httplib2 +from parameterized import parameterized -from googleapiclient.discovery import build +try: + from google.api_core import universe + + HAS_UNIVERSE = True +except ImportError: + HAS_UNIVERSE = False + +from googleapiclient import _universe +from googleapiclient.discovery import APICoreVersionError, build, build_from_document from googleapiclient.errors import BatchError, HttpError, InvalidChunkSizeError from googleapiclient.http import ( DEFAULT_CHUNK_SIZE, @@ -1889,6 +1904,670 @@ def test_deserialize_non_dict_payload_raises_value_error(self): MediaFileUpload.from_json(payload) +def _make_universe_credentials(universe_domain): + credentials = mock.Mock(spec=google.auth.credentials.Credentials) + credentials.universe_domain = universe_domain + credentials.valid = True + credentials.expired = False + return credentials + + +def _read_datafile(filename): + with open(datafile(filename), "r") as f: + return f.read() + + +@unittest.skipUnless(HAS_UNIVERSE, "google-api-core >= 2.18.0 is required") +class TestExecuteUniverseValidation(unittest.TestCase): + """Per-request execute(http=...) and batch overrides validate universe_domain.""" + + FAKE_UNIVERSE = "foo.com" + OTHER_UNIVERSE = "bar.com" + + def setUp(self): + environ_patcher = mock.patch.dict("os.environ") + environ_patcher.start() + self.addCleanup(environ_patcher.stop) + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None) + + def _build_zoo(self, universe_domain=None, credentials_universe=None): + if credentials_universe is None: + credentials_universe = universe_domain or universe.DEFAULT_UNIVERSE + client_options = ( + {"universe_domain": universe_domain} + if universe_domain is not None + else None + ) + http = google_auth_httplib2.AuthorizedHttp( + _make_universe_credentials(credentials_universe), + http=HttpMockSequence([]), + ) + return build_from_document( + _read_datafile("zoo.json"), + http=http, + client_options=client_options, + ) + + def _make_authorized_http(self, universe_domain, responses=(), valid=True): + creds = _make_universe_credentials(universe_domain) + creds.valid = valid + http_mock = HttpMockSequence(list(responses)) + http = google_auth_httplib2.AuthorizedHttp(creds, http=http_mock) + return http, creds, http_mock + + def _assert_mismatch_raises(self, fn, creds, http_mock, check_refresh=False): + with self.assertRaises(universe.UniverseMismatchError): + fn() + self.assertEqual(http_mock.request_sequence, []) + creds.before_request.assert_not_called() + if check_refresh: + creds.refresh.assert_not_called() + + @parameterized.expand( + [ + ("custom_creds_on_default_resource", None, "foo.com"), + ("default_creds_on_custom_resource", "foo.com", "googleapis.com"), + ("other_universe_creds_on_custom_resource", "foo.com", "bar.com"), + ] + ) + def test_http_request_execute_http_override_mismatch_raises( + self, _, resource_universe, override_universe + ): + request = self._build_zoo(universe_domain=resource_universe).animals().list() + override_http, override_creds, http_mock = self._make_authorized_http( + override_universe + ) + self._assert_mismatch_raises( + lambda: request.execute(http=override_http), override_creds, http_mock + ) + + def test_http_request_execute_http_override_matching_universe_succeeds(self): + request = self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list() + override_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[({"status": "200"}, '{"items": []}')] + ) + + self.assertEqual(request.execute(http=override_http), {"items": []}) + self.assertEqual(len(http_mock.request_sequence), 1) + self.assertIn(self.FAKE_UNIVERSE, http_mock.request_sequence[0][0]) + + def test_http_request_execute_http_override_anonymous_and_unauthenticated_succeed( + self, + ): + request = self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list() + + anon_mock = HttpMockSequence([({"status": "200"}, "{}")]) + anon_http = google_auth_httplib2.AuthorizedHttp( + google.auth.credentials.AnonymousCredentials(), http=anon_mock + ) + self.assertEqual(request.execute(http=anon_http), {}) + self.assertEqual(len(anon_mock.request_sequence), 1) + + plain_mock = HttpMockSequence([({"status": "200"}, "{}")]) + self.assertEqual(request.execute(http=plain_mock), {}) + self.assertEqual(len(plain_mock.request_sequence), 1) + + @unittest.skipUnless( + hasattr(google.auth.compute_engine.Credentials, "universe_domain"), + "google-auth >= 2.28.0 is required", + ) + def test_http_request_execute_http_override_uncached_compute_engine_mismatch(self): + request = self._build_zoo().animals().list() + + gce_creds = google.auth.compute_engine.Credentials() + gce_creds._universe_domain_cached = False + gce_creds.before_request = mock.Mock() + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(gce_creds, http=http_mock) + + with mock.patch.object( + google.auth.compute_engine.Credentials, + "universe_domain", + new_callable=mock.PropertyMock, + return_value=self.FAKE_UNIVERSE, + ) as mock_universe_domain: + self._assert_mismatch_raises( + lambda: request.execute(http=override_http), gce_creds, http_mock + ) + + mock_universe_domain.assert_called_once_with() + + def test_http_request_mutated_http_attribute_mismatch_raises(self): + request = self._build_zoo().animals().list() + request.http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises(request.execute, creds, http_mock) + + def test_http_request_next_page_preserves_universe_validation(self): + gdu_http, _, _ = self._make_authorized_http(universe.DEFAULT_UNIVERSE) + drive = build_from_document(_read_datafile("drive.json"), http=gdu_http) + request = drive.changes().list(pageToken="1") + next_request = drive.changes().list_next( + request, {"nextPageToken": "next-token"} + ) + + override_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: next_request.execute(http=override_http), creds, http_mock + ) + + def test_http_request_to_from_json_preserves_universe_validation(self): + request = self._build_zoo().animals().list() + mismatched_http, creds, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE + ) + restored = HttpRequest.from_json( + request.to_json(), mismatched_http, request.postproc + ) + self._assert_mismatch_raises(restored.execute, creds, http_mock) + + def test_http_request_next_chunk_http_override_mismatch_raises(self): + upload = MediaInMemoryUpload( + b"hello world", mimetype="text/plain", resumable=True + ) + request = self._build_zoo().animals().insert(body={}, media_body=upload) + override_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: request.next_chunk(http=override_http), creds, http_mock + ) + + def test_media_download_next_chunk_mutated_http_mismatch_raises(self): + request = self._build_zoo().animals().get_media(name="Lion") + request.http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + download = MediaIoBaseDownload(io.BytesIO(), request) + self._assert_mismatch_raises(download.next_chunk, creds, http_mock) + + def test_standalone_http_request_without_universe_allows_custom_credentials(self): + http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[({"status": "200"}, "{}")] + ) + request = HttpRequest( + http, JsonModel().response, "https://custom.example.com/resource" + ) + self.assertEqual(request.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + @parameterized.expand( + [ + ("custom_creds_on_default_batch", None, "foo.com"), + ("default_creds_on_custom_batch", "foo.com", "googleapis.com"), + ("other_universe_creds_on_custom_batch", "foo.com", "bar.com"), + ] + ) + def test_batch_execute_http_override_mismatch_raises( + self, _, resource_universe, override_universe + ): + zoo = self._build_zoo(universe_domain=resource_universe) + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + override_http, creds, http_mock = self._make_authorized_http( + override_universe, valid=False + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=override_http), + creds, + http_mock, + check_refresh=True, + ) + + def test_batch_execute_http_override_matching_universe_succeeds(self): + zoo = self._build_zoo(universe_domain=self.FAKE_UNIVERSE) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + batch_response = ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + override_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[batch_response] + ) + + batch.execute(http=override_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + self.assertIn(self.FAKE_UNIVERSE, http_mock.request_sequence[0][0]) + + def test_batch_execute_http_override_anonymous_succeeds(self): + zoo = self._build_zoo(universe_domain=self.FAKE_UNIVERSE) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + anon_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + anon_http = google_auth_httplib2.AuthorizedHttp( + google.auth.credentials.AnonymousCredentials(), http=anon_mock + ) + + batch.execute(http=anon_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(anon_mock.request_sequence), 1) + + @unittest.skipUnless( + hasattr(google.auth.compute_engine.Credentials, "universe_domain"), + "google-auth >= 2.28.0 is required", + ) + def test_batch_execute_http_override_uncached_compute_engine_mismatch(self): + zoo = self._build_zoo() + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + gce_creds = google.auth.compute_engine.Credentials() + gce_creds._universe_domain_cached = False + gce_creds.before_request = mock.Mock() + gce_creds.refresh = mock.Mock() + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(gce_creds, http=http_mock) + + with mock.patch.object( + google.auth.compute_engine.Credentials, + "universe_domain", + new_callable=mock.PropertyMock, + return_value=self.FAKE_UNIVERSE, + ) as mock_universe_domain: + self._assert_mismatch_raises( + lambda: batch.execute(http=override_http), + gce_creds, + http_mock, + check_refresh=True, + ) + + mock_universe_domain.assert_called_once_with() + + def test_batch_execute_cross_universe_subrequest_raises(self): + batch = self._build_zoo().new_batch_http_request() + batch.add(self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list()) + + gdu_http, creds, http_mock = self._make_authorized_http( + universe.DEFAULT_UNIVERSE + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=gdu_http), creds, http_mock + ) + + def test_batch_execute_legacy_batch_with_custom_universe_override_raises(self): + batch = BatchHttpRequest() + batch.add( + HttpRequest( + None, JsonModel().response, "https://www.googleapis.com/zoo/v1/animals" + ) + ) + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + + def test_batch_execute_api_specific_googleapis_uri_with_tpc_subrequest_raises(self): + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + tpc_zoo = build_from_document( + _read_datafile("zoo.json"), + http=tpc_http, + client_options={"universe_domain": self.FAKE_UNIVERSE}, + ) + batch = BatchHttpRequest(batch_uri="https://www.googleapis.com/batch/zoo/v1") + batch.add(tpc_zoo.animals().list()) + + self._assert_mismatch_raises(batch.execute, creds, http_mock) + + def test_batch_execute_api_specific_googleapis_uri_standalone_tpc_override_raises( + self, + ): + batch = BatchHttpRequest( + batch_uri="https://storage.googleapis.com/batch/storage/v1" + ) + batch.add( + HttpRequest(None, JsonModel().response, "https://storage.googleapis.com/x") + ) + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + + def test_batch_execute_custom_uri_uses_subrequest_universe(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + batch.add(self._build_zoo().animals().list()) + + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + + def test_standalone_batch_allows_custom_credentials(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + batch_response = ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + tpc_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[batch_response] + ) + + batch.execute(http=tpc_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_batch_execute_mutated_subrequest_http_mismatch_raises(self): + zoo = self._build_zoo() + batch = zoo.new_batch_http_request() + req = zoo.animals().list() + req.http, tpc_creds, _ = self._make_authorized_http(self.FAKE_UNIVERSE) + batch.add(req) + + gdu_http, _, gdu_http_mock = self._make_authorized_http( + universe.DEFAULT_UNIVERSE + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=gdu_http), tpc_creds, gdu_http_mock + ) + + +class TestExecuteWithoutUniverseSupport(unittest.TestCase): + """Per-request execute(http=...) on google-api-core < 2.18.0.""" + + FAKE_UNIVERSE = "foo.com" + + @classmethod + def setUpClass(cls): + spec = importlib.util.spec_from_file_location( + "_universe_no_universe_http_test", _universe.__file__ + ) + module = importlib.util.module_from_spec(spec) + with mock.patch.dict( + "sys.modules", {"google.api_core.universe": None} + ), mock.patch.dict(google.api_core.__dict__): + google.api_core.__dict__.pop("universe", None) + spec.loader.exec_module(module) + module.APICoreVersionError = APICoreVersionError + cls.legacy_universe = module + + def setUp(self): + environ_patcher = mock.patch.dict("os.environ") + environ_patcher.start() + self.addCleanup(environ_patcher.stop) + os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None) + os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None) + + discovery_patcher = mock.patch( + "googleapiclient.discovery._universe", self.legacy_universe + ) + http_patcher = mock.patch( + "googleapiclient.http._universe", self.legacy_universe + ) + discovery_patcher.start() + http_patcher.start() + self.addCleanup(discovery_patcher.stop) + self.addCleanup(http_patcher.stop) + + def test_http_request_execute_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().list() + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + request.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_http_request_next_chunk_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + upload = MediaInMemoryUpload(b"hello", mimetype="text/plain", resumable=True) + request = zoo.animals().insert(body={}, media_body=upload) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + request.next_chunk(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_batch_execute_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_batch_execute_api_specific_googleapis_uri_custom_universe_raises(self): + batch = BatchHttpRequest(batch_uri="https://www.googleapis.com/batch/zoo/v1") + batch.add( + HttpRequest( + None, JsonModel().response, "https://www.googleapis.com/zoo/v1/animals" + ) + ) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_batch_execute_subrequest_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + req = zoo.animals().list() + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + req.http = google_auth_httplib2.AuthorizedHttp( + tpc_creds, http=HttpMockSequence([]) + ) + batch.add(req) + + gdu_http_mock = HttpMockSequence([]) + gdu_http = google_auth_httplib2.AuthorizedHttp( + _make_universe_credentials("googleapis.com"), http=gdu_http_mock + ) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=gdu_http) + + self.assertEqual(gdu_http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_http_request_execute_default_universe_succeeds(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().list() + + gdu_creds = _make_universe_credentials("googleapis.com") + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + override_http = google_auth_httplib2.AuthorizedHttp(gdu_creds, http=http_mock) + + self.assertEqual(request.execute(http=override_http), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_batch_execute_default_universe_succeeds(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + gdu_creds = _make_universe_credentials("googleapis.com") + http_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + override_http = google_auth_httplib2.AuthorizedHttp(gdu_creds, http=http_mock) + + batch.execute(http=override_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_media_download_next_chunk_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().get_media(name="Lion") + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + request.http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + download = MediaIoBaseDownload(io.BytesIO(), request) + + with self.assertRaises(APICoreVersionError): + download.next_chunk() + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_resource_stamps_default_universe(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + + self.assertIsNone(zoo._universe_domain) + self.assertEqual(zoo.animals().list()._universe_domain, "googleapis.com") + self.assertEqual( + zoo.new_batch_http_request()._universe_domain, "googleapis.com" + ) + + def test_standalone_http_request_allows_custom_credentials(self): + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + request = HttpRequest( + http, JsonModel().response, "https://custom.example.com/resource" + ) + + self.assertEqual(request.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_standalone_batch_allows_custom_credentials(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + batch.execute(http=http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + + +class TestExecuteWithoutUniverseAttribute(unittest.TestCase): + """Requests and batches created by an earlier release keep working.""" + + BATCH_HEADERS = { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + } + + def test_request_created_before_universe_tracking(self): + request = HttpRequest( + HttpMockSequence([({"status": "200"}, "{}")]), + JsonModel().response, + "https://custom.example.com/resource", + ) + # A request pickled by an earlier release has no _universe_domain. + del request.__dict__["_universe_domain"] + request = pickle.loads(pickle.dumps(request)) + + self.assertIsNone(request._universe_domain) + self.assertEqual(request.execute(), {}) + + def test_batch_created_before_universe_tracking(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + # A batch pickled by an earlier release has no _universe_domain. + del batch.__dict__["_universe_domain"] + batch = pickle.loads(pickle.dumps(batch)) + self.assertIsNone(batch._universe_domain) + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + + batch.execute( + http=HttpMockSequence([(self.BATCH_HEADERS, BATCH_SINGLE_RESPONSE)]) + ) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + + def test_from_json_without_universe_domain_key(self): + request = HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ) + payload = json.loads(request.to_json()) + payload.pop("_universe_domain", None) + + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + restored = HttpRequest.from_json( + json.dumps(payload), http_mock, request.postproc + ) + + self.assertIsNone(restored._universe_domain) + self.assertEqual(restored.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + if __name__ == "__main__": logging.getLogger().setLevel(logging.ERROR) unittest.main()