Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 1 | # Copyright 2016 Google Inc. |
| 2 | # |
| 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 | |
| 15 | """Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0 |
| 16 | |
| 17 | This module implements the JWT Profile for OAuth 2.0 Authorization Grants |
| 18 | as defined by `RFC 7523`_ with particular support for how this RFC is |
| 19 | implemented in Google's infrastructure. Google refers to these credentials |
| 20 | as *Service Accounts*. |
| 21 | |
| 22 | Service accounts are used for server-to-server communication, such as |
| 23 | interactions between a web application server and a Google service. The |
| 24 | service account belongs to your application instead of to an individual end |
| 25 | user. In contrast to other OAuth 2.0 profiles, no users are involved and your |
| 26 | application "acts" as the service account. |
| 27 | |
| 28 | Typically an application uses a service account when the application uses |
| 29 | Google APIs to work with its own data rather than a user's data. For example, |
| 30 | an application that uses Google Cloud Datastore for data persistence would use |
| 31 | a service account to authenticate its calls to the Google Cloud Datastore API. |
| 32 | However, an application that needs to access a user's Drive documents would |
| 33 | use the normal OAuth 2.0 profile. |
| 34 | |
| 35 | Additionally, Google Apps domain administrators can grant service accounts |
| 36 | `domain-wide delegation`_ authority to access user data on behalf of users in |
| 37 | the domain. |
| 38 | |
| 39 | This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used |
| 40 | in place of the usual authorization token returned during the standard |
| 41 | OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as |
| 42 | the acquired access token is used as the bearer token when making requests |
| 43 | using these credentials. |
| 44 | |
| 45 | This profile differs from normal OAuth 2.0 profile because no user consent |
| 46 | step is required. The use of the private key allows this profile to assert |
| 47 | identity directly. |
| 48 | |
| 49 | This profile also differs from the :mod:`google.auth.jwt` authentication |
| 50 | because the JWT credentials use the JWT directly as the bearer token. This |
| 51 | profile instead only uses the JWT to obtain an OAuth 2.0 access token. The |
| 52 | obtained OAuth 2.0 access token is used as the bearer token. |
| 53 | |
| 54 | Domain-wide delegation |
| 55 | ---------------------- |
| 56 | |
| 57 | Domain-wide delegation allows a service account to access user data on |
| 58 | behalf of any user in a Google Apps domain without consent from the user. |
| 59 | For example, an application that uses the Google Calendar API to add events to |
| 60 | the calendars of all users in a Google Apps domain would use a service account |
| 61 | to access the Google Calendar API on behalf of users. |
| 62 | |
| 63 | The Google Apps administrator must explicitly authorize the service account to |
| 64 | do this. This authorization step is referred to as "delegating domain-wide |
| 65 | authority" to a service account. |
| 66 | |
| 67 | You can use domain-wise delegation by creating a set of credentials with a |
| 68 | specific subject using :meth:`~Credentials.with_subject`. |
| 69 | |
| 70 | .. _RFC 7523: https://tools.ietf.org/html/rfc7523 |
| 71 | """ |
| 72 | |
Jon Wayne Parrott | 75c78b2 | 2017-03-23 13:14:53 -0700 | [diff] [blame] | 73 | import copy |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 74 | import datetime |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 75 | |
| 76 | from google.auth import _helpers |
Jon Wayne Parrott | 807032c | 2016-10-18 09:38:26 -0700 | [diff] [blame] | 77 | from google.auth import _service_account_info |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 78 | from google.auth import credentials |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 79 | from google.auth import jwt |
| 80 | from google.oauth2 import _client |
| 81 | |
Albert-Jan Nijburg | b7b48f1 | 2017-11-08 20:15:18 +0000 | [diff] [blame] | 82 | _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 83 | |
| 84 | |
| 85 | class Credentials(credentials.Signing, |
| 86 | credentials.Scoped, |
| 87 | credentials.Credentials): |
| 88 | """Service account credentials |
| 89 | |
| 90 | Usually, you'll create these credentials with one of the helper |
| 91 | constructors. To create credentials using a Google service account |
| 92 | private key JSON file:: |
| 93 | |
| 94 | credentials = service_account.Credentials.from_service_account_file( |
| 95 | 'service-account.json') |
| 96 | |
| 97 | Or if you already have the service account file loaded:: |
| 98 | |
| 99 | service_account_info = json.load(open('service_account.json')) |
| 100 | credentials = service_account.Credentials.from_service_account_info( |
| 101 | service_account_info) |
| 102 | |
| 103 | Both helper methods pass on arguments to the constructor, so you can |
| 104 | specify additional scopes and a subject if necessary:: |
| 105 | |
| 106 | credentials = service_account.Credentials.from_service_account_file( |
| 107 | 'service-account.json', |
| 108 | scopes=['email'], |
| 109 | subject='user@example.com') |
| 110 | |
| 111 | The credentials are considered immutable. If you want to modify the scopes |
| 112 | or the subject used for delegation, use :meth:`with_scopes` or |
| 113 | :meth:`with_subject`:: |
| 114 | |
| 115 | scoped_credentials = credentials.with_scopes(['email']) |
| 116 | delegated_credentials = credentials.with_subject(subject) |
| 117 | """ |
| 118 | |
| 119 | def __init__(self, signer, service_account_email, token_uri, scopes=None, |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 120 | subject=None, project_id=None, additional_claims=None): |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 121 | """ |
| 122 | Args: |
| 123 | signer (google.auth.crypt.Signer): The signer used to sign JWTs. |
| 124 | service_account_email (str): The service account's email. |
| 125 | scopes (Sequence[str]): Scopes to request during the authorization |
| 126 | grant. |
| 127 | token_uri (str): The OAuth 2.0 Token URI. |
| 128 | subject (str): For domain-wide delegation, the email address of the |
| 129 | user to for which to request delegated access. |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 130 | project_id (str): Project ID associated with the service account |
| 131 | credential. |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 132 | additional_claims (Mapping[str, str]): Any additional claims for |
| 133 | the JWT assertion used in the authorization grant. |
| 134 | |
| 135 | .. note:: Typically one of the helper constructors |
| 136 | :meth:`from_service_account_file` or |
| 137 | :meth:`from_service_account_info` are used instead of calling the |
| 138 | constructor directly. |
| 139 | """ |
| 140 | super(Credentials, self).__init__() |
| 141 | |
| 142 | self._scopes = scopes |
| 143 | self._signer = signer |
| 144 | self._service_account_email = service_account_email |
| 145 | self._subject = subject |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 146 | self._project_id = project_id |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 147 | self._token_uri = token_uri |
| 148 | |
| 149 | if additional_claims is not None: |
| 150 | self._additional_claims = additional_claims |
| 151 | else: |
| 152 | self._additional_claims = {} |
| 153 | |
| 154 | @classmethod |
Jon Wayne Parrott | 807032c | 2016-10-18 09:38:26 -0700 | [diff] [blame] | 155 | def _from_signer_and_info(cls, signer, info, **kwargs): |
| 156 | """Creates a Credentials instance from a signer and service account |
| 157 | info. |
| 158 | |
| 159 | Args: |
| 160 | signer (google.auth.crypt.Signer): The signer used to sign JWTs. |
| 161 | info (Mapping[str, str]): The service account info. |
| 162 | kwargs: Additional arguments to pass to the constructor. |
| 163 | |
| 164 | Returns: |
| 165 | google.auth.jwt.Credentials: The constructed credentials. |
| 166 | |
| 167 | Raises: |
| 168 | ValueError: If the info is not in the expected format. |
| 169 | """ |
| 170 | return cls( |
| 171 | signer, |
| 172 | service_account_email=info['client_email'], |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 173 | token_uri=info['token_uri'], |
| 174 | project_id=info.get('project_id'), **kwargs) |
Jon Wayne Parrott | 807032c | 2016-10-18 09:38:26 -0700 | [diff] [blame] | 175 | |
| 176 | @classmethod |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 177 | def from_service_account_info(cls, info, **kwargs): |
| 178 | """Creates a Credentials instance from parsed service account info. |
| 179 | |
| 180 | Args: |
| 181 | info (Mapping[str, str]): The service account info in Google |
| 182 | format. |
| 183 | kwargs: Additional arguments to pass to the constructor. |
| 184 | |
| 185 | Returns: |
| 186 | google.auth.service_account.Credentials: The constructed |
| 187 | credentials. |
| 188 | |
| 189 | Raises: |
| 190 | ValueError: If the info is not in the expected format. |
| 191 | """ |
Jon Wayne Parrott | 807032c | 2016-10-18 09:38:26 -0700 | [diff] [blame] | 192 | signer = _service_account_info.from_dict( |
| 193 | info, require=['client_email', 'token_uri']) |
| 194 | return cls._from_signer_and_info(signer, info, **kwargs) |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 195 | |
| 196 | @classmethod |
| 197 | def from_service_account_file(cls, filename, **kwargs): |
| 198 | """Creates a Credentials instance from a service account json file. |
| 199 | |
| 200 | Args: |
| 201 | filename (str): The path to the service account json file. |
| 202 | kwargs: Additional arguments to pass to the constructor. |
| 203 | |
| 204 | Returns: |
| 205 | google.auth.service_account.Credentials: The constructed |
| 206 | credentials. |
| 207 | """ |
Jon Wayne Parrott | 807032c | 2016-10-18 09:38:26 -0700 | [diff] [blame] | 208 | info, signer = _service_account_info.from_filename( |
| 209 | filename, require=['client_email', 'token_uri']) |
| 210 | return cls._from_signer_and_info(signer, info, **kwargs) |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 211 | |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 212 | @property |
Jon Wayne Parrott | 61ffb05 | 2016-11-08 09:30:30 -0800 | [diff] [blame] | 213 | def service_account_email(self): |
| 214 | """The service account email.""" |
| 215 | return self._service_account_email |
| 216 | |
| 217 | @property |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 218 | def project_id(self): |
| 219 | """Project ID associated with this credential.""" |
| 220 | return self._project_id |
| 221 | |
| 222 | @property |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 223 | def requires_scopes(self): |
| 224 | """Checks if the credentials requires scopes. |
| 225 | |
| 226 | Returns: |
| 227 | bool: True if there are no scopes set otherwise False. |
| 228 | """ |
| 229 | return True if not self._scopes else False |
| 230 | |
| 231 | @_helpers.copy_docstring(credentials.Scoped) |
| 232 | def with_scopes(self, scopes): |
| 233 | return Credentials( |
| 234 | self._signer, |
| 235 | service_account_email=self._service_account_email, |
| 236 | scopes=scopes, |
| 237 | token_uri=self._token_uri, |
| 238 | subject=self._subject, |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 239 | project_id=self._project_id, |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 240 | additional_claims=self._additional_claims.copy()) |
| 241 | |
| 242 | def with_subject(self, subject): |
| 243 | """Create a copy of these credentials with the specified subject. |
| 244 | |
| 245 | Args: |
| 246 | subject (str): The subject claim. |
| 247 | |
| 248 | Returns: |
| 249 | google.auth.service_account.Credentials: A new credentials |
| 250 | instance. |
| 251 | """ |
| 252 | return Credentials( |
| 253 | self._signer, |
| 254 | service_account_email=self._service_account_email, |
| 255 | scopes=self._scopes, |
| 256 | token_uri=self._token_uri, |
| 257 | subject=subject, |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 258 | project_id=self._project_id, |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 259 | additional_claims=self._additional_claims.copy()) |
| 260 | |
Jon Wayne Parrott | 75c78b2 | 2017-03-23 13:14:53 -0700 | [diff] [blame] | 261 | def with_claims(self, additional_claims): |
| 262 | """Returns a copy of these credentials with modified claims. |
| 263 | |
| 264 | Args: |
| 265 | additional_claims (Mapping[str, str]): Any additional claims for |
| 266 | the JWT payload. This will be merged with the current |
| 267 | additional claims. |
| 268 | |
| 269 | Returns: |
| 270 | google.auth.service_account.Credentials: A new credentials |
| 271 | instance. |
| 272 | """ |
| 273 | new_additional_claims = copy.deepcopy(self._additional_claims) |
| 274 | new_additional_claims.update(additional_claims or {}) |
| 275 | |
| 276 | return Credentials( |
| 277 | self._signer, |
| 278 | service_account_email=self._service_account_email, |
| 279 | scopes=self._scopes, |
| 280 | token_uri=self._token_uri, |
| 281 | subject=self._subject, |
Hiranya Jayathilaka | 6a3f0ec | 2017-08-10 09:11:02 -0700 | [diff] [blame] | 282 | project_id=self._project_id, |
Jon Wayne Parrott | 75c78b2 | 2017-03-23 13:14:53 -0700 | [diff] [blame] | 283 | additional_claims=new_additional_claims) |
| 284 | |
Jon Wayne Parrott | ab9eba3 | 2016-10-17 10:49:57 -0700 | [diff] [blame] | 285 | def _make_authorization_grant_assertion(self): |
| 286 | """Create the OAuth 2.0 assertion. |
| 287 | |
| 288 | This assertion is used during the OAuth 2.0 grant to acquire an |
| 289 | access token. |
| 290 | |
| 291 | Returns: |
| 292 | bytes: The authorization grant assertion. |
| 293 | """ |
| 294 | now = _helpers.utcnow() |
| 295 | lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS) |
| 296 | expiry = now + lifetime |
| 297 | |
| 298 | payload = { |
| 299 | 'iat': _helpers.datetime_to_secs(now), |
| 300 | 'exp': _helpers.datetime_to_secs(expiry), |
| 301 | # The issuer must be the service account email. |
| 302 | 'iss': self._service_account_email, |
| 303 | # The audience must be the auth token endpoint's URI |
| 304 | 'aud': self._token_uri, |
| 305 | 'scope': _helpers.scopes_to_string(self._scopes or ()) |
| 306 | } |
| 307 | |
| 308 | payload.update(self._additional_claims) |
| 309 | |
| 310 | # The subject can be a user email for domain-wide delegation. |
| 311 | if self._subject: |
| 312 | payload.setdefault('sub', self._subject) |
| 313 | |
| 314 | token = jwt.encode(self._signer, payload) |
| 315 | |
| 316 | return token |
| 317 | |
| 318 | @_helpers.copy_docstring(credentials.Credentials) |
| 319 | def refresh(self, request): |
| 320 | assertion = self._make_authorization_grant_assertion() |
| 321 | access_token, expiry, _ = _client.jwt_grant( |
| 322 | request, self._token_uri, assertion) |
| 323 | self.token = access_token |
| 324 | self.expiry = expiry |
| 325 | |
| 326 | @_helpers.copy_docstring(credentials.Signing) |
| 327 | def sign_bytes(self, message): |
| 328 | return self._signer.sign(message) |
Jon Wayne Parrott | 4c883f0 | 2016-12-02 14:26:33 -0800 | [diff] [blame] | 329 | |
| 330 | @property |
| 331 | @_helpers.copy_docstring(credentials.Signing) |
Jon Wayne Parrott | d722167 | 2017-02-16 09:05:11 -0800 | [diff] [blame] | 332 | def signer(self): |
| 333 | return self._signer |
| 334 | |
| 335 | @property |
| 336 | @_helpers.copy_docstring(credentials.Signing) |
Jon Wayne Parrott | 4c883f0 | 2016-12-02 14:26:33 -0800 | [diff] [blame] | 337 | def signer_email(self): |
| 338 | return self._service_account_email |