blob: 6fb89d8302e1b0740ca0b8b9f0604804904d8f0e [file] [log] [blame]
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -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
15
16"""Interfaces for credentials."""
17
18import abc
19
20import six
21
22from google.auth import _helpers
23
24
25@six.add_metaclass(abc.ABCMeta)
26class Credentials(object):
27 """Base class for all credentials.
28
29 All credentials have a :attr:`token` that is used for authentication and
30 may also optionally set an :attr:`expiry` to indicate when the token will
31 no longer be valid.
32
33 Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
34 Credentials can do this automatically before the first HTTP request in
35 :meth:`before_request`.
36
37 Although the token and expiration will change as the credentials are
38 :meth:`refreshed <refresh>` and used, credentials should be considered
39 immutable. Various credentials will accept configuration such as private
40 keys, scopes, and other options. These options are not changeable after
41 construction. Some classes will provide mechanisms to copy the credentials
42 with modifications such as :meth:`ScopedCredentials.with_scopes`.
43 """
44 def __init__(self):
45 self.token = None
46 """str: The bearer token that can be used in HTTP headers to make
47 authenticated requests."""
48 self.expiry = None
49 """Optional[datetime]: When the token expires and is no longer valid.
50 If this is None, the token is assumed to never expire."""
51
52 @property
53 def expired(self):
54 """Checks if the credentials are expired.
55
56 Note that credentials can be invalid but not expired becaue Credentials
57 with :attr:`expiry` set to None is considered to never expire.
58 """
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -070059 # Err on the side of reporting expiration early so that we avoid
60 # the 403-refresh-retry loop.
61 adjusted_now = _helpers.utcnow() - _helpers.CLOCK_SKEW
62 return self.expiry is not None and self.expiry <= adjusted_now
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070063
64 @property
65 def valid(self):
66 """Checks the validity of the credentials.
67
68 This is True if the credentials have a :attr:`token` and the token
69 is not :attr:`expired`.
70 """
71 return self.token is not None and not self.expired
72
73 @abc.abstractmethod
74 def refresh(self, request):
75 """Refreshes the access token.
76
77 Args:
78 request (google.auth.transport.Request): The object used to make
79 HTTP requests.
80
81 Raises:
82 google.auth.exceptions.RefreshError: If the credentials could
83 not be refreshed.
84 """
85 # pylint: disable=missing-raises-doc
86 # (pylint doesn't recognize that this is abstract)
87 raise NotImplementedError('Refresh must be implemented')
88
89 def apply(self, headers, token=None):
90 """Apply the token to the authentication header.
91
92 Args:
93 headers (Mapping): The HTTP request headers.
94 token (Optional[str]): If specified, overrides the current access
95 token.
96 """
97 headers['authorization'] = 'Bearer {}'.format(
98 _helpers.from_bytes(token or self.token))
99
100 def before_request(self, request, method, url, headers):
101 """Performs credential-specific before request logic.
102
103 Refreshes the credentials if necessary, then calls :meth:`apply` to
104 apply the token to the authentication header.
105
106 Args:
Jon Wayne Parrotta0425492016-10-17 10:48:35 -0700107 request (google.auth.transport.Request): The object used to make
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700108 HTTP requests.
Jon Wayne Parrotta2098192017-02-22 09:27:32 -0800109 method (str): The request's HTTP method or the RPC method being
110 invoked.
111 url (str): The request's URI or the RPC service's URI.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700112 headers (Mapping): The request's headers.
113 """
114 # pylint: disable=unused-argument
115 # (Subclasses may use these arguments to ascertain information about
116 # the http request.)
117 if not self.valid:
118 self.refresh(request)
119 self.apply(headers)
120
121
122@six.add_metaclass(abc.ABCMeta)
123class Scoped(object):
124 """Interface for scoped credentials.
125
126 OAuth 2.0-based credentials allow limiting access using scopes as described
127 in `RFC6749 Section 3.3`_.
128 If a credential class implements this interface then the credentials either
129 use scopes in their implementation.
130
131 Some credentials require scopes in order to obtain a token. You can check
132 if scoping is necessary with :attr:`requires_scopes`::
133
134 if credentials.requires_scopes:
135 # Scoping is required.
136 credentials = credentials.create_scoped(['one', 'two'])
137
138 Credentials that require scopes must either be constructed with scopes::
139
140 credentials = SomeScopedCredentials(scopes=['one', 'two'])
141
142 Or must copy an existing instance using :meth:`with_scopes`::
143
144 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
145
146 Some credentials have scopes but do not allow or require scopes to be set,
147 these credentials can be used as-is.
148
149 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
150 """
151 def __init__(self):
152 super(Scoped, self).__init__()
153 self._scopes = None
154
155 @property
156 def scopes(self):
157 """Sequence[str]: the credentials' current set of scopes."""
158 return self._scopes
159
160 @abc.abstractproperty
161 def requires_scopes(self):
162 """True if these credentials require scopes to obtain an access token.
163 """
164 return False
165
166 @abc.abstractmethod
167 def with_scopes(self, scopes):
168 """Create a copy of these credentials with the specified scopes.
169
170 Args:
171 scopes (Sequence[str]): The list of scopes to request.
172
173 Raises:
174 NotImplementedError: If the credentials' scopes can not be changed.
175 This can be avoided by checking :attr:`requires_scopes` before
176 calling this method.
177 """
178 raise NotImplementedError('This class does not require scoping.')
179
180 def has_scopes(self, scopes):
181 """Checks if the credentials have the given scopes.
182
183 .. warning: This method is not guaranteed to be accurate if the
184 credentials are :attr:`~Credentials.invalid`.
185
186 Returns:
187 bool: True if the credentials have the given scopes.
188 """
189 return set(scopes).issubset(set(self._scopes or []))
190
191
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700192def with_scopes_if_required(credentials, scopes):
193 """Creates a copy of the credentials with scopes if scoping is required.
194
195 This helper function is useful when you do not know (or care to know) the
196 specific type of credentials you are using (such as when you use
197 :func:`google.auth.default`). This function will call
198 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
199 the credentials require scoping. Otherwise, it will return the credentials
200 as-is.
201
202 Args:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800203 credentials (google.auth.credentials.Credentials): The credentials to
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800204 scope if necessary.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700205 scopes (Sequence[str]): The list of scopes to use.
206
207 Returns:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800208 google.auth.credentials.Credentials: Either a new set of scoped
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800209 credentials, or the passed in credentials instance if no scoping
210 was required.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700211 """
212 if isinstance(credentials, Scoped) and credentials.requires_scopes:
213 return credentials.with_scopes(scopes)
214 else:
215 return credentials
216
217
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700218@six.add_metaclass(abc.ABCMeta)
219class Signing(object):
220 """Interface for credentials that can cryptographically sign messages."""
221
222 @abc.abstractmethod
223 def sign_bytes(self, message):
224 """Signs the given message.
225
226 Args:
227 message (bytes): The message to sign.
228
229 Returns:
230 bytes: The message's cryptographic signature.
231 """
232 # pylint: disable=missing-raises-doc,redundant-returns-doc
233 # (pylint doesn't recognize that this is abstract)
234 raise NotImplementedError('Sign bytes must be implemented.')
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800235
236 @abc.abstractproperty
237 def signer_email(self):
238 """Optional[str]: An email address that identifies the signer."""
239 # pylint: disable=missing-raises-doc
240 # (pylint doesn't recognize that this is abstract)
241 raise NotImplementedError('Signer email must be implemented.')
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800242
243 @abc.abstractproperty
244 def signer(self):
245 """google.auth.crypt.Signer: The signer used to sign bytes."""
246 # pylint: disable=missing-raises-doc
247 # (pylint doesn't recognize that this is abstract)
248 raise NotImplementedError('Signer must be implemented.')