From 0407fbee57006fcc2b2a9568fb6fd1f168f3a0fe Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Fri, 27 Nov 2026 12:14:15 +0000 Subject: [PATCH 1/6] fix(storage): honor GOOGLE_CLOUD_UNIVERSE_DOMAIN in the REST client storage.Client read the universe domain only from client_options. A workload that set only GOOGLE_CLOUD_UNIVERSE_DOMAIN got a googleapis.com client. Resolve the universe domain from client_options first, then from the environment variable. Anonymous credentials are now accepted in every universe, so the emulator and create_anonymous_client keep working when a non-default universe is configured. [Generated-by: AI] --- .../google/cloud/storage/_helpers.py | 23 +++ .../google/cloud/storage/client.py | 18 ++- .../tests/unit/conftest.py | 6 + .../tests/unit/test__helpers.py | 32 ++++ .../tests/unit/test_client.py | 142 ++++++++++++++++++ 5 files changed, 216 insertions(+), 5 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/_helpers.py b/packages/google-cloud-storage/google/cloud/storage/_helpers.py index 9bea6c40845e..3b9ac33df0d2 100644 --- a/packages/google-cloud-storage/google/cloud/storage/_helpers.py +++ b/packages/google-cloud-storage/google/cloud/storage/_helpers.py @@ -29,6 +29,7 @@ from uuid import uuid4 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 +58,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 +114,25 @@ def _get_api_endpoint_override(): return None +def _get_universe_domain_override(): + """Returns the non-default universe domain set in the environment, if any. + + :rtype: str or None + :returns: The value of ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` without surrounding + whitespace, or ``None`` if the variable is unset or names the default + universe. + + :raises ValueError: If the variable is set to an empty string. + """ + env_universe_domain = os.environ.get(_UNIVERSE_DOMAIN_ENV_VAR) + if env_universe_domain is None: + return None + universe_domain = universe.determine_domain(None, env_universe_domain.strip()) + if universe_domain == _DEFAULT_UNIVERSE_DOMAIN: + return None + return 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/client.py b/packages/google-cloud-storage/google/cloud/storage/client.py index 5559dbc7d763..0d86bb8033d6 100644 --- a/packages/google-cloud-storage/google/cloud/storage/client.py +++ b/packages/google-cloud-storage/google/cloud/storage/client.py @@ -44,6 +44,7 @@ _get_api_endpoint_override, _get_environ_project, _get_storage_emulator_override, + _get_universe_domain_override, _virtual_hosted_style_base_url, create_trace_span_helper, ) @@ -109,6 +110,8 @@ 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. 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. :type use_auth_w_custom_endpoint: bool :param use_auth_w_custom_endpoint: @@ -186,7 +189,7 @@ def __init__( if client_options and client_options.universe_domain: self._universe_domain = client_options.universe_domain else: - self._universe_domain = None + self._universe_domain = _get_universe_domain_override() storage_emulator_override = _get_storage_emulator_override() api_endpoint_override = _get_api_endpoint_override() @@ -208,8 +211,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 +276,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 " 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..becbb826a606 100644 --- a/packages/google-cloud-storage/tests/unit/test__helpers.py +++ b/packages/google-cloud-storage/tests/unit/test__helpers.py @@ -78,6 +78,38 @@ def test_w_env_var(self): self.assertEqual(override, BASE_URL) +class Test__get_universe_domain_override(unittest.TestCase): + @staticmethod + def _call_fut(): + from google.cloud.storage._helpers import _get_universe_domain_override + + return _get_universe_domain_override() + + def test_wo_env_var(self): + with mock.patch("os.environ", {}): + self.assertIsNone(self._call_fut()) + + def test_w_default_universe(self): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"} + with mock.patch("os.environ", environ): + self.assertIsNone(self._call_fut()) + + def test_w_non_default_universe(self): + for value in ("example.com", " example.com "): + with self.subTest(value=value): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + with mock.patch("os.environ", environ): + self.assertEqual(self._call_fut(), "example.com") + + def test_w_empty_value(self): + for value in ("", " "): + with self.subTest(value=value): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + with mock.patch("os.environ", environ): + with self.assertRaises(ValueError): + self._call_fut() + + class Test__get_environ_project(unittest.TestCase): @staticmethod def _call_fut(): diff --git a/packages/google-cloud-storage/tests/unit/test_client.py b/packages/google-cloud-storage/tests/unit/test_client.py index 87d82581490d..a523d3dd1a9d 100644 --- a/packages/google-cloud-storage/tests/unit/test_client.py +++ b/packages/google-cloud-storage/tests/unit/test_client.py @@ -284,6 +284,132 @@ 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("os.environ", environ): + 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("os.environ", environ): + 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("os.environ", environ): + 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("os.environ", environ): + 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("os.environ", environ): + 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("os.environ", environ): + with self.assertRaises(ValueError): + self._make_one(project="PROJECT", credentials=credentials) + + 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("os.environ", environ): + 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("os.environ", environ): + 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 +590,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("os.environ", environ): + 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 From 7781f6ae6e545b369429f880402bcefa0ae2abf7 Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Mon, 30 Nov 2026 09:02:43 +0000 Subject: [PATCH 2/6] fix(storage): validate the universe domain of per-call signing credentials Blob.generate_signed_url, Bucket.generate_signed_url and Client.generate_signed_post_policy_v4 accept credentials for a single call. Nothing compared the universe domain of those credentials with the universe domain of the client. The result could be a signed URL or POST policy for the default Storage endpoint of one universe domain, signed by an identity from another. That endpoint does not accept it. Raise ValueError early when the credentials sign the result, report a non-default universe domain that differs from the client's, and the result uses the default Storage endpoint of the client's universe domain. Credentials that report the default universe domain are not compared, because credentials also report that value when no universe domain was set on them. The check is skipped for a custom endpoint, a bucket-bound hostname or the emulator, and when an access token and a service account email sign the result. Client.generate_signed_post_policy_v4 now also passes the client's universe domain when it signs with an access token and a service account email, as Blob.generate_signed_url does. [Generated-by: AI] --- .../google/cloud/storage/_helpers.py | 62 +++++ .../google/cloud/storage/blob.py | 13 + .../google/cloud/storage/bucket.py | 11 + .../google/cloud/storage/client.py | 20 +- .../tests/unit/test__helpers.py | 139 ++++++++++ .../tests/unit/test_blob.py | 184 ++++++++++++ .../tests/unit/test_bucket.py | 184 ++++++++++++ .../tests/unit/test_client.py | 262 +++++++++++++++++- 8 files changed, 870 insertions(+), 5 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/_helpers.py b/packages/google-cloud-storage/google/cloud/storage/_helpers.py index 3b9ac33df0d2..1ffe352eb4b1 100644 --- a/packages/google-cloud-storage/google/cloud/storage/_helpers.py +++ b/packages/google-cloud-storage/google/cloud/storage/_helpers.py @@ -28,6 +28,7 @@ from urllib.parse import urlsplit, urlunsplit from uuid import uuid4 +import google.auth.credentials from google.api_core import exceptions as api_exceptions from google.api_core import universe from google.auth import environment_vars @@ -133,6 +134,67 @@ def _get_universe_domain_override(): return universe_domain +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 0d86bb8033d6..7d8abec9e2bf 100644 --- a/packages/google-cloud-storage/google/cloud/storage/client.py +++ b/packages/google-cloud-storage/google/cloud/storage/client.py @@ -45,6 +45,7 @@ _get_environ_project, _get_storage_emulator_override, _get_universe_domain_override, + _validate_signing_credentials_universe_domain, _virtual_hosted_style_base_url, create_trace_span_helper, ) @@ -1998,6 +1999,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. @@ -2008,6 +2013,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: @@ -2062,7 +2075,12 @@ def generate_signed_post_policy_v4( # sign the policy and get its cryptographic signature if access_token and service_account_email: - signature = _sign_message(str_to_sign, access_token, service_account_email) + signature = _sign_message( + str_to_sign, + access_token, + service_account_email, + universe_domain=self.universe_domain, + ) signature_bytes = base64.b64decode(signature) else: signature_bytes = credentials.sign_bytes(str_to_sign) diff --git a/packages/google-cloud-storage/tests/unit/test__helpers.py b/packages/google-cloud-storage/tests/unit/test__helpers.py index becbb826a606..9ab5d303896f 100644 --- a/packages/google-cloud-storage/tests/unit/test__helpers.py +++ b/packages/google-cloud-storage/tests/unit/test__helpers.py @@ -110,6 +110,145 @@ def test_w_empty_value(self): self._call_fut() +class Test__validate_signing_credentials_universe_domain(unittest.TestCase): + @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}", + ) + + @staticmethod + 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) + + def test_w_non_signing_credentials(self): + import google.auth.credentials + + client = self._make_client(universe_domain="example.com") + token_credentials = mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ) + + for credentials in ( + None, + google.auth.credentials.AnonymousCredentials(), + token_credentials, + object(), + ): + with self.subTest(credentials=credentials): + self.assertIsNone(self._call_fut(client, credentials)) + + def test_w_credentials_wo_universe_domain(self): + import google.auth.credentials + + client = self._make_client(universe_domain="example.com") + credentials = mock.Mock(spec=google.auth.credentials.Signing) + + self.assertIsNone(self._call_fut(client, credentials)) + + def test_w_credentials_in_default_universe(self): + from google.auth import compute_engine + + # 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") + id_token_credentials = compute_engine.IDTokenCredentials( + mock.Mock(), + "audience", + service_account_email="service-account@example.com", + signer=mock.Mock(), + ) + self.assertEqual(id_token_credentials.universe_domain, "googleapis.com") + + for credentials in ( + self._make_signing_credentials("googleapis.com"), + id_token_credentials, + ): + with self.subTest(credentials=credentials): + self.assertIsNone(self._call_fut(client, credentials)) + + def test_w_client_wo_universe_domain(self): + from google.cloud.storage.client import Client + + credentials = self._make_signing_credentials("example.com") + + for client in (None, mock.create_autospec(Client, instance=True)): + with self.subTest(client=client): + self.assertIsNone( + self._call_fut( + client, credentials, "https://storage.googleapis.com" + ) + ) + + def test_w_other_endpoint(self): + client = self._make_client(universe_domain="example.com") + credentials = self._make_signing_credentials("other.example.com") + + for api_endpoint in ( + "https://storage.custom.example.com", + "https://storage.googleapis.com", + "http://localhost:8080", + "https://storage.example.com/", + "http://storage.example.com", + ): + with self.subTest(api_endpoint=api_endpoint): + self.assertIsNone(self._call_fut(client, credentials, api_endpoint)) + + def test_w_matching_universe_domain(self): + client = self._make_client(universe_domain="example.com") + credentials = self._make_signing_credentials("example.com") + + self.assertIsNone(self._call_fut(client, credentials)) + + def test_w_mismatched_universe_domain(self): + cases = ( + ("example.com", "other.example.com"), + ("googleapis.com", "example.com"), + ) + for client_universe_domain, credentials_universe_domain in cases: + with self.subTest( + client=client_universe_domain, credentials=credentials_universe_domain + ): + client = self._make_client(universe_domain=client_universe_domain) + credentials = self._make_signing_credentials( + credentials_universe_domain + ) + with self.assertRaises(ValueError) as exc_info: + self._call_fut(client, credentials) + + self.assertEqual( + str(exc_info.exception), + 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..c399ec007fef 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): @@ -748,6 +759,179 @@ def test_generate_signed_url_v4_w_incompatible_params(self): virtual_hosted_style=True, bucket_bound_hostname="cdn.example.com" ) + def _make_signed_url_target(self, client): + return self._make_one("blob-name", bucket=_Bucket(client)) + + def _generate_signed_url_w_universe_domain_helper( + self, + version, + client_universe_domain="example.com", + credentials_universe_domain="other.example.com", + client_api_endpoint=None, + raises=False, + **kw, + ): + if client_api_endpoint is None: + client_api_endpoint = f"https://storage.{client_universe_domain}" + + client = self._make_client( + _credentials=object(), + universe_domain=client_universe_domain, + api_endpoint=client_api_endpoint, + ) + credentials = _make_signing_credentials(credentials_universe_domain) + target = self._make_signed_url_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 self.assertRaisesRegex(ValueError, "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 + + self.assertEqual(signed_uri, signer.return_value) + signer.assert_called_once() + self.assertIs(signer.call_args.args[0], credentials) + return signer.call_args.kwargs + + def test_generate_signed_url_w_credentials_universe_domain_mismatch(self): + cases = ( + ("example.com", "other.example.com"), + ("googleapis.com", "example.com"), + ) + for version in ("v2", "v4"): + for client_universe_domain, credentials_universe_domain in cases: + default_endpoint = f"https://storage.{client_universe_domain}" + for kw in ( + {}, + {"virtual_hosted_style": True}, + {"api_access_endpoint": default_endpoint}, + ): + with self.subTest( + version=version, + client=client_universe_domain, + credentials=credentials_universe_domain, + **kw, + ): + self._generate_signed_url_w_universe_domain_helper( + version, + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + raises=True, + **kw, + ) + + def test_generate_signed_url_w_credentials_universe_domain_match(self): + for version in ("v2", "v4"): + with self.subTest(version=version): + kwargs = self._generate_signed_url_w_universe_domain_helper( + version, + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + self.assertEqual( + kwargs["api_access_endpoint"], "https://storage.example.com" + ) + + def test_generate_signed_url_w_credentials_universe_domain_not_checked(self): + cases = ( + # The URL does not use the default endpoint of the client. + {"api_access_endpoint": "https://storage.other.example.com"}, + {"api_access_endpoint": "https://storage.googleapis.com"}, + {"bucket_bound_hostname": "cdn.example.com"}, + {"client_api_endpoint": "https://storage.custom.example.com"}, + {"client_api_endpoint": "http://localhost:8080"}, + { + "client_api_endpoint": "https://storage.custom.example.com", + "virtual_hosted_style": True, + }, + # Credentials report the default universe domain when none is set. + {"credentials_universe_domain": "googleapis.com"}, + # An access token and a service account email sign the URL. + {"access_token": "token", "service_account_email": "sa@example.com"}, + ) + for version in ("v2", "v4"): + for case in cases: + with self.subTest(version=version, **case): + self._generate_signed_url_w_universe_domain_helper(version, **case) + + def test_generate_signed_url_w_credentials_universe_domain_w_client(self): + # The client passed for the call is the one that is compared. + other_client = self._make_client( + _credentials=object(), + universe_domain="other.example.com", + api_endpoint="https://storage.other.example.com", + ) + for version in ("v2", "v4"): + with self.subTest(version=version, credentials="other.example.com"): + kwargs = self._generate_signed_url_w_universe_domain_helper( + version, client=other_client + ) + self.assertEqual( + kwargs["api_access_endpoint"], "https://storage.other.example.com" + ) + + with self.subTest(version=version, credentials="example.com"): + self._generate_signed_url_w_universe_domain_helper( + version, + credentials_universe_domain="example.com", + client=other_client, + raises=True, + ) + + def test_generate_signed_url_w_non_signing_credentials_universe_domain(self): + import google.auth.credentials + + # Credentials that cannot sign keep raising AttributeError. + client = self._make_client( + _credentials=object(), + universe_domain="example.com", + api_endpoint="https://storage.example.com", + ) + credentials = mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ) + target = self._make_signed_url_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + + for version in ("v2", "v4"): + with self.subTest(version=version): + with self.assertRaisesRegex(AttributeError, "private key"): + target.generate_signed_url( + expiration=expiration, credentials=credentials, version=version + ) + + def test_generate_signed_url_w_credentials_universe_domain_partial_token(self): + # ``credentials`` sign the URL unless both the access token and the + # service account email are passed. + cases = ( + {"access_token": "token"}, + {"service_account_email": "sa@example.com"}, + ) + for version in ("v2", "v4"): + for case in cases: + with self.subTest(version=version, **case): + self._generate_signed_url_w_universe_domain_helper( + version, raises=True, **case + ) + def test_exists_miss_w_defaults(self): from google.cloud.exceptions import NotFound diff --git a/packages/google-cloud-storage/tests/unit/test_bucket.py b/packages/google-cloud-storage/tests/unit/test_bucket.py index 19b3456b816e..6cea5c3b4e84 100644 --- a/packages/google-cloud-storage/tests/unit/test_bucket.py +++ b/packages/google-cloud-storage/tests/unit/test_bucket.py @@ -48,6 +48,17 @@ class _SigningCredentials( return 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__blobs_page_start(unittest.TestCase): @staticmethod def _call_fut(iterator, page, response): @@ -4845,6 +4856,179 @@ def test_generate_signed_url_v4_w_incompatible_params(self): virtual_hosted_style=True, bucket_bound_hostname="cdn.example.com" ) + def _make_signed_url_target(self, client): + return self._make_one(name="bucket-name", client=client) + + def _generate_signed_url_w_universe_domain_helper( + self, + version, + client_universe_domain="example.com", + credentials_universe_domain="other.example.com", + client_api_endpoint=None, + raises=False, + **kw, + ): + if client_api_endpoint is None: + client_api_endpoint = f"https://storage.{client_universe_domain}" + + client = self._make_client( + _credentials=object(), + universe_domain=client_universe_domain, + api_endpoint=client_api_endpoint, + ) + credentials = _make_signing_credentials(credentials_universe_domain) + target = self._make_signed_url_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 self.assertRaisesRegex(ValueError, "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 + + self.assertEqual(signed_uri, signer.return_value) + signer.assert_called_once() + self.assertIs(signer.call_args.args[0], credentials) + return signer.call_args.kwargs + + def test_generate_signed_url_w_credentials_universe_domain_mismatch(self): + cases = ( + ("example.com", "other.example.com"), + ("googleapis.com", "example.com"), + ) + for version in ("v2", "v4"): + for client_universe_domain, credentials_universe_domain in cases: + default_endpoint = f"https://storage.{client_universe_domain}" + for kw in ( + {}, + {"virtual_hosted_style": True}, + {"api_access_endpoint": default_endpoint}, + ): + with self.subTest( + version=version, + client=client_universe_domain, + credentials=credentials_universe_domain, + **kw, + ): + self._generate_signed_url_w_universe_domain_helper( + version, + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + raises=True, + **kw, + ) + + def test_generate_signed_url_w_credentials_universe_domain_match(self): + for version in ("v2", "v4"): + with self.subTest(version=version): + kwargs = self._generate_signed_url_w_universe_domain_helper( + version, + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + self.assertEqual( + kwargs["api_access_endpoint"], "https://storage.example.com" + ) + + def test_generate_signed_url_w_credentials_universe_domain_not_checked(self): + cases = ( + # The URL does not use the default endpoint of the client. + {"api_access_endpoint": "https://storage.other.example.com"}, + {"api_access_endpoint": "https://storage.googleapis.com"}, + {"bucket_bound_hostname": "cdn.example.com"}, + {"client_api_endpoint": "https://storage.custom.example.com"}, + {"client_api_endpoint": "http://localhost:8080"}, + { + "client_api_endpoint": "https://storage.custom.example.com", + "virtual_hosted_style": True, + }, + # Credentials report the default universe domain when none is set. + {"credentials_universe_domain": "googleapis.com"}, + ) + for version in ("v2", "v4"): + for case in cases: + with self.subTest(version=version, **case): + self._generate_signed_url_w_universe_domain_helper(version, **case) + + def test_generate_signed_url_w_credentials_universe_domain_w_client(self): + # The client passed for the call is the one that is compared. + other_client = self._make_client( + _credentials=object(), + universe_domain="other.example.com", + api_endpoint="https://storage.other.example.com", + ) + for version in ("v2", "v4"): + with self.subTest(version=version, credentials="other.example.com"): + kwargs = self._generate_signed_url_w_universe_domain_helper( + version, client=other_client + ) + self.assertEqual( + kwargs["api_access_endpoint"], "https://storage.other.example.com" + ) + + with self.subTest(version=version, credentials="example.com"): + self._generate_signed_url_w_universe_domain_helper( + version, + credentials_universe_domain="example.com", + client=other_client, + raises=True, + ) + + def test_generate_signed_url_w_non_signing_credentials_universe_domain(self): + import google.auth.credentials + + # Credentials that cannot sign keep raising AttributeError. + client = self._make_client( + _credentials=object(), + universe_domain="example.com", + api_endpoint="https://storage.example.com", + ) + credentials = mock.Mock( + spec=google.auth.credentials.Credentials, + universe_domain="other.example.com", + ) + target = self._make_signed_url_target(client) + expiration = _NOW(_UTC) + datetime.timedelta(hours=1) + + for version in ("v2", "v4"): + with self.subTest(version=version): + with self.assertRaisesRegex(AttributeError, "private key"): + target.generate_signed_url( + expiration=expiration, credentials=credentials, version=version + ) + + 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 = _make_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() diff --git a/packages/google-cloud-storage/tests/unit/test_client.py b/packages/google-cloud-storage/tests/unit/test_client.py index a523d3dd1a9d..fc5f9848c112 100644 --- a/packages/google-cloud-storage/tests/unit/test_client.py +++ b/packages/google-cloud-storage/tests/unit/test_client.py @@ -69,7 +69,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 +77,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 @@ -3274,6 +3272,262 @@ def test_get_signed_policy_v4_no_expiration(self): ) self.assertEqual(policy["fields"]["policy"], EXPECTED_POLICY) + def _signed_policy_v4_w_universe_domain_helper( + 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 self.assertRaisesRegex(raises, 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 + + def test_get_signed_policy_v4_w_credentials_universe_domain_mismatch(self): + cases = ( + ("example.com", "other.example.com"), + (_DEFAULT_UNIVERSE_DOMAIN, "example.com"), + ) + for client_universe_domain, credentials_universe_domain in cases: + for virtual_hosted_style in (False, True): + with self.subTest( + client=client_universe_domain, + credentials=credentials_universe_domain, + virtual_hosted_style=virtual_hosted_style, + ): + _, credentials = self._signed_policy_v4_w_universe_domain_helper( + 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_w_universe_domain_helper( + client_universe_domain="example.com", + credentials_universe_domain="example.com", + ) + + self.assertEqual(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_w_universe_domain_helper( + credentials_universe_domain="example.com", environ=environ + ) + self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") + credentials.sign_bytes.assert_called_once() + + _, credentials = self._signed_policy_v4_w_universe_domain_helper( + 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_w_universe_domain_helper( + client_credentials=client_credentials, credentials=client_credentials + ) + + self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") + credentials.sign_bytes.assert_called_once() + + def test_get_signed_policy_v4_w_credentials_universe_domain_not_checked(self): + host = "https://storage.custom.example.com" + cases = ( + # The policy URL does not use the default endpoint of the client. + ( + {"bucket_bound_hostname": "https://cdn.example.com"}, + "https://cdn.example.com/", + ), + ( + {"client_options": {"api_endpoint": host}}, + f"{host}/bucket-name/", + ), + ( + { + "client_options": {"api_endpoint": host}, + "virtual_hosted_style": True, + }, + "https://bucket-name.storage.custom.example.com/", + ), + ( + {"environ": {_API_ENDPOINT_OVERRIDE_ENV_VAR: host}}, + f"{host}/bucket-name/", + ), + ( + {"environ": {STORAGE_EMULATOR_ENV_VAR: "http://localhost:8080"}}, + "http://localhost:8080/bucket-name/", + ), + ) + for case, expected_url in cases: + with self.subTest(**case): + policy, credentials = self._signed_policy_v4_w_universe_domain_helper( + client_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, + credentials_universe_domain="example.com", + **case, + ) + + self.assertEqual(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_w_universe_domain_helper( + client_universe_domain="example.com", + credentials_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, + ) + + self.assertEqual(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): + host = "https://storage.custom.example.com" + + policy, credentials = self._signed_policy_v4_w_universe_domain_helper( + client_options={"universe_domain": "example.com", "api_endpoint": host}, + ) + + self.assertEqual(policy["url"], f"{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_w_universe_domain_helper( + client_universe_domain="example.com", credentials=credentials + ) + self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") + self.assertTrue(policy["fields"]["x-goog-signature"]) + + for client_universe_domain in (_DEFAULT_UNIVERSE_DOMAIN, "other.example.com"): + with self.subTest(client=client_universe_domain): + self._signed_policy_v4_w_universe_domain_helper( + 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_w_universe_domain_helper( + credentials=credentials, + raises=AttributeError, + raises_regex="private key", + ) + + def test_get_signed_policy_v4_w_access_token_and_other_universe_credentials( + self, + ): + # ``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. + cases = ( + ("example.com", "other.example.com"), + (_DEFAULT_UNIVERSE_DOMAIN, "example.com"), + ) + for client_universe_domain, credentials_universe_domain in cases: + with self.subTest(client=client_universe_domain): + with mock.patch( + "google.cloud.storage.client._sign_message", + return_value=b"DEADBEEF", + ) as sign_message: + policy, credentials = ( + self._signed_policy_v4_w_universe_domain_helper( + client_universe_domain=client_universe_domain, + credentials_universe_domain=credentials_universe_domain, + service_account_email="test@mail.com", + access_token="token", + ) + ) + + self.assertEqual( + 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, + ) + + def test_get_signed_policy_v4_w_partial_token_and_other_universe_credentials(self): + for case in ( + {"access_token": "token"}, + {"service_account_email": "test@mail.com"}, + ): + with self.subTest(**case): + _, credentials = self._signed_policy_v4_w_universe_domain_helper( + raises=ValueError, **case + ) + credentials.sign_bytes.assert_not_called() + def test_get_signed_policy_v4_with_access_token(self): import datetime From a71752f5d2782c19a56b6fa338c00a3c108080c9 Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Mon, 30 Nov 2026 10:50:17 +0000 Subject: [PATCH 3/6] test(storage): patch os.environ with mock.patch.dict in new tests Use mock.patch.dict("os.environ", ..., clear=True) in the environment variable tests this change adds. It keeps os.environ as the standard mapping object instead of replacing it with a plain dict. [Generated-by: AI] --- .../tests/unit/test__helpers.py | 8 ++++---- .../tests/unit/test_client.py | 18 +++++++++--------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/google-cloud-storage/tests/unit/test__helpers.py b/packages/google-cloud-storage/tests/unit/test__helpers.py index 9ab5d303896f..bed4d1c641dc 100644 --- a/packages/google-cloud-storage/tests/unit/test__helpers.py +++ b/packages/google-cloud-storage/tests/unit/test__helpers.py @@ -86,26 +86,26 @@ def _call_fut(): return _get_universe_domain_override() def test_wo_env_var(self): - with mock.patch("os.environ", {}): + with mock.patch.dict("os.environ", {}, clear=True): self.assertIsNone(self._call_fut()) def test_w_default_universe(self): environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): self.assertIsNone(self._call_fut()) def test_w_non_default_universe(self): for value in ("example.com", " example.com "): with self.subTest(value=value): environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): self.assertEqual(self._call_fut(), "example.com") def test_w_empty_value(self): for value in ("", " "): with self.subTest(value=value): environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): with self.assertRaises(ValueError): self._call_fut() diff --git a/packages/google-cloud-storage/tests/unit/test_client.py b/packages/google-cloud-storage/tests/unit/test_client.py index fc5f9848c112..b1b88a039920 100644 --- a/packages/google-cloud-storage/tests/unit/test_client.py +++ b/packages/google-cloud-storage/tests/unit/test_client.py @@ -291,7 +291,7 @@ def test_ctor_w_universe_domain_env_and_matched_credentials(self): "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", } - with mock.patch("os.environ", environ): + 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) @@ -305,7 +305,7 @@ def test_ctor_w_universe_domain_env_and_mismatched_credentials(self): "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", } - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): with self.assertRaisesRegex(ValueError, "does not match"): self._make_one(project="PROJECT", credentials=credentials) @@ -319,7 +319,7 @@ def test_ctor_w_universe_domain_env_and_client_options(self): "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false", } - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): client = self._make_one( project="PROJECT", credentials=credentials, @@ -336,7 +336,7 @@ def test_ctor_w_universe_domain_env_and_api_endpoint(self): client_options = {"api_endpoint": api_endpoint} environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): client = self._make_one( project="PROJECT", credentials=credentials, @@ -350,7 +350,7 @@ def test_ctor_w_universe_domain_env_default_universe(self): credentials = _make_credentials() environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": _DEFAULT_UNIVERSE_DOMAIN} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): client = self._make_one(project="PROJECT", credentials=credentials) self.assertIsNone(client._universe_domain) @@ -363,7 +363,7 @@ def test_ctor_w_universe_domain_env_empty(self): credentials = _make_credentials() environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""} - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): with self.assertRaises(ValueError): self._make_one(project="PROJECT", credentials=credentials) @@ -375,7 +375,7 @@ def test_ctor_w_universe_domain_env_and_mtls(self): "GOOGLE_API_USE_CLIENT_CERTIFICATE": "true", } - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): with self.assertRaisesRegex(ValueError, "mTLS"): self._make_one(project="PROJECT", credentials=credentials) @@ -388,7 +388,7 @@ def test_ctor_w_universe_domain_env_w_emulator(self): "GOOGLE_CLOUD_UNIVERSE_DOMAIN": universe_domain, } - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): client = self._make_one() self.assertEqual(client.universe_domain, universe_domain) @@ -596,7 +596,7 @@ def test_create_anonymous_client_w_universe_domain_env(self): } klass = self._get_target_class() - with mock.patch("os.environ", environ): + with mock.patch.dict("os.environ", environ, clear=True): client = klass.create_anonymous_client() self.assertIsNone(client.project) From 0f79a762d70d81b11c55eee228f6bf259cdfc8f3 Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Mon, 30 Nov 2026 18:30:52 +0000 Subject: [PATCH 4/6] refactor(storage): resolve the universe domain with a resolve_client_universe mirror Replace `_get_universe_domain_override` with `_resolve_client_universe`, a local mirror of the shared `resolve_client_universe` helper. The mirror has the `TODO(universe-domain)` header, so it can be replaced by `google.api_core.universe.resolve_client_universe` later. The local copy strips surrounding whitespace, because `determine_domain` in older google-api-core releases returns the value unstripped. `Client._universe_domain` stays `None` for the default universe unless `client_options` names it, so the default endpoint handling is unchanged. Behavior changes: - An empty or whitespace-only `client_options.universe_domain` raises `EmptyUniverseError`. - Surrounding whitespace in `client_options.universe_domain` is stripped. - `client_options` that is not a `ClientOptions`, `Mapping`, or `None` raises `TypeError`. [Generated-by: AI] --- .../google/cloud/storage/_helpers.py | 55 ++++++++--- .../google/cloud/storage/client.py | 16 +++- .../tests/unit/test__helpers.py | 91 +++++++++++++++---- .../tests/unit/test_client.py | 68 ++++++++++++++ 4 files changed, 194 insertions(+), 36 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/_helpers.py b/packages/google-cloud-storage/google/cloud/storage/_helpers.py index 1ffe352eb4b1..d258b0a5e900 100644 --- a/packages/google-cloud-storage/google/cloud/storage/_helpers.py +++ b/packages/google-cloud-storage/google/cloud/storage/_helpers.py @@ -23,12 +23,15 @@ 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 @@ -115,23 +118,47 @@ def _get_api_endpoint_override(): return None -def _get_universe_domain_override(): - """Returns the non-default universe domain set in the environment, if any. +# TODO(universe-domain): Replace with google.api_core.universe.resolve_client_universe +# once minimum allowed google-api-core version exceeds 2.44.0. +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. - :rtype: str or None - :returns: The value of ``GOOGLE_CLOUD_UNIVERSE_DOMAIN`` without surrounding - whitespace, or ``None`` if the variable is unset or names the default - universe. + Follows AIP-4113 precedence: ``client_options.universe_domain``, then + ``GOOGLE_CLOUD_UNIVERSE_DOMAIN``, then ``"googleapis.com"``. - :raises ValueError: If the variable is set to an empty string. + 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``. """ - env_universe_domain = os.environ.get(_UNIVERSE_DOMAIN_ENV_VAR) - if env_universe_domain is None: - return None - universe_domain = universe.determine_domain(None, env_universe_domain.strip()) - if universe_domain == _DEFAULT_UNIVERSE_DOMAIN: - return None - return universe_domain + 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): diff --git a/packages/google-cloud-storage/google/cloud/storage/client.py b/packages/google-cloud-storage/google/cloud/storage/client.py index 7d8abec9e2bf..1fb0508b7f15 100644 --- a/packages/google-cloud-storage/google/cloud/storage/client.py +++ b/packages/google-cloud-storage/google/cloud/storage/client.py @@ -44,7 +44,7 @@ _get_api_endpoint_override, _get_environ_project, _get_storage_emulator_override, - _get_universe_domain_override, + _resolve_client_universe, _validate_signing_credentials_universe_domain, _virtual_hosted_style_base_url, create_trace_span_helper, @@ -112,7 +112,8 @@ class Client(ClientWithProject): :param client_options: (Optional) Client options used to set user options on the client. 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. + 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: @@ -187,10 +188,15 @@ 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. + universe_domain = _resolve_client_universe(client_options) + if ( + client_options and client_options.universe_domain + ) or universe_domain != _DEFAULT_UNIVERSE_DOMAIN: + self._universe_domain = universe_domain else: - self._universe_domain = _get_universe_domain_override() + self._universe_domain = None storage_emulator_override = _get_storage_emulator_override() api_endpoint_override = _get_api_endpoint_override() diff --git a/packages/google-cloud-storage/tests/unit/test__helpers.py b/packages/google-cloud-storage/tests/unit/test__helpers.py index bed4d1c641dc..02b560e3873f 100644 --- a/packages/google-cloud-storage/tests/unit/test__helpers.py +++ b/packages/google-cloud-storage/tests/unit/test__helpers.py @@ -78,37 +78,94 @@ def test_w_env_var(self): self.assertEqual(override, BASE_URL) -class Test__get_universe_domain_override(unittest.TestCase): +class Test__resolve_client_universe(unittest.TestCase): @staticmethod - def _call_fut(): - from google.cloud.storage._helpers import _get_universe_domain_override + def _call_fut(*args, **kwargs): + from google.cloud.storage._helpers import _resolve_client_universe - return _get_universe_domain_override() + return _resolve_client_universe(*args, **kwargs) - def test_wo_env_var(self): + @staticmethod + def _options(universe_domain): + import types + + from google.api_core.client_options import ClientOptions + + return ( + ClientOptions(universe_domain=universe_domain), + {"universe_domain": universe_domain}, + types.MappingProxyType({"universe_domain": universe_domain}), + ) + + def test_wo_client_options_wo_env_var(self): with mock.patch.dict("os.environ", {}, clear=True): - self.assertIsNone(self._call_fut()) + self.assertEqual(self._call_fut(), "googleapis.com") + self.assertEqual(self._call_fut(None), "googleapis.com") - def test_w_default_universe(self): - environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"} - with mock.patch.dict("os.environ", environ, clear=True): - self.assertIsNone(self._call_fut()) + def test_w_env_var(self): + from google.api_core.client_options import ClientOptions - def test_w_non_default_universe(self): - for value in ("example.com", " example.com "): - with self.subTest(value=value): - environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + cases = ( + ("example.com", "example.com"), + (" example.com ", "example.com"), + ("googleapis.com", "googleapis.com"), + ) + for value, expected in cases: + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + for client_options in (None, {}, {"api_endpoint": "x"}, ClientOptions()): + with self.subTest(value=value, client_options=client_options): + with mock.patch.dict("os.environ", environ, clear=True): + self.assertEqual(self._call_fut(client_options), expected) + + def test_w_client_options(self): + cases = ( + ("example.com", "example.com"), + (" example.com ", "example.com"), + ("googleapis.com", "googleapis.com"), + ) + for value, expected in cases: + for client_options in self._options(value): + with self.subTest(value=value, client_options=client_options): + with mock.patch.dict("os.environ", {}, clear=True): + self.assertEqual(self._call_fut(client_options), expected) + + def test_client_options_take_precedence_over_env_var(self): + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "other.example.com"} + for client_options in self._options("example.com"): + with self.subTest(client_options=client_options): with mock.patch.dict("os.environ", environ, clear=True): - self.assertEqual(self._call_fut(), "example.com") + self.assertEqual(self._call_fut(client_options), "example.com") + + def test_w_empty_env_var(self): + from google.api_core.universe import EmptyUniverseError - def test_w_empty_value(self): for value in ("", " "): with self.subTest(value=value): environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} with mock.patch.dict("os.environ", environ, clear=True): - with self.assertRaises(ValueError): + with self.assertRaises(EmptyUniverseError): self._call_fut() + def test_w_empty_client_options_universe_domain(self): + 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"} + for value in ("", " "): + for client_options in self._options(value): + with self.subTest(value=value, client_options=client_options): + with mock.patch.dict("os.environ", environ, clear=True): + with self.assertRaises(EmptyUniverseError): + self._call_fut(client_options) + + def test_w_invalid_client_options_type(self): + for client_options in (object(), "example.com", ["example.com"]): + with self.subTest(client_options=client_options): + with mock.patch.dict("os.environ", {}, clear=True): + with self.assertRaisesRegex(TypeError, "client_options must be"): + self._call_fut(client_options) + class Test__validate_signing_credentials_universe_domain(unittest.TestCase): @staticmethod diff --git a/packages/google-cloud-storage/tests/unit/test_client.py b/packages/google-cloud-storage/tests/unit/test_client.py index b1b88a039920..992d2f717a1d 100644 --- a/packages/google-cloud-storage/tests/unit/test_client.py +++ b/packages/google-cloud-storage/tests/unit/test_client.py @@ -367,6 +367,74 @@ def test_ctor_w_universe_domain_env_empty(self): with self.assertRaises(ValueError): self._make_one(project="PROJECT", credentials=credentials) + def test_ctor_w_empty_universe_domain_option(self): + from google.api_core.client_options import ClientOptions + + credentials = _make_credentials() + # The environment variable is not used when client_options sets an + # empty universe domain. + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} + + for value in ("", " "): + for client_options in ( + {"universe_domain": value}, + ClientOptions(universe_domain=value), + ): + with self.subTest(value=value, client_options=client_options): + with mock.patch.dict("os.environ", environ, clear=True): + with self.assertRaisesRegex(ValueError, "empty string"): + self._make_one( + project="PROJECT", + credentials=credentials, + client_options=client_options, + ) + + 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) From ffca71c0c028f158b4d1f872f99f1699999ee001 Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Wed, 2 Dec 2026 06:01:46 +0000 Subject: [PATCH 5/6] fix(storage): accept any mapping for client_options, parametrize tests Address review comments on the universe domain change. - `Client.__init__` converts a `client_options` mapping that is not a `dict` to a `dict`, so the constructor accepts every type that `_resolve_client_universe` accepts. - `Client.__init__` matches the default universe without regard to case. `GOOGLE_CLOUD_UNIVERSE_DOMAIN=GoogleApis.com` keeps the default endpoint. - The `TODO(universe-domain)` header of `_resolve_client_universe` names its tracking bug and issue. - Tests with several cases use `pytest.mark.parametrize`. They are in plain pytest classes, because `unittest.TestCase` does not support it. - `tests/unit/test_bucket.py` has one signing credentials helper. [Generated-by: AI] --- .../google/cloud/storage/_helpers.py | 2 + .../google/cloud/storage/client.py | 10 +- .../tests/unit/test__helpers.py | 333 +++++---- .../tests/unit/test_blob.py | 387 +++++----- .../tests/unit/test_bucket.py | 369 +++++----- .../tests/unit/test_client.py | 666 ++++++++++-------- 6 files changed, 988 insertions(+), 779 deletions(-) diff --git a/packages/google-cloud-storage/google/cloud/storage/_helpers.py b/packages/google-cloud-storage/google/cloud/storage/_helpers.py index d258b0a5e900..d7384e1c725d 100644 --- a/packages/google-cloud-storage/google/cloud/storage/_helpers.py +++ b/packages/google-cloud-storage/google/cloud/storage/_helpers.py @@ -120,6 +120,8 @@ def _get_api_endpoint_override(): # 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: diff --git a/packages/google-cloud-storage/google/cloud/storage/client.py b/packages/google-cloud-storage/google/cloud/storage/client.py index 1fb0508b7f15..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 @@ -110,6 +111,7 @@ 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 @@ -163,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 @@ -190,10 +197,11 @@ def __init__( # ``_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 != _DEFAULT_UNIVERSE_DOMAIN: + ) or universe_domain.lower() != _DEFAULT_UNIVERSE_DOMAIN: self._universe_domain = universe_domain else: self._universe_domain = None diff --git a/packages/google-cloud-storage/tests/unit/test__helpers.py b/packages/google-cloud-storage/tests/unit/test__helpers.py index 02b560e3873f..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,96 +81,125 @@ def test_w_env_var(self): self.assertEqual(override, BASE_URL) -class Test__resolve_client_universe(unittest.TestCase): +_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) - @staticmethod - def _options(universe_domain): - import types + @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" - from google.api_core.client_options import ClientOptions + @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} - return ( - ClientOptions(universe_domain=universe_domain), - {"universe_domain": universe_domain}, - types.MappingProxyType({"universe_domain": universe_domain}), - ) + with mock.patch.dict("os.environ", environ, clear=True): + assert self._call_fut(client_options) == expected - def test_wo_client_options_wo_env_var(self): + @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): - self.assertEqual(self._call_fut(), "googleapis.com") - self.assertEqual(self._call_fut(None), "googleapis.com") - - def test_w_env_var(self): - from google.api_core.client_options import ClientOptions + assert self._call_fut(make_client_options(value)) == expected - cases = ( - ("example.com", "example.com"), - (" example.com ", "example.com"), - ("googleapis.com", "googleapis.com"), - ) - for value, expected in cases: - environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} - for client_options in (None, {}, {"api_endpoint": "x"}, ClientOptions()): - with self.subTest(value=value, client_options=client_options): - with mock.patch.dict("os.environ", environ, clear=True): - self.assertEqual(self._call_fut(client_options), expected) - - def test_w_client_options(self): - cases = ( - ("example.com", "example.com"), - (" example.com ", "example.com"), - ("googleapis.com", "googleapis.com"), - ) - for value, expected in cases: - for client_options in self._options(value): - with self.subTest(value=value, client_options=client_options): - with mock.patch.dict("os.environ", {}, clear=True): - self.assertEqual(self._call_fut(client_options), expected) - - def test_client_options_take_precedence_over_env_var(self): + @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"} - for client_options in self._options("example.com"): - with self.subTest(client_options=client_options): - with mock.patch.dict("os.environ", environ, clear=True): - self.assertEqual(self._call_fut(client_options), "example.com") - def test_w_empty_env_var(self): + 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 - for value in ("", " "): - with self.subTest(value=value): - environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} - with mock.patch.dict("os.environ", environ, clear=True): - with self.assertRaises(EmptyUniverseError): - self._call_fut() + environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": value} + + with mock.patch.dict("os.environ", environ, clear=True): + with pytest.raises(EmptyUniverseError): + self._call_fut() - def test_w_empty_client_options_universe_domain(self): + @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"} - for value in ("", " "): - for client_options in self._options(value): - with self.subTest(value=value, client_options=client_options): - with mock.patch.dict("os.environ", environ, clear=True): - with self.assertRaises(EmptyUniverseError): - self._call_fut(client_options) - - def test_w_invalid_client_options_type(self): - for client_options in (object(), "example.com", ["example.com"]): - with self.subTest(client_options=client_options): - with mock.patch.dict("os.environ", {}, clear=True): - with self.assertRaisesRegex(TypeError, "client_options must be"): - self._call_fut(client_options) - - -class Test__validate_signing_credentials_universe_domain(unittest.TestCase): + + 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 ( @@ -189,121 +221,112 @@ def _make_client(universe_domain="googleapis.com"): api_endpoint=f"https://storage.{universe_domain}", ) - @staticmethod - 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) - - def test_w_non_signing_credentials(self): - import google.auth.credentials - + @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") - token_credentials = mock.Mock( - spec=google.auth.credentials.Credentials, - universe_domain="other.example.com", - ) - for credentials in ( - None, - google.auth.credentials.AnonymousCredentials(), - token_credentials, - object(), - ): - with self.subTest(credentials=credentials): - self.assertIsNone(self._call_fut(client, credentials)) + assert self._call_fut(client, make_credentials()) is None def test_w_credentials_wo_universe_domain(self): - import google.auth.credentials - client = self._make_client(universe_domain="example.com") credentials = mock.Mock(spec=google.auth.credentials.Signing) - self.assertIsNone(self._call_fut(client, credentials)) - - def test_w_credentials_in_default_universe(self): - from google.auth import compute_engine + 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") - id_token_credentials = compute_engine.IDTokenCredentials( - mock.Mock(), - "audience", - service_account_email="service-account@example.com", - signer=mock.Mock(), - ) - self.assertEqual(id_token_credentials.universe_domain, "googleapis.com") - - for credentials in ( - self._make_signing_credentials("googleapis.com"), - id_token_credentials, - ): - with self.subTest(credentials=credentials): - self.assertIsNone(self._call_fut(client, credentials)) + credentials = make_credentials() + assert credentials.universe_domain == "googleapis.com" - def test_w_client_wo_universe_domain(self): - from google.cloud.storage.client import Client + assert self._call_fut(client, credentials) is None - credentials = self._make_signing_credentials("example.com") + @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") - for client in (None, mock.create_autospec(Client, instance=True)): - with self.subTest(client=client): - self.assertIsNone( - self._call_fut( - client, credentials, "https://storage.googleapis.com" - ) - ) + result = self._call_fut( + make_client(), credentials, "https://storage.googleapis.com" + ) - def test_w_other_endpoint(self): - client = self._make_client(universe_domain="example.com") - credentials = self._make_signing_credentials("other.example.com") + assert result is None - for api_endpoint in ( + @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", - ): - with self.subTest(api_endpoint=api_endpoint): - self.assertIsNone(self._call_fut(client, credentials, api_endpoint)) + ], + ) + 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 = self._make_signing_credentials("example.com") + credentials = _make_signing_credentials("example.com") - self.assertIsNone(self._call_fut(client, credentials)) + assert self._call_fut(client, credentials) is None - def test_w_mismatched_universe_domain(self): - cases = ( + @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." ) - for client_universe_domain, credentials_universe_domain in cases: - with self.subTest( - client=client_universe_domain, credentials=credentials_universe_domain - ): - client = self._make_client(universe_domain=client_universe_domain) - credentials = self._make_signing_credentials( - credentials_universe_domain - ) - with self.assertRaises(ValueError) as exc_info: - self._call_fut(client, credentials) - - self.assertEqual( - str(exc_info.exception), - 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): diff --git a/packages/google-cloud-storage/tests/unit/test_blob.py b/packages/google-cloud-storage/tests/unit/test_blob.py index c399ec007fef..cb5dbbd69b0c 100644 --- a/packages/google-cloud-storage/tests/unit/test_blob.py +++ b/packages/google-cloud-storage/tests/unit/test_blob.py @@ -759,179 +759,6 @@ def test_generate_signed_url_v4_w_incompatible_params(self): virtual_hosted_style=True, bucket_bound_hostname="cdn.example.com" ) - def _make_signed_url_target(self, client): - return self._make_one("blob-name", bucket=_Bucket(client)) - - def _generate_signed_url_w_universe_domain_helper( - self, - version, - client_universe_domain="example.com", - credentials_universe_domain="other.example.com", - client_api_endpoint=None, - raises=False, - **kw, - ): - if client_api_endpoint is None: - client_api_endpoint = f"https://storage.{client_universe_domain}" - - client = self._make_client( - _credentials=object(), - universe_domain=client_universe_domain, - api_endpoint=client_api_endpoint, - ) - credentials = _make_signing_credentials(credentials_universe_domain) - target = self._make_signed_url_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 self.assertRaisesRegex(ValueError, "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 - - self.assertEqual(signed_uri, signer.return_value) - signer.assert_called_once() - self.assertIs(signer.call_args.args[0], credentials) - return signer.call_args.kwargs - - def test_generate_signed_url_w_credentials_universe_domain_mismatch(self): - cases = ( - ("example.com", "other.example.com"), - ("googleapis.com", "example.com"), - ) - for version in ("v2", "v4"): - for client_universe_domain, credentials_universe_domain in cases: - default_endpoint = f"https://storage.{client_universe_domain}" - for kw in ( - {}, - {"virtual_hosted_style": True}, - {"api_access_endpoint": default_endpoint}, - ): - with self.subTest( - version=version, - client=client_universe_domain, - credentials=credentials_universe_domain, - **kw, - ): - self._generate_signed_url_w_universe_domain_helper( - version, - client_universe_domain=client_universe_domain, - credentials_universe_domain=credentials_universe_domain, - raises=True, - **kw, - ) - - def test_generate_signed_url_w_credentials_universe_domain_match(self): - for version in ("v2", "v4"): - with self.subTest(version=version): - kwargs = self._generate_signed_url_w_universe_domain_helper( - version, - client_universe_domain="example.com", - credentials_universe_domain="example.com", - ) - self.assertEqual( - kwargs["api_access_endpoint"], "https://storage.example.com" - ) - - def test_generate_signed_url_w_credentials_universe_domain_not_checked(self): - cases = ( - # The URL does not use the default endpoint of the client. - {"api_access_endpoint": "https://storage.other.example.com"}, - {"api_access_endpoint": "https://storage.googleapis.com"}, - {"bucket_bound_hostname": "cdn.example.com"}, - {"client_api_endpoint": "https://storage.custom.example.com"}, - {"client_api_endpoint": "http://localhost:8080"}, - { - "client_api_endpoint": "https://storage.custom.example.com", - "virtual_hosted_style": True, - }, - # Credentials report the default universe domain when none is set. - {"credentials_universe_domain": "googleapis.com"}, - # An access token and a service account email sign the URL. - {"access_token": "token", "service_account_email": "sa@example.com"}, - ) - for version in ("v2", "v4"): - for case in cases: - with self.subTest(version=version, **case): - self._generate_signed_url_w_universe_domain_helper(version, **case) - - def test_generate_signed_url_w_credentials_universe_domain_w_client(self): - # The client passed for the call is the one that is compared. - other_client = self._make_client( - _credentials=object(), - universe_domain="other.example.com", - api_endpoint="https://storage.other.example.com", - ) - for version in ("v2", "v4"): - with self.subTest(version=version, credentials="other.example.com"): - kwargs = self._generate_signed_url_w_universe_domain_helper( - version, client=other_client - ) - self.assertEqual( - kwargs["api_access_endpoint"], "https://storage.other.example.com" - ) - - with self.subTest(version=version, credentials="example.com"): - self._generate_signed_url_w_universe_domain_helper( - version, - credentials_universe_domain="example.com", - client=other_client, - raises=True, - ) - - def test_generate_signed_url_w_non_signing_credentials_universe_domain(self): - import google.auth.credentials - - # Credentials that cannot sign keep raising AttributeError. - client = self._make_client( - _credentials=object(), - universe_domain="example.com", - api_endpoint="https://storage.example.com", - ) - credentials = mock.Mock( - spec=google.auth.credentials.Credentials, - universe_domain="other.example.com", - ) - target = self._make_signed_url_target(client) - expiration = _NOW(_UTC) + datetime.timedelta(hours=1) - - for version in ("v2", "v4"): - with self.subTest(version=version): - with self.assertRaisesRegex(AttributeError, "private key"): - target.generate_signed_url( - expiration=expiration, credentials=credentials, version=version - ) - - def test_generate_signed_url_w_credentials_universe_domain_partial_token(self): - # ``credentials`` sign the URL unless both the access token and the - # service account email are passed. - cases = ( - {"access_token": "token"}, - {"service_account_email": "sa@example.com"}, - ) - for version in ("v2", "v4"): - for case in cases: - with self.subTest(version=version, **case): - self._generate_signed_url_w_universe_domain_helper( - version, raises=True, **case - ) - def test_exists_miss_w_defaults(self): from google.cloud.exceptions import NotFound @@ -6840,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 6cea5c3b4e84..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,18 +43,8 @@ class _SigningCredentials( ): pass - credentials = mock.Mock(spec=_SigningCredentials) - - return credentials - - -def _make_signing_credentials(universe_domain): - import google.auth.credentials - - class _SigningCredentials( - google.auth.credentials.Credentials, google.auth.credentials.Signing - ): - pass + if universe_domain is None: + return mock.Mock(spec=_SigningCredentials) return mock.Mock(spec=_SigningCredentials, universe_domain=universe_domain) @@ -4856,167 +4846,10 @@ def test_generate_signed_url_v4_w_incompatible_params(self): virtual_hosted_style=True, bucket_bound_hostname="cdn.example.com" ) - def _make_signed_url_target(self, client): - return self._make_one(name="bucket-name", client=client) - - def _generate_signed_url_w_universe_domain_helper( - self, - version, - client_universe_domain="example.com", - credentials_universe_domain="other.example.com", - client_api_endpoint=None, - raises=False, - **kw, - ): - if client_api_endpoint is None: - client_api_endpoint = f"https://storage.{client_universe_domain}" - - client = self._make_client( - _credentials=object(), - universe_domain=client_universe_domain, - api_endpoint=client_api_endpoint, - ) - credentials = _make_signing_credentials(credentials_universe_domain) - target = self._make_signed_url_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 self.assertRaisesRegex(ValueError, "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 - - self.assertEqual(signed_uri, signer.return_value) - signer.assert_called_once() - self.assertIs(signer.call_args.args[0], credentials) - return signer.call_args.kwargs - - def test_generate_signed_url_w_credentials_universe_domain_mismatch(self): - cases = ( - ("example.com", "other.example.com"), - ("googleapis.com", "example.com"), - ) - for version in ("v2", "v4"): - for client_universe_domain, credentials_universe_domain in cases: - default_endpoint = f"https://storage.{client_universe_domain}" - for kw in ( - {}, - {"virtual_hosted_style": True}, - {"api_access_endpoint": default_endpoint}, - ): - with self.subTest( - version=version, - client=client_universe_domain, - credentials=credentials_universe_domain, - **kw, - ): - self._generate_signed_url_w_universe_domain_helper( - version, - client_universe_domain=client_universe_domain, - credentials_universe_domain=credentials_universe_domain, - raises=True, - **kw, - ) - - def test_generate_signed_url_w_credentials_universe_domain_match(self): - for version in ("v2", "v4"): - with self.subTest(version=version): - kwargs = self._generate_signed_url_w_universe_domain_helper( - version, - client_universe_domain="example.com", - credentials_universe_domain="example.com", - ) - self.assertEqual( - kwargs["api_access_endpoint"], "https://storage.example.com" - ) - - def test_generate_signed_url_w_credentials_universe_domain_not_checked(self): - cases = ( - # The URL does not use the default endpoint of the client. - {"api_access_endpoint": "https://storage.other.example.com"}, - {"api_access_endpoint": "https://storage.googleapis.com"}, - {"bucket_bound_hostname": "cdn.example.com"}, - {"client_api_endpoint": "https://storage.custom.example.com"}, - {"client_api_endpoint": "http://localhost:8080"}, - { - "client_api_endpoint": "https://storage.custom.example.com", - "virtual_hosted_style": True, - }, - # Credentials report the default universe domain when none is set. - {"credentials_universe_domain": "googleapis.com"}, - ) - for version in ("v2", "v4"): - for case in cases: - with self.subTest(version=version, **case): - self._generate_signed_url_w_universe_domain_helper(version, **case) - - def test_generate_signed_url_w_credentials_universe_domain_w_client(self): - # The client passed for the call is the one that is compared. - other_client = self._make_client( - _credentials=object(), - universe_domain="other.example.com", - api_endpoint="https://storage.other.example.com", - ) - for version in ("v2", "v4"): - with self.subTest(version=version, credentials="other.example.com"): - kwargs = self._generate_signed_url_w_universe_domain_helper( - version, client=other_client - ) - self.assertEqual( - kwargs["api_access_endpoint"], "https://storage.other.example.com" - ) - - with self.subTest(version=version, credentials="example.com"): - self._generate_signed_url_w_universe_domain_helper( - version, - credentials_universe_domain="example.com", - client=other_client, - raises=True, - ) - - def test_generate_signed_url_w_non_signing_credentials_universe_domain(self): - import google.auth.credentials - - # Credentials that cannot sign keep raising AttributeError. - client = self._make_client( - _credentials=object(), - universe_domain="example.com", - api_endpoint="https://storage.example.com", - ) - credentials = mock.Mock( - spec=google.auth.credentials.Credentials, - universe_domain="other.example.com", - ) - target = self._make_signed_url_target(client) - expiration = _NOW(_UTC) + datetime.timedelta(hours=1) - - for version in ("v2", "v4"): - with self.subTest(version=version): - with self.assertRaisesRegex(AttributeError, "private key"): - target.generate_signed_url( - expiration=expiration, credentials=credentials, version=version - ) - 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 = _make_signing_credentials("example.com") + 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: @@ -5078,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 3b640c586598..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): @@ -367,28 +377,6 @@ def test_ctor_w_universe_domain_env_empty(self): with self.assertRaises(ValueError): self._make_one(project="PROJECT", credentials=credentials) - def test_ctor_w_empty_universe_domain_option(self): - from google.api_core.client_options import ClientOptions - - credentials = _make_credentials() - # The environment variable is not used when client_options sets an - # empty universe domain. - environ = {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "example.com"} - - for value in ("", " "): - for client_options in ( - {"universe_domain": value}, - ClientOptions(universe_domain=value), - ): - with self.subTest(value=value, client_options=client_options): - with mock.patch.dict("os.environ", environ, clear=True): - with self.assertRaisesRegex(ValueError, "empty string"): - self._make_one( - project="PROJECT", - credentials=credentials, - client_options=client_options, - ) - def test_ctor_w_universe_domain_option_w_whitespace(self): universe_domain = "example.com" credentials = _make_credentials(universe_domain=universe_domain) @@ -3340,262 +3328,6 @@ def test_get_signed_policy_v4_no_expiration(self): ) self.assertEqual(policy["fields"]["policy"], EXPECTED_POLICY) - def _signed_policy_v4_w_universe_domain_helper( - 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 self.assertRaisesRegex(raises, 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 - - def test_get_signed_policy_v4_w_credentials_universe_domain_mismatch(self): - cases = ( - ("example.com", "other.example.com"), - (_DEFAULT_UNIVERSE_DOMAIN, "example.com"), - ) - for client_universe_domain, credentials_universe_domain in cases: - for virtual_hosted_style in (False, True): - with self.subTest( - client=client_universe_domain, - credentials=credentials_universe_domain, - virtual_hosted_style=virtual_hosted_style, - ): - _, credentials = self._signed_policy_v4_w_universe_domain_helper( - 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_w_universe_domain_helper( - client_universe_domain="example.com", - credentials_universe_domain="example.com", - ) - - self.assertEqual(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_w_universe_domain_helper( - credentials_universe_domain="example.com", environ=environ - ) - self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") - credentials.sign_bytes.assert_called_once() - - _, credentials = self._signed_policy_v4_w_universe_domain_helper( - 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_w_universe_domain_helper( - client_credentials=client_credentials, credentials=client_credentials - ) - - self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") - credentials.sign_bytes.assert_called_once() - - def test_get_signed_policy_v4_w_credentials_universe_domain_not_checked(self): - host = "https://storage.custom.example.com" - cases = ( - # The policy URL does not use the default endpoint of the client. - ( - {"bucket_bound_hostname": "https://cdn.example.com"}, - "https://cdn.example.com/", - ), - ( - {"client_options": {"api_endpoint": host}}, - f"{host}/bucket-name/", - ), - ( - { - "client_options": {"api_endpoint": host}, - "virtual_hosted_style": True, - }, - "https://bucket-name.storage.custom.example.com/", - ), - ( - {"environ": {_API_ENDPOINT_OVERRIDE_ENV_VAR: host}}, - f"{host}/bucket-name/", - ), - ( - {"environ": {STORAGE_EMULATOR_ENV_VAR: "http://localhost:8080"}}, - "http://localhost:8080/bucket-name/", - ), - ) - for case, expected_url in cases: - with self.subTest(**case): - policy, credentials = self._signed_policy_v4_w_universe_domain_helper( - client_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, - credentials_universe_domain="example.com", - **case, - ) - - self.assertEqual(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_w_universe_domain_helper( - client_universe_domain="example.com", - credentials_universe_domain=_DEFAULT_UNIVERSE_DOMAIN, - ) - - self.assertEqual(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): - host = "https://storage.custom.example.com" - - policy, credentials = self._signed_policy_v4_w_universe_domain_helper( - client_options={"universe_domain": "example.com", "api_endpoint": host}, - ) - - self.assertEqual(policy["url"], f"{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_w_universe_domain_helper( - client_universe_domain="example.com", credentials=credentials - ) - self.assertEqual(policy["url"], "https://storage.example.com/bucket-name/") - self.assertTrue(policy["fields"]["x-goog-signature"]) - - for client_universe_domain in (_DEFAULT_UNIVERSE_DOMAIN, "other.example.com"): - with self.subTest(client=client_universe_domain): - self._signed_policy_v4_w_universe_domain_helper( - 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_w_universe_domain_helper( - credentials=credentials, - raises=AttributeError, - raises_regex="private key", - ) - - def test_get_signed_policy_v4_w_access_token_and_other_universe_credentials( - self, - ): - # ``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. - cases = ( - ("example.com", "other.example.com"), - (_DEFAULT_UNIVERSE_DOMAIN, "example.com"), - ) - for client_universe_domain, credentials_universe_domain in cases: - with self.subTest(client=client_universe_domain): - with mock.patch( - "google.cloud.storage.client._sign_message", - return_value=b"DEADBEEF", - ) as sign_message: - policy, credentials = ( - self._signed_policy_v4_w_universe_domain_helper( - client_universe_domain=client_universe_domain, - credentials_universe_domain=credentials_universe_domain, - service_account_email="test@mail.com", - access_token="token", - ) - ) - - self.assertEqual( - 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, - ) - - def test_get_signed_policy_v4_w_partial_token_and_other_universe_credentials(self): - for case in ( - {"access_token": "token"}, - {"service_account_email": "test@mail.com"}, - ): - with self.subTest(**case): - _, credentials = self._signed_policy_v4_w_universe_domain_helper( - raises=ValueError, **case - ) - credentials.sign_bytes.assert_not_called() - def test_get_signed_policy_v4_with_access_token(self): import datetime @@ -3785,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 From 77dc85fb4ec50c70fca04f41ba9ebfc5e9083bb0 Mon Sep 17 00:00:00 2001 From: Shradha Katyal Date: Wed, 2 Dec 2026 11:34:30 +0000 Subject: [PATCH 6/6] test(storage): add system tests for signing credentials of another universe `Blob.generate_signed_url`, `Bucket.generate_signed_url` and `Client.generate_signed_post_policy_v4` raise `ValueError` when the per-call credentials report a universe domain that differs from the client's universe domain. The tests pass `universe_domain_credential` to the default `storage_client`. They are skipped when `TEST_UNIVERSE_DOMAIN_CREDENTIAL` is not set, and when the client does not use the default storage endpoint. [Generated-by: AI] --- .../tests/system/test__signing.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) 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, + )