client.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  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. """An OAuth 2.0 client.
  15. Tools for interacting with OAuth 2.0 protected resources.
  16. """
  17. import collections
  18. import copy
  19. import datetime
  20. import json
  21. import logging
  22. import os
  23. import shutil
  24. import socket
  25. import sys
  26. import tempfile
  27. import six
  28. from six.moves import http_client
  29. from six.moves import urllib
  30. import oauth2client
  31. from oauth2client import _helpers
  32. from oauth2client import _pkce
  33. from oauth2client import clientsecrets
  34. from oauth2client import transport
  35. HAS_OPENSSL = False
  36. HAS_CRYPTO = False
  37. try:
  38. from oauth2client import crypt
  39. HAS_CRYPTO = True
  40. HAS_OPENSSL = crypt.OpenSSLVerifier is not None
  41. except ImportError: # pragma: NO COVER
  42. pass
  43. logger = logging.getLogger(__name__)
  44. # Expiry is stored in RFC3339 UTC format
  45. EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  46. # Which certs to use to validate id_tokens received.
  47. ID_TOKEN_VERIFICATION_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
  48. # This symbol previously had a typo in the name; we keep the old name
  49. # around for now, but will remove it in the future.
  50. ID_TOKEN_VERIFICATON_CERTS = ID_TOKEN_VERIFICATION_CERTS
  51. # Constant to use for the out of band OAuth 2.0 flow.
  52. OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
  53. # The value representing user credentials.
  54. AUTHORIZED_USER = 'authorized_user'
  55. # The value representing service account credentials.
  56. SERVICE_ACCOUNT = 'service_account'
  57. # The environment variable pointing the file with local
  58. # Application Default Credentials.
  59. GOOGLE_APPLICATION_CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
  60. # The ~/.config subdirectory containing gcloud credentials. Intended
  61. # to be swapped out in tests.
  62. _CLOUDSDK_CONFIG_DIRECTORY = 'gcloud'
  63. # The environment variable name which can replace ~/.config if set.
  64. _CLOUDSDK_CONFIG_ENV_VAR = 'CLOUDSDK_CONFIG'
  65. # The error message we show users when we can't find the Application
  66. # Default Credentials.
  67. ADC_HELP_MSG = (
  68. 'The Application Default Credentials are not available. They are '
  69. 'available if running in Google Compute Engine. Otherwise, the '
  70. 'environment variable ' +
  71. GOOGLE_APPLICATION_CREDENTIALS +
  72. ' must be defined pointing to a file defining the credentials. See '
  73. 'https://developers.google.com/accounts/docs/'
  74. 'application-default-credentials for more information.')
  75. _WELL_KNOWN_CREDENTIALS_FILE = 'application_default_credentials.json'
  76. # The access token along with the seconds in which it expires.
  77. AccessTokenInfo = collections.namedtuple(
  78. 'AccessTokenInfo', ['access_token', 'expires_in'])
  79. DEFAULT_ENV_NAME = 'UNKNOWN'
  80. # If set to True _get_environment avoid GCE check (_detect_gce_environment)
  81. NO_GCE_CHECK = os.getenv('NO_GCE_CHECK', 'False')
  82. # Timeout in seconds to wait for the GCE metadata server when detecting the
  83. # GCE environment.
  84. try:
  85. GCE_METADATA_TIMEOUT = int(os.getenv('GCE_METADATA_TIMEOUT', 3))
  86. except ValueError: # pragma: NO COVER
  87. GCE_METADATA_TIMEOUT = 3
  88. _SERVER_SOFTWARE = 'SERVER_SOFTWARE'
  89. _GCE_METADATA_URI = 'http://' + os.getenv('GCE_METADATA_IP', '169.254.169.254')
  90. _METADATA_FLAVOR_HEADER = 'metadata-flavor' # lowercase header
  91. _DESIRED_METADATA_FLAVOR = 'Google'
  92. _GCE_HEADERS = {_METADATA_FLAVOR_HEADER: _DESIRED_METADATA_FLAVOR}
  93. # Expose utcnow() at module level to allow for
  94. # easier testing (by replacing with a stub).
  95. _UTCNOW = datetime.datetime.utcnow
  96. # NOTE: These names were previously defined in this module but have been
  97. # moved into `oauth2client.transport`,
  98. clean_headers = transport.clean_headers
  99. MemoryCache = transport.MemoryCache
  100. REFRESH_STATUS_CODES = transport.REFRESH_STATUS_CODES
  101. class SETTINGS(object):
  102. """Settings namespace for globally defined values."""
  103. env_name = None
  104. class Error(Exception):
  105. """Base error for this module."""
  106. class FlowExchangeError(Error):
  107. """Error trying to exchange an authorization grant for an access token."""
  108. class AccessTokenRefreshError(Error):
  109. """Error trying to refresh an expired access token."""
  110. class HttpAccessTokenRefreshError(AccessTokenRefreshError):
  111. """Error (with HTTP status) trying to refresh an expired access token."""
  112. def __init__(self, *args, **kwargs):
  113. super(HttpAccessTokenRefreshError, self).__init__(*args)
  114. self.status = kwargs.get('status')
  115. class TokenRevokeError(Error):
  116. """Error trying to revoke a token."""
  117. class UnknownClientSecretsFlowError(Error):
  118. """The client secrets file called for an unknown type of OAuth 2.0 flow."""
  119. class AccessTokenCredentialsError(Error):
  120. """Having only the access_token means no refresh is possible."""
  121. class VerifyJwtTokenError(Error):
  122. """Could not retrieve certificates for validation."""
  123. class NonAsciiHeaderError(Error):
  124. """Header names and values must be ASCII strings."""
  125. class ApplicationDefaultCredentialsError(Error):
  126. """Error retrieving the Application Default Credentials."""
  127. class OAuth2DeviceCodeError(Error):
  128. """Error trying to retrieve a device code."""
  129. class CryptoUnavailableError(Error, NotImplementedError):
  130. """Raised when a crypto library is required, but none is available."""
  131. def _parse_expiry(expiry):
  132. if expiry and isinstance(expiry, datetime.datetime):
  133. return expiry.strftime(EXPIRY_FORMAT)
  134. else:
  135. return None
  136. class Credentials(object):
  137. """Base class for all Credentials objects.
  138. Subclasses must define an authorize() method that applies the credentials
  139. to an HTTP transport.
  140. Subclasses must also specify a classmethod named 'from_json' that takes a
  141. JSON string as input and returns an instantiated Credentials object.
  142. """
  143. NON_SERIALIZED_MEMBERS = frozenset(['store'])
  144. def authorize(self, http):
  145. """Take an httplib2.Http instance (or equivalent) and authorizes it.
  146. Authorizes it for the set of credentials, usually by replacing
  147. http.request() with a method that adds in the appropriate headers and
  148. then delegates to the original Http.request() method.
  149. Args:
  150. http: httplib2.Http, an http object to be used to make the refresh
  151. request.
  152. """
  153. raise NotImplementedError
  154. def refresh(self, http):
  155. """Forces a refresh of the access_token.
  156. Args:
  157. http: httplib2.Http, an http object to be used to make the refresh
  158. request.
  159. """
  160. raise NotImplementedError
  161. def revoke(self, http):
  162. """Revokes a refresh_token and makes the credentials void.
  163. Args:
  164. http: httplib2.Http, an http object to be used to make the revoke
  165. request.
  166. """
  167. raise NotImplementedError
  168. def apply(self, headers):
  169. """Add the authorization to the headers.
  170. Args:
  171. headers: dict, the headers to add the Authorization header to.
  172. """
  173. raise NotImplementedError
  174. def _to_json(self, strip, to_serialize=None):
  175. """Utility function that creates JSON repr. of a Credentials object.
  176. Args:
  177. strip: array, An array of names of members to exclude from the
  178. JSON.
  179. to_serialize: dict, (Optional) The properties for this object
  180. that will be serialized. This allows callers to
  181. modify before serializing.
  182. Returns:
  183. string, a JSON representation of this instance, suitable to pass to
  184. from_json().
  185. """
  186. curr_type = self.__class__
  187. if to_serialize is None:
  188. to_serialize = copy.copy(self.__dict__)
  189. else:
  190. # Assumes it is a str->str dictionary, so we don't deep copy.
  191. to_serialize = copy.copy(to_serialize)
  192. for member in strip:
  193. if member in to_serialize:
  194. del to_serialize[member]
  195. to_serialize['token_expiry'] = _parse_expiry(
  196. to_serialize.get('token_expiry'))
  197. # Add in information we will need later to reconstitute this instance.
  198. to_serialize['_class'] = curr_type.__name__
  199. to_serialize['_module'] = curr_type.__module__
  200. for key, val in to_serialize.items():
  201. if isinstance(val, bytes):
  202. to_serialize[key] = val.decode('utf-8')
  203. if isinstance(val, set):
  204. to_serialize[key] = list(val)
  205. return json.dumps(to_serialize)
  206. def to_json(self):
  207. """Creating a JSON representation of an instance of Credentials.
  208. Returns:
  209. string, a JSON representation of this instance, suitable to pass to
  210. from_json().
  211. """
  212. return self._to_json(self.NON_SERIALIZED_MEMBERS)
  213. @classmethod
  214. def new_from_json(cls, json_data):
  215. """Utility class method to instantiate a Credentials subclass from JSON.
  216. Expects the JSON string to have been produced by to_json().
  217. Args:
  218. json_data: string or bytes, JSON from to_json().
  219. Returns:
  220. An instance of the subclass of Credentials that was serialized with
  221. to_json().
  222. """
  223. json_data_as_unicode = _helpers._from_bytes(json_data)
  224. data = json.loads(json_data_as_unicode)
  225. # Find and call the right classmethod from_json() to restore
  226. # the object.
  227. module_name = data['_module']
  228. try:
  229. module_obj = __import__(module_name)
  230. except ImportError:
  231. # In case there's an object from the old package structure,
  232. # update it
  233. module_name = module_name.replace('.googleapiclient', '')
  234. module_obj = __import__(module_name)
  235. module_obj = __import__(module_name,
  236. fromlist=module_name.split('.')[:-1])
  237. kls = getattr(module_obj, data['_class'])
  238. return kls.from_json(json_data_as_unicode)
  239. @classmethod
  240. def from_json(cls, unused_data):
  241. """Instantiate a Credentials object from a JSON description of it.
  242. The JSON should have been produced by calling .to_json() on the object.
  243. Args:
  244. unused_data: dict, A deserialized JSON object.
  245. Returns:
  246. An instance of a Credentials subclass.
  247. """
  248. return Credentials()
  249. class Flow(object):
  250. """Base class for all Flow objects."""
  251. pass
  252. class Storage(object):
  253. """Base class for all Storage objects.
  254. Store and retrieve a single credential. This class supports locking
  255. such that multiple processes and threads can operate on a single
  256. store.
  257. """
  258. def __init__(self, lock=None):
  259. """Create a Storage instance.
  260. Args:
  261. lock: An optional threading.Lock-like object. Must implement at
  262. least acquire() and release(). Does not need to be
  263. re-entrant.
  264. """
  265. self._lock = lock
  266. def acquire_lock(self):
  267. """Acquires any lock necessary to access this Storage.
  268. This lock is not reentrant.
  269. """
  270. if self._lock is not None:
  271. self._lock.acquire()
  272. def release_lock(self):
  273. """Release the Storage lock.
  274. Trying to release a lock that isn't held will result in a
  275. RuntimeError in the case of a threading.Lock or multiprocessing.Lock.
  276. """
  277. if self._lock is not None:
  278. self._lock.release()
  279. def locked_get(self):
  280. """Retrieve credential.
  281. The Storage lock must be held when this is called.
  282. Returns:
  283. oauth2client.client.Credentials
  284. """
  285. raise NotImplementedError
  286. def locked_put(self, credentials):
  287. """Write a credential.
  288. The Storage lock must be held when this is called.
  289. Args:
  290. credentials: Credentials, the credentials to store.
  291. """
  292. raise NotImplementedError
  293. def locked_delete(self):
  294. """Delete a credential.
  295. The Storage lock must be held when this is called.
  296. """
  297. raise NotImplementedError
  298. def get(self):
  299. """Retrieve credential.
  300. The Storage lock must *not* be held when this is called.
  301. Returns:
  302. oauth2client.client.Credentials
  303. """
  304. self.acquire_lock()
  305. try:
  306. return self.locked_get()
  307. finally:
  308. self.release_lock()
  309. def put(self, credentials):
  310. """Write a credential.
  311. The Storage lock must be held when this is called.
  312. Args:
  313. credentials: Credentials, the credentials to store.
  314. """
  315. self.acquire_lock()
  316. try:
  317. self.locked_put(credentials)
  318. finally:
  319. self.release_lock()
  320. def delete(self):
  321. """Delete credential.
  322. Frees any resources associated with storing the credential.
  323. The Storage lock must *not* be held when this is called.
  324. Returns:
  325. None
  326. """
  327. self.acquire_lock()
  328. try:
  329. return self.locked_delete()
  330. finally:
  331. self.release_lock()
  332. class OAuth2Credentials(Credentials):
  333. """Credentials object for OAuth 2.0.
  334. Credentials can be applied to an httplib2.Http object using the authorize()
  335. method, which then adds the OAuth 2.0 access token to each request.
  336. OAuth2Credentials objects may be safely pickled and unpickled.
  337. """
  338. @_helpers.positional(8)
  339. def __init__(self, access_token, client_id, client_secret, refresh_token,
  340. token_expiry, token_uri, user_agent, revoke_uri=None,
  341. id_token=None, token_response=None, scopes=None,
  342. token_info_uri=None, id_token_jwt=None):
  343. """Create an instance of OAuth2Credentials.
  344. This constructor is not usually called by the user, instead
  345. OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
  346. Args:
  347. access_token: string, access token.
  348. client_id: string, client identifier.
  349. client_secret: string, client secret.
  350. refresh_token: string, refresh token.
  351. token_expiry: datetime, when the access_token expires.
  352. token_uri: string, URI of token endpoint.
  353. user_agent: string, The HTTP User-Agent to provide for this
  354. application.
  355. revoke_uri: string, URI for revoke endpoint. Defaults to None; a
  356. token can't be revoked if this is None.
  357. id_token: object, The identity of the resource owner.
  358. token_response: dict, the decoded response to the token request.
  359. None if a token hasn't been requested yet. Stored
  360. because some providers (e.g. wordpress.com) include
  361. extra fields that clients may want.
  362. scopes: list, authorized scopes for these credentials.
  363. token_info_uri: string, the URI for the token info endpoint.
  364. Defaults to None; scopes can not be refreshed if
  365. this is None.
  366. id_token_jwt: string, the encoded and signed identity JWT. The
  367. decoded version of this is stored in id_token.
  368. Notes:
  369. store: callable, A callable that when passed a Credential
  370. will store the credential back to where it came from.
  371. This is needed to store the latest access_token if it
  372. has expired and been refreshed.
  373. """
  374. self.access_token = access_token
  375. self.client_id = client_id
  376. self.client_secret = client_secret
  377. self.refresh_token = refresh_token
  378. self.store = None
  379. self.token_expiry = token_expiry
  380. self.token_uri = token_uri
  381. self.user_agent = user_agent
  382. self.revoke_uri = revoke_uri
  383. self.id_token = id_token
  384. self.id_token_jwt = id_token_jwt
  385. self.token_response = token_response
  386. self.scopes = set(_helpers.string_to_scopes(scopes or []))
  387. self.token_info_uri = token_info_uri
  388. # True if the credentials have been revoked or expired and can't be
  389. # refreshed.
  390. self.invalid = False
  391. def authorize(self, http):
  392. """Authorize an httplib2.Http instance with these credentials.
  393. The modified http.request method will add authentication headers to
  394. each request and will refresh access_tokens when a 401 is received on a
  395. request. In addition the http.request method has a credentials
  396. property, http.request.credentials, which is the Credentials object
  397. that authorized it.
  398. Args:
  399. http: An instance of ``httplib2.Http`` or something that acts
  400. like it.
  401. Returns:
  402. A modified instance of http that was passed in.
  403. Example::
  404. h = httplib2.Http()
  405. h = credentials.authorize(h)
  406. You can't create a new OAuth subclass of httplib2.Authentication
  407. because it never gets passed the absolute URI, which is needed for
  408. signing. So instead we have to overload 'request' with a closure
  409. that adds in the Authorization header and then calls the original
  410. version of 'request()'.
  411. """
  412. transport.wrap_http_for_auth(self, http)
  413. return http
  414. def refresh(self, http):
  415. """Forces a refresh of the access_token.
  416. Args:
  417. http: httplib2.Http, an http object to be used to make the refresh
  418. request.
  419. """
  420. self._refresh(http)
  421. def revoke(self, http):
  422. """Revokes a refresh_token and makes the credentials void.
  423. Args:
  424. http: httplib2.Http, an http object to be used to make the revoke
  425. request.
  426. """
  427. self._revoke(http)
  428. def apply(self, headers):
  429. """Add the authorization to the headers.
  430. Args:
  431. headers: dict, the headers to add the Authorization header to.
  432. """
  433. headers['Authorization'] = 'Bearer ' + self.access_token
  434. def has_scopes(self, scopes):
  435. """Verify that the credentials are authorized for the given scopes.
  436. Returns True if the credentials authorized scopes contain all of the
  437. scopes given.
  438. Args:
  439. scopes: list or string, the scopes to check.
  440. Notes:
  441. There are cases where the credentials are unaware of which scopes
  442. are authorized. Notably, credentials obtained and stored before
  443. this code was added will not have scopes, AccessTokenCredentials do
  444. not have scopes. In both cases, you can use refresh_scopes() to
  445. obtain the canonical set of scopes.
  446. """
  447. scopes = _helpers.string_to_scopes(scopes)
  448. return set(scopes).issubset(self.scopes)
  449. def retrieve_scopes(self, http):
  450. """Retrieves the canonical list of scopes for this access token.
  451. Gets the scopes from the OAuth2 provider.
  452. Args:
  453. http: httplib2.Http, an http object to be used to make the refresh
  454. request.
  455. Returns:
  456. A set of strings containing the canonical list of scopes.
  457. """
  458. self._retrieve_scopes(http)
  459. return self.scopes
  460. @classmethod
  461. def from_json(cls, json_data):
  462. """Instantiate a Credentials object from a JSON description of it.
  463. The JSON should have been produced by calling .to_json() on the object.
  464. Args:
  465. json_data: string or bytes, JSON to deserialize.
  466. Returns:
  467. An instance of a Credentials subclass.
  468. """
  469. data = json.loads(_helpers._from_bytes(json_data))
  470. if (data.get('token_expiry') and
  471. not isinstance(data['token_expiry'], datetime.datetime)):
  472. try:
  473. data['token_expiry'] = datetime.datetime.strptime(
  474. data['token_expiry'], EXPIRY_FORMAT)
  475. except ValueError:
  476. data['token_expiry'] = None
  477. retval = cls(
  478. data['access_token'],
  479. data['client_id'],
  480. data['client_secret'],
  481. data['refresh_token'],
  482. data['token_expiry'],
  483. data['token_uri'],
  484. data['user_agent'],
  485. revoke_uri=data.get('revoke_uri', None),
  486. id_token=data.get('id_token', None),
  487. id_token_jwt=data.get('id_token_jwt', None),
  488. token_response=data.get('token_response', None),
  489. scopes=data.get('scopes', None),
  490. token_info_uri=data.get('token_info_uri', None))
  491. retval.invalid = data['invalid']
  492. return retval
  493. @property
  494. def access_token_expired(self):
  495. """True if the credential is expired or invalid.
  496. If the token_expiry isn't set, we assume the token doesn't expire.
  497. """
  498. if self.invalid:
  499. return True
  500. if not self.token_expiry:
  501. return False
  502. now = _UTCNOW()
  503. if now >= self.token_expiry:
  504. logger.info('access_token is expired. Now: %s, token_expiry: %s',
  505. now, self.token_expiry)
  506. return True
  507. return False
  508. def get_access_token(self, http=None):
  509. """Return the access token and its expiration information.
  510. If the token does not exist, get one.
  511. If the token expired, refresh it.
  512. """
  513. if not self.access_token or self.access_token_expired:
  514. if not http:
  515. http = transport.get_http_object()
  516. self.refresh(http)
  517. return AccessTokenInfo(access_token=self.access_token,
  518. expires_in=self._expires_in())
  519. def set_store(self, store):
  520. """Set the Storage for the credential.
  521. Args:
  522. store: Storage, an implementation of Storage object.
  523. This is needed to store the latest access_token if it
  524. has expired and been refreshed. This implementation uses
  525. locking to check for updates before updating the
  526. access_token.
  527. """
  528. self.store = store
  529. def _expires_in(self):
  530. """Return the number of seconds until this token expires.
  531. If token_expiry is in the past, this method will return 0, meaning the
  532. token has already expired.
  533. If token_expiry is None, this method will return None. Note that
  534. returning 0 in such a case would not be fair: the token may still be
  535. valid; we just don't know anything about it.
  536. """
  537. if self.token_expiry:
  538. now = _UTCNOW()
  539. if self.token_expiry > now:
  540. time_delta = self.token_expiry - now
  541. # TODO(orestica): return time_delta.total_seconds()
  542. # once dropping support for Python 2.6
  543. return time_delta.days * 86400 + time_delta.seconds
  544. else:
  545. return 0
  546. def _updateFromCredential(self, other):
  547. """Update this Credential from another instance."""
  548. self.__dict__.update(other.__getstate__())
  549. def __getstate__(self):
  550. """Trim the state down to something that can be pickled."""
  551. d = copy.copy(self.__dict__)
  552. del d['store']
  553. return d
  554. def __setstate__(self, state):
  555. """Reconstitute the state of the object from being pickled."""
  556. self.__dict__.update(state)
  557. self.store = None
  558. def _generate_refresh_request_body(self):
  559. """Generate the body that will be used in the refresh request."""
  560. body = urllib.parse.urlencode({
  561. 'grant_type': 'refresh_token',
  562. 'client_id': self.client_id,
  563. 'client_secret': self.client_secret,
  564. 'refresh_token': self.refresh_token,
  565. })
  566. return body
  567. def _generate_refresh_request_headers(self):
  568. """Generate the headers that will be used in the refresh request."""
  569. headers = {
  570. 'content-type': 'application/x-www-form-urlencoded',
  571. }
  572. if self.user_agent is not None:
  573. headers['user-agent'] = self.user_agent
  574. return headers
  575. def _refresh(self, http):
  576. """Refreshes the access_token.
  577. This method first checks by reading the Storage object if available.
  578. If a refresh is still needed, it holds the Storage lock until the
  579. refresh is completed.
  580. Args:
  581. http: an object to be used to make HTTP requests.
  582. Raises:
  583. HttpAccessTokenRefreshError: When the refresh fails.
  584. """
  585. if not self.store:
  586. self._do_refresh_request(http)
  587. else:
  588. self.store.acquire_lock()
  589. try:
  590. new_cred = self.store.locked_get()
  591. if (new_cred and not new_cred.invalid and
  592. new_cred.access_token != self.access_token and
  593. not new_cred.access_token_expired):
  594. logger.info('Updated access_token read from Storage')
  595. self._updateFromCredential(new_cred)
  596. else:
  597. self._do_refresh_request(http)
  598. finally:
  599. self.store.release_lock()
  600. def _do_refresh_request(self, http):
  601. """Refresh the access_token using the refresh_token.
  602. Args:
  603. http: an object to be used to make HTTP requests.
  604. Raises:
  605. HttpAccessTokenRefreshError: When the refresh fails.
  606. """
  607. body = self._generate_refresh_request_body()
  608. headers = self._generate_refresh_request_headers()
  609. logger.info('Refreshing access_token')
  610. resp, content = transport.request(
  611. http, self.token_uri, method='POST',
  612. body=body, headers=headers)
  613. content = _helpers._from_bytes(content)
  614. if resp.status == http_client.OK:
  615. d = json.loads(content)
  616. self.token_response = d
  617. self.access_token = d['access_token']
  618. self.refresh_token = d.get('refresh_token', self.refresh_token)
  619. if 'expires_in' in d:
  620. delta = datetime.timedelta(seconds=int(d['expires_in']))
  621. self.token_expiry = delta + _UTCNOW()
  622. else:
  623. self.token_expiry = None
  624. if 'id_token' in d:
  625. self.id_token = _extract_id_token(d['id_token'])
  626. self.id_token_jwt = d['id_token']
  627. else:
  628. self.id_token = None
  629. self.id_token_jwt = None
  630. # On temporary refresh errors, the user does not actually have to
  631. # re-authorize, so we unflag here.
  632. self.invalid = False
  633. if self.store:
  634. self.store.locked_put(self)
  635. else:
  636. # An {'error':...} response body means the token is expired or
  637. # revoked, so we flag the credentials as such.
  638. logger.info('Failed to retrieve access token: %s', content)
  639. error_msg = 'Invalid response {0}.'.format(resp.status)
  640. try:
  641. d = json.loads(content)
  642. if 'error' in d:
  643. error_msg = d['error']
  644. if 'error_description' in d:
  645. error_msg += ': ' + d['error_description']
  646. self.invalid = True
  647. if self.store is not None:
  648. self.store.locked_put(self)
  649. except (TypeError, ValueError):
  650. pass
  651. raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
  652. def _revoke(self, http):
  653. """Revokes this credential and deletes the stored copy (if it exists).
  654. Args:
  655. http: an object to be used to make HTTP requests.
  656. """
  657. self._do_revoke(http, self.refresh_token or self.access_token)
  658. def _do_revoke(self, http, token):
  659. """Revokes this credential and deletes the stored copy (if it exists).
  660. Args:
  661. http: an object to be used to make HTTP requests.
  662. token: A string used as the token to be revoked. Can be either an
  663. access_token or refresh_token.
  664. Raises:
  665. TokenRevokeError: If the revoke request does not return with a
  666. 200 OK.
  667. """
  668. logger.info('Revoking token')
  669. query_params = {'token': token}
  670. token_revoke_uri = _helpers.update_query_params(
  671. self.revoke_uri, query_params)
  672. resp, content = transport.request(http, token_revoke_uri)
  673. if resp.status == http_client.METHOD_NOT_ALLOWED:
  674. body = urllib.parse.urlencode(query_params)
  675. resp, content = transport.request(http, token_revoke_uri,
  676. method='POST', body=body)
  677. if resp.status == http_client.OK:
  678. self.invalid = True
  679. else:
  680. error_msg = 'Invalid response {0}.'.format(resp.status)
  681. try:
  682. d = json.loads(_helpers._from_bytes(content))
  683. if 'error' in d:
  684. error_msg = d['error']
  685. except (TypeError, ValueError):
  686. pass
  687. raise TokenRevokeError(error_msg)
  688. if self.store:
  689. self.store.delete()
  690. def _retrieve_scopes(self, http):
  691. """Retrieves the list of authorized scopes from the OAuth2 provider.
  692. Args:
  693. http: an object to be used to make HTTP requests.
  694. """
  695. self._do_retrieve_scopes(http, self.access_token)
  696. def _do_retrieve_scopes(self, http, token):
  697. """Retrieves the list of authorized scopes from the OAuth2 provider.
  698. Args:
  699. http: an object to be used to make HTTP requests.
  700. token: A string used as the token to identify the credentials to
  701. the provider.
  702. Raises:
  703. Error: When refresh fails, indicating the the access token is
  704. invalid.
  705. """
  706. logger.info('Refreshing scopes')
  707. query_params = {'access_token': token, 'fields': 'scope'}
  708. token_info_uri = _helpers.update_query_params(
  709. self.token_info_uri, query_params)
  710. resp, content = transport.request(http, token_info_uri)
  711. content = _helpers._from_bytes(content)
  712. if resp.status == http_client.OK:
  713. d = json.loads(content)
  714. self.scopes = set(_helpers.string_to_scopes(d.get('scope', '')))
  715. else:
  716. error_msg = 'Invalid response {0}.'.format(resp.status)
  717. try:
  718. d = json.loads(content)
  719. if 'error_description' in d:
  720. error_msg = d['error_description']
  721. except (TypeError, ValueError):
  722. pass
  723. raise Error(error_msg)
  724. class AccessTokenCredentials(OAuth2Credentials):
  725. """Credentials object for OAuth 2.0.
  726. Credentials can be applied to an httplib2.Http object using the
  727. authorize() method, which then signs each request from that object
  728. with the OAuth 2.0 access token. This set of credentials is for the
  729. use case where you have acquired an OAuth 2.0 access_token from
  730. another place such as a JavaScript client or another web
  731. application, and wish to use it from Python. Because only the
  732. access_token is present it can not be refreshed and will in time
  733. expire.
  734. AccessTokenCredentials objects may be safely pickled and unpickled.
  735. Usage::
  736. credentials = AccessTokenCredentials('<an access token>',
  737. 'my-user-agent/1.0')
  738. http = httplib2.Http()
  739. http = credentials.authorize(http)
  740. Raises:
  741. AccessTokenCredentialsExpired: raised when the access_token expires or
  742. is revoked.
  743. """
  744. def __init__(self, access_token, user_agent, revoke_uri=None):
  745. """Create an instance of OAuth2Credentials
  746. This is one of the few types if Credentials that you should contrust,
  747. Credentials objects are usually instantiated by a Flow.
  748. Args:
  749. access_token: string, access token.
  750. user_agent: string, The HTTP User-Agent to provide for this
  751. application.
  752. revoke_uri: string, URI for revoke endpoint. Defaults to None; a
  753. token can't be revoked if this is None.
  754. """
  755. super(AccessTokenCredentials, self).__init__(
  756. access_token,
  757. None,
  758. None,
  759. None,
  760. None,
  761. None,
  762. user_agent,
  763. revoke_uri=revoke_uri)
  764. @classmethod
  765. def from_json(cls, json_data):
  766. data = json.loads(_helpers._from_bytes(json_data))
  767. retval = AccessTokenCredentials(
  768. data['access_token'],
  769. data['user_agent'])
  770. return retval
  771. def _refresh(self, http):
  772. """Refreshes the access token.
  773. Args:
  774. http: unused HTTP object.
  775. Raises:
  776. AccessTokenCredentialsError: always
  777. """
  778. raise AccessTokenCredentialsError(
  779. 'The access_token is expired or invalid and can\'t be refreshed.')
  780. def _revoke(self, http):
  781. """Revokes the access_token and deletes the store if available.
  782. Args:
  783. http: an object to be used to make HTTP requests.
  784. """
  785. self._do_revoke(http, self.access_token)
  786. def _detect_gce_environment():
  787. """Determine if the current environment is Compute Engine.
  788. Returns:
  789. Boolean indicating whether or not the current environment is Google
  790. Compute Engine.
  791. """
  792. # NOTE: The explicit ``timeout`` is a workaround. The underlying
  793. # issue is that resolving an unknown host on some networks will take
  794. # 20-30 seconds; making this timeout short fixes the issue, but
  795. # could lead to false negatives in the event that we are on GCE, but
  796. # the metadata resolution was particularly slow. The latter case is
  797. # "unlikely".
  798. http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)
  799. try:
  800. response, _ = transport.request(
  801. http, _GCE_METADATA_URI, headers=_GCE_HEADERS)
  802. return (
  803. response.status == http_client.OK and
  804. response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR)
  805. except socket.error: # socket.timeout or socket.error(64, 'Host is down')
  806. logger.info('Timeout attempting to reach GCE metadata service.')
  807. return False
  808. def _in_gae_environment():
  809. """Detects if the code is running in the App Engine environment.
  810. Returns:
  811. True if running in the GAE environment, False otherwise.
  812. """
  813. if SETTINGS.env_name is not None:
  814. return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL')
  815. try:
  816. import google.appengine # noqa: unused import
  817. except ImportError:
  818. pass
  819. else:
  820. server_software = os.environ.get(_SERVER_SOFTWARE, '')
  821. if server_software.startswith('Google App Engine/'):
  822. SETTINGS.env_name = 'GAE_PRODUCTION'
  823. return True
  824. elif server_software.startswith('Development/'):
  825. SETTINGS.env_name = 'GAE_LOCAL'
  826. return True
  827. return False
  828. def _in_gce_environment():
  829. """Detect if the code is running in the Compute Engine environment.
  830. Returns:
  831. True if running in the GCE environment, False otherwise.
  832. """
  833. if SETTINGS.env_name is not None:
  834. return SETTINGS.env_name == 'GCE_PRODUCTION'
  835. if NO_GCE_CHECK != 'True' and _detect_gce_environment():
  836. SETTINGS.env_name = 'GCE_PRODUCTION'
  837. return True
  838. return False
  839. class GoogleCredentials(OAuth2Credentials):
  840. """Application Default Credentials for use in calling Google APIs.
  841. The Application Default Credentials are being constructed as a function of
  842. the environment where the code is being run.
  843. More details can be found on this page:
  844. https://developers.google.com/accounts/docs/application-default-credentials
  845. Here is an example of how to use the Application Default Credentials for a
  846. service that requires authentication::
  847. from googleapiclient.discovery import build
  848. from oauth2client.client import GoogleCredentials
  849. credentials = GoogleCredentials.get_application_default()
  850. service = build('compute', 'v1', credentials=credentials)
  851. PROJECT = 'bamboo-machine-422'
  852. ZONE = 'us-central1-a'
  853. request = service.instances().list(project=PROJECT, zone=ZONE)
  854. response = request.execute()
  855. print(response)
  856. """
  857. NON_SERIALIZED_MEMBERS = (
  858. frozenset(['_private_key']) |
  859. OAuth2Credentials.NON_SERIALIZED_MEMBERS)
  860. """Members that aren't serialized when object is converted to JSON."""
  861. def __init__(self, access_token, client_id, client_secret, refresh_token,
  862. token_expiry, token_uri, user_agent,
  863. revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
  864. """Create an instance of GoogleCredentials.
  865. This constructor is not usually called by the user, instead
  866. GoogleCredentials objects are instantiated by
  867. GoogleCredentials.from_stream() or
  868. GoogleCredentials.get_application_default().
  869. Args:
  870. access_token: string, access token.
  871. client_id: string, client identifier.
  872. client_secret: string, client secret.
  873. refresh_token: string, refresh token.
  874. token_expiry: datetime, when the access_token expires.
  875. token_uri: string, URI of token endpoint.
  876. user_agent: string, The HTTP User-Agent to provide for this
  877. application.
  878. revoke_uri: string, URI for revoke endpoint. Defaults to
  879. oauth2client.GOOGLE_REVOKE_URI; a token can't be
  880. revoked if this is None.
  881. """
  882. super(GoogleCredentials, self).__init__(
  883. access_token, client_id, client_secret, refresh_token,
  884. token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)
  885. def create_scoped_required(self):
  886. """Whether this Credentials object is scopeless.
  887. create_scoped(scopes) method needs to be called in order to create
  888. a Credentials object for API calls.
  889. """
  890. return False
  891. def create_scoped(self, scopes):
  892. """Create a Credentials object for the given scopes.
  893. The Credentials type is preserved.
  894. """
  895. return self
  896. @classmethod
  897. def from_json(cls, json_data):
  898. # TODO(issue 388): eliminate the circularity that is the reason for
  899. # this non-top-level import.
  900. from oauth2client import service_account
  901. data = json.loads(_helpers._from_bytes(json_data))
  902. # We handle service_account.ServiceAccountCredentials since it is a
  903. # possible return type of GoogleCredentials.get_application_default()
  904. if (data['_module'] == 'oauth2client.service_account' and
  905. data['_class'] == 'ServiceAccountCredentials'):
  906. return service_account.ServiceAccountCredentials.from_json(data)
  907. elif (data['_module'] == 'oauth2client.service_account' and
  908. data['_class'] == '_JWTAccessCredentials'):
  909. return service_account._JWTAccessCredentials.from_json(data)
  910. token_expiry = _parse_expiry(data.get('token_expiry'))
  911. google_credentials = cls(
  912. data['access_token'],
  913. data['client_id'],
  914. data['client_secret'],
  915. data['refresh_token'],
  916. token_expiry,
  917. data['token_uri'],
  918. data['user_agent'],
  919. revoke_uri=data.get('revoke_uri', None))
  920. google_credentials.invalid = data['invalid']
  921. return google_credentials
  922. @property
  923. def serialization_data(self):
  924. """Get the fields and values identifying the current credentials."""
  925. return {
  926. 'type': 'authorized_user',
  927. 'client_id': self.client_id,
  928. 'client_secret': self.client_secret,
  929. 'refresh_token': self.refresh_token
  930. }
  931. @staticmethod
  932. def _implicit_credentials_from_gae():
  933. """Attempts to get implicit credentials in Google App Engine env.
  934. If the current environment is not detected as App Engine, returns None,
  935. indicating no Google App Engine credentials can be detected from the
  936. current environment.
  937. Returns:
  938. None, if not in GAE, else an appengine.AppAssertionCredentials
  939. object.
  940. """
  941. if not _in_gae_environment():
  942. return None
  943. return _get_application_default_credential_GAE()
  944. @staticmethod
  945. def _implicit_credentials_from_gce():
  946. """Attempts to get implicit credentials in Google Compute Engine env.
  947. If the current environment is not detected as Compute Engine, returns
  948. None, indicating no Google Compute Engine credentials can be detected
  949. from the current environment.
  950. Returns:
  951. None, if not in GCE, else a gce.AppAssertionCredentials object.
  952. """
  953. if not _in_gce_environment():
  954. return None
  955. return _get_application_default_credential_GCE()
  956. @staticmethod
  957. def _implicit_credentials_from_files():
  958. """Attempts to get implicit credentials from local credential files.
  959. First checks if the environment variable GOOGLE_APPLICATION_CREDENTIALS
  960. is set with a filename and then falls back to a configuration file (the
  961. "well known" file) associated with the 'gcloud' command line tool.
  962. Returns:
  963. Credentials object associated with the
  964. GOOGLE_APPLICATION_CREDENTIALS file or the "well known" file if
  965. either exist. If neither file is define, returns None, indicating
  966. no credentials from a file can detected from the current
  967. environment.
  968. """
  969. credentials_filename = _get_environment_variable_file()
  970. if not credentials_filename:
  971. credentials_filename = _get_well_known_file()
  972. if os.path.isfile(credentials_filename):
  973. extra_help = (' (produced automatically when running'
  974. ' "gcloud auth login" command)')
  975. else:
  976. credentials_filename = None
  977. else:
  978. extra_help = (' (pointed to by ' + GOOGLE_APPLICATION_CREDENTIALS +
  979. ' environment variable)')
  980. if not credentials_filename:
  981. return
  982. # If we can read the credentials from a file, we don't need to know
  983. # what environment we are in.
  984. SETTINGS.env_name = DEFAULT_ENV_NAME
  985. try:
  986. return _get_application_default_credential_from_file(
  987. credentials_filename)
  988. except (ApplicationDefaultCredentialsError, ValueError) as error:
  989. _raise_exception_for_reading_json(credentials_filename,
  990. extra_help, error)
  991. @classmethod
  992. def _get_implicit_credentials(cls):
  993. """Gets credentials implicitly from the environment.
  994. Checks environment in order of precedence:
  995. - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to
  996. a file with stored credentials information.
  997. - Stored "well known" file associated with `gcloud` command line tool.
  998. - Google App Engine (production and testing)
  999. - Google Compute Engine production environment.
  1000. Raises:
  1001. ApplicationDefaultCredentialsError: raised when the credentials
  1002. fail to be retrieved.
  1003. """
  1004. # Environ checks (in order).
  1005. environ_checkers = [
  1006. cls._implicit_credentials_from_files,
  1007. cls._implicit_credentials_from_gae,
  1008. cls._implicit_credentials_from_gce,
  1009. ]
  1010. for checker in environ_checkers:
  1011. credentials = checker()
  1012. if credentials is not None:
  1013. return credentials
  1014. # If no credentials, fail.
  1015. raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
  1016. @staticmethod
  1017. def get_application_default():
  1018. """Get the Application Default Credentials for the current environment.
  1019. Raises:
  1020. ApplicationDefaultCredentialsError: raised when the credentials
  1021. fail to be retrieved.
  1022. """
  1023. return GoogleCredentials._get_implicit_credentials()
  1024. @staticmethod
  1025. def from_stream(credential_filename):
  1026. """Create a Credentials object by reading information from a file.
  1027. It returns an object of type GoogleCredentials.
  1028. Args:
  1029. credential_filename: the path to the file from where the
  1030. credentials are to be read
  1031. Raises:
  1032. ApplicationDefaultCredentialsError: raised when the credentials
  1033. fail to be retrieved.
  1034. """
  1035. if credential_filename and os.path.isfile(credential_filename):
  1036. try:
  1037. return _get_application_default_credential_from_file(
  1038. credential_filename)
  1039. except (ApplicationDefaultCredentialsError, ValueError) as error:
  1040. extra_help = (' (provided as parameter to the '
  1041. 'from_stream() method)')
  1042. _raise_exception_for_reading_json(credential_filename,
  1043. extra_help,
  1044. error)
  1045. else:
  1046. raise ApplicationDefaultCredentialsError(
  1047. 'The parameter passed to the from_stream() '
  1048. 'method should point to a file.')
  1049. def _save_private_file(filename, json_contents):
  1050. """Saves a file with read-write permissions on for the owner.
  1051. Args:
  1052. filename: String. Absolute path to file.
  1053. json_contents: JSON serializable object to be saved.
  1054. """
  1055. temp_filename = tempfile.mktemp()
  1056. file_desc = os.open(temp_filename, os.O_WRONLY | os.O_CREAT, 0o600)
  1057. with os.fdopen(file_desc, 'w') as file_handle:
  1058. json.dump(json_contents, file_handle, sort_keys=True,
  1059. indent=2, separators=(',', ': '))
  1060. shutil.move(temp_filename, filename)
  1061. def save_to_well_known_file(credentials, well_known_file=None):
  1062. """Save the provided GoogleCredentials to the well known file.
  1063. Args:
  1064. credentials: the credentials to be saved to the well known file;
  1065. it should be an instance of GoogleCredentials
  1066. well_known_file: the name of the file where the credentials are to be
  1067. saved; this parameter is supposed to be used for
  1068. testing only
  1069. """
  1070. # TODO(orestica): move this method to tools.py
  1071. # once the argparse import gets fixed (it is not present in Python 2.6)
  1072. if well_known_file is None:
  1073. well_known_file = _get_well_known_file()
  1074. config_dir = os.path.dirname(well_known_file)
  1075. if not os.path.isdir(config_dir):
  1076. raise OSError(
  1077. 'Config directory does not exist: {0}'.format(config_dir))
  1078. credentials_data = credentials.serialization_data
  1079. _save_private_file(well_known_file, credentials_data)
  1080. def _get_environment_variable_file():
  1081. application_default_credential_filename = (
  1082. os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None))
  1083. if application_default_credential_filename:
  1084. if os.path.isfile(application_default_credential_filename):
  1085. return application_default_credential_filename
  1086. else:
  1087. raise ApplicationDefaultCredentialsError(
  1088. 'File ' + application_default_credential_filename +
  1089. ' (pointed by ' +
  1090. GOOGLE_APPLICATION_CREDENTIALS +
  1091. ' environment variable) does not exist!')
  1092. def _get_well_known_file():
  1093. """Get the well known file produced by command 'gcloud auth login'."""
  1094. # TODO(orestica): Revisit this method once gcloud provides a better way
  1095. # of pinpointing the exact location of the file.
  1096. default_config_dir = os.getenv(_CLOUDSDK_CONFIG_ENV_VAR)
  1097. if default_config_dir is None:
  1098. if os.name == 'nt':
  1099. try:
  1100. default_config_dir = os.path.join(os.environ['APPDATA'],
  1101. _CLOUDSDK_CONFIG_DIRECTORY)
  1102. except KeyError:
  1103. # This should never happen unless someone is really
  1104. # messing with things.
  1105. drive = os.environ.get('SystemDrive', 'C:')
  1106. default_config_dir = os.path.join(drive, '\\',
  1107. _CLOUDSDK_CONFIG_DIRECTORY)
  1108. else:
  1109. default_config_dir = os.path.join(os.path.expanduser('~'),
  1110. '.config',
  1111. _CLOUDSDK_CONFIG_DIRECTORY)
  1112. return os.path.join(default_config_dir, _WELL_KNOWN_CREDENTIALS_FILE)
  1113. def _get_application_default_credential_from_file(filename):
  1114. """Build the Application Default Credentials from file."""
  1115. # read the credentials from the file
  1116. with open(filename) as file_obj:
  1117. client_credentials = json.load(file_obj)
  1118. credentials_type = client_credentials.get('type')
  1119. if credentials_type == AUTHORIZED_USER:
  1120. required_fields = set(['client_id', 'client_secret', 'refresh_token'])
  1121. elif credentials_type == SERVICE_ACCOUNT:
  1122. required_fields = set(['client_id', 'client_email', 'private_key_id',
  1123. 'private_key'])
  1124. else:
  1125. raise ApplicationDefaultCredentialsError(
  1126. "'type' field should be defined (and have one of the '" +
  1127. AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")
  1128. missing_fields = required_fields.difference(client_credentials.keys())
  1129. if missing_fields:
  1130. _raise_exception_for_missing_fields(missing_fields)
  1131. if client_credentials['type'] == AUTHORIZED_USER:
  1132. return GoogleCredentials(
  1133. access_token=None,
  1134. client_id=client_credentials['client_id'],
  1135. client_secret=client_credentials['client_secret'],
  1136. refresh_token=client_credentials['refresh_token'],
  1137. token_expiry=None,
  1138. token_uri=oauth2client.GOOGLE_TOKEN_URI,
  1139. user_agent='Python client library')
  1140. else: # client_credentials['type'] == SERVICE_ACCOUNT
  1141. from oauth2client import service_account
  1142. return service_account._JWTAccessCredentials.from_json_keyfile_dict(
  1143. client_credentials)
  1144. def _raise_exception_for_missing_fields(missing_fields):
  1145. raise ApplicationDefaultCredentialsError(
  1146. 'The following field(s) must be defined: ' + ', '.join(missing_fields))
  1147. def _raise_exception_for_reading_json(credential_file,
  1148. extra_help,
  1149. error):
  1150. raise ApplicationDefaultCredentialsError(
  1151. 'An error was encountered while reading json file: ' +
  1152. credential_file + extra_help + ': ' + str(error))
  1153. def _get_application_default_credential_GAE():
  1154. from oauth2client.contrib.appengine import AppAssertionCredentials
  1155. return AppAssertionCredentials([])
  1156. def _get_application_default_credential_GCE():
  1157. from oauth2client.contrib.gce import AppAssertionCredentials
  1158. return AppAssertionCredentials()
  1159. class AssertionCredentials(GoogleCredentials):
  1160. """Abstract Credentials object used for OAuth 2.0 assertion grants.
  1161. This credential does not require a flow to instantiate because it
  1162. represents a two legged flow, and therefore has all of the required
  1163. information to generate and refresh its own access tokens. It must
  1164. be subclassed to generate the appropriate assertion string.
  1165. AssertionCredentials objects may be safely pickled and unpickled.
  1166. """
  1167. @_helpers.positional(2)
  1168. def __init__(self, assertion_type, user_agent=None,
  1169. token_uri=oauth2client.GOOGLE_TOKEN_URI,
  1170. revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
  1171. **unused_kwargs):
  1172. """Constructor for AssertionFlowCredentials.
  1173. Args:
  1174. assertion_type: string, assertion type that will be declared to the
  1175. auth server
  1176. user_agent: string, The HTTP User-Agent to provide for this
  1177. application.
  1178. token_uri: string, URI for token endpoint. For convenience defaults
  1179. to Google's endpoints but any OAuth 2.0 provider can be
  1180. used.
  1181. revoke_uri: string, URI for revoke endpoint.
  1182. """
  1183. super(AssertionCredentials, self).__init__(
  1184. None,
  1185. None,
  1186. None,
  1187. None,
  1188. None,
  1189. token_uri,
  1190. user_agent,
  1191. revoke_uri=revoke_uri)
  1192. self.assertion_type = assertion_type
  1193. def _generate_refresh_request_body(self):
  1194. assertion = self._generate_assertion()
  1195. body = urllib.parse.urlencode({
  1196. 'assertion': assertion,
  1197. 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
  1198. })
  1199. return body
  1200. def _generate_assertion(self):
  1201. """Generate assertion string to be used in the access token request."""
  1202. raise NotImplementedError
  1203. def _revoke(self, http):
  1204. """Revokes the access_token and deletes the store if available.
  1205. Args:
  1206. http: an object to be used to make HTTP requests.
  1207. """
  1208. self._do_revoke(http, self.access_token)
  1209. def sign_blob(self, blob):
  1210. """Cryptographically sign a blob (of bytes).
  1211. Args:
  1212. blob: bytes, Message to be signed.
  1213. Returns:
  1214. tuple, A pair of the private key ID used to sign the blob and
  1215. the signed contents.
  1216. """
  1217. raise NotImplementedError('This method is abstract.')
  1218. def _require_crypto_or_die():
  1219. """Ensure we have a crypto library, or throw CryptoUnavailableError.
  1220. The oauth2client.crypt module requires either PyCrypto or PyOpenSSL
  1221. to be available in order to function, but these are optional
  1222. dependencies.
  1223. """
  1224. if not HAS_CRYPTO:
  1225. raise CryptoUnavailableError('No crypto library available')
  1226. @_helpers.positional(2)
  1227. def verify_id_token(id_token, audience, http=None,
  1228. cert_uri=ID_TOKEN_VERIFICATION_CERTS):
  1229. """Verifies a signed JWT id_token.
  1230. This function requires PyOpenSSL and because of that it does not work on
  1231. App Engine.
  1232. Args:
  1233. id_token: string, A Signed JWT.
  1234. audience: string, The audience 'aud' that the token should be for.
  1235. http: httplib2.Http, instance to use to make the HTTP request. Callers
  1236. should supply an instance that has caching enabled.
  1237. cert_uri: string, URI of the certificates in JSON format to
  1238. verify the JWT against.
  1239. Returns:
  1240. The deserialized JSON in the JWT.
  1241. Raises:
  1242. oauth2client.crypt.AppIdentityError: if the JWT fails to verify.
  1243. CryptoUnavailableError: if no crypto library is available.
  1244. """
  1245. _require_crypto_or_die()
  1246. if http is None:
  1247. http = transport.get_cached_http()
  1248. resp, content = transport.request(http, cert_uri)
  1249. if resp.status == http_client.OK:
  1250. certs = json.loads(_helpers._from_bytes(content))
  1251. return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
  1252. else:
  1253. raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))
  1254. def _extract_id_token(id_token):
  1255. """Extract the JSON payload from a JWT.
  1256. Does the extraction w/o checking the signature.
  1257. Args:
  1258. id_token: string or bytestring, OAuth 2.0 id_token.
  1259. Returns:
  1260. object, The deserialized JSON payload.
  1261. """
  1262. if type(id_token) == bytes:
  1263. segments = id_token.split(b'.')
  1264. else:
  1265. segments = id_token.split(u'.')
  1266. if len(segments) != 3:
  1267. raise VerifyJwtTokenError(
  1268. 'Wrong number of segments in token: {0}'.format(id_token))
  1269. return json.loads(
  1270. _helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1])))
  1271. def _parse_exchange_token_response(content):
  1272. """Parses response of an exchange token request.
  1273. Most providers return JSON but some (e.g. Facebook) return a
  1274. url-encoded string.
  1275. Args:
  1276. content: The body of a response
  1277. Returns:
  1278. Content as a dictionary object. Note that the dict could be empty,
  1279. i.e. {}. That basically indicates a failure.
  1280. """
  1281. resp = {}
  1282. content = _helpers._from_bytes(content)
  1283. try:
  1284. resp = json.loads(content)
  1285. except Exception:
  1286. # different JSON libs raise different exceptions,
  1287. # so we just do a catch-all here
  1288. resp = _helpers.parse_unique_urlencoded(content)
  1289. # some providers respond with 'expires', others with 'expires_in'
  1290. if resp and 'expires' in resp:
  1291. resp['expires_in'] = resp.pop('expires')
  1292. return resp
  1293. @_helpers.positional(4)
  1294. def credentials_from_code(client_id, client_secret, scope, code,
  1295. redirect_uri='postmessage', http=None,
  1296. user_agent=None,
  1297. token_uri=oauth2client.GOOGLE_TOKEN_URI,
  1298. auth_uri=oauth2client.GOOGLE_AUTH_URI,
  1299. revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
  1300. device_uri=oauth2client.GOOGLE_DEVICE_URI,
  1301. token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,
  1302. pkce=False,
  1303. code_verifier=None):
  1304. """Exchanges an authorization code for an OAuth2Credentials object.
  1305. Args:
  1306. client_id: string, client identifier.
  1307. client_secret: string, client secret.
  1308. scope: string or iterable of strings, scope(s) to request.
  1309. code: string, An authorization code, most likely passed down from
  1310. the client
  1311. redirect_uri: string, this is generally set to 'postmessage' to match
  1312. the redirect_uri that the client specified
  1313. http: httplib2.Http, optional http instance to use to do the fetch
  1314. token_uri: string, URI for token endpoint. For convenience defaults
  1315. to Google's endpoints but any OAuth 2.0 provider can be
  1316. used.
  1317. auth_uri: string, URI for authorization endpoint. For convenience
  1318. defaults to Google's endpoints but any OAuth 2.0 provider
  1319. can be used.
  1320. revoke_uri: string, URI for revoke endpoint. For convenience
  1321. defaults to Google's endpoints but any OAuth 2.0 provider
  1322. can be used.
  1323. device_uri: string, URI for device authorization endpoint. For
  1324. convenience defaults to Google's endpoints but any OAuth
  1325. 2.0 provider can be used.
  1326. pkce: boolean, default: False, Generate and include a "Proof Key
  1327. for Code Exchange" (PKCE) with your authorization and token
  1328. requests. This adds security for installed applications that
  1329. cannot protect a client_secret. See RFC 7636 for details.
  1330. code_verifier: bytestring or None, default: None, parameter passed
  1331. as part of the code exchange when pkce=True. If
  1332. None, a code_verifier will automatically be
  1333. generated as part of step1_get_authorize_url(). See
  1334. RFC 7636 for details.
  1335. Returns:
  1336. An OAuth2Credentials object.
  1337. Raises:
  1338. FlowExchangeError if the authorization code cannot be exchanged for an
  1339. access token
  1340. """
  1341. flow = OAuth2WebServerFlow(client_id, client_secret, scope,
  1342. redirect_uri=redirect_uri,
  1343. user_agent=user_agent,
  1344. auth_uri=auth_uri,
  1345. token_uri=token_uri,
  1346. revoke_uri=revoke_uri,
  1347. device_uri=device_uri,
  1348. token_info_uri=token_info_uri,
  1349. pkce=pkce,
  1350. code_verifier=code_verifier)
  1351. credentials = flow.step2_exchange(code, http=http)
  1352. return credentials
  1353. @_helpers.positional(3)
  1354. def credentials_from_clientsecrets_and_code(filename, scope, code,
  1355. message=None,
  1356. redirect_uri='postmessage',
  1357. http=None,
  1358. cache=None,
  1359. device_uri=None):
  1360. """Returns OAuth2Credentials from a clientsecrets file and an auth code.
  1361. Will create the right kind of Flow based on the contents of the
  1362. clientsecrets file or will raise InvalidClientSecretsError for unknown
  1363. types of Flows.
  1364. Args:
  1365. filename: string, File name of clientsecrets.
  1366. scope: string or iterable of strings, scope(s) to request.
  1367. code: string, An authorization code, most likely passed down from
  1368. the client
  1369. message: string, A friendly string to display to the user if the
  1370. clientsecrets file is missing or invalid. If message is
  1371. provided then sys.exit will be called in the case of an error.
  1372. If message in not provided then
  1373. clientsecrets.InvalidClientSecretsError will be raised.
  1374. redirect_uri: string, this is generally set to 'postmessage' to match
  1375. the redirect_uri that the client specified
  1376. http: httplib2.Http, optional http instance to use to do the fetch
  1377. cache: An optional cache service client that implements get() and set()
  1378. methods. See clientsecrets.loadfile() for details.
  1379. device_uri: string, OAuth 2.0 device authorization endpoint
  1380. pkce: boolean, default: False, Generate and include a "Proof Key
  1381. for Code Exchange" (PKCE) with your authorization and token
  1382. requests. This adds security for installed applications that
  1383. cannot protect a client_secret. See RFC 7636 for details.
  1384. code_verifier: bytestring or None, default: None, parameter passed
  1385. as part of the code exchange when pkce=True. If
  1386. None, a code_verifier will automatically be
  1387. generated as part of step1_get_authorize_url(). See
  1388. RFC 7636 for details.
  1389. Returns:
  1390. An OAuth2Credentials object.
  1391. Raises:
  1392. FlowExchangeError: if the authorization code cannot be exchanged for an
  1393. access token
  1394. UnknownClientSecretsFlowError: if the file describes an unknown kind
  1395. of Flow.
  1396. clientsecrets.InvalidClientSecretsError: if the clientsecrets file is
  1397. invalid.
  1398. """
  1399. flow = flow_from_clientsecrets(filename, scope, message=message,
  1400. cache=cache, redirect_uri=redirect_uri,
  1401. device_uri=device_uri)
  1402. credentials = flow.step2_exchange(code, http=http)
  1403. return credentials
  1404. class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', (
  1405. 'device_code', 'user_code', 'interval', 'verification_url',
  1406. 'user_code_expiry'))):
  1407. """Intermediate information the OAuth2 for devices flow."""
  1408. @classmethod
  1409. def FromResponse(cls, response):
  1410. """Create a DeviceFlowInfo from a server response.
  1411. The response should be a dict containing entries as described here:
  1412. http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1
  1413. """
  1414. # device_code, user_code, and verification_url are required.
  1415. kwargs = {
  1416. 'device_code': response['device_code'],
  1417. 'user_code': response['user_code'],
  1418. }
  1419. # The response may list the verification address as either
  1420. # verification_url or verification_uri, so we check for both.
  1421. verification_url = response.get(
  1422. 'verification_url', response.get('verification_uri'))
  1423. if verification_url is None:
  1424. raise OAuth2DeviceCodeError(
  1425. 'No verification_url provided in server response')
  1426. kwargs['verification_url'] = verification_url
  1427. # expires_in and interval are optional.
  1428. kwargs.update({
  1429. 'interval': response.get('interval'),
  1430. 'user_code_expiry': None,
  1431. })
  1432. if 'expires_in' in response:
  1433. kwargs['user_code_expiry'] = (
  1434. _UTCNOW() +
  1435. datetime.timedelta(seconds=int(response['expires_in'])))
  1436. return cls(**kwargs)
  1437. def _oauth2_web_server_flow_params(kwargs):
  1438. """Configures redirect URI parameters for OAuth2WebServerFlow."""
  1439. params = {
  1440. 'access_type': 'offline',
  1441. 'response_type': 'code',
  1442. }
  1443. params.update(kwargs)
  1444. # Check for the presence of the deprecated approval_prompt param and
  1445. # warn appropriately.
  1446. approval_prompt = params.get('approval_prompt')
  1447. if approval_prompt is not None:
  1448. logger.warning(
  1449. 'The approval_prompt parameter for OAuth2WebServerFlow is '
  1450. 'deprecated. Please use the prompt parameter instead.')
  1451. if approval_prompt == 'force':
  1452. logger.warning(
  1453. 'approval_prompt="force" has been adjusted to '
  1454. 'prompt="consent"')
  1455. params['prompt'] = 'consent'
  1456. del params['approval_prompt']
  1457. return params
  1458. class OAuth2WebServerFlow(Flow):
  1459. """Does the Web Server Flow for OAuth 2.0.
  1460. OAuth2WebServerFlow objects may be safely pickled and unpickled.
  1461. """
  1462. @_helpers.positional(4)
  1463. def __init__(self, client_id,
  1464. client_secret=None,
  1465. scope=None,
  1466. redirect_uri=None,
  1467. user_agent=None,
  1468. auth_uri=oauth2client.GOOGLE_AUTH_URI,
  1469. token_uri=oauth2client.GOOGLE_TOKEN_URI,
  1470. revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
  1471. login_hint=None,
  1472. device_uri=oauth2client.GOOGLE_DEVICE_URI,
  1473. token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,
  1474. authorization_header=None,
  1475. pkce=False,
  1476. code_verifier=None,
  1477. **kwargs):
  1478. """Constructor for OAuth2WebServerFlow.
  1479. The kwargs argument is used to set extra query parameters on the
  1480. auth_uri. For example, the access_type and prompt
  1481. query parameters can be set via kwargs.
  1482. Args:
  1483. client_id: string, client identifier.
  1484. client_secret: string client secret.
  1485. scope: string or iterable of strings, scope(s) of the credentials
  1486. being requested.
  1487. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'
  1488. for a non-web-based application, or a URI that
  1489. handles the callback from the authorization server.
  1490. user_agent: string, HTTP User-Agent to provide for this
  1491. application.
  1492. auth_uri: string, URI for authorization endpoint. For convenience
  1493. defaults to Google's endpoints but any OAuth 2.0 provider
  1494. can be used.
  1495. token_uri: string, URI for token endpoint. For convenience
  1496. defaults to Google's endpoints but any OAuth 2.0
  1497. provider can be used.
  1498. revoke_uri: string, URI for revoke endpoint. For convenience
  1499. defaults to Google's endpoints but any OAuth 2.0
  1500. provider can be used.
  1501. login_hint: string, Either an email address or domain. Passing this
  1502. hint will either pre-fill the email box on the sign-in
  1503. form or select the proper multi-login session, thereby
  1504. simplifying the login flow.
  1505. device_uri: string, URI for device authorization endpoint. For
  1506. convenience defaults to Google's endpoints but any
  1507. OAuth 2.0 provider can be used.
  1508. authorization_header: string, For use with OAuth 2.0 providers that
  1509. require a client to authenticate using a
  1510. header value instead of passing client_secret
  1511. in the POST body.
  1512. pkce: boolean, default: False, Generate and include a "Proof Key
  1513. for Code Exchange" (PKCE) with your authorization and token
  1514. requests. This adds security for installed applications that
  1515. cannot protect a client_secret. See RFC 7636 for details.
  1516. code_verifier: bytestring or None, default: None, parameter passed
  1517. as part of the code exchange when pkce=True. If
  1518. None, a code_verifier will automatically be
  1519. generated as part of step1_get_authorize_url(). See
  1520. RFC 7636 for details.
  1521. **kwargs: dict, The keyword arguments are all optional and required
  1522. parameters for the OAuth calls.
  1523. """
  1524. # scope is a required argument, but to preserve backwards-compatibility
  1525. # we don't want to rearrange the positional arguments
  1526. if scope is None:
  1527. raise TypeError("The value of scope must not be None")
  1528. self.client_id = client_id
  1529. self.client_secret = client_secret
  1530. self.scope = _helpers.scopes_to_string(scope)
  1531. self.redirect_uri = redirect_uri
  1532. self.login_hint = login_hint
  1533. self.user_agent = user_agent
  1534. self.auth_uri = auth_uri
  1535. self.token_uri = token_uri
  1536. self.revoke_uri = revoke_uri
  1537. self.device_uri = device_uri
  1538. self.token_info_uri = token_info_uri
  1539. self.authorization_header = authorization_header
  1540. self._pkce = pkce
  1541. self.code_verifier = code_verifier
  1542. self.params = _oauth2_web_server_flow_params(kwargs)
  1543. @_helpers.positional(1)
  1544. def step1_get_authorize_url(self, redirect_uri=None, state=None):
  1545. """Returns a URI to redirect to the provider.
  1546. Args:
  1547. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob'
  1548. for a non-web-based application, or a URI that
  1549. handles the callback from the authorization server.
  1550. This parameter is deprecated, please move to passing
  1551. the redirect_uri in via the constructor.
  1552. state: string, Opaque state string which is passed through the
  1553. OAuth2 flow and returned to the client as a query parameter
  1554. in the callback.
  1555. Returns:
  1556. A URI as a string to redirect the user to begin the authorization
  1557. flow.
  1558. """
  1559. if redirect_uri is not None:
  1560. logger.warning((
  1561. 'The redirect_uri parameter for '
  1562. 'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '
  1563. 'Please move to passing the redirect_uri in via the '
  1564. 'constructor.'))
  1565. self.redirect_uri = redirect_uri
  1566. if self.redirect_uri is None:
  1567. raise ValueError('The value of redirect_uri must not be None.')
  1568. query_params = {
  1569. 'client_id': self.client_id,
  1570. 'redirect_uri': self.redirect_uri,
  1571. 'scope': self.scope,
  1572. }
  1573. if state is not None:
  1574. query_params['state'] = state
  1575. if self.login_hint is not None:
  1576. query_params['login_hint'] = self.login_hint
  1577. if self._pkce:
  1578. if not self.code_verifier:
  1579. self.code_verifier = _pkce.code_verifier()
  1580. challenge = _pkce.code_challenge(self.code_verifier)
  1581. query_params['code_challenge'] = challenge
  1582. query_params['code_challenge_method'] = 'S256'
  1583. query_params.update(self.params)
  1584. return _helpers.update_query_params(self.auth_uri, query_params)
  1585. @_helpers.positional(1)
  1586. def step1_get_device_and_user_codes(self, http=None):
  1587. """Returns a user code and the verification URL where to enter it
  1588. Returns:
  1589. A user code as a string for the user to authorize the application
  1590. An URL as a string where the user has to enter the code
  1591. """
  1592. if self.device_uri is None:
  1593. raise ValueError('The value of device_uri must not be None.')
  1594. body = urllib.parse.urlencode({
  1595. 'client_id': self.client_id,
  1596. 'scope': self.scope,
  1597. })
  1598. headers = {
  1599. 'content-type': 'application/x-www-form-urlencoded',
  1600. }
  1601. if self.user_agent is not None:
  1602. headers['user-agent'] = self.user_agent
  1603. if http is None:
  1604. http = transport.get_http_object()
  1605. resp, content = transport.request(
  1606. http, self.device_uri, method='POST', body=body, headers=headers)
  1607. content = _helpers._from_bytes(content)
  1608. if resp.status == http_client.OK:
  1609. try:
  1610. flow_info = json.loads(content)
  1611. except ValueError as exc:
  1612. raise OAuth2DeviceCodeError(
  1613. 'Could not parse server response as JSON: "{0}", '
  1614. 'error: "{1}"'.format(content, exc))
  1615. return DeviceFlowInfo.FromResponse(flow_info)
  1616. else:
  1617. error_msg = 'Invalid response {0}.'.format(resp.status)
  1618. try:
  1619. error_dict = json.loads(content)
  1620. if 'error' in error_dict:
  1621. error_msg += ' Error: {0}'.format(error_dict['error'])
  1622. except ValueError:
  1623. # Couldn't decode a JSON response, stick with the
  1624. # default message.
  1625. pass
  1626. raise OAuth2DeviceCodeError(error_msg)
  1627. @_helpers.positional(2)
  1628. def step2_exchange(self, code=None, http=None, device_flow_info=None):
  1629. """Exchanges a code for OAuth2Credentials.
  1630. Args:
  1631. code: string, a dict-like object, or None. For a non-device
  1632. flow, this is either the response code as a string, or a
  1633. dictionary of query parameters to the redirect_uri. For a
  1634. device flow, this should be None.
  1635. http: httplib2.Http, optional http instance to use when fetching
  1636. credentials.
  1637. device_flow_info: DeviceFlowInfo, return value from step1 in the
  1638. case of a device flow.
  1639. Returns:
  1640. An OAuth2Credentials object that can be used to authorize requests.
  1641. Raises:
  1642. FlowExchangeError: if a problem occurred exchanging the code for a
  1643. refresh_token.
  1644. ValueError: if code and device_flow_info are both provided or both
  1645. missing.
  1646. """
  1647. if code is None and device_flow_info is None:
  1648. raise ValueError('No code or device_flow_info provided.')
  1649. if code is not None and device_flow_info is not None:
  1650. raise ValueError('Cannot provide both code and device_flow_info.')
  1651. if code is None:
  1652. code = device_flow_info.device_code
  1653. elif not isinstance(code, (six.string_types, six.binary_type)):
  1654. if 'code' not in code:
  1655. raise FlowExchangeError(code.get(
  1656. 'error', 'No code was supplied in the query parameters.'))
  1657. code = code['code']
  1658. post_data = {
  1659. 'client_id': self.client_id,
  1660. 'code': code,
  1661. 'scope': self.scope,
  1662. }
  1663. if self.client_secret is not None:
  1664. post_data['client_secret'] = self.client_secret
  1665. if self._pkce:
  1666. post_data['code_verifier'] = self.code_verifier
  1667. if device_flow_info is not None:
  1668. post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0'
  1669. else:
  1670. post_data['grant_type'] = 'authorization_code'
  1671. post_data['redirect_uri'] = self.redirect_uri
  1672. body = urllib.parse.urlencode(post_data)
  1673. headers = {
  1674. 'content-type': 'application/x-www-form-urlencoded',
  1675. }
  1676. if self.authorization_header is not None:
  1677. headers['Authorization'] = self.authorization_header
  1678. if self.user_agent is not None:
  1679. headers['user-agent'] = self.user_agent
  1680. if http is None:
  1681. http = transport.get_http_object()
  1682. resp, content = transport.request(
  1683. http, self.token_uri, method='POST', body=body, headers=headers)
  1684. d = _parse_exchange_token_response(content)
  1685. if resp.status == http_client.OK and 'access_token' in d:
  1686. access_token = d['access_token']
  1687. refresh_token = d.get('refresh_token', None)
  1688. if not refresh_token:
  1689. logger.info(
  1690. 'Received token response with no refresh_token. Consider '
  1691. "reauthenticating with prompt='consent'.")
  1692. token_expiry = None
  1693. if 'expires_in' in d:
  1694. delta = datetime.timedelta(seconds=int(d['expires_in']))
  1695. token_expiry = delta + _UTCNOW()
  1696. extracted_id_token = None
  1697. id_token_jwt = None
  1698. if 'id_token' in d:
  1699. extracted_id_token = _extract_id_token(d['id_token'])
  1700. id_token_jwt = d['id_token']
  1701. logger.info('Successfully retrieved access token')
  1702. return OAuth2Credentials(
  1703. access_token, self.client_id, self.client_secret,
  1704. refresh_token, token_expiry, self.token_uri, self.user_agent,
  1705. revoke_uri=self.revoke_uri, id_token=extracted_id_token,
  1706. id_token_jwt=id_token_jwt, token_response=d, scopes=self.scope,
  1707. token_info_uri=self.token_info_uri)
  1708. else:
  1709. logger.info('Failed to retrieve access token: %s', content)
  1710. if 'error' in d:
  1711. # you never know what those providers got to say
  1712. error_msg = (str(d['error']) +
  1713. str(d.get('error_description', '')))
  1714. else:
  1715. error_msg = 'Invalid response: {0}.'.format(str(resp.status))
  1716. raise FlowExchangeError(error_msg)
  1717. @_helpers.positional(2)
  1718. def flow_from_clientsecrets(filename, scope, redirect_uri=None,
  1719. message=None, cache=None, login_hint=None,
  1720. device_uri=None, pkce=None, code_verifier=None,
  1721. prompt=None):
  1722. """Create a Flow from a clientsecrets file.
  1723. Will create the right kind of Flow based on the contents of the
  1724. clientsecrets file or will raise InvalidClientSecretsError for unknown
  1725. types of Flows.
  1726. Args:
  1727. filename: string, File name of client secrets.
  1728. scope: string or iterable of strings, scope(s) to request.
  1729. redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
  1730. a non-web-based application, or a URI that handles the
  1731. callback from the authorization server.
  1732. message: string, A friendly string to display to the user if the
  1733. clientsecrets file is missing or invalid. If message is
  1734. provided then sys.exit will be called in the case of an error.
  1735. If message in not provided then
  1736. clientsecrets.InvalidClientSecretsError will be raised.
  1737. cache: An optional cache service client that implements get() and set()
  1738. methods. See clientsecrets.loadfile() for details.
  1739. login_hint: string, Either an email address or domain. Passing this
  1740. hint will either pre-fill the email box on the sign-in form
  1741. or select the proper multi-login session, thereby
  1742. simplifying the login flow.
  1743. device_uri: string, URI for device authorization endpoint. For
  1744. convenience defaults to Google's endpoints but any
  1745. OAuth 2.0 provider can be used.
  1746. Returns:
  1747. A Flow object.
  1748. Raises:
  1749. UnknownClientSecretsFlowError: if the file describes an unknown kind of
  1750. Flow.
  1751. clientsecrets.InvalidClientSecretsError: if the clientsecrets file is
  1752. invalid.
  1753. """
  1754. try:
  1755. client_type, client_info = clientsecrets.loadfile(filename,
  1756. cache=cache)
  1757. if client_type in (clientsecrets.TYPE_WEB,
  1758. clientsecrets.TYPE_INSTALLED):
  1759. constructor_kwargs = {
  1760. 'redirect_uri': redirect_uri,
  1761. 'auth_uri': client_info['auth_uri'],
  1762. 'token_uri': client_info['token_uri'],
  1763. 'login_hint': login_hint,
  1764. }
  1765. revoke_uri = client_info.get('revoke_uri')
  1766. optional = (
  1767. 'revoke_uri',
  1768. 'device_uri',
  1769. 'pkce',
  1770. 'code_verifier',
  1771. 'prompt'
  1772. )
  1773. for param in optional:
  1774. if locals()[param] is not None:
  1775. constructor_kwargs[param] = locals()[param]
  1776. return OAuth2WebServerFlow(
  1777. client_info['client_id'], client_info['client_secret'],
  1778. scope, **constructor_kwargs)
  1779. except clientsecrets.InvalidClientSecretsError as e:
  1780. if message is not None:
  1781. if e.args:
  1782. message = ('The client secrets were invalid: '
  1783. '\n{0}\n{1}'.format(e, message))
  1784. sys.exit(message)
  1785. else:
  1786. raise
  1787. else:
  1788. raise UnknownClientSecretsFlowError(
  1789. 'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))