blob: e6e84d26add1ea690b03bd401ca315d1cce38930 [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):
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080037 """Signs messages using the App Engine App Identity service.
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080038
39 This can be used in place of :class:`google.auth.crypt.Signer` when
40 running in the App Engine standard environment.
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080041
42 .. warning::
43 The App Identity service signs bytes using Google-managed keys.
44 Because of this it's possible that the key used to sign bytes will
45 change. In some cases this change can occur between successive calls
46 to :attr:`key_id` and :meth:`sign`. This could result in a signature
47 that was signed with a different key than the one indicated by
48 :attr:`key_id`. It's recommended that if you use this in your code
49 that you account for this behavior by building in retry logic.
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080050 """
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080051
52 @property
53 def key_id(self):
54 """Optional[str]: The key ID used to identify this private key.
55
56 .. note::
57 This makes a request to the App Identity service.
58 """
59 key_id, _ = app_identity.sign_blob(b'')
60 return key_id
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080061
62 @staticmethod
63 def sign(message):
64 """Signs a message.
65
66 Args:
67 message (Union[str, bytes]): The message to be signed.
68
69 Returns:
70 bytes: The signature of the message.
71 """
72 message = _helpers.to_bytes(message)
Jon Wayne Parrott5b4e9c82017-02-15 16:44:00 -080073 _, signature = app_identity.sign_blob(message)
74 return signature
Jon Wayne Parrott256d2bf2016-12-13 16:12:02 -080075
76
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070077def get_project_id():
78 """Gets the project ID for the current App Engine application.
79
80 Returns:
81 str: The project ID
82
83 Raises:
84 EnvironmentError: If the App Engine APIs are unavailable.
85 """
Jon Wayne Parrott20e6e582016-12-19 10:21:23 -080086 # pylint: disable=missing-raises-doc
87 # Pylint rightfully thinks EnvironmentError is OSError, but doesn't
88 # realize it's a valid alias.
Jon Wayne Parrott2148fde2016-10-24 13:44:25 -070089 if app_identity is None:
90 raise EnvironmentError(
91 'The App Engine APIs are not available.')
92 return app_identity.get_application_id()
93
94
Jon Wayne Parrott04714752016-10-24 10:00:58 -070095class Credentials(credentials.Scoped, credentials.Signing,
96 credentials.Credentials):
97 """App Engine standard environment credentials.
98
99 These credentials use the App Engine App Identity API to obtain access
100 tokens.
101 """
102
103 def __init__(self, scopes=None, service_account_id=None):
104 """
105 Args:
106 scopes (Sequence[str]): Scopes to request from the App Identity
107 API.
108 service_account_id (str): The service account ID passed into
109 :func:`google.appengine.api.app_identity.get_access_token`.
110 If not specified, the default application service account
111 ID will be used.
112
113 Raises:
114 EnvironmentError: If the App Engine APIs are unavailable.
115 """
Jon Wayne Parrott20e6e582016-12-19 10:21:23 -0800116 # pylint: disable=missing-raises-doc
117 # Pylint rightfully thinks EnvironmentError is OSError, but doesn't
118 # realize it's a valid alias.
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700119 if app_identity is None:
120 raise EnvironmentError(
121 'The App Engine APIs are not available.')
122
123 super(Credentials, self).__init__()
124 self._scopes = scopes
125 self._service_account_id = service_account_id
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800126 self._signer = Signer()
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700127
128 @_helpers.copy_docstring(credentials.Credentials)
129 def refresh(self, request):
130 # pylint: disable=unused-argument
131 token, ttl = app_identity.get_access_token(
132 self._scopes, self._service_account_id)
133 expiry = _helpers.utcnow() + datetime.timedelta(seconds=ttl)
134
135 self.token, self.expiry = token, expiry
136
137 @property
Jon Wayne Parrott61ffb052016-11-08 09:30:30 -0800138 def service_account_email(self):
139 """The service account email."""
140 if self._service_account_id is None:
141 self._service_account_id = app_identity.get_service_account_name()
142 return self._service_account_id
143
144 @property
Jon Wayne Parrott04714752016-10-24 10:00:58 -0700145 def requires_scopes(self):
146 """Checks if the credentials requires scopes.
147
148 Returns:
149 bool: True if there are no scopes set otherwise False.
150 """
151 return not self._scopes
152
153 @_helpers.copy_docstring(credentials.Scoped)
154 def with_scopes(self, scopes):
155 return Credentials(
156 scopes=scopes, service_account_id=self._service_account_id)
157
158 @_helpers.copy_docstring(credentials.Signing)
159 def sign_bytes(self, message):
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800160 return self._signer.sign(message)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800161
162 @property
163 @_helpers.copy_docstring(credentials.Signing)
164 def signer_email(self):
165 return self.service_account_email
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800166
167 @property
168 @_helpers.copy_docstring(credentials.Signing)
169 def signer(self):
170 return self._signer