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
36 changes: 34 additions & 2 deletions packages/google-auth/google/auth/impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ def __init__(
quota_project_id=None,
iam_endpoint_override=None,
trust_boundary=None,
universe_domain=None,
):
"""
Args:
Expand Down Expand Up @@ -243,10 +244,21 @@ def __init__(
if you wish to impersonate as a user. This feature is useful when
using domain wide delegation.
trust_boundary (Mapping[str,str]): A credential trust boundary.
universe_domain (Optional[str]): The universe domain value. If
provided, it must match ``source_credentials.universe_domain``.

Raises:
InvalidValue: If ``universe_domain`` is invalid or does not match
``source_credentials.universe_domain``.
"""

super(Credentials, self).__init__()

# Validate early to fail fast before cloning/scoping source_credentials
# or triggering a metadata lookup on uncached compute_engine.Credentials.
if universe_domain is not None:
_helpers.validate_universe_domain(universe_domain)
Comment thread
parthea marked this conversation as resolved.
Resolved

self._source_credentials = copy.copy(source_credentials)
# Service account source credentials must have the _IAM_SCOPE
# added to refresh correctly. User credentials cannot have
Expand All @@ -263,7 +275,14 @@ def __init__(
):
self._source_credentials._create_self_signed_jwt(None)

self._universe_domain = source_credentials.universe_domain
source_universe = getattr(self._source_credentials, "universe_domain", None)
if source_universe is None:
source_universe = credentials.DEFAULT_UNIVERSE_DOMAIN
if universe_domain is not None:
_helpers.compare_universe_domains(universe_domain, source_universe)
else:
_helpers.validate_universe_domain(source_universe)
self._universe_domain = source_universe
self._target_principal = target_principal
self._target_scopes = target_scopes
self._delegates = delegates
Expand Down Expand Up @@ -450,6 +469,7 @@ def _make_copy(self):
quota_project_id=self._quota_project_id,
iam_endpoint_override=self._iam_endpoint_override,
trust_boundary=self._trust_boundary,
universe_domain=self._universe_domain,
)
cred._cred_file_path = self._cred_file_path
self._copy_regional_access_boundary_manager(cred)
Expand Down Expand Up @@ -491,11 +511,22 @@ def from_impersonated_service_account_info(cls, info, scopes=None):

Raises:
InvalidType: If the info["source_credentials"] are not a supported impersonation type
InvalidValue: If the info["service_account_impersonation_url"] is not in the expected format.
InvalidValue: If ``info`` has an invalid or conflicting
``universe_domain`` or ``service_account_impersonation_url``.
ValueError: If the info is not in the expected format.
"""

source_credentials_info = info.get("source_credentials")
universe_domain = info.get("universe_domain")
source_universe_domain = source_credentials_info.get("universe_domain")
if source_universe_domain is not None:
_helpers.validate_universe_domain(source_universe_domain)
elif universe_domain is not None:
source_credentials_info = {
**source_credentials_info,
"universe_domain": universe_domain,
}
Comment thread
parthea marked this conversation as resolved.
Resolved

source_credentials_type = source_credentials_info.get("type")
if source_credentials_type == _SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE:
from google.oauth2 import credentials
Expand Down Expand Up @@ -545,6 +576,7 @@ def from_impersonated_service_account_info(cls, info, scopes=None):
delegates,
quota_project_id=quota_project_id,
trust_boundary=trust_boundary,
universe_domain=universe_domain,
)


Expand Down
249 changes: 249 additions & 0 deletions packages/google-auth/tests/test_impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import pytest # type: ignore

from google.auth import _helpers, crypt, exceptions, impersonated_credentials, transport
from google.auth import credentials as auth_credentials
from google.auth.impersonated_credentials import Credentials
from google.oauth2 import credentials, service_account

Expand All @@ -31,6 +32,9 @@
PRIVATE_KEY_BYTES = fh.read()

SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json")
EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_FILE = os.path.join(
DATA_DIR, "external_account_authorized_user.json"
)
IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE = os.path.join(
DATA_DIR, "impersonated_service_account_authorized_user_source.json"
)
Expand All @@ -48,6 +52,9 @@
with open(SERVICE_ACCOUNT_JSON_FILE, "rb") as fh:
SERVICE_ACCOUNT_INFO = json.load(fh)

with open(EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_FILE, "rb") as fh:
EXTERNAL_ACCOUNT_AUTHORIZED_USER_INFO = json.load(fh)

with open(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE, "rb") as fh:
IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO = json.load(fh)

Expand Down Expand Up @@ -1079,3 +1086,245 @@ def test_sign_jwt_request_invalid_response_error(self):
== "Unable to acquire impersonated credentials: No signed JWT in response."
)
assert excinfo.value.args[1] == "invalid_data"

@pytest.mark.parametrize(
"source_info",
[
pytest.param(
IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO[
"source_credentials"
],
id="authorized_user_source",
),
pytest.param(
SERVICE_ACCOUNT_INFO,
id="service_account_source",
),
pytest.param(
EXTERNAL_ACCOUNT_AUTHORIZED_USER_INFO,
id="external_account_authorized_user_source",
),
],
)
Comment thread
parthea marked this conversation as resolved.
Resolved
def test_from_impersonated_service_account_info_top_level_universe_domain(
self, source_info
):
info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO)
info["source_credentials"] = copy.deepcopy(source_info)
info["universe_domain"] = "example.com"
info["service_account_impersonation_url"] = (
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken"
)
original_source = copy.deepcopy(info["source_credentials"])

creds = (
impersonated_credentials.Credentials.from_impersonated_service_account_info(
info
)
)

assert creds.universe_domain == "example.com"
assert creds._source_credentials.universe_domain == "example.com"
# Caller's source_credentials dict must not be mutated.
assert info["source_credentials"] == original_source
assert creds.with_quota_project("qp").universe_domain == "example.com"

expire_time = (
_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
).isoformat("T") + "Z"
request = self.make_request(
data=json.dumps({"accessToken": "token", "expireTime": expire_time}),
status=http_client.OK,
)
with mock.patch.object(creds._source_credentials, "refresh"):
creds._source_credentials.token = "source-token"
creds._source_credentials.expiry = _helpers.utcnow() + datetime.timedelta(
seconds=500
)
creds.refresh(request)

assert (
request.call_args[1]["url"] == "https://iamcredentials.example.com"
"/v1/projects/-/serviceAccounts/[email protected]:generateAccessToken"
)

def test_from_impersonated_service_account_info_matching_universes(self):
info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO)
info["universe_domain"] = "example.com"
info["source_credentials"]["universe_domain"] = "example.com"
info["service_account_impersonation_url"] = (
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken"
)

creds = (
impersonated_credentials.Credentials.from_impersonated_service_account_info(
info
)
)
assert creds.universe_domain == "example.com"
assert creds._source_credentials.universe_domain == "example.com"

def test_from_impersonated_service_account_info_source_only_universe(self):
info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO)
info["source_credentials"]["universe_domain"] = "example.com"
info["service_account_impersonation_url"] = (
"https://iamcredentials.example.com/v1/projects/-"
"/serviceAccounts/[email protected]:generateAccessToken"
)

creds = (
impersonated_credentials.Credentials.from_impersonated_service_account_info(
info
)
)
assert creds.universe_domain == "example.com"
assert creds._source_credentials.universe_domain == "example.com"

@pytest.mark.parametrize(
"top_level_universe,source_universe,expected_match",
[
pytest.param(
"googleapis.com",
"other.com",
"does not match the expected universe domain",
id="top_level_conflicts_with_source",
),
pytest.param(
"",
None,
"must be a valid non-empty domain string",
id="empty_top_level_universe",
),
pytest.param(
" example.com ",
None,
"must be a valid non-empty domain string",
id="whitespace_top_level_universe",
),
pytest.param(
123,
None,
"must be a valid non-empty domain string",
id="non_string_top_level_universe",
),
],
)
def test_from_impersonated_service_account_info_universe_validation_errors(
self, top_level_universe, source_universe, expected_match
):
info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO)
if top_level_universe is not None:
info["universe_domain"] = top_level_universe
if source_universe is not None:
info["source_credentials"]["universe_domain"] = source_universe

with pytest.raises(exceptions.InvalidValue, match=expected_match):
impersonated_credentials.Credentials.from_impersonated_service_account_info(
info
)

def test_constructor_universe_domain_validation(self):
source = service_account.Credentials(
SIGNER, "[email protected]", TOKEN_URI, universe_domain="example.com"
)
creds = impersonated_credentials.Credentials(
source_credentials=source,
target_principal=self.TARGET_PRINCIPAL,
target_scopes=self.TARGET_SCOPES,
universe_domain="example.com",
)
assert creds.universe_domain == "example.com"

with pytest.raises(
exceptions.InvalidValue,
match="does not match the expected universe domain",
):
impersonated_credentials.Credentials(
source_credentials=source,
target_principal=self.TARGET_PRINCIPAL,
target_scopes=self.TARGET_SCOPES,
universe_domain="other.com",
)

with pytest.raises(
exceptions.InvalidValue,
match="must be a valid non-empty domain string",
):
impersonated_credentials.Credentials(
source_credentials=source,
target_principal=self.TARGET_PRINCIPAL,
target_scopes=self.TARGET_SCOPES,
universe_domain=" ",
)

@pytest.mark.parametrize(
"top_level_universe,source_universe",
[
pytest.param(None, "", id="empty_source_universe"),
pytest.param("googleapis.com", "", id="default_top_level_empty_source"),
pytest.param("example.com", "", id="custom_top_level_empty_source"),
pytest.param(None, " ", id="whitespace_source_universe"),
pytest.param(
None, "[email protected]", id="userinfo_injection_source"
),
pytest.param(None, 123, id="non_string_source_universe"),
],
)
def test_from_impersonated_service_account_info_invalid_source_universe_domain(
self, top_level_universe, source_universe
):
info = copy.deepcopy(IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_INFO)
if top_level_universe is None:
info.pop("universe_domain", None)
else:
info["universe_domain"] = top_level_universe
info["source_credentials"]["universe_domain"] = source_universe

with pytest.raises(
exceptions.InvalidValue,
match="must be a valid non-empty domain string",
):
impersonated_credentials.Credentials.from_impersonated_service_account_info(
info
)

@pytest.mark.parametrize(
"invalid_source_universe",
[
pytest.param(" ", id="whitespace"),
pytest.param("[email protected]", id="userinfo_injection"),
],
)
def test_constructor_invalid_source_universe_domain_when_universe_omitted(
self, invalid_source_universe
):
source = service_account.Credentials(
SIGNER, "[email protected]", TOKEN_URI, universe_domain=invalid_source_universe
)

with pytest.raises(
exceptions.InvalidValue,
match="must be a valid non-empty domain string",
):
impersonated_credentials.Credentials(
source_credentials=source,
target_principal=self.TARGET_PRINCIPAL,
target_scopes=self.TARGET_SCOPES,
)

def test_impersonated_credentials_source_universe_none_defaults_to_default_universe(
self,
):
source = mock.Mock(spec=["universe_domain", "refresh", "apply", "token_state"])
source.universe_domain = None
source.token_state = auth_credentials.TokenState.FRESH

creds = impersonated_credentials.Credentials(
source_credentials=source,
target_principal=self.TARGET_PRINCIPAL,
target_scopes=self.TARGET_SCOPES,
)

assert creds.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN
Loading