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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,6 @@ pylintrc.test
pytype_output/

.python-version
.DS_Store
cert_path
key_path
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@

[1]: https://pypi.org/project/google-auth/#history

### [1.21.1](https://www.github.com/googleapis/google-auth-library-python/compare/v1.21.0...v1.21.1) (2020-09-03)


### Bug Fixes

* dummy commit to trigger a auto release ([#597](https://www.github.com/googleapis/google-auth-library-python/issues/597)) ([d32f7df](https://www.github.com/googleapis/google-auth-library-python/commit/d32f7df4895122ef23b664672d7db3f58d9b7d36))

## [1.21.0](https://www.github.com/googleapis/google-auth-library-python/compare/v1.20.1...v1.21.0) (2020-08-27)


Expand Down
2 changes: 1 addition & 1 deletion google/auth/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class CredentialsWithQuotaProject(Credentials):
"""Abstract base for credentials supporting ``with_quota_project`` factory"""

def with_quota_project(self, quota_project_id):
"""Returns a copy of these credentials with a modified quota project
"""Returns a copy of these credentials with a modified quota project.

Args:
quota_project_id (str): The project to use for quota and
Expand Down
162 changes: 162 additions & 0 deletions google/auth/external_account.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""External Account Credentials.

This module provides credentials that exchange workload identity pool external
credentials for Google access tokens. This facilitates calling Google APIs from
Kubernetes, Azure and AWS workloads securely, using native credentials retrieved
from the current environment without the need to copy, save and manage service
account keys.

Specifically, this is intended to use access tokens acquired using the GCP STS
token exchange endpoint following the `OAuth 2.0 Token Exchange`_ spec.

.. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693
"""

import abc
import datetime

import six

from google.auth import _helpers
from google.auth import credentials
from google.oauth2 import sts
from google.oauth2 import utils

# The token exchange grant_type used for exchanging credentials.
_STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
# The token exchange requested_token_type. This is always an access_token.
_STS_REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"


@six.add_metaclass(abc.ABCMeta)
class Credentials(credentials.Scoped, credentials.CredentialsWithQuotaProject):
"""Base class for all external account credentials.

This is used to instantiate Credentials for exchanging external account
credentials for Google access token and authorizing requests to Google APIs.
The base class implements the common logic for exchanging external account
credentials for Google access tokens.
"""

def __init__(
self,
audience,
subject_token_type,
token_url,
credential_source,
client_id=None,
client_secret=None,
quota_project_id=None,
scopes=None,
):
"""Instantiates an external account credentials object.

Args:
audience (str): The STS audience field.
subject_token_type (str): The subject token type.
token_url (str): The STS endpoint URL.
credential_source (Mapping): The credential source dictionary.
client_id (Optional[str]): The optional client ID.
client_secret (Optional[str]): The optional client secret.
quota_project_id (Optional[str]): The optional quota project ID.
scopes (Optional[Sequence[str]]): Optional scopes to request during the
authorization grant.
"""
super(Credentials, self).__init__()
self._audience = audience
self._subject_token_type = subject_token_type
self._token_url = token_url
self._credential_source = credential_source
self._client_id = client_id
self._client_secret = client_secret
self._quota_project_id = quota_project_id
self._scopes = scopes

if self._client_id:
self._client_auth = utils.ClientAuthentication(
utils.ClientAuthType.basic, self._client_id, self._client_secret
)
else:
self._client_auth = None
self._sts_client = sts.Client(self._token_url, self._client_auth)

@property
def requires_scopes(self):
"""Checks if the credentials requires scopes.

Returns:
bool: True if there are no scopes set otherwise False.
"""
return True if not self._scopes else False

@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes):
return self.__class__(
audience=self._audience,
subject_token_type=self._subject_token_type,
token_url=self._token_url,
credential_source=self._credential_source,
client_id=self._client_id,
client_secret=self._client_secret,
quota_project_id=self._quota_project_id,
scopes=scopes,
)

@abc.abstractmethod
def retrieve_subject_token(self, request):
"""Retrieves the subject token using the credential_source object.

Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
Returns:
str: The retrieved subject token.
"""
# pylint: disable=missing-raises-doc
# (pylint doesn't recognize that this is abstract)
raise NotImplementedError("retrieve_subject_token must be implemented")

@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
now = _helpers.utcnow()
response_data = self._sts_client.exchange_token(
request=request,
grant_type=_STS_GRANT_TYPE,
subject_token=self.retrieve_subject_token(request),
subject_token_type=self._subject_token_type,
audience=self._audience,
scopes=self._scopes,
requested_token_type=_STS_REQUESTED_TOKEN_TYPE,
)

self.token = response_data.get("access_token")
lifetime = datetime.timedelta(seconds=response_data.get("expires_in"))
self.expiry = now + lifetime

@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
# Return copy of instance with the provided quota project ID.
return self.__class__(
audience=self._audience,
subject_token_type=self._subject_token_type,
token_url=self._token_url,
credential_source=self._credential_source,
client_id=self._client_id,
client_secret=self._client_secret,
quota_project_id=quota_project_id,
scopes=self._scopes,
)
6 changes: 3 additions & 3 deletions google/auth/iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from google.auth import crypt
from google.auth import exceptions

_IAM_API_ROOT_URI = "https://iam.googleapis.com/v1"
_IAM_API_ROOT_URI = "https://iamcredentials.googleapis.com/v1"
_SIGN_BLOB_URI = _IAM_API_ROOT_URI + "/projects/-/serviceAccounts/{}:signBlob?alt=json"


Expand Down Expand Up @@ -71,7 +71,7 @@ def _make_signing_request(self, message):
url = _SIGN_BLOB_URI.format(self._service_account_email)
headers = {"Content-Type": "application/json"}
body = json.dumps(
{"bytesToSign": base64.b64encode(message).decode("utf-8")}
{"payload": base64.b64encode(message).decode("utf-8")}
).encode("utf-8")

self._credentials.before_request(self._request, method, url, headers)
Expand All @@ -97,4 +97,4 @@ def key_id(self):
@_helpers.copy_docstring(crypt.Signer)
def sign(self, message):
response = self._make_signing_request(message)
return base64.b64decode(response["signature"])
return base64.b64decode(response["signedBlob"])
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
with io.open("README.rst", "r") as fh:
long_description = fh.read()

version = "1.21.0"
version = "1.21.1"

setup(
name="google-auth",
Expand Down
17 changes: 17 additions & 0 deletions system_tests/test_service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from google.auth import _helpers
from google.auth import exceptions
from google.auth import iam
from google.oauth2 import service_account


Expand Down Expand Up @@ -46,3 +47,19 @@ def test_refresh_success(http_request, credentials, token_info):
"https://www.googleapis.com/auth/userinfo.profile",
]
)

def test_iam_signer(http_request, credentials):
credentials = credentials.with_scopes(
["https://www.googleapis.com/auth/iam"]
)

# Verify iamcredentials signer.
signer = iam.Signer(
http_request,
credentials,
credentials.service_account_email
)

signed_blob = signer.sign("message")

assert isinstance(signed_blob, bytes)
12 changes: 6 additions & 6 deletions tests/compute_engine/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,11 +363,11 @@ def test_with_target_audience_integration(self):
signature = base64.b64encode(b"some-signature").decode("utf-8")
responses.add(
responses.POST,
"https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
"[email protected]:signBlob?alt=json",
"https://iamcredentials.googleapis.com/v1/projects/-/"
"serviceAccounts/[email protected]:signBlob?alt=json",
status=200,
content_type="application/json",
json={"keyId": "some-key-id", "signature": signature},
json={"keyId": "some-key-id", "signedBlob": signature},
)

id_token = "{}.{}.{}".format(
Expand Down Expand Up @@ -477,11 +477,11 @@ def test_with_quota_project_integration(self):
signature = base64.b64encode(b"some-signature").decode("utf-8")
responses.add(
responses.POST,
"https://iam.googleapis.com/v1/projects/-/serviceAccounts/"
"[email protected]:signBlob?alt=json",
"https://iamcredentials.googleapis.com/v1/projects/-/"
"serviceAccounts/[email protected]:signBlob?alt=json",
status=200,
content_type="application/json",
json={"keyId": "some-key-id", "signature": signature},
json={"keyId": "some-key-id", "signedBlob": signature},
)

id_token = "{}.{}.{}".format(
Expand Down
Loading