1
2
3
4
5
6
7
8
9
10
11
12
13
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 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
21
22 import json
23 import logging
24 from six.moves import urllib
25
26 from oauth2client import util
27 from oauth2client.client import AccessTokenRefreshError
28 from oauth2client.client import AssertionCredentials
29
30 logger = logging.getLogger(__name__)
31
32
33 META = ('http://metadata.google.internal/0.1/meta-data/service-accounts/'
34 'default/acquire{?scope}')
38 """Credentials object for Compute Engine Assertion Grants
39
40 This object will allow a Compute Engine instance to identify itself to
41 Google and other OAuth 2.0 servers that can verify assertions. It can be used
42 for the purpose of accessing data stored under an account assigned to the
43 Compute Engine instance itself.
44
45 This credential does not require a flow to instantiate because it represents
46 a two legged flow, and therefore has all of the required information to
47 generate and refresh its own access tokens.
48 """
49
50 @util.positional(2)
52 """Constructor for AppAssertionCredentials
53
54 Args:
55 scope: string or iterable of strings, scope(s) of the credentials being
56 requested.
57 """
58 self.scope = util.scopes_to_string(scope)
59 self.kwargs = kwargs
60
61
62 super(AppAssertionCredentials, self).__init__(None)
63
64 @classmethod
68
70 """Refreshes the access_token.
71
72 Skip all the storage hoops and just refresh using the API.
73
74 Args:
75 http_request: callable, a callable that matches the method signature of
76 httplib2.Http.request, used to make the refresh request.
77
78 Raises:
79 AccessTokenRefreshError: When the refresh fails.
80 """
81 query = '?scope=%s' % urllib.parse.quote(self.scope, '')
82 uri = META.replace('{?scope}', query)
83 response, content = http_request(uri)
84 if response.status == 200:
85 try:
86 d = json.loads(content)
87 except Exception as e:
88 raise AccessTokenRefreshError(str(e))
89 self.access_token = d['accessToken']
90 else:
91 if response.status == 404:
92 content += (' This can occur if a VM was created'
93 ' with no service account or scopes.')
94 raise AccessTokenRefreshError(content)
95
96 @property
98 raise NotImplementedError(
99 'Cannot serialize credentials for GCE service accounts.')
100
102 return not self.scope
103
106