blob: 81aef73b45061155a04f3194b2d51024ece55672 [file] [log] [blame]
C.J. Collier37141e42020-02-13 13:49:49 -08001# Copyright 2016 Google LLC
Jon Wayne Parrott04714752016-10-24 10:00:58 -07002#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080015"""Google App Engine standard environment support.
Jon Wayne Parrott04714752016-10-24 10:00:58 -070016
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080017This module provides authentication and signing for applications running on App
18Engine in the standard environment using the `App Identity API`_.
Jon Wayne Parrott04714752016-10-24 10:00:58 -070019
20
21.. _App Identity API:
22 https://cloud.google.com/appengine/docs/python/appidentity/
23"""
24
25import datetime
26
27from google.auth import _helpers
28from google.auth import credentials
Jon Wayne Parrott254befe2017-02-22 14:37:31 -080029from google.auth import crypt
Jon Wayne Parrott04714752016-10-24 10:00:58 -070030
Teddy Sudola10b15e2018-10-05 10:20:33 -070031# pytype: disable=import-error
Jon Wayne Parrott04714752016-10-24 10:00:58 -070032try:
33 from google.appengine.api import app_identity
34except ImportError:
35 app_identity = None
Teddy Sudola10b15e2018-10-05 10:20:33 -070036# pytype: enable=import-error
Jon Wayne Parrott04714752016-10-24 10:00:58 -070037
38
Jon Wayne Parrott254befe2017-02-22 14:37:31 -080039class Signer(crypt.Signer):
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080040 """Signs messages using the App Engine App Identity service.
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080041
42 This can be used in place of :class:`google.auth.crypt.Signer` when
43 running in the App Engine standard environment.
44 """
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080045
46 @property
47 def key_id(self):
48 """Optional[str]: The key ID used to identify this private key.
49
Jon Wayne Parrott254befe2017-02-22 14:37:31 -080050 .. warning::
51 This is always ``None``. The key ID used by App Engine can not
52 be reliably determined ahead of time.
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080053 """
Jon Wayne Parrott254befe2017-02-22 14:37:31 -080054 return None
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080055
Jon Wayne Parrott254befe2017-02-22 14:37:31 -080056 @_helpers.copy_docstring(crypt.Signer)
57 def sign(self, message):
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080058 message = _helpers.to_bytes(message)
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080059 _, signature = app_identity.sign_blob(message)
60 return signature
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080061
62
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070063def get_project_id():
64 """Gets the project ID for the current App Engine application.
65
66 Returns:
67 str: The project ID
68
69 Raises:
70 EnvironmentError: If the App Engine APIs are unavailable.
71 """
Jon Wayne Parrott20e6e582016-12-19 10:21:23 -080072 # pylint: disable=missing-raises-doc
73 # Pylint rightfully thinks EnvironmentError is OSError, but doesn't
74 # realize it's a valid alias.
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070075 if app_identity is None:
Bu Sun Kim9eec0912019-10-21 17:04:21 -070076 raise EnvironmentError("The App Engine APIs are not available.")
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070077 return app_identity.get_application_id()
78
79
Bu Sun Kim41599ae2020-09-02 12:55:42 -060080class Credentials(
81 credentials.Scoped, credentials.Signing, credentials.CredentialsWithQuotaProject
82):
Jon Wayne Parrott04714752016-10-24 10:00:58 -070083 """App Engine standard environment credentials.
84
85 These credentials use the App Engine App Identity API to obtain access
86 tokens.
87 """
88
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -070089 def __init__(
90 self,
91 scopes=None,
92 default_scopes=None,
93 service_account_id=None,
94 quota_project_id=None,
95 ):
Jon Wayne Parrott04714752016-10-24 10:00:58 -070096 """
97 Args:
98 scopes (Sequence[str]): Scopes to request from the App Identity
99 API.
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700100 default_scopes (Sequence[str]): Default scopes passed by a
101 Google client library. Use 'scopes' for user-defined scopes.
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700102 service_account_id (str): The service account ID passed into
103 :func:`google.appengine.api.app_identity.get_access_token`.
104 If not specified, the default application service account
105 ID will be used.
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700106 quota_project_id (Optional[str]): The project ID used for quota
107 and billing.
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700108
109 Raises:
110 EnvironmentError: If the App Engine APIs are unavailable.
111 """
Jon Wayne Parrott20e6e582016-12-19 10:21:23 -0800112 # pylint: disable=missing-raises-doc
113 # Pylint rightfully thinks EnvironmentError is OSError, but doesn't
114 # realize it's a valid alias.
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700115 if app_identity is None:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700116 raise EnvironmentError("The App Engine APIs are not available.")
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700117
118 super(Credentials, self).__init__()
119 self._scopes = scopes
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700120 self._default_scopes = default_scopes
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700121 self._service_account_id = service_account_id
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800122 self._signer = Signer()
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700123 self._quota_project_id = quota_project_id
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700124
125 @_helpers.copy_docstring(credentials.Credentials)
126 def refresh(self, request):
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700127 scopes = self._scopes if self._scopes is not None else self._default_scopes
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700128 # pylint: disable=unused-argument
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700129 token, ttl = app_identity.get_access_token(scopes, self._service_account_id)
Jon Wayne Parrott1cba0f82017-09-12 10:21:02 -0700130 expiry = datetime.datetime.utcfromtimestamp(ttl)
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700131
132 self.token, self.expiry = token, expiry
133
134 @property
Jon Wayne Parrott61ffb052016-11-08 09:30:30 -0800135 def service_account_email(self):
136 """The service account email."""
137 if self._service_account_id is None:
138 self._service_account_id = app_identity.get_service_account_name()
139 return self._service_account_id
140
141 @property
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700142 def requires_scopes(self):
143 """Checks if the credentials requires scopes.
144
145 Returns:
146 bool: True if there are no scopes set otherwise False.
147 """
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700148 return not self._scopes and not self._default_scopes
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700149
150 @_helpers.copy_docstring(credentials.Scoped)
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700151 def with_scopes(self, scopes, default_scopes=None):
Christophe Tatonb649b432018-02-08 14:12:23 -0800152 return self.__class__(
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700153 scopes=scopes,
Bu Sun Kimbf5ce0c2021-02-01 15:17:49 -0700154 default_scopes=default_scopes,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700155 service_account_id=self._service_account_id,
156 quota_project_id=self.quota_project_id,
157 )
158
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600159 @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700160 def with_quota_project(self, quota_project_id):
161 return self.__class__(
162 scopes=self._scopes,
163 service_account_id=self._service_account_id,
164 quota_project_id=quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700165 )
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700166
167 @_helpers.copy_docstring(credentials.Signing)
168 def sign_bytes(self, message):
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800169 return self._signer.sign(message)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800170
171 @property
172 @_helpers.copy_docstring(credentials.Signing)
173 def signer_email(self):
174 return self.service_account_email
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800175
176 @property
177 @_helpers.copy_docstring(credentials.Signing)
178 def signer(self):
179 return self._signer