Skip to content
Open
2 changes: 1 addition & 1 deletion googleapiclient/_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
64 changes: 58 additions & 6 deletions googleapiclient/_universe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)
29 changes: 15 additions & 14 deletions googleapiclient/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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


Expand Down
77 changes: 76 additions & 1 deletion googleapiclient/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@

from googleapiclient import _auth
from googleapiclient import _helpers as util
from googleapiclient import _universe
from googleapiclient.errors import (
BatchError,
HttpError,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"],
Expand All @@ -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):
Expand Down Expand Up @@ -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
Comment on lines +1380 to +1383

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Some subrequests in the batch may not have an explicit http transport configured (i.e., self._requests[i].http is None). To prevent passing None to _auth.get_credentials_from_http, filter out None transports from the iteration.

Suggested change
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
for transport in (http, *(self._requests[i].http for i in self._order)):
if transport is not None:
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.
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions tests/test__auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Loading
Loading