Skip to content
Open
114 changes: 114 additions & 0 deletions packages/google-cloud-storage/google/cloud/storage/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,17 @@
import os
import secrets
import sys
from collections.abc import Mapping
from contextlib import contextmanager
from hashlib import md5
from typing import Any
from urllib.parse import urlsplit, urlunsplit
from uuid import uuid4

import google.auth.credentials
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as api_exceptions
from google.api_core import universe
from google.auth import environment_vars
from google.cloud.exceptions import NotFound

Expand Down Expand Up @@ -57,6 +62,9 @@

_DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"

_UNIVERSE_DOMAIN_ENV_VAR = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
"""Environment variable defining the universe domain."""

_STORAGE_HOST_TEMPLATE = "storage.{universe_domain}"

_TRUE_DEFAULT_STORAGE_HOST = _STORAGE_HOST_TEMPLATE.format(
Expand Down Expand Up @@ -110,6 +118,112 @@ def _get_api_endpoint_override():
return None


# TODO(universe-domain): Replace with google.api_core.universe.resolve_client_universe
Comment thread
shradhakatyal marked this conversation as resolved.
Resolved
# once minimum allowed google-api-core version exceeds 2.44.0.
# Tracked in b/592414616 and
# https://github.com/googleapis/google-cloud-python/issues/19297.
def _resolve_client_universe(
client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None,
) -> str:
"""Resolve a client's universe domain from ``client_options`` or the environment.

Follows AIP-4113 precedence: ``client_options.universe_domain``, then
``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``.

Args:
client_options: Optional ``ClientOptions`` instance or mapping passed to
``Client.__init__``. If ``None``, falls back to
``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` and then ``"googleapis.com"``.

Returns:
The resolved universe domain string, without surrounding whitespace.

Raises:
google.api_core.universe.EmptyUniverseError: If the configured universe
domain is empty or contains only whitespace.
TypeError: If ``client_options`` is not a ``ClientOptions`` instance,
``Mapping``, or ``None``.
"""
if client_options is None:
options_universe = None
elif isinstance(client_options, Mapping):
options_universe = client_options.get("universe_domain")
elif isinstance(client_options, client_options_lib.ClientOptions):
options_universe = client_options.universe_domain
else:
raise TypeError(
"client_options must be a ClientOptions instance, Mapping, or None; "
f"got {type(client_options).__name__}"
)
# Older google-api-core releases return the value with its surrounding
# whitespace, so strip it here.
return universe.determine_domain(
options_universe,
os.getenv(_UNIVERSE_DOMAIN_ENV_VAR),
).strip()
Comment thread
shradhakatyal marked this conversation as resolved.
Resolved


def _validate_signing_credentials_universe_domain(client, credentials, api_endpoint):
"""Checks per-call signing credentials against the client's universe domain.

The default Storage endpoint of a universe domain accepts a signed URL or
POST policy only from an identity in that universe domain. This function
raises when the result targets the default endpoint of the client's
universe domain and ``credentials`` report a different, non-default
universe domain.

It does nothing when the two cannot be compared:

- ``credentials`` cannot sign, or do not report a universe domain.
- ``credentials`` report the default universe domain. Credentials also
report that value when no universe domain was set on them.
- ``api_endpoint`` is not the default Storage endpoint of the client's
universe domain, for example a custom endpoint or an emulator.

:type client: :class:`~google.cloud.storage.client.Client`
:param client: The client used for the signing call.

:type credentials: :class:`google.auth.credentials.Signing` or ``NoneType``
:param credentials: The credentials passed for a single signing call.

:type api_endpoint: str
:param api_endpoint: The endpoint used in the signed URL or POST policy.

:raises ValueError: If ``credentials`` report a non-default universe domain
that differs from the universe domain of ``client``.
"""
if not isinstance(credentials, google.auth.credentials.Signing):
return

credentials_universe_domain = getattr(credentials, "universe_domain", None)
if not isinstance(credentials_universe_domain, str):
return

if credentials_universe_domain == _DEFAULT_UNIVERSE_DOMAIN:
return

client_universe_domain = getattr(client, "universe_domain", None)
if not isinstance(client_universe_domain, str):
return

default_api_endpoint = _DEFAULT_SCHEME + _STORAGE_HOST_TEMPLATE.format(
universe_domain=client_universe_domain
)
if api_endpoint != default_api_endpoint:
return
Comment thread
shradhakatyal marked this conversation as resolved.
Resolved

if credentials_universe_domain != client_universe_domain:
raise ValueError(
"The universe domain of the signing credentials ({cred_ud}) does "
"not match the universe domain of the client ({client_ud}). Pass "
"credentials from the client's universe domain, or configure the "
"client for the universe domain of the credentials.".format(
cred_ud=credentials_universe_domain,
client_ud=client_universe_domain,
Comment thread
shradhakatyal marked this conversation as resolved.
Resolved
)
)


def _virtual_hosted_style_base_url(url, bucket, trailing_slash=False):
"""Returns the scheme and netloc sections of the url, with the bucket
prepended to the netloc.
Expand Down
13 changes: 13 additions & 0 deletions packages/google-cloud-storage/google/cloud/storage/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
_PropertyMixin,
_raise_if_more_than_one_set,
_scalar_property,
_validate_signing_credentials_universe_domain,
_virtual_hosted_style_base_url,
)
from google.cloud.storage._media.requests import (
Expand Down Expand Up @@ -593,6 +594,10 @@ def generate_signed_url(
when using a CDN. Defaults to ``"http"``.

:raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used.
:raises: :exc:`ValueError` when ``credentials`` sign the URL, report a
non-default universe domain that differs from the universe
domain of the client, and the URL uses the default endpoint of
the client's universe domain.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
Expand All @@ -618,6 +623,14 @@ def generate_signed_url(
client = self._require_client(client)
api_access_endpoint = client.api_endpoint

# A bucket-bound hostname replaces the endpoint in the signed URL, and
# ``credentials`` do not sign the URL when an access token and a
# service account email are both passed.
if not bucket_bound_hostname and not (access_token and service_account_email):
_validate_signing_credentials_universe_domain(
self._require_client(client), credentials, api_access_endpoint
)

quoted_name = _quote(self.name, safe=b"/~")

# If you are on Google Compute Engine, you can't generate a signed URL
Expand Down
11 changes: 11 additions & 0 deletions packages/google-cloud-storage/google/cloud/storage/bucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
_PropertyMixin,
_scalar_property,
_validate_name,
_validate_signing_credentials_universe_domain,
_virtual_hosted_style_base_url,
)
from google.cloud.storage._signing import generate_signed_url_v2, generate_signed_url_v4
Expand Down Expand Up @@ -3923,6 +3924,10 @@ def generate_signed_url(
Defaults to ``"http"``.

:raises: :exc:`ValueError` when version is invalid or mutually exclusive arguments are used.
:raises: :exc:`ValueError` when ``credentials`` sign the URL, report a
non-default universe domain that differs from the universe
domain of the client, and the URL uses the default endpoint of
the client's universe domain.
:raises: :exc:`TypeError` when expiration is not a valid type.
:raises: :exc:`AttributeError` if credentials is not an instance
of :class:`google.auth.credentials.Signing`.
Expand All @@ -3948,6 +3953,12 @@ def generate_signed_url(
client = self._require_client(client)
api_access_endpoint = client.api_endpoint

# A bucket-bound hostname replaces the endpoint in the signed URL.
if not bucket_bound_hostname:
_validate_signing_credentials_universe_domain(
self._require_client(client), credentials, api_access_endpoint
)

# If you are on Google Compute Engine, you can't generate a signed URL
# using GCE service account.
# See https://github.com/googleapis/google-auth-library-python/issues/50
Expand Down
47 changes: 41 additions & 6 deletions packages/google-cloud-storage/google/cloud/storage/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import json
import os
import warnings
from collections.abc import Mapping

import google.api_core.client_options
from google.api_core import exceptions as api_exceptions
Expand All @@ -44,6 +45,8 @@
_get_api_endpoint_override,
_get_environ_project,
_get_storage_emulator_override,
_resolve_client_universe,
_validate_signing_credentials_universe_domain,
_virtual_hosted_style_base_url,
create_trace_span_helper,
)
Expand Down Expand Up @@ -108,7 +111,11 @@ class Client(ClientWithProject):

:type client_options: :class:`~google.api_core.client_options.ClientOptions` or :class:`dict`
:param client_options: (Optional) Client options used to set user options on the client.
Any mapping is accepted in place of a ``dict``.
A non-default universe domain or api endpoint should be set through client_options.
If ``universe_domain`` is not set here, the ``GOOGLE_CLOUD_UNIVERSE_DOMAIN``
environment variable is used. An empty universe domain raises
``google.api_core.universe.EmptyUniverseError``.

:type use_auth_w_custom_endpoint: bool
:param use_auth_w_custom_endpoint:
Expand Down Expand Up @@ -158,6 +165,11 @@ def __init__(
if project is _marker:
project = None

# ``client_options`` can be any mapping. Convert other mappings to a
# ``dict``, which the code below and pickling support.
if isinstance(client_options, Mapping) and not isinstance(client_options, dict):
client_options = dict(client_options)

# Save the initial value of constructor arguments before they
# are passed along, for use in __reduce__ defined elsewhere.
self._initial_client_info = client_info
Expand All @@ -183,8 +195,14 @@ def __init__(
client_options
)

if client_options and client_options.universe_domain:
self._universe_domain = client_options.universe_domain
# ``_universe_domain`` stays ``None`` for the default universe unless
# ``client_options`` names it, so the default endpoint handling applies.
# The default universe is matched without regard to case.
universe_domain = _resolve_client_universe(client_options)
if (
client_options and client_options.universe_domain
) or universe_domain.lower() != _DEFAULT_UNIVERSE_DOMAIN:
self._universe_domain = universe_domain
else:
self._universe_domain = None

Expand All @@ -208,8 +226,9 @@ def __init__(
elif api_endpoint_override:
api_endpoint = api_endpoint_override

# 4. Elif the `universe_domain` is set in `client_options`,
# create the endpoint using that as the default.
# 4. Elif the `universe_domain` is set in `client_options` or in the
# "GOOGLE_CLOUD_UNIVERSE_DOMAIN" env var, create the endpoint using
# that as the default.
#
# Mutual TLS is not compatible with a non-default universe domain
# at this time. If such settings are enabled along with the
Expand Down Expand Up @@ -272,8 +291,12 @@ def __init__(
)

# Validate that the universe domain of the credentials matches the
# universe domain of the client.
if self._credentials.universe_domain != self.universe_domain:
# universe domain of the client. Anonymous credentials carry no token,
# so they are valid in every universe.
if (
not isinstance(self._credentials, AnonymousCredentials)
and self._credentials.universe_domain != self.universe_domain
):
raise ValueError(
"The configured universe domain ({client_ud}) does not match "
"the universe domain found in the credentials ({cred_ud}). If "
Expand Down Expand Up @@ -1990,6 +2013,10 @@ def generate_signed_post_policy_v4(
:param access_token: (Optional) Access token for a service account.

:raises: :exc:`ValueError` when mutually exclusive arguments are used.
:raises: :exc:`ValueError` when ``credentials`` sign the policy, report
a non-default universe domain that differs from the universe
domain of the client, and the policy URL uses the default
endpoint of the client's universe domain.

:rtype: dict
:returns: Signed POST policy.
Expand All @@ -2000,6 +2027,14 @@ def generate_signed_post_policy_v4(
"can be specified."
)

# A bucket-bound hostname replaces the endpoint in the policy URL, and
# ``credentials`` do not sign the policy when an access token and a
# service account email are both passed.
if not bucket_bound_hostname and not (access_token and service_account_email):
_validate_signing_credentials_universe_domain(
self, credentials, self.api_endpoint
)

credentials = self._credentials if credentials is None else credentials
client_email = service_account_email
if not access_token or not service_account_email:
Expand Down
51 changes: 51 additions & 0 deletions packages/google-cloud-storage/tests/system/test__signing.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,3 +579,54 @@ def test_generate_signed_post_policy_v4_invalid_field(
)

assert list(bucket.list_blobs()) == []


def _skip_unless_default_endpoint(client):
# Signing credentials are compared with the client only for the default
# storage endpoint.
if client.api_endpoint != "https://storage.googleapis.com":
pytest.skip("Test requires the default storage endpoint.")


@pytest.mark.parametrize("version", ["v2", "v4"])
def test_create_signed_read_url_w_credentials_universe_domain_mismatch(
storage_client, universe_domain_credential, version
):
_skip_unless_default_endpoint(storage_client)
blob = storage_client.bucket("bucket-name").blob("blob-name")

with pytest.raises(ValueError, match="signing credentials"):
blob.generate_signed_url(
expiration=datetime.timedelta(minutes=10),
version=version,
credentials=universe_domain_credential,
)


@pytest.mark.parametrize("version", ["v2", "v4"])
def test_create_signed_list_blobs_url_w_credentials_universe_domain_mismatch(
storage_client, universe_domain_credential, version
):
_skip_unless_default_endpoint(storage_client)
bucket = storage_client.bucket("bucket-name")

with pytest.raises(ValueError, match="signing credentials"):
bucket.generate_signed_url(
expiration=datetime.timedelta(minutes=10),
version=version,
credentials=universe_domain_credential,
)


def test_generate_signed_post_policy_v4_w_credentials_universe_domain_mismatch(
storage_client, universe_domain_credential
):
_skip_unless_default_endpoint(storage_client)

with pytest.raises(ValueError, match="signing credentials"):
storage_client.generate_signed_post_policy_v4(
"bucket-name",
"blob-name",
expiration=datetime.timedelta(minutes=10),
credentials=universe_domain_credential,
)
6 changes: 6 additions & 0 deletions packages/google-cloud-storage/tests/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
import pytest


@pytest.fixture(autouse=True)
def _clear_universe_domain_env(monkeypatch):
"""Keeps the runner's environment from changing the universe clients resolve."""
monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False)


@pytest.fixture(autouse=True)
def set_event_loop():
try:
Expand Down
Loading
Loading