Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(711)

Side by Side Diff: client/third_party/oauth2client/contrib/gce.py

Issue 1768993002: Update oauth2client to v2.0.1 and googleapiclient to v1.5.0. Base URL: git@github.com:luci/luci-py.git@master
Patch Set: . Created 4 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2014 Google Inc. All rights reserved.
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 """Utilities for Google Compute Engine
16
17 Utilities for making it easier to use OAuth 2.0 on Google Compute Engine.
18 """
19
20 import json
21 import logging
22 import warnings
23
24 import httplib2
25 from six.moves import http_client
26 from six.moves import urllib
27
28 from oauth2client._helpers import _from_bytes
29 from oauth2client import util
30 from oauth2client.client import HttpAccessTokenRefreshError
31 from oauth2client.client import AssertionCredentials
32
33
34 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
35
36 logger = logging.getLogger(__name__)
37
38 # URI Template for the endpoint that returns access_tokens.
39 _METADATA_ROOT = ('http://metadata.google.internal/computeMetadata/v1/'
40 'instance/service-accounts/default/')
41 META = _METADATA_ROOT + 'token'
42 _DEFAULT_EMAIL_METADATA = _METADATA_ROOT + 'email'
43 _SCOPES_WARNING = """\
44 You have requested explicit scopes to be used with a GCE service account.
45 Using this argument will have no effect on the actual scopes for tokens
46 requested. These scopes are set at VM instance creation time and
47 can't be overridden in the request.
48 """
49
50
51 def _get_service_account_email(http_request=None):
52 """Get the GCE service account email from the current environment.
53
54 Args:
55 http_request: callable, (Optional) a callable that matches the method
56 signature of httplib2.Http.request, used to make
57 the request to the metadata service.
58
59 Returns:
60 tuple, A pair where the first entry is an optional response (from a
61 failed request) and the second is service account email found (as
62 a string).
63 """
64 if http_request is None:
65 http_request = httplib2.Http().request
66 response, content = http_request(
67 _DEFAULT_EMAIL_METADATA, headers={'Metadata-Flavor': 'Google'})
68 if response.status == http_client.OK:
69 content = _from_bytes(content)
70 return None, content
71 else:
72 return response, content
73
74
75 class AppAssertionCredentials(AssertionCredentials):
76 """Credentials object for Compute Engine Assertion Grants
77
78 This object will allow a Compute Engine instance to identify itself to
79 Google and other OAuth 2.0 servers that can verify assertions. It can be
80 used for the purpose of accessing data stored under an account assigned to
81 the Compute Engine instance itself.
82
83 This credential does not require a flow to instantiate because it
84 represents a two legged flow, and therefore has all of the required
85 information to generate and refresh its own access tokens.
86 """
87
88 @util.positional(2)
89 def __init__(self, scope='', **kwargs):
90 """Constructor for AppAssertionCredentials
91
92 Args:
93 scope: string or iterable of strings, scope(s) of the credentials
94 being requested. Using this argument will have no effect on
95 the actual scopes for tokens requested. These scopes are
96 set at VM instance creation time and won't change.
97 """
98 if scope:
99 warnings.warn(_SCOPES_WARNING)
100 # This is just provided for backwards compatibility, but is not
101 # used by this class.
102 self.scope = util.scopes_to_string(scope)
103 self.kwargs = kwargs
104
105 # Assertion type is no longer used, but still in the
106 # parent class signature.
107 super(AppAssertionCredentials, self).__init__(None)
108 self._service_account_email = None
109
110 @classmethod
111 def from_json(cls, json_data):
112 data = json.loads(_from_bytes(json_data))
113 return AppAssertionCredentials(data['scope'])
114
115 def _refresh(self, http_request):
116 """Refreshes the access_token.
117
118 Skip all the storage hoops and just refresh using the API.
119
120 Args:
121 http_request: callable, a callable that matches the method
122 signature of httplib2.Http.request, used to make
123 the refresh request.
124
125 Raises:
126 HttpAccessTokenRefreshError: When the refresh fails.
127 """
128 response, content = http_request(
129 META, headers={'Metadata-Flavor': 'Google'})
130 content = _from_bytes(content)
131 if response.status == http_client.OK:
132 try:
133 token_content = json.loads(content)
134 except Exception as e:
135 raise HttpAccessTokenRefreshError(str(e),
136 status=response.status)
137 self.access_token = token_content['access_token']
138 else:
139 if response.status == http_client.NOT_FOUND:
140 content += (' This can occur if a VM was created'
141 ' with no service account or scopes.')
142 raise HttpAccessTokenRefreshError(content, status=response.status)
143
144 @property
145 def serialization_data(self):
146 raise NotImplementedError(
147 'Cannot serialize credentials for GCE service accounts.')
148
149 def create_scoped_required(self):
150 return False
151
152 def create_scoped(self, scopes):
153 return AppAssertionCredentials(scopes, **self.kwargs)
154
155 def sign_blob(self, blob):
156 """Cryptographically sign a blob (of bytes).
157
158 This method is provided to support a common interface, but
159 the actual key used for a Google Compute Engine service account
160 is not available, so it can't be used to sign content.
161
162 Args:
163 blob: bytes, Message to be signed.
164
165 Raises:
166 NotImplementedError, always.
167 """
168 raise NotImplementedError(
169 'Compute Engine service accounts cannot sign blobs')
170
171 @property
172 def service_account_email(self):
173 """Get the email for the current service account.
174
175 Uses the Google Compute Engine metadata service to retrieve the email
176 of the default service account.
177
178 Returns:
179 string, The email associated with the Google Compute Engine
180 service account.
181
182 Raises:
183 AttributeError, if the email can not be retrieved from the Google
184 Compute Engine metadata service.
185 """
186 if self._service_account_email is None:
187 failure, email = _get_service_account_email()
188 if failure is None:
189 self._service_account_email = email
190 else:
191 raise AttributeError('Failed to retrieve the email from the '
192 'Google Compute Engine metadata service',
193 failure, email)
194 return self._service_account_email
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698