Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion packages/google-auth/google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@
import hashlib
import json
import logging
import re
import sys
import urllib
import urllib.parse
from email.message import Message
from typing import Any, Dict, Mapping, Optional, Union

from google.auth import exceptions

DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"
_DEFAULT_UNIVERSE_HOST_PATTERN = re.compile(
rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE_DOMAIN)}$"
)

# _BASE_LOGGER_NAME is the base logger for all google-based loggers.
_BASE_LOGGER_NAME = "google"
Expand Down Expand Up @@ -247,6 +251,31 @@ def update_query(url, params, remove=None):
return urllib.parse.urlunparse(new_parts)


def has_default_universe_host(url):
"""Checks whether a URL's host is in the default universe domain.

Args:
url (Optional[str]): The URL to inspect.

Returns:
bool: True if ``url`` has a valid ``googleapis.com`` or
``*.googleapis.com`` host without userinfo or fragments; False
otherwise.
"""
if not isinstance(url, str) or "#" in url:
return False
try:
parsed = urllib.parse.urlparse(url)
# Reject userinfo ("@" in netloc) without rejecting "@" in the path
# (such as service account emails in service_account_impersonation_url).
if "@" in parsed.netloc:
return False
host = parsed.hostname
return bool(host and _DEFAULT_UNIVERSE_HOST_PATTERN.fullmatch(host))
except ValueError:
return False


def scopes_to_string(scopes):
"""Converts scope value to a string suitable for sending to OAuth 2.0
authorization servers.
Expand Down
17 changes: 17 additions & 0 deletions packages/google-auth/google/auth/external_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,23 @@ def get_project_id(self, request):
# Scopes are required in order to retrieve a valid access token.
project_number = self.project_number or self._workforce_pool_user_project
if project_number and scopes:
# Avoid sending tokens minted for non-googleapis.com endpoints
# (e.g. another universe domain or custom proxy) to
# cloudresourcemanager.googleapis.com.
if _helpers.has_default_universe_host(self._cloud_resource_manager_url):
if not _helpers.has_default_universe_host(self._token_url):
return None
# Impersonation is optional; calling
# has_default_universe_host(None) returns False and would block
# non-impersonated default-universe credentials.
if (
self._service_account_impersonation_url
and not _helpers.has_default_universe_host(
self._service_account_impersonation_url
)
):
return None

headers = {}
url = "{}{}".format(self._cloud_resource_manager_url, project_number)
self.before_request(request, "GET", url, headers)
Expand Down
45 changes: 45 additions & 0 deletions packages/google-auth/tests/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,3 +697,48 @@ def test_out_of_range(self):
with pytest.raises((OverflowError, OSError, ValueError)):
# Large enough to fail on most systems (Year 300,000+)
_helpers.utcfromtimestamp(9999999999999)


@pytest.mark.parametrize(
"url,expected",
[
pytest.param("https://googleapis.com/v1/token", True, id="exact_default"),
pytest.param("https://sts.googleapis.com/v1/token", True, id="subdomain"),
pytest.param("HTTPS://STS.GOOGLEAPIS.COM/v1/token", True, id="uppercase_host"),
pytest.param(
"https://us-east1-iamcredentials.googleapis.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken",
True,
id="at_sign_in_path",
),
pytest.param("https://sts.example.com/v1/token", False, id="other_universe"),
pytest.param(
"https://sts.googleapis.com.evil.com/v1/token",
False,
id="spoofed_suffix",
),
pytest.param("https://evilgoogleapis.com/v1/token", False, id="missing_dot"),
pytest.param(
"https://.googleapis.com/v1/token", False, id="empty_leading_label"
),
pytest.param(
"https://foo..googleapis.com/v1/token", False, id="empty_middle_label"
),
pytest.param(
"https://[email protected]/v1/token",
False,
id="userinfo_at",
),
pytest.param(
"https://evil.com\\@sts.googleapis.com/v1/token",
False,
id="userinfo_backslash_at",
),
pytest.param("https://sts.googleapis.com#evil.com", False, id="fragment_hash"),
pytest.param("https://[invalid/v1/token", False, id="malformed_url"),
pytest.param("", False, id="empty_string"),
pytest.param(None, False, id="none_input"),
],
)
def test_has_default_universe_host(url, expected):
assert _helpers.has_default_universe_host(url) is expected
115 changes: 115 additions & 0 deletions packages/google-auth/tests/test_external_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -2319,6 +2319,121 @@ def test_get_project_id_cloud_resource_manager_custom_universe_domain(self):
)
assert crm_request_kwargs["url"] == expected_url

@pytest.mark.parametrize(
"token_url,impersonation_url",
[
pytest.param(
"https://sts.example.com/v1/token",
None,
id="non_default_token_url",
),
pytest.param(
"https://sts.googleapis.com/v1/token",
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken",
id="non_default_impersonation_url",
),
pytest.param(
"https://sts.googleapis.com.evil.com/v1/token",
None,
id="spoofed_host_suffix",
),
pytest.param(
"https://evilgoogleapis.com/v1/token",
None,
id="missing_subdomain_dot",
),
pytest.param(None, None, id="missing_token_url"),
pytest.param("https://[invalid/v1/token", None, id="malformed_token_url"),
pytest.param(
"https://evil.com\\@sts.googleapis.com/v1/token",
None,
id="userinfo_in_token_url",
),
pytest.param(
"https://sts.googleapis.com#evil.com",
None,
id="fragment_in_token_url",
),
pytest.param(
"https://.googleapis.com/v1/token",
None,
id="empty_label_token_url",
),
],
)
def test_get_project_id_skips_non_default_universe_endpoints(
self, token_url, impersonation_url
):
request = mock.create_autospec(transport.Request)
info = {
"type": "external_account",
"audience": self.AUDIENCE,
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"token_url": token_url,
"credential_source": self.CREDENTIAL_SOURCE,
}
if impersonation_url is not None:
info["service_account_impersonation_url"] = impersonation_url
credentials = CredentialsImpl.from_info(info, scopes=self.SCOPES)

project_id = credentials.get_project_id(request)

assert project_id is None
request.assert_not_called()

@pytest.mark.parametrize(
"universe_domain",
[
pytest.param("example.com", id="custom_universe"),
pytest.param(None, id="none_universe"),
pytest.param("", id="empty_universe"),
],
)
def test_get_project_id_skips_default_crm_url_after_with_universe_domain(
self, universe_domain
):
request = mock.create_autospec(transport.Request)
credentials = CredentialsImpl.from_info(
{
"type": "external_account",
"audience": self.AUDIENCE,
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"token_url": "https://sts.example.com/v1/token",
"credential_source": self.CREDENTIAL_SOURCE,
},
scopes=self.SCOPES,
).with_universe_domain(universe_domain)

project_id = credentials.get_project_id(request)

assert project_id is None
request.assert_not_called()

def test_get_project_id_allows_default_universe_token_url_when_universe_omitted(
self,
):
request = self.make_mock_request(
status=http_client.OK,
data=self.SUCCESS_RESPONSE.copy(),
cloud_resource_manager_status=http_client.OK,
cloud_resource_manager_data=self.CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE,
)
credentials = CredentialsImpl.from_info(
{
"type": "external_account",
"audience": self.AUDIENCE,
"subject_token_type": self.SUBJECT_TOKEN_TYPE,
"token_url": self.TOKEN_URL,
"credential_source": self.CREDENTIAL_SOURCE,
},
scopes=self.SCOPES,
)

project_id = credentials.get_project_id(request)

assert project_id == self.PROJECT_ID

def test_refresh_with_existing_impersonated_credentials(self):
credentials = self.make_credentials(
service_account_impersonation_url=self.SERVICE_ACCOUNT_IMPERSONATION_URL
Expand Down
Loading