diff --git a/packages/google-cloud-storage/google/cloud/storage/_helpers.py b/packages/google-cloud-storage/google/cloud/storage/_helpers.py index 9bea6c40845e..d7384e1c725d 100644 --- a/packages/google-cloud-storage/google/cloud/storage/_helpers.py +++ b/packages/google-cloud-storage/google/cloud/storage/_helpers.py @@ -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 @@ -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( @@ -110,6 +118,112 @@ def _get_api_endpoint_override(): return None +# TODO(universe-domain): Replace with google.api_core.universe.resolve_client_universe +# 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() + + +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 + + 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, + ) + ) + + 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. diff --git a/packages/google-cloud-storage/google/cloud/storage/blob.py b/packages/google-cloud-storage/google/cloud/storage/blob.py index 87493a30dfc0..bc25b1e57112 100644 --- a/packages/google-cloud-storage/google/cloud/storage/blob.py +++ b/packages/google-cloud-storage/google/cloud/storage/blob.py @@ -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 ( @@ -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`. @@ -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 diff --git a/packages/google-cloud-storage/google/cloud/storage/bucket.py b/packages/google-cloud-storage/google/cloud/storage/bucket.py index 7954e70e08f9..5d32886df7ae 100644 --- a/packages/google-cloud-storage/google/cloud/storage/bucket.py +++ b/packages/google-cloud-storage/google/cloud/storage/bucket.py @@ -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 @@ -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`. @@ -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 diff --git a/packages/google-cloud-storage/google/cloud/storage/client.py b/packages/google-cloud-storage/google/cloud/storage/client.py index 58e2b68ca52d..10825465447e 100644 --- a/packages/google-cloud-storage/google/cloud/storage/client.py +++ b/packages/google-cloud-storage/google/cloud/storage/client.py @@ -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 @@ -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, ) @@ -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: @@ -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 @@ -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 @@ -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 @@ -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 " @@ -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. @@ -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: diff --git a/packages/google-cloud-storage/tests/system/test__signing.py b/packages/google-cloud-storage/tests/system/test__signing.py index 6fd912ae679a..c15d61b5fda8 100644 --- a/packages/google-cloud-storage/tests/system/test__signing.py +++ b/packages/google-cloud-storage/tests/system/test__signing.py @@ -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, + ) diff --git a/packages/google-cloud-storage/tests/unit/conftest.py b/packages/google-cloud-storage/tests/unit/conftest.py index ef3d3a1afc21..0f5dcd90b377 100644 --- a/packages/google-cloud-storage/tests/unit/conftest.py +++ b/packages/google-cloud-storage/tests/unit/conftest.py @@ -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: diff --git a/packages/google-cloud-storage/tests/unit/test__helpers.py b/packages/google-cloud-storage/tests/unit/test__helpers.py index c7b036d2c655..a1f2a8d32fd8 100644 --- a/packages/google-cloud-storage/tests/unit/test__helpers.py +++ b/packages/google-cloud-storage/tests/unit/test__helpers.py @@ -12,10 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +import types import unittest +import google.auth.credentials import mock import pytest +from google.api_core.client_options import ClientOptions from google.cloud.storage.retry import ( DEFAULT_RETRY, @@ -78,6 +81,254 @@ def test_w_env_var(self): self.assertEqual(override, BASE_URL) +_UNIVERSE_DOMAIN_VALUES = [ + pytest.param("example.com", "example.com", id="plain"), + pytest.param(" example.com ", "example.com", id="padded"), + pytest.param("googleapis.com", "googleapis.com", id="default_universe"), +] +_EMPTY_UNIVERSE_DOMAIN_VALUES = [ + pytest.param("", id="empty"), + pytest.param(" ", id="whitespace"), +] +_CLIENT_OPTIONS_FACTORIES = [ + pytest.param( + lambda value: ClientOptions(universe_domain=value), id="ClientOptions" + ), + pytest.param(lambda value: {"universe_domain": value}, id="dict"), + pytest.param( + lambda value: types.MappingProxyType({"universe_domain": value}), + id="mappingproxy", + ), +] + + +def _make_signing_credentials(universe_domain): + class _SigningCredentials( + google.auth.credentials.Credentials, google.auth.credentials.Signing + ): + pass + + return mock.Mock(spec=_SigningCredentials, universe_domain=universe_domain) + + +def _make_id_token_credentials(): + from google.auth import compute_engine + + return compute_engine.IDTokenCredentials( + mock.Mock(), + "audience", + service_account_email="service-account@example.com", + signer=mock.Mock(), + ) + + +def _make_autospec_client(): + from google.cloud.storage.client import Client + + return mock.create_autospec(Client, instance=True) + + +class Test__resolve_client_universe: + @staticmethod + def _call_fut(*args, **kwargs): + from google.cloud.storage._helpers import _resolve_client_universe + + return _resolve_client_universe(*args, **kwargs) + + @pytest.mark.parametrize("args", [(), (None,)], ids=["no_argument", "none"]) + def test_wo_client_options_wo_env_var(self, args): + with mock.patch.dict("os.environ", {}, clear=True): + assert self._call_fut(*args) == "googleapis.com" + + @pytest.mark.parametrize("value, expected", _UNIVERSE_DOMAIN_VALUES) + @pytest.mark.parametrize( + "client_options", + [None, {}, {"api_endpoint": "x"}, ClientOptions()], + ids=["none", "empty_dict", "dict_wo_universe_domain", "ClientOptions"], + ) + def test_w_env_var(self, client_options, value, expected): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + + with mock.patch.dict("os.environ", environ, clear=True): + assert self._call_fut(client_options) == expected + + @pytest.mark.parametrize("value, expected", _UNIVERSE_DOMAIN_VALUES) + @pytest.mark.parametrize("make_client_options", _CLIENT_OPTIONS_FACTORIES) + def test_w_client_options(self, make_client_options, value, expected): + with mock.patch.dict("os.environ", {}, clear=True): + assert self._call_fut(make_client_options(value)) == expected + + @pytest.mark.parametrize("make_client_options", _CLIENT_OPTIONS_FACTORIES) + def test_client_options_take_precedence_over_env_var(self, make_client_options): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example.com"} + + with mock.patch.dict("os.environ", environ, clear=True): + assert self._call_fut(make_client_options("example.com")) == "example.com" + + @pytest.mark.parametrize("value", _EMPTY_UNIVERSE_DOMAIN_VALUES) + def test_w_empty_env_var(self, value): + from google.api_core.universe import EmptyUniverseError + + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + + with mock.patch.dict("os.environ", environ, clear=True): + with pytest.raises(EmptyUniverseError): + self._call_fut() + + @pytest.mark.parametrize("value", _EMPTY_UNIVERSE_DOMAIN_VALUES) + @pytest.mark.parametrize("make_client_options", _CLIENT_OPTIONS_FACTORIES) + def test_w_empty_client_options_universe_domain(self, make_client_options, value): + from google.api_core.universe import EmptyUniverseError + + # An empty value in client_options is an error; the environment + # variable is not used as a fallback. + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} + + with mock.patch.dict("os.environ", environ, clear=True): + with pytest.raises(EmptyUniverseError): + self._call_fut(make_client_options(value)) + + @pytest.mark.parametrize( + "client_options", + [object(), "example.com", ["example.com"]], + ids=["object", "str", "list"], + ) + def test_w_invalid_client_options_type(self, client_options): + with mock.patch.dict("os.environ", {}, clear=True): + with pytest.raises(TypeError, match="client_options must be"): + self._call_fut(client_options) + + +class Test__validate_signing_credentials_universe_domain: + @staticmethod + def _call_fut(client, credentials, api_endpoint=None): + from google.cloud.storage._helpers import ( + _validate_signing_credentials_universe_domain, + ) + + if api_endpoint is None: + api_endpoint = client.api_endpoint + + return _validate_signing_credentials_universe_domain( + client, credentials, api_endpoint + ) + + @staticmethod + def _make_client(universe_domain="googleapis.com"): + return mock.Mock( + spec=["universe_domain", "api_endpoint"], + universe_domain=universe_domain, + api_endpoint=f"https://storage.{universe_domain}", + ) + + @pytest.mark.parametrize( + "make_credentials", + [ + pytest.param(lambda: None, id="none"), + pytest.param(google.auth.credentials.AnonymousCredentials, id="anonymous"), + pytest.param( + lambda: mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ), + id="token_credentials", + ), + pytest.param(object, id="object"), + ], + ) + def test_w_non_signing_credentials(self, make_credentials): + client = self._make_client(universe_domain="example.com") + + assert self._call_fut(client, make_credentials()) is None + + def test_w_credentials_wo_universe_domain(self): + client = self._make_client(universe_domain="example.com") + credentials = mock.Mock(spec=google.auth.credentials.Signing) + + assert self._call_fut(client, credentials) is None + + @pytest.mark.parametrize( + "make_credentials", + [ + pytest.param( + lambda: _make_signing_credentials("googleapis.com"), + id="signing_credentials", + ), + pytest.param(_make_id_token_credentials, id="id_token_credentials"), + ], + ) + def test_w_credentials_in_default_universe(self, make_credentials): + # Credentials report the default universe domain when none was set on + # them, so that value is not compared with the client. + client = self._make_client(universe_domain="example.com") + credentials = make_credentials() + assert credentials.universe_domain == "googleapis.com" + + assert self._call_fut(client, credentials) is None + + @pytest.mark.parametrize( + "make_client", + [ + pytest.param(lambda: None, id="none"), + pytest.param(_make_autospec_client, id="autospec_client"), + ], + ) + def test_w_client_wo_universe_domain(self, make_client): + credentials = _make_signing_credentials("example.com") + + result = self._call_fut( + make_client(), credentials, "https://storage.googleapis.com" + ) + + assert result is None + + @pytest.mark.parametrize( + "api_endpoint", + [ + "https://storage.custom.example.com", + "https://storage.googleapis.com", + "http://localhost:8080", + "https://storage.example.com/", + "http://storage.example.com", + ], + ) + def test_w_other_endpoint(self, api_endpoint): + client = self._make_client(universe_domain="example.com") + credentials = _make_signing_credentials("other.example.com") + + assert self._call_fut(client, credentials, api_endpoint) is None + + def test_w_matching_universe_domain(self): + client = self._make_client(universe_domain="example.com") + credentials = _make_signing_credentials("example.com") + + assert self._call_fut(client, credentials) is None + + @pytest.mark.parametrize( + "client_universe_domain, credentials_universe_domain", + [ + ("example.com", "other.example.com"), + ("googleapis.com", "example.com"), + ], + ) + def test_w_mismatched_universe_domain( + self, client_universe_domain, credentials_universe_domain + ): + client = self._make_client(universe_domain=client_universe_domain) + credentials = _make_signing_credentials(credentials_universe_domain) + + with pytest.raises(ValueError) as exc_info: + self._call_fut(client, credentials) + + assert str(exc_info.value) == ( + f"The universe domain of the signing credentials " + f"({credentials_universe_domain}) does not match the universe " + f"domain of the client ({client_universe_domain}). Pass " + f"credentials from the client's universe domain, or configure " + f"the client for the universe domain of the credentials." + ) + + class Test__get_environ_project(unittest.TestCase): @staticmethod def _call_fut(): diff --git a/packages/google-cloud-storage/tests/unit/test_blob.py b/packages/google-cloud-storage/tests/unit/test_blob.py index c5609e3dd5c6..cb5dbbd69b0c 100644 --- a/packages/google-cloud-storage/tests/unit/test_blob.py +++ b/packages/google-cloud-storage/tests/unit/test_blob.py @@ -51,6 +51,17 @@ def _make_credentials(): return mock.Mock(spec=google.auth.credentials.Credentials) +def _make_signing_credentials(universe_domain): + import google.auth.credentials + + class _SigningCredentials( + google.auth.credentials.Credentials, google.auth.credentials.Signing + ): + pass + + return mock.Mock(spec=_SigningCredentials, universe_domain=universe_domain) + + class Test_Blob(unittest.TestCase): @staticmethod def _make_one(*args, **kw): @@ -6656,6 +6667,220 @@ def test_patch_contexts_none(self): self.assertIsNone(sent_resource["contexts"]) +@pytest.mark.parametrize("version", ["v2", "v4"]) +class Test_Blob_generate_signed_url_universe_domain: + """Checks of per-call signing credentials against the client's universe domain. + + ``Test_Blob`` is a ``unittest.TestCase``, which does not support + ``pytest.mark.parametrize``, so these tests are in their own class. + """ + + @staticmethod + def _make_client(universe_domain, api_endpoint=None): + if api_endpoint is None: + api_endpoint = f"https://storage.{universe_domain}" + + return Test_Blob._make_client( + _credentials=object(), + universe_domain=universe_domain, + api_endpoint=api_endpoint, + ) + + @staticmethod + def _make_target(client): + return Test_Blob._make_one("blob-name", bucket=_Bucket(client)) + + def _generate_signed_url( + self, + version, + client_universe_domain="example.com", + credentials_universe_domain="other.example.com", + client_api_endpoint=None, + raises=False, + **kw, + ): + client = self._make_client(client_universe_domain, client_api_endpoint) + credentials = _make_signing_credentials(credentials_universe_domain) + target = self._make_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + to_patch = f"google.cloud.storage.blob.generate_signed_url_{version}" + + with mock.patch(to_patch) as signer: + if raises: + with pytest.raises(ValueError, match="signing credentials"): + target.generate_signed_url( + expiration=expiration, + credentials=credentials, + version=version, + **kw, + ) + else: + signed_uri = target.generate_signed_url( + expiration=expiration, + credentials=credentials, + version=version, + **kw, + ) + + if raises: + signer.assert_not_called() + return None + + assert signed_uri == signer.return_value + signer.assert_called_once() + assert signer.call_args.args[0] is credentials + return signer.call_args.kwargs + + @pytest.mark.parametrize( + "client_universe_domain, credentials_universe_domain, kw", + [ + pytest.param("example.com", "other.example.com", {}, id="path_style"), + pytest.param( + "example.com", + "other.example.com", + {"virtual_hosted_style": True}, + id="virtual_hosted_style", + ), + pytest.param( + "example.com", + "other.example.com", + {"api_access_endpoint": "https://storage.example.com"}, + id="explicit_default_endpoint", + ), + pytest.param( + "googleapis.com", "example.com", {}, id="default_universe_path_style" + ), + pytest.param( + "googleapis.com", + "example.com", + {"virtual_hosted_style": True}, + id="default_universe_virtual_hosted_style", + ), + pytest.param( + "googleapis.com", + "example.com", + {"api_access_endpoint": "https://storage.googleapis.com"}, + id="default_universe_explicit_default_endpoint", + ), + ], + ) + def test_w_credentials_universe_domain_mismatch( + self, version, client_universe_domain, credentials_universe_domain, kw + ): + self._generate_signed_url( + version, + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + raises=True, + **kw, + ) + + def test_w_credentials_universe_domain_match(self, version): + kwargs = self._generate_signed_url( + version, + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + + assert kwargs["api_access_endpoint"] == "https://storage.example.com" + + @pytest.mark.parametrize( + "case", + [ + # The URL does not use the default endpoint of the client. + pytest.param( + {"api_access_endpoint": "https://storage.other.example.com"}, + id="other_api_access_endpoint", + ), + pytest.param( + {"api_access_endpoint": "https://storage.googleapis.com"}, + id="default_universe_api_access_endpoint", + ), + pytest.param( + {"bucket_bound_hostname": "cdn.example.com"}, + id="bucket_bound_hostname", + ), + pytest.param( + {"client_api_endpoint": "https://storage.custom.example.com"}, + id="custom_client_endpoint", + ), + pytest.param( + {"client_api_endpoint": "http://localhost:8080"}, + id="local_client_endpoint", + ), + pytest.param( + { + "client_api_endpoint": "https://storage.custom.example.com", + "virtual_hosted_style": True, + }, + id="custom_client_endpoint_virtual_hosted_style", + ), + # Credentials report the default universe domain when none is set. + pytest.param( + {"credentials_universe_domain": "googleapis.com"}, + id="default_universe_credentials", + ), + # An access token and a service account email sign the URL. + pytest.param( + {"access_token": "token", "service_account_email": "sa@example.com"}, + id="access_token_and_service_account_email", + ), + ], + ) + def test_w_credentials_universe_domain_not_checked(self, version, case): + self._generate_signed_url(version, **case) + + def test_w_client_passed_for_call(self, version): + # The client passed for the call is the one that is compared. + other_client = self._make_client("other.example.com") + + kwargs = self._generate_signed_url(version, client=other_client) + + assert kwargs["api_access_endpoint"] == "https://storage.other.example.com" + + def test_w_client_passed_for_call_and_universe_domain_mismatch(self, version): + other_client = self._make_client("other.example.com") + + self._generate_signed_url( + version, + credentials_universe_domain="example.com", + client=other_client, + raises=True, + ) + + def test_w_non_signing_credentials(self, version): + import google.auth.credentials + + # Credentials that cannot sign keep raising AttributeError. + client = self._make_client("example.com") + credentials = mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ) + target = self._make_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + + with pytest.raises(AttributeError, match="private key"): + target.generate_signed_url( + expiration=expiration, credentials=credentials, version=version + ) + + @pytest.mark.parametrize( + "kw", + [ + pytest.param({"access_token": "token"}, id="access_token"), + pytest.param( + {"service_account_email": "sa@example.com"}, + id="service_account_email", + ), + ], + ) + def test_w_partial_token(self, version, kw): + # ``credentials`` sign the URL unless both the access token and the + # service account email are passed. + self._generate_signed_url(version, raises=True, **kw) + + class Test__quote(unittest.TestCase): @staticmethod def _call_fut(*args, **kw): diff --git a/packages/google-cloud-storage/tests/unit/test_bucket.py b/packages/google-cloud-storage/tests/unit/test_bucket.py index 19b3456b816e..d200bf2559ea 100644 --- a/packages/google-cloud-storage/tests/unit/test_bucket.py +++ b/packages/google-cloud-storage/tests/unit/test_bucket.py @@ -35,7 +35,7 @@ ) -def _create_signing_credentials(): +def _create_signing_credentials(universe_domain=None): import google.auth.credentials class _SigningCredentials( @@ -43,9 +43,10 @@ class _SigningCredentials( ): pass - credentials = mock.Mock(spec=_SigningCredentials) + if universe_domain is None: + return mock.Mock(spec=_SigningCredentials) - return credentials + return mock.Mock(spec=_SigningCredentials, universe_domain=universe_domain) class Test__blobs_page_start(unittest.TestCase): @@ -4845,6 +4846,22 @@ def test_generate_signed_url_v4_w_incompatible_params(self): virtual_hosted_style=True, bucket_bound_hostname="cdn.example.com" ) + def test_generate_signed_url_w_credentials_universe_domain_wo_client(self): + # A bucket without a client can sign with an explicit endpoint. + bucket = self._get_target_class()(None, name="bucket-name") + credentials = _create_signing_credentials("example.com") + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + + with mock.patch("google.cloud.storage.bucket.generate_signed_url_v4") as signer: + signed_uri = bucket.generate_signed_url( + expiration=expiration, + api_access_endpoint="https://storage.googleapis.com", + credentials=credentials, + version="v4", + ) + + self.assertEqual(signed_uri, signer.return_value) + def test_ip_filter_getter_unset(self): """Test that ip_filter is None when not set.""" bucket = self._make_one() @@ -4894,6 +4911,200 @@ def test_ip_filter_setter_w_none(self): self.assertIsNone(bucket._properties.get(_IP_FILTER_PROPERTY)) +@pytest.mark.parametrize("version", ["v2", "v4"]) +class Test_Bucket_generate_signed_url_universe_domain: + """Checks of per-call signing credentials against the client's universe domain. + + ``Test_Bucket`` is a ``unittest.TestCase``, which does not support + ``pytest.mark.parametrize``, so these tests are in their own class. + """ + + @staticmethod + def _make_client(universe_domain, api_endpoint=None): + if api_endpoint is None: + api_endpoint = f"https://storage.{universe_domain}" + + return Test_Bucket._make_client( + _credentials=object(), + universe_domain=universe_domain, + api_endpoint=api_endpoint, + ) + + @staticmethod + def _make_target(client): + return Test_Bucket._get_target_class()(client, name="bucket-name") + + def _generate_signed_url( + self, + version, + client_universe_domain="example.com", + credentials_universe_domain="other.example.com", + client_api_endpoint=None, + raises=False, + **kw, + ): + client = self._make_client(client_universe_domain, client_api_endpoint) + credentials = _create_signing_credentials(credentials_universe_domain) + target = self._make_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + to_patch = f"google.cloud.storage.bucket.generate_signed_url_{version}" + + with mock.patch(to_patch) as signer: + if raises: + with pytest.raises(ValueError, match="signing credentials"): + target.generate_signed_url( + expiration=expiration, + credentials=credentials, + version=version, + **kw, + ) + else: + signed_uri = target.generate_signed_url( + expiration=expiration, + credentials=credentials, + version=version, + **kw, + ) + + if raises: + signer.assert_not_called() + return None + + assert signed_uri == signer.return_value + signer.assert_called_once() + assert signer.call_args.args[0] is credentials + return signer.call_args.kwargs + + @pytest.mark.parametrize( + "client_universe_domain, credentials_universe_domain, kw", + [ + pytest.param("example.com", "other.example.com", {}, id="path_style"), + pytest.param( + "example.com", + "other.example.com", + {"virtual_hosted_style": True}, + id="virtual_hosted_style", + ), + pytest.param( + "example.com", + "other.example.com", + {"api_access_endpoint": "https://storage.example.com"}, + id="explicit_default_endpoint", + ), + pytest.param( + "googleapis.com", "example.com", {}, id="default_universe_path_style" + ), + pytest.param( + "googleapis.com", + "example.com", + {"virtual_hosted_style": True}, + id="default_universe_virtual_hosted_style", + ), + pytest.param( + "googleapis.com", + "example.com", + {"api_access_endpoint": "https://storage.googleapis.com"}, + id="default_universe_explicit_default_endpoint", + ), + ], + ) + def test_w_credentials_universe_domain_mismatch( + self, version, client_universe_domain, credentials_universe_domain, kw + ): + self._generate_signed_url( + version, + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + raises=True, + **kw, + ) + + def test_w_credentials_universe_domain_match(self, version): + kwargs = self._generate_signed_url( + version, + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + + assert kwargs["api_access_endpoint"] == "https://storage.example.com" + + @pytest.mark.parametrize( + "case", + [ + # The URL does not use the default endpoint of the client. + pytest.param( + {"api_access_endpoint": "https://storage.other.example.com"}, + id="other_api_access_endpoint", + ), + pytest.param( + {"api_access_endpoint": "https://storage.googleapis.com"}, + id="default_universe_api_access_endpoint", + ), + pytest.param( + {"bucket_bound_hostname": "cdn.example.com"}, + id="bucket_bound_hostname", + ), + pytest.param( + {"client_api_endpoint": "https://storage.custom.example.com"}, + id="custom_client_endpoint", + ), + pytest.param( + {"client_api_endpoint": "http://localhost:8080"}, + id="local_client_endpoint", + ), + pytest.param( + { + "client_api_endpoint": "https://storage.custom.example.com", + "virtual_hosted_style": True, + }, + id="custom_client_endpoint_virtual_hosted_style", + ), + # Credentials report the default universe domain when none is set. + pytest.param( + {"credentials_universe_domain": "googleapis.com"}, + id="default_universe_credentials", + ), + ], + ) + def test_w_credentials_universe_domain_not_checked(self, version, case): + self._generate_signed_url(version, **case) + + def test_w_client_passed_for_call(self, version): + # The client passed for the call is the one that is compared. + other_client = self._make_client("other.example.com") + + kwargs = self._generate_signed_url(version, client=other_client) + + assert kwargs["api_access_endpoint"] == "https://storage.other.example.com" + + def test_w_client_passed_for_call_and_universe_domain_mismatch(self, version): + other_client = self._make_client("other.example.com") + + self._generate_signed_url( + version, + credentials_universe_domain="example.com", + client=other_client, + raises=True, + ) + + def test_w_non_signing_credentials(self, version): + import google.auth.credentials + + # Credentials that cannot sign keep raising AttributeError. + client = self._make_client("example.com") + credentials = mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ) + target = self._make_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + + with pytest.raises(AttributeError, match="private key"): + target.generate_signed_url( + expiration=expiration, credentials=credentials, version=version + ) + + class Test__item_to_notification(unittest.TestCase): def _call_fut(self, iterator, item): from google.cloud.storage.bucket import _item_to_notification diff --git a/packages/google-cloud-storage/tests/unit/test_client.py b/packages/google-cloud-storage/tests/unit/test_client.py index 108e84091c02..00b209f82ea7 100644 --- a/packages/google-cloud-storage/tests/unit/test_client.py +++ b/packages/google-cloud-storage/tests/unit/test_client.py @@ -17,6 +17,7 @@ import io import json import re +import types import unittest import urllib from unittest.mock import patch @@ -42,7 +43,11 @@ DEFAULT_RETRY, DEFAULT_RETRY_IF_GENERATION_SPECIFIED, ) -from tests.unit.test__helpers import GCCL_INVOCATION_TEST_CONST +from tests.unit.test__helpers import ( + _CLIENT_OPTIONS_FACTORIES, + _EMPTY_UNIVERSE_DOMAIN_VALUES, + GCCL_INVOCATION_TEST_CONST, +) from . import _read_local_json @@ -52,6 +57,11 @@ ] _POST_POLICY_TESTS = [test for test in _CONFORMANCE_TESTS if "policyInput" in test] _FAKE_CREDENTIALS = Credentials.from_service_account_info(_SERVICE_ACCOUNT_JSON) +_CUSTOM_HOST = "https://storage.custom.example.com" +_MISMATCHED_UNIVERSES = [ + ("example.com", "other.example.com"), + (_DEFAULT_UNIVERSE_DOMAIN, "example.com"), +] def _make_credentials(project=None, universe_domain=_DEFAULT_UNIVERSE_DOMAIN): @@ -69,7 +79,7 @@ def _make_credentials(project=None, universe_domain=_DEFAULT_UNIVERSE_DOMAIN): ) -def _create_signing_credentials(): +def _create_signing_credentials(universe_domain=_DEFAULT_UNIVERSE_DOMAIN): import google.auth.credentials class _SigningCredentials( @@ -77,9 +87,7 @@ class _SigningCredentials( ): pass - credentials = mock.Mock( - spec=_SigningCredentials, universe_domain=_DEFAULT_UNIVERSE_DOMAIN - ) + credentials = mock.Mock(spec=_SigningCredentials, universe_domain=universe_domain) credentials.sign_bytes = mock.Mock(return_value=b"Signature_bytes") credentials.signer_email = "test@mail.com" return credentials @@ -284,6 +292,178 @@ def test_ctor_w_universe_domain_and_mtls(self): with self.assertRaises(ValueError): self._make_one(credentials=credentials, client_options=client_options) + def test_ctor_w_universe_domain_env_and_matched_credentials(self): + universe_domain = "example.com" + expected_api_endpoint = f"https://storage.{universe_domain}" + credentials = _make_credentials(universe_domain=universe_domain) + environ = { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain, + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + } + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one(project="PROJECT", credentials=credentials) + + self.assertEqual(client._connection.API_BASE_URL, expected_api_endpoint) + self.assertEqual(client.api_endpoint, expected_api_endpoint) + self.assertEqual(client.universe_domain, universe_domain) + + def test_ctor_w_universe_domain_env_and_mismatched_credentials(self): + credentials = _make_credentials() # default universe domain + environ = { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com", + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + } + + with mock.patch.dict("os.environ", environ, clear=True): + with self.assertRaisesRegex(ValueError, "does not match"): + self._make_one(project="PROJECT", credentials=credentials) + + def test_ctor_w_universe_domain_env_and_client_options(self): + # client_options takes precedence over the environment variable. + universe_domain = "other.example" + credentials = _make_credentials(universe_domain=universe_domain) + client_options = {"universe_domain": universe_domain} + environ = { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com", + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + } + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options=client_options, + ) + + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client.api_endpoint, f"https://storage.{universe_domain}") + + def test_ctor_w_universe_domain_env_and_api_endpoint(self): + universe_domain = "example.com" + api_endpoint = "https://storage.custom.example.com" + credentials = _make_credentials(universe_domain=universe_domain) + client_options = {"api_endpoint": api_endpoint} + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options=client_options, + ) + + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client.api_endpoint, api_endpoint) + + def test_ctor_w_universe_domain_env_default_universe(self): + credentials = _make_credentials() + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": _DEFAULT_UNIVERSE_DOMAIN} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one(project="PROJECT", credentials=credentials) + + self.assertIsNone(client._universe_domain) + self.assertEqual(client.universe_domain, _DEFAULT_UNIVERSE_DOMAIN) + self.assertEqual( + client._connection.API_BASE_URL, client._connection.DEFAULT_API_ENDPOINT + ) + + def test_ctor_w_universe_domain_env_empty(self): + credentials = _make_credentials() + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""} + + with mock.patch.dict("os.environ", environ, clear=True): + with self.assertRaises(ValueError): + self._make_one(project="PROJECT", credentials=credentials) + + def test_ctor_w_universe_domain_option_w_whitespace(self): + universe_domain = "example.com" + credentials = _make_credentials(universe_domain=universe_domain) + environ = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options={"universe_domain": f" {universe_domain} "}, + ) + + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client.api_endpoint, f"https://storage.{universe_domain}") + + def test_ctor_w_default_universe_domain_option(self): + # Naming the default universe in client_options keeps the explicit + # endpoint for that universe, and takes precedence over the + # environment variable. + credentials = _make_credentials() + environ = { + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com", + } + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options={"universe_domain": _DEFAULT_UNIVERSE_DOMAIN}, + ) + + self.assertEqual(client._universe_domain, _DEFAULT_UNIVERSE_DOMAIN) + self.assertEqual(client.universe_domain, _DEFAULT_UNIVERSE_DOMAIN) + self.assertEqual( + client.api_endpoint, f"https://storage.{_DEFAULT_UNIVERSE_DOMAIN}" + ) + + def test_ctor_w_invalid_client_options_type(self): + credentials = _make_credentials() + + with self.assertRaisesRegex(TypeError, "client_options must be"): + self._make_one( + project="PROJECT", credentials=credentials, client_options=object() + ) + + def test_ctor_w_universe_domain_env_and_mtls(self): + universe_domain = "example.com" + credentials = _make_credentials(universe_domain=universe_domain) + environ = { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain, + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "true", + } + + with mock.patch.dict("os.environ", environ, clear=True): + with self.assertRaisesRegex(ValueError, "mTLS"): + self._make_one(project="PROJECT", credentials=credentials) + + def test_ctor_w_universe_domain_env_w_emulator(self): + # The emulator path uses anonymous credentials, which any universe accepts. + host = "http://localhost:8080" + universe_domain = "example.com" + environ = { + STORAGE_EMULATOR_ENV_VAR: host, + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain, + } + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one() + + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client._connection.API_BASE_URL, host) + self.assertIsInstance(client._connection.credentials, AnonymousCredentials) + + def test_ctor_w_universe_domain_and_anonymous_credentials(self): + universe_domain = "example.com" + client_options = {"universe_domain": universe_domain} + + client = self._make_one( + project="PROJECT", + credentials=AnonymousCredentials(), + client_options=client_options, + ) + + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client.api_endpoint, f"https://storage.{universe_domain}") + def test_ctor_w_custom_headers(self): PROJECT = "PROJECT" credentials = _make_credentials() @@ -464,6 +644,22 @@ def test_create_anonymous_client(self): self.assertIsInstance(client._connection, Connection) self.assertIsInstance(client._connection.credentials, AnonymousCredentials) + def test_create_anonymous_client_w_universe_domain_env(self): + universe_domain = "example.com" + environ = { + "GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain, + "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", + } + klass = self._get_target_class() + + with mock.patch.dict("os.environ", environ, clear=True): + client = klass.create_anonymous_client() + + self.assertIsNone(client.project) + self.assertEqual(client.universe_domain, universe_domain) + self.assertEqual(client.api_endpoint, f"https://storage.{universe_domain}") + self.assertIsInstance(client._connection.credentials, AnonymousCredentials) + def test__push_batch_and__pop_batch(self): from google.cloud.storage.batch import Batch @@ -3321,6 +3517,382 @@ def test_list_buckets_w_partial_success(self): ) +class TestClientUniverseDomain: + """Parametrized universe domain tests. + + ``TestClient`` is a ``unittest.TestCase``, which does not support + ``pytest.mark.parametrize``, so these tests are in their own class. + """ + + @staticmethod + def _make_one(*args, **kw): + from google.cloud.storage.client import Client + + return Client(*args, **kw) + + @pytest.mark.parametrize("make_client_options", _CLIENT_OPTIONS_FACTORIES) + def test_ctor_w_universe_domain_option(self, make_client_options): + universe_domain = "example.com" + credentials = _make_credentials(universe_domain=universe_domain) + environ = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options=make_client_options(universe_domain), + ) + + assert client.universe_domain == universe_domain + assert client.api_endpoint == f"https://storage.{universe_domain}" + + @pytest.mark.parametrize("value", _EMPTY_UNIVERSE_DOMAIN_VALUES) + @pytest.mark.parametrize("make_client_options", _CLIENT_OPTIONS_FACTORIES) + def test_ctor_w_empty_universe_domain_option(self, make_client_options, value): + credentials = _make_credentials() + # The environment variable is not used when client_options sets an + # empty universe domain. + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} + + with mock.patch.dict("os.environ", environ, clear=True): + with pytest.raises(ValueError, match="empty string"): + self._make_one( + project="PROJECT", + credentials=credentials, + client_options=make_client_options(value), + ) + + @pytest.mark.parametrize("value", ["GoogleApis.com", "GOOGLEAPIS.COM"]) + def test_ctor_w_universe_domain_env_default_universe_ignores_case(self, value): + credentials = _make_credentials() + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one(project="PROJECT", credentials=credentials) + + assert client._universe_domain is None + assert client.universe_domain == _DEFAULT_UNIVERSE_DOMAIN + assert ( + client._connection.API_BASE_URL == client._connection.DEFAULT_API_ENDPOINT + ) + + @pytest.mark.parametrize( + "options, expected_api_endpoint", + [ + pytest.param({}, "https://storage.googleapis.com", id="empty"), + pytest.param( + {"api_endpoint": "https://storage.custom.example.com"}, + "https://storage.custom.example.com", + id="api_endpoint", + ), + ], + ) + def test_ctor_w_mapping_client_options(self, options, expected_api_endpoint): + client_options = types.MappingProxyType(options) + credentials = _make_credentials() + environ = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=credentials, + client_options=client_options, + ) + + assert client.universe_domain == _DEFAULT_UNIVERSE_DOMAIN + assert client.api_endpoint == expected_api_endpoint + # The saved options are a ``dict``, which can be pickled. + assert type(client._initial_client_options) is dict + assert client._initial_client_options == options + + def test_ctor_w_mapping_client_options_and_api_key(self): + from google.auth.api_key import Credentials + + api_endpoint = "https://www.foo-googleapis.com" + client_options = types.MappingProxyType({"api_endpoint": api_endpoint}) + + client = self._make_one( + project="PROJECT", client_options=client_options, api_key="my_api_key" + ) + + assert client._connection.API_BASE_URL == api_endpoint + assert isinstance(client._credentials, Credentials) + assert client._credentials.token == "my_api_key" + # The caller's mapping is not changed. + assert dict(client_options) == {"api_endpoint": api_endpoint} + + def _signed_policy_v4( + self, + client_universe_domain="example.com", + credentials_universe_domain="other.example.com", + client_credentials=None, + client_options=None, + environ=None, + raises=None, + raises_regex="signing credentials", + **kw, + ): + import datetime + + if ( + client_options is None + and environ is None + and client_universe_domain != _DEFAULT_UNIVERSE_DOMAIN + ): + client_options = {"universe_domain": client_universe_domain} + + if client_credentials is None: + client_credentials = _make_credentials( + universe_domain=client_universe_domain + ) + + # Keep the runner's environment out of client construction. + environ = {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", **(environ or {})} + with mock.patch.dict("os.environ", environ, clear=True): + client = self._make_one( + project="PROJECT", + credentials=client_credentials, + client_options=client_options, + ) + + if "credentials" in kw: + credentials = kw.pop("credentials") + else: + credentials = _create_signing_credentials(credentials_universe_domain) + + dtstamps_patch, now_patch, expire_secs_patch = _time_functions_patches() + with dtstamps_patch, now_patch, expire_secs_patch: + if raises: + with pytest.raises(raises, match=raises_regex): + client.generate_signed_post_policy_v4( + "bucket-name", + "object-name", + expiration=datetime.datetime(2020, 3, 12), + credentials=credentials, + **kw, + ) + else: + policy = client.generate_signed_post_policy_v4( + "bucket-name", + "object-name", + expiration=datetime.datetime(2020, 3, 12), + credentials=credentials, + **kw, + ) + + if raises: + return None, credentials + + return policy, credentials + + @pytest.mark.parametrize( + "client_universe_domain, credentials_universe_domain", _MISMATCHED_UNIVERSES + ) + @pytest.mark.parametrize("virtual_hosted_style", [False, True]) + def test_get_signed_policy_v4_w_credentials_universe_domain_mismatch( + self, virtual_hosted_style, client_universe_domain, credentials_universe_domain + ): + _, credentials = self._signed_policy_v4( + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + virtual_hosted_style=virtual_hosted_style, + raises=ValueError, + ) + + credentials.sign_bytes.assert_not_called() + + def test_get_signed_policy_v4_w_credentials_universe_domain_match(self): + policy, credentials = self._signed_policy_v4( + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + + assert policy["url"] == "https://storage.example.com/bucket-name/" + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_credentials_universe_domain_from_env(self): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} + + policy, credentials = self._signed_policy_v4( + credentials_universe_domain="example.com", environ=environ + ) + + assert policy["url"] == "https://storage.example.com/bucket-name/" + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_credentials_universe_domain_from_env_mismatch( + self, + ): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} + + _, credentials = self._signed_policy_v4( + credentials_universe_domain="other.example.com", + environ=environ, + raises=ValueError, + ) + + credentials.sign_bytes.assert_not_called() + + def test_get_signed_policy_v4_w_client_credentials_passed_explicitly(self): + client_credentials = _create_signing_credentials("example.com") + + policy, credentials = self._signed_policy_v4( + client_credentials=client_credentials, credentials=client_credentials + ) + + assert policy["url"] == "https://storage.example.com/bucket-name/" + credentials.sign_bytes.assert_called_once() + + @pytest.mark.parametrize( + "case, expected_url", + [ + # The policy URL does not use the default endpoint of the client. + pytest.param( + {"bucket_bound_hostname": "https://cdn.example.com"}, + "https://cdn.example.com/", + id="bucket_bound_hostname", + ), + pytest.param( + {"client_options": {"api_endpoint": _CUSTOM_HOST}}, + f"{_CUSTOM_HOST}/bucket-name/", + id="client_options_api_endpoint", + ), + pytest.param( + { + "client_options": {"api_endpoint": _CUSTOM_HOST}, + "virtual_hosted_style": True, + }, + "https://bucket-name.storage.custom.example.com/", + id="client_options_api_endpoint_virtual_hosted_style", + ), + pytest.param( + {"environ": {_API_ENDPOINT_OVERRIDE_ENV_VAR: _CUSTOM_HOST}}, + f"{_CUSTOM_HOST}/bucket-name/", + id="api_endpoint_override_env_var", + ), + pytest.param( + {"environ": {STORAGE_EMULATOR_ENV_VAR: "http://localhost:8080"}}, + "http://localhost:8080/bucket-name/", + id="emulator", + ), + ], + ) + def test_get_signed_policy_v4_w_credentials_universe_domain_not_checked( + self, case, expected_url + ): + policy, credentials = self._signed_policy_v4( + client_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, + credentials_universe_domain="example.com", + **case, + ) + + assert policy["url"] == expected_url + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_default_universe_credentials(self): + # Credentials report the default universe domain when none was set on + # them, so that value is not compared with the client. + policy, credentials = self._signed_policy_v4( + client_universe_domain="example.com", + credentials_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, + ) + + assert policy["url"] == "https://storage.example.com/bucket-name/" + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_custom_endpoint_and_universe_domain(self): + policy, credentials = self._signed_policy_v4( + client_options={ + "universe_domain": "example.com", + "api_endpoint": _CUSTOM_HOST, + }, + ) + + assert policy["url"] == f"{_CUSTOM_HOST}/bucket-name/" + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_service_account_credentials_universe_domain( + self, + ): + credentials = _FAKE_CREDENTIALS.with_universe_domain("example.com") + + policy, _ = self._signed_policy_v4( + client_universe_domain="example.com", credentials=credentials + ) + + assert policy["url"] == "https://storage.example.com/bucket-name/" + assert policy["fields"]["x-goog-signature"] + + @pytest.mark.parametrize( + "client_universe_domain", [_DEFAULT_UNIVERSE_DOMAIN, "other.example.com"] + ) + def test_get_signed_policy_v4_w_service_account_universe_domain_mismatch( + self, client_universe_domain + ): + credentials = _FAKE_CREDENTIALS.with_universe_domain("example.com") + + self._signed_policy_v4( + client_universe_domain=client_universe_domain, + credentials=credentials, + raises=ValueError, + ) + + def test_get_signed_policy_v4_w_non_signing_credentials_universe_domain(self): + # Credentials that cannot sign keep raising AttributeError. + credentials = _make_credentials(universe_domain="other.example.com") + + self._signed_policy_v4( + credentials=credentials, + raises=AttributeError, + raises_regex="private key", + ) + + @pytest.mark.parametrize( + "client_universe_domain, credentials_universe_domain", _MISMATCHED_UNIVERSES + ) + def test_get_signed_policy_v4_w_access_token_and_other_universe_credentials( + self, client_universe_domain, credentials_universe_domain + ): + # ``credentials`` do not sign the policy when both an access token and + # a service account email are passed. The client's universe domain is + # used for that signing request. + with mock.patch( + "google.cloud.storage.client._sign_message", + return_value=b"DEADBEEF", + ) as sign_message: + policy, credentials = self._signed_policy_v4( + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + service_account_email="test@mail.com", + access_token="token", + ) + + assert policy["url"] == f"https://storage.{client_universe_domain}/bucket-name/" + credentials.sign_bytes.assert_not_called() + sign_message.assert_called_once_with( + mock.ANY, + "token", + "test@mail.com", + universe_domain=client_universe_domain, + ) + + @pytest.mark.parametrize( + "kw", + [ + pytest.param({"access_token": "token"}, id="access_token"), + pytest.param( + {"service_account_email": "test@mail.com"}, id="service_account_email" + ), + ], + ) + def test_get_signed_policy_v4_w_partial_token_and_other_universe_credentials( + self, kw + ): + _, credentials = self._signed_policy_v4(raises=ValueError, **kw) + + credentials.sign_bytes.assert_not_called() + + class Test__item_to_bucket(unittest.TestCase): def _call_fut(self, iterator, item): from google.cloud.storage.client import _item_to_bucket