blob: 846bcec08b49efb2c5a64aaea3afca42a1a4cc1b [file] [log] [blame]
Jon Wayne Parrott04714752016-10-24 10:00:58 -07001# 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
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
29
30try:
31 from google.appengine.api import app_identity
32except ImportError:
33 app_identity = None
34
35
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080036class Signer(object):
37 """Signs messages using the App Engine app identity service.
38
39 This can be used in place of :class:`google.auth.crypt.Signer` when
40 running in the App Engine standard environment.
41 """
42 def __init__(self):
43 self.key_id = None
44
45 @staticmethod
46 def sign(message):
47 """Signs a message.
48
49 Args:
50 message (Union[str, bytes]): The message to be signed.
51
52 Returns:
53 bytes: The signature of the message.
54 """
55 message = _helpers.to_bytes(message)
56 return app_identity.sign_blob(message)
57
58
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070059def get_project_id():
60 """Gets the project ID for the current App Engine application.
61
62 Returns:
63 str: The project ID
64
65 Raises:
66 EnvironmentError: If the App Engine APIs are unavailable.
67 """
68 if app_identity is None:
69 raise EnvironmentError(
70 'The App Engine APIs are not available.')
71 return app_identity.get_application_id()
72
73
Jon Wayne Parrott04714752016-10-24 10:00:58 -070074class Credentials(credentials.Scoped, credentials.Signing,
75 credentials.Credentials):
76 """App Engine standard environment credentials.
77
78 These credentials use the App Engine App Identity API to obtain access
79 tokens.
80 """
81
82 def __init__(self, scopes=None, service_account_id=None):
83 """
84 Args:
85 scopes (Sequence[str]): Scopes to request from the App Identity
86 API.
87 service_account_id (str): The service account ID passed into
88 :func:`google.appengine.api.app_identity.get_access_token`.
89 If not specified, the default application service account
90 ID will be used.
91
92 Raises:
93 EnvironmentError: If the App Engine APIs are unavailable.
94 """
95 if app_identity is None:
96 raise EnvironmentError(
97 'The App Engine APIs are not available.')
98
99 super(Credentials, self).__init__()
100 self._scopes = scopes
101 self._service_account_id = service_account_id
102
103 @_helpers.copy_docstring(credentials.Credentials)
104 def refresh(self, request):
105 # pylint: disable=unused-argument
106 token, ttl = app_identity.get_access_token(
107 self._scopes, self._service_account_id)
108 expiry = _helpers.utcnow() + datetime.timedelta(seconds=ttl)
109
110 self.token, self.expiry = token, expiry
111
112 @property
Jon Wayne Parrott61ffb052016-11-08 09:30:30 -0800113 def service_account_email(self):
114 """The service account email."""
115 if self._service_account_id is None:
116 self._service_account_id = app_identity.get_service_account_name()
117 return self._service_account_id
118
119 @property
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700120 def requires_scopes(self):
121 """Checks if the credentials requires scopes.
122
123 Returns:
124 bool: True if there are no scopes set otherwise False.
125 """
126 return not self._scopes
127
128 @_helpers.copy_docstring(credentials.Scoped)
129 def with_scopes(self, scopes):
130 return Credentials(
131 scopes=scopes, service_account_id=self._service_account_id)
132
133 @_helpers.copy_docstring(credentials.Signing)
134 def sign_bytes(self, message):
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -0800135 return Signer().sign(message)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800136
137 @property
138 @_helpers.copy_docstring(credentials.Signing)
139 def signer_email(self):
140 return self.service_account_email