credentials.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. # Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/
  2. # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"). You
  5. # may not use this file except in compliance with the License. A copy of
  6. # the License is located at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # or in the "license" file accompanying this file. This file is
  11. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. # ANY KIND, either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the License.
  14. import time
  15. import datetime
  16. import logging
  17. import os
  18. import getpass
  19. import threading
  20. from collections import namedtuple
  21. from dateutil.parser import parse
  22. from dateutil.tz import tzlocal
  23. import kscore.configloader
  24. import kscore.compat
  25. from kscore.compat import total_seconds
  26. from kscore.exceptions import UnknownCredentialError
  27. from kscore.exceptions import PartialCredentialsError
  28. from kscore.exceptions import ConfigNotFound
  29. from kscore.exceptions import InvalidConfigError
  30. from kscore.exceptions import RefreshWithMFAUnsupportedError
  31. from kscore.utils import InstanceMetadataFetcher, parse_key_val_file
  32. logger = logging.getLogger(__name__)
  33. ReadOnlyCredentials = namedtuple('ReadOnlyCredentials',
  34. ['access_key', 'secret_key', 'token'])
  35. def create_credential_resolver(session):
  36. """Create a default credential resolver.
  37. This creates a pre-configured credential resolver
  38. that includes the default lookup chain for
  39. credentials.
  40. """
  41. profile_name = session.get_config_variable('profile') or 'default'
  42. credential_file = session.get_config_variable('credentials_file')
  43. config_file = session.get_config_variable('config_file')
  44. metadata_timeout = session.get_config_variable('metadata_service_timeout')
  45. num_attempts = session.get_config_variable('metadata_service_num_attempts')
  46. env_provider = EnvProvider()
  47. providers = [
  48. env_provider,
  49. AssumeRoleProvider(
  50. load_config=lambda: session.full_config,
  51. client_creator=session.create_client,
  52. cache={},
  53. profile_name=profile_name,
  54. ),
  55. SharedCredentialProvider(
  56. creds_filename=credential_file,
  57. profile_name=profile_name
  58. ),
  59. # The new config file has precedence over the legacy
  60. # config file.
  61. ConfigProvider(config_filename=config_file, profile_name=profile_name),
  62. OriginalEC2Provider(),
  63. KSCoreProvider(),
  64. InstanceMetadataProvider(
  65. iam_role_fetcher=InstanceMetadataFetcher(
  66. timeout=metadata_timeout,
  67. num_attempts=num_attempts)
  68. )
  69. ]
  70. explicit_profile = session.get_config_variable('profile',
  71. methods=('instance',))
  72. if explicit_profile is not None:
  73. # An explicitly provided profile will negate an EnvProvider.
  74. # We will defer to providers that understand the "profile"
  75. # concept to retrieve credentials.
  76. # The one edge case if is all three values are provided via
  77. # env vars:
  78. # export KS_ACCESS_KEY_ID=foo
  79. # export KS_SECRET_ACCESS_KEY=bar
  80. # export KS_PROFILE=baz
  81. # Then, just like our client() calls, the explicit credentials
  82. # will take precedence.
  83. #
  84. # This precedence is enforced by leaving the EnvProvider in the chain.
  85. # This means that the only way a "profile" would win is if the
  86. # EnvProvider does not return credentials, which is what we want
  87. # in this scenario.
  88. providers.remove(env_provider)
  89. else:
  90. logger.debug('Skipping environment variable credential check'
  91. ' because profile name was explicitly set.')
  92. resolver = CredentialResolver(providers=providers)
  93. return resolver
  94. def get_credentials(session):
  95. resolver = create_credential_resolver(session)
  96. return resolver.load_credentials()
  97. def _local_now():
  98. return datetime.datetime.now(tzlocal())
  99. def _parse_if_needed(value):
  100. if isinstance(value, datetime.datetime):
  101. return value
  102. return parse(value)
  103. def _serialize_if_needed(value):
  104. if isinstance(value, datetime.datetime):
  105. return value.strftime('%Y-%m-%dT%H:%M:%S%Z')
  106. return value
  107. def create_assume_role_refresher(client, params):
  108. def refresh():
  109. response = client.assume_role(**params)
  110. credentials = response['Credentials']
  111. # We need to normalize the credential names to
  112. # the values expected by the refresh creds.
  113. return {
  114. 'access_key': credentials['AccessKeyId'],
  115. 'secret_key': credentials['SecretAccessKey'],
  116. 'token': credentials['SessionToken'],
  117. 'expiry_time': _serialize_if_needed(credentials['Expiration']),
  118. }
  119. return refresh
  120. def create_mfa_serial_refresher():
  121. def _refresher():
  122. # We can explore an option in the future to support
  123. # reprompting for MFA, but for now we just error out
  124. # when the temp creds expire.
  125. raise RefreshWithMFAUnsupportedError()
  126. return _refresher
  127. class Credentials(object):
  128. """
  129. Holds the credentials needed to authenticate requests.
  130. :ivar access_key: The access key part of the credentials.
  131. :ivar secret_key: The secret key part of the credentials.
  132. :ivar token: The security token, valid only for session credentials.
  133. :ivar method: A string which identifies where the credentials
  134. were found.
  135. """
  136. def __init__(self, access_key, secret_key, token=None,
  137. method=None):
  138. self.access_key = access_key
  139. self.secret_key = secret_key
  140. self.token = token
  141. if method is None:
  142. method = 'explicit'
  143. self.method = method
  144. self._normalize()
  145. def _normalize(self):
  146. # Keys would sometimes (accidentally) contain non-ascii characters.
  147. # It would cause a confusing UnicodeDecodeError in Python 2.
  148. # We explicitly convert them into unicode to avoid such error.
  149. #
  150. # Eventually the service will decide whether to accept the credential.
  151. # This also complies with the behavior in Python 3.
  152. self.access_key = kscore.compat.ensure_unicode(self.access_key)
  153. self.secret_key = kscore.compat.ensure_unicode(self.secret_key)
  154. def get_frozen_credentials(self):
  155. return ReadOnlyCredentials(self.access_key,
  156. self.secret_key,
  157. self.token)
  158. class RefreshableCredentials(Credentials):
  159. """
  160. Holds the credentials needed to authenticate requests. In addition, it
  161. knows how to refresh itself.
  162. :ivar refresh_timeout: How long a given set of credentials are valid for.
  163. Useful for credentials fetched over the network.
  164. :ivar access_key: The access key part of the credentials.
  165. :ivar secret_key: The secret key part of the credentials.
  166. :ivar token: The security token, valid only for session credentials.
  167. :ivar method: A string which identifies where the credentials
  168. were found.
  169. """
  170. # The time at which we'll attempt to refresh, but not
  171. # block if someone else is refreshing.
  172. _advisory_refresh_timeout = 15 * 60
  173. # The time at which all threads will block waiting for
  174. # refreshed credentials.
  175. _mandatory_refresh_timeout = 10 * 60
  176. def __init__(self, access_key, secret_key, token,
  177. expiry_time, refresh_using, method,
  178. time_fetcher=_local_now):
  179. self._refresh_using = refresh_using
  180. self._access_key = access_key
  181. self._secret_key = secret_key
  182. self._token = token
  183. self._expiry_time = expiry_time
  184. self._time_fetcher = time_fetcher
  185. self._refresh_lock = threading.Lock()
  186. self.method = method
  187. self._frozen_credentials = ReadOnlyCredentials(
  188. access_key, secret_key, token)
  189. self._normalize()
  190. def _normalize(self):
  191. self._access_key = kscore.compat.ensure_unicode(self._access_key)
  192. self._secret_key = kscore.compat.ensure_unicode(self._secret_key)
  193. @classmethod
  194. def create_from_metadata(cls, metadata, refresh_using, method):
  195. instance = cls(
  196. access_key=metadata['access_key'],
  197. secret_key=metadata['secret_key'],
  198. token=metadata['token'],
  199. expiry_time=cls._expiry_datetime(metadata['expiry_time']),
  200. method=method,
  201. refresh_using=refresh_using
  202. )
  203. return instance
  204. @property
  205. def access_key(self):
  206. self._refresh()
  207. return self._access_key
  208. @access_key.setter
  209. def access_key(self, value):
  210. self._access_key = value
  211. @property
  212. def secret_key(self):
  213. self._refresh()
  214. return self._secret_key
  215. @secret_key.setter
  216. def secret_key(self, value):
  217. self._secret_key = value
  218. @property
  219. def token(self):
  220. self._refresh()
  221. return self._token
  222. @token.setter
  223. def token(self, value):
  224. self._token = value
  225. def _seconds_remaining(self):
  226. delta = self._expiry_time - self._time_fetcher()
  227. return total_seconds(delta)
  228. def refresh_needed(self, refresh_in=None):
  229. """Check if a refresh is needed.
  230. A refresh is needed if the expiry time associated
  231. with the temporary credentials is less than the
  232. provided ``refresh_in``. If ``time_delta`` is not
  233. provided, ``self.advisory_refresh_needed`` will be used.
  234. For example, if your temporary credentials expire
  235. in 10 minutes and the provided ``refresh_in`` is
  236. ``15 * 60``, then this function will return ``True``.
  237. :type refresh_in: int
  238. :param refresh_in: The number of seconds before the
  239. credentials expire in which refresh attempts should
  240. be made.
  241. :return: True if refresh neeeded, False otherwise.
  242. """
  243. if self._expiry_time is None:
  244. # No expiration, so assume we don't need to refresh.
  245. return False
  246. if refresh_in is None:
  247. refresh_in = self._advisory_refresh_timeout
  248. # The credentials should be refreshed if they're going to expire
  249. # in less than 5 minutes.
  250. if self._seconds_remaining() >= refresh_in:
  251. # There's enough time left. Don't refresh.
  252. return False
  253. logger.debug("Credentials need to be refreshed.")
  254. return True
  255. def _is_expired(self):
  256. # Checks if the current credentials are expired.
  257. return self.refresh_needed(refresh_in=0)
  258. def _refresh(self):
  259. # In the common case where we don't need a refresh, we
  260. # can immediately exit and not require acquiring the
  261. # refresh lock.
  262. if not self.refresh_needed(self._advisory_refresh_timeout):
  263. return
  264. # acquire() doesn't accept kwargs, but False is indicating
  265. # that we should not block if we can't acquire the lock.
  266. # If we aren't able to acquire the lock, we'll trigger
  267. # the else clause.
  268. if self._refresh_lock.acquire(False):
  269. try:
  270. if not self.refresh_needed(self._advisory_refresh_timeout):
  271. return
  272. is_mandatory_refresh = self.refresh_needed(
  273. self._mandatory_refresh_timeout)
  274. self._protected_refresh(is_mandatory=is_mandatory_refresh)
  275. return
  276. finally:
  277. self._refresh_lock.release()
  278. elif self.refresh_needed(self._mandatory_refresh_timeout):
  279. # If we're within the mandatory refresh window,
  280. # we must block until we get refreshed credentials.
  281. with self._refresh_lock:
  282. if not self.refresh_needed(self._mandatory_refresh_timeout):
  283. return
  284. self._protected_refresh(is_mandatory=True)
  285. def _protected_refresh(self, is_mandatory):
  286. # precondition: this method should only be called if you've acquired
  287. # the self._refresh_lock.
  288. try:
  289. metadata = self._refresh_using()
  290. except Exception as e:
  291. period_name = 'mandatory' if is_mandatory else 'advisory'
  292. logger.warning("Refreshing temporary credentials failed "
  293. "during %s refresh period.",
  294. period_name, exc_info=True)
  295. if is_mandatory:
  296. # If this is a mandatory refresh, then
  297. # all errors that occur when we attempt to refresh
  298. # credentials are propagated back to the user.
  299. raise
  300. # Otherwise we'll just return.
  301. # The end result will be that we'll use the current
  302. # set of temporary credentials we have.
  303. return
  304. self._set_from_data(metadata)
  305. if self._is_expired():
  306. # We successfully refreshed credentials but for whatever
  307. # reason, our refreshing function returned credentials
  308. # that are still expired. In this scenario, the only
  309. # thing we can do is let the user know and raise
  310. # an exception.
  311. msg = ("Credentials were refreshed, but the "
  312. "refreshed credentials are still expired.")
  313. logger.warning(msg)
  314. raise RuntimeError(msg)
  315. self._frozen_credentials = ReadOnlyCredentials(
  316. self._access_key, self._secret_key, self._token)
  317. @staticmethod
  318. def _expiry_datetime(time_str):
  319. return parse(time_str)
  320. def _set_from_data(self, data):
  321. self.access_key = data['access_key']
  322. self.secret_key = data['secret_key']
  323. self.token = data['token']
  324. self._expiry_time = parse(data['expiry_time'])
  325. logger.debug("Retrieved credentials will expire at: %s", self._expiry_time)
  326. self._normalize()
  327. def get_frozen_credentials(self):
  328. """Return immutable credentials.
  329. The ``access_key``, ``secret_key``, and ``token`` properties
  330. on this class will always check and refresh credentials if
  331. needed before returning the particular credentials.
  332. This has an edge case where you can get inconsistent
  333. credentials. Imagine this:
  334. # Current creds are "t1"
  335. tmp.access_key ---> expired? no, so return t1.access_key
  336. # ---- time is now expired, creds need refreshing to "t2" ----
  337. tmp.secret_key ---> expired? yes, refresh and return t2.secret_key
  338. This means we're using the access key from t1 with the secret key
  339. from t2. To fix this issue, you can request a frozen credential object
  340. which is guaranteed not to change.
  341. The frozen credentials returned from this method should be used
  342. immediately and then discarded. The typical usage pattern would
  343. be::
  344. creds = RefreshableCredentials(...)
  345. some_code = SomeSignerObject()
  346. # I'm about to sign the request.
  347. # The frozen credentials are only used for the
  348. # duration of generate_presigned_url and will be
  349. # immediately thrown away.
  350. request = some_code.sign_some_request(
  351. with_credentials=creds.get_frozen_credentials())
  352. print("Signed request:", request)
  353. """
  354. self._refresh()
  355. return self._frozen_credentials
  356. class CredentialProvider(object):
  357. # Implementations must provide a method.
  358. METHOD = None
  359. def __init__(self, session=None):
  360. self.session = session
  361. def load(self):
  362. """
  363. Loads the credentials from their source & sets them on the object.
  364. Subclasses should implement this method (by reading from disk, the
  365. environment, the network or wherever), returning ``True`` if they were
  366. found & loaded.
  367. If not found, this method should return ``False``, indictating that the
  368. ``CredentialResolver`` should fall back to the next available method.
  369. The default implementation does nothing, assuming the user has set the
  370. ``access_key/secret_key/token`` themselves.
  371. :returns: Whether credentials were found & set
  372. :rtype: boolean
  373. """
  374. return True
  375. def _extract_creds_from_mapping(self, mapping, *key_names):
  376. found = []
  377. for key_name in key_names:
  378. try:
  379. found.append(mapping[key_name])
  380. except KeyError:
  381. raise PartialCredentialsError(provider=self.METHOD,
  382. cred_var=key_name)
  383. return found
  384. class InstanceMetadataProvider(CredentialProvider):
  385. METHOD = 'iam-role'
  386. def __init__(self, iam_role_fetcher):
  387. self._role_fetcher = iam_role_fetcher
  388. def load(self):
  389. fetcher = self._role_fetcher
  390. # We do the first request, to see if we get useful data back.
  391. # If not, we'll pass & move on to whatever's next in the credential
  392. # chain.
  393. metadata = fetcher.retrieve_iam_role_credentials()
  394. if not metadata:
  395. return None
  396. logger.info('Found credentials from IAM Role: %s', metadata['role_name'])
  397. # We manually set the data here, since we already made the request &
  398. # have it. When the expiry is hit, the credentials will auto-refresh
  399. # themselves.
  400. creds = RefreshableCredentials.create_from_metadata(
  401. metadata,
  402. method=self.METHOD,
  403. refresh_using=fetcher.retrieve_iam_role_credentials,
  404. )
  405. return creds
  406. class EnvProvider(CredentialProvider):
  407. METHOD = 'env'
  408. ACCESS_KEY = 'KS_ACCESS_KEY_ID'
  409. SECRET_KEY = 'KS_SECRET_ACCESS_KEY'
  410. # The token can come from either of these env var.
  411. # KS_SESSION_TOKEN is what other KS SDKs have standardized on.
  412. TOKENS = ['KS_SECURITY_TOKEN', 'KS_SESSION_TOKEN']
  413. def __init__(self, environ=None, mapping=None):
  414. """
  415. :param environ: The environment variables (defaults to
  416. ``os.environ`` if no value is provided).
  417. :param mapping: An optional mapping of variable names to
  418. environment variable names. Use this if you want to
  419. change the mapping of access_key->KS_ACCESS_KEY_ID, etc.
  420. The dict can have up to 3 keys: ``access_key``, ``secret_key``,
  421. ``session_token``.
  422. """
  423. if environ is None:
  424. environ = os.environ
  425. self.environ = environ
  426. self._mapping = self._build_mapping(mapping)
  427. def _build_mapping(self, mapping):
  428. # Mapping of variable name to env var name.
  429. var_mapping = {}
  430. if mapping is None:
  431. # Use the class var default.
  432. var_mapping['access_key'] = self.ACCESS_KEY
  433. var_mapping['secret_key'] = self.SECRET_KEY
  434. var_mapping['token'] = self.TOKENS
  435. else:
  436. var_mapping['access_key'] = mapping.get(
  437. 'access_key', self.ACCESS_KEY)
  438. var_mapping['secret_key'] = mapping.get(
  439. 'secret_key', self.SECRET_KEY)
  440. var_mapping['token'] = mapping.get(
  441. 'token', self.TOKENS)
  442. if not isinstance(var_mapping['token'], list):
  443. var_mapping['token'] = [var_mapping['token']]
  444. return var_mapping
  445. def load(self):
  446. """
  447. Search for credentials in explicit environment variables.
  448. """
  449. if self._mapping['access_key'] in self.environ:
  450. logger.info('Found credentials in environment variables.')
  451. access_key, secret_key = self._extract_creds_from_mapping(
  452. self.environ, self._mapping['access_key'],
  453. self._mapping['secret_key'])
  454. token = self._get_session_token()
  455. return Credentials(access_key, secret_key, token,
  456. method=self.METHOD)
  457. else:
  458. return None
  459. def _get_session_token(self):
  460. for token_envvar in self._mapping['token']:
  461. if token_envvar in self.environ:
  462. return self.environ[token_envvar]
  463. class OriginalEC2Provider(CredentialProvider):
  464. METHOD = 'ec2-credentials-file'
  465. CRED_FILE_ENV = 'KS_CREDENTIAL_FILE'
  466. ACCESS_KEY = 'KSAccessKeyId'
  467. SECRET_KEY = 'KSSecretKey'
  468. def __init__(self, environ=None, parser=None):
  469. if environ is None:
  470. environ = os.environ
  471. if parser is None:
  472. parser = parse_key_val_file
  473. self._environ = environ
  474. self._parser = parser
  475. def load(self):
  476. """
  477. Search for a credential file used by original EC2 CLI tools.
  478. """
  479. if 'KS_CREDENTIAL_FILE' in self._environ:
  480. full_path = os.path.expanduser(self._environ['KS_CREDENTIAL_FILE'])
  481. creds = self._parser(full_path)
  482. if self.ACCESS_KEY in creds:
  483. logger.info('Found credentials in KS_CREDENTIAL_FILE.')
  484. access_key = creds[self.ACCESS_KEY]
  485. secret_key = creds[self.SECRET_KEY]
  486. # EC2 creds file doesn't support session tokens.
  487. return Credentials(access_key, secret_key, method=self.METHOD)
  488. else:
  489. return None
  490. class SharedCredentialProvider(CredentialProvider):
  491. METHOD = 'shared-credentials-file'
  492. ACCESS_KEY = 'ks_access_key_id'
  493. SECRET_KEY = 'ks_secret_access_key'
  494. # Same deal as the EnvProvider above. KSCore originally supported
  495. # ks_security_token, but the SDKs are standardizing on ks_session_token
  496. # so we support both.
  497. TOKENS = ['ks_security_token', 'ks_session_token']
  498. def __init__(self, creds_filename, profile_name=None, ini_parser=None):
  499. self._creds_filename = creds_filename
  500. if profile_name is None:
  501. profile_name = 'default'
  502. self._profile_name = profile_name
  503. if ini_parser is None:
  504. ini_parser = kscore.configloader.raw_config_parse
  505. self._ini_parser = ini_parser
  506. def load(self):
  507. try:
  508. available_creds = self._ini_parser(self._creds_filename)
  509. except ConfigNotFound:
  510. return None
  511. if self._profile_name in available_creds:
  512. config = available_creds[self._profile_name]
  513. if self.ACCESS_KEY in config:
  514. logger.info("Found credentials in shared credentials file: %s",
  515. self._creds_filename)
  516. access_key, secret_key = self._extract_creds_from_mapping(
  517. config, self.ACCESS_KEY, self.SECRET_KEY)
  518. token = self._get_session_token(config)
  519. return Credentials(access_key, secret_key, token,
  520. method=self.METHOD)
  521. def _get_session_token(self, config):
  522. for token_envvar in self.TOKENS:
  523. if token_envvar in config:
  524. return config[token_envvar]
  525. class ConfigProvider(CredentialProvider):
  526. """INI based config provider with profile sections."""
  527. METHOD = 'config-file'
  528. ACCESS_KEY = 'ks_access_key_id'
  529. SECRET_KEY = 'ks_secret_access_key'
  530. # Same deal as the EnvProvider above. KSCore originally supported
  531. # ks_security_token, but the SDKs are standardizing on ks_session_token
  532. # so we support both.
  533. TOKENS = ['ks_security_token', 'ks_session_token']
  534. def __init__(self, config_filename, profile_name, config_parser=None):
  535. """
  536. :param config_filename: The session configuration scoped to the current
  537. profile. This is available via ``session.config``.
  538. :param profile_name: The name of the current profile.
  539. :param config_parser: A config parser callable.
  540. """
  541. self._config_filename = config_filename
  542. self._profile_name = profile_name
  543. if config_parser is None:
  544. config_parser = kscore.configloader.load_config
  545. self._config_parser = config_parser
  546. def load(self):
  547. """
  548. If there is are credentials in the configuration associated with
  549. the session, use those.
  550. """
  551. try:
  552. full_config = self._config_parser(self._config_filename)
  553. except ConfigNotFound:
  554. return None
  555. if self._profile_name in full_config['profiles']:
  556. profile_config = full_config['profiles'][self._profile_name]
  557. if self.ACCESS_KEY in profile_config:
  558. logger.info("Credentials found in config file: %s",
  559. self._config_filename)
  560. access_key, secret_key = self._extract_creds_from_mapping(
  561. profile_config, self.ACCESS_KEY, self.SECRET_KEY)
  562. token = self._get_session_token(profile_config)
  563. return Credentials(access_key, secret_key, token,
  564. method=self.METHOD)
  565. else:
  566. return None
  567. def _get_session_token(self, profile_config):
  568. for token_name in self.TOKENS:
  569. if token_name in profile_config:
  570. return profile_config[token_name]
  571. class KSCoreProvider(CredentialProvider):
  572. METHOD = 'ksc-config'
  573. KSC_CONFIG_ENV = 'KSC_CONFIG'
  574. DEFAULT_CONFIG_FILENAMES = ['/etc/kscore.cfg', './.kscore.cfg', 'C:\\kscore.cfg']
  575. ACCESS_KEY = 'ks_access_key_id'
  576. SECRET_KEY = 'ks_secret_access_key'
  577. def __init__(self, environ=None, ini_parser=None):
  578. if environ is None:
  579. environ = os.environ
  580. if ini_parser is None:
  581. ini_parser = kscore.configloader.raw_config_parse
  582. self._environ = environ
  583. self._ini_parser = ini_parser
  584. def load(self):
  585. """
  586. Look for credentials in ksc config file.
  587. """
  588. if self.KSC_CONFIG_ENV in self._environ:
  589. potential_locations = [self._environ[self.KSC_CONFIG_ENV]]
  590. else:
  591. potential_locations = self.DEFAULT_CONFIG_FILENAMES
  592. for filename in potential_locations:
  593. try:
  594. config = self._ini_parser(filename)
  595. except ConfigNotFound:
  596. # Move on to the next potential config file name.
  597. continue
  598. if 'Credentials' in config:
  599. credentials = config['Credentials']
  600. if self.ACCESS_KEY in credentials:
  601. logger.info("Found credentials in ksc config file: %s",
  602. filename)
  603. access_key, secret_key = self._extract_creds_from_mapping(
  604. credentials, self.ACCESS_KEY, self.SECRET_KEY)
  605. return Credentials(access_key, secret_key,
  606. method=self.METHOD)
  607. class AssumeRoleProvider(CredentialProvider):
  608. METHOD = 'assume-role'
  609. ROLE_CONFIG_VAR = 'role_arn'
  610. # Credentials are considered expired (and will be refreshed) once the total
  611. # remaining time left until the credentials expires is less than the
  612. # EXPIRY_WINDOW.
  613. EXPIRY_WINDOW_SECONDS = 60 * 15
  614. def __init__(self, load_config, client_creator, cache, profile_name,
  615. prompter=getpass.getpass):
  616. """
  617. :type load_config: callable
  618. :param load_config: A function that accepts no arguments, and
  619. when called, will return the full configuration dictionary
  620. for the session (``session.full_config``).
  621. :type client_creator: callable
  622. :param client_creator: A factory function that will create
  623. a client when called. Has the same interface as
  624. ``kscore.session.Session.create_client``.
  625. :type cache: JSONFileCache
  626. :param cache: An object that supports ``__getitem__``,
  627. ``__setitem__``, and ``__contains__``. An example
  628. of this is the ``JSONFileCache`` class.
  629. :type profile_name: str
  630. :param profile_name: The name of the profile.
  631. :type prompter: callable
  632. :param prompter: A callable that returns input provided
  633. by the user (i.e raw_input, getpass.getpass, etc.).
  634. """
  635. #: The cache used to first check for assumed credentials.
  636. #: This is checked before making the AssumeRole API
  637. #: calls and can be useful if you have short lived
  638. #: scripts and you'd like to avoid calling AssumeRole
  639. #: until the credentials are expired.
  640. self.cache = cache
  641. self._load_config = load_config
  642. # client_creator is a callable that creates function.
  643. # It's basically session.create_client
  644. self._client_creator = client_creator
  645. self._profile_name = profile_name
  646. self._prompter = prompter
  647. # The _loaded_config attribute will be populated from the
  648. # load_config() function once the configuration is actually
  649. # loaded. The reason we go through all this instead of just
  650. # requiring that the loaded_config be passed to us is to that
  651. # we can defer configuration loaded until we actually try
  652. # to load credentials (as opposed to when the object is
  653. # instantiated).
  654. self._loaded_config = {}
  655. def load(self):
  656. self._loaded_config = self._load_config()
  657. if self._has_assume_role_config_vars():
  658. return self._load_creds_via_assume_role()
  659. def _has_assume_role_config_vars(self):
  660. profiles = self._loaded_config.get('profiles', {})
  661. return self.ROLE_CONFIG_VAR in profiles.get(self._profile_name, {})
  662. def _load_creds_via_assume_role(self):
  663. # We can get creds in one of two ways:
  664. # * It can either be cached on disk from an pre-existing session
  665. # * Cache doesn't have the creds (or is expired) so we need to make
  666. # an assume role call to get temporary creds, which we then cache
  667. # for subsequent requests.
  668. creds = self._load_creds_from_cache()
  669. if creds is not None:
  670. logger.debug("Credentials for role retrieved from cache.")
  671. return creds
  672. else:
  673. # We get the Credential used by kscore as well
  674. # as the original parsed response from the server.
  675. creds, response = self._retrieve_temp_credentials()
  676. cache_key = self._create_cache_key()
  677. self._write_cached_credentials(response, cache_key)
  678. return creds
  679. def _load_creds_from_cache(self):
  680. cache_key = self._create_cache_key()
  681. try:
  682. from_cache = self.cache[cache_key]
  683. if self._is_expired(from_cache):
  684. # Don't need to delete the cache entry,
  685. # when we refresh via AssumeRole, we'll
  686. # update the cache with the new entry.
  687. logger.debug("Credentials were found in cache, but they are expired.")
  688. return None
  689. else:
  690. return self._create_creds_from_response(from_cache)
  691. except KeyError:
  692. return None
  693. def _is_expired(self, credentials):
  694. end_time = parse(credentials['Credentials']['Expiration'])
  695. now = datetime.datetime.now(tzlocal())
  696. seconds = total_seconds(end_time - now)
  697. return seconds < self.EXPIRY_WINDOW_SECONDS
  698. def _create_cache_key(self):
  699. role_config = self._get_role_config_values()
  700. # On windows, ':' is not allowed in filenames, so we'll
  701. # replace them with '_' instead.
  702. role_arn = role_config['role_arn'].replace(':', '_')
  703. role_session_name=role_config.get('role_session_name')
  704. if role_session_name:
  705. cache_key = '%s--%s--%s' % (self._profile_name, role_arn, role_session_name)
  706. else:
  707. cache_key = '%s--%s' % (self._profile_name, role_arn)
  708. return cache_key.replace('/', '-')
  709. def _write_cached_credentials(self, creds, cache_key):
  710. self.cache[cache_key] = creds
  711. def _get_role_config_values(self):
  712. # This returns the role related configuration.
  713. profiles = self._loaded_config.get('profiles', {})
  714. try:
  715. source_profile = profiles[self._profile_name]['source_profile']
  716. role_arn = profiles[self._profile_name]['role_arn']
  717. mfa_serial = profiles[self._profile_name].get('mfa_serial')
  718. except KeyError as e:
  719. raise PartialCredentialsError(provider=self.METHOD,
  720. cred_var=str(e))
  721. external_id = profiles[self._profile_name].get('external_id')
  722. role_session_name = profiles[self._profile_name].get('role_session_name')
  723. if source_profile not in profiles:
  724. raise InvalidConfigError(
  725. error_msg=(
  726. 'The source_profile "%s" referenced in '
  727. 'the profile "%s" does not exist.' % (
  728. source_profile, self._profile_name)))
  729. source_cred_values = profiles[source_profile]
  730. return {
  731. 'role_arn': role_arn,
  732. 'external_id': external_id,
  733. 'source_profile': source_profile,
  734. 'mfa_serial': mfa_serial,
  735. 'source_cred_values': source_cred_values,
  736. 'role_session_name': role_session_name
  737. }
  738. def _create_creds_from_response(self, response):
  739. config = self._get_role_config_values()
  740. if config.get('mfa_serial') is not None:
  741. # MFA would require getting a new TokenCode which would require
  742. # prompting the user for a new token, so we use a different
  743. # refresh_func.
  744. refresh_func = create_mfa_serial_refresher()
  745. else:
  746. refresh_func = create_assume_role_refresher(
  747. self._create_client_from_config(config),
  748. self._assume_role_base_kwargs(config))
  749. return RefreshableCredentials(
  750. access_key=response['Credentials']['AccessKeyId'],
  751. secret_key=response['Credentials']['SecretAccessKey'],
  752. token=response['Credentials']['SessionToken'],
  753. method=self.METHOD,
  754. expiry_time=_parse_if_needed(
  755. response['Credentials']['Expiration']),
  756. refresh_using=refresh_func)
  757. def _create_client_from_config(self, config):
  758. source_cred_values = config['source_cred_values']
  759. client = self._client_creator(
  760. 'sts', ks_access_key_id=source_cred_values['ks_access_key_id'],
  761. ks_secret_access_key=source_cred_values['ks_secret_access_key'],
  762. ks_session_token=source_cred_values.get('ks_session_token'),
  763. )
  764. return client
  765. def _retrieve_temp_credentials(self):
  766. logger.debug("Retrieving credentials via AssumeRole.")
  767. config = self._get_role_config_values()
  768. client = self._create_client_from_config(config)
  769. assume_role_kwargs = self._assume_role_base_kwargs(config)
  770. response = client.assume_role(**assume_role_kwargs)
  771. creds = self._create_creds_from_response(response)
  772. return creds, response
  773. def _assume_role_base_kwargs(self, config):
  774. assume_role_kwargs = {'RoleArn': config['role_arn']}
  775. if config['external_id'] is not None:
  776. assume_role_kwargs['ExternalId'] = config['external_id']
  777. if config['mfa_serial'] is not None:
  778. token_code = self._prompter("Enter MFA code: ")
  779. assume_role_kwargs['SerialNumber'] = config['mfa_serial']
  780. assume_role_kwargs['TokenCode'] = token_code
  781. if config['role_session_name'] is not None:
  782. assume_role_kwargs['RoleSessionName'] = config['role_session_name']
  783. else:
  784. role_session_name = 'KS-CLI-session-%s' % (int(time.time()))
  785. assume_role_kwargs['RoleSessionName'] = role_session_name
  786. return assume_role_kwargs
  787. class CredentialResolver(object):
  788. def __init__(self, providers):
  789. """
  790. :param providers: A list of ``CredentialProvider`` instances.
  791. """
  792. self.providers = providers
  793. def insert_before(self, name, credential_provider):
  794. """
  795. Inserts a new instance of ``CredentialProvider`` into the chain that will
  796. be tried before an existing one.
  797. :param name: The short name of the credentials you'd like to insert the
  798. new credentials before. (ex. ``env`` or ``config``). Existing names
  799. & ordering can be discovered via ``self.available_methods``.
  800. :type name: string
  801. :param cred_instance: An instance of the new ``Credentials`` object
  802. you'd like to add to the chain.
  803. :type cred_instance: A subclass of ``Credentials``
  804. """
  805. try:
  806. offset = [p.METHOD for p in self.providers].index(name)
  807. except ValueError:
  808. raise UnknownCredentialError(name=name)
  809. self.providers.insert(offset, credential_provider)
  810. def insert_after(self, name, credential_provider):
  811. """
  812. Inserts a new type of ``Credentials`` instance into the chain that will
  813. be tried after an existing one.
  814. :param name: The short name of the credentials you'd like to insert the
  815. new credentials after. (ex. ``env`` or ``config``). Existing names
  816. & ordering can be discovered via ``self.available_methods``.
  817. :type name: string
  818. :param cred_instance: An instance of the new ``Credentials`` object
  819. you'd like to add to the chain.
  820. :type cred_instance: A subclass of ``Credentials``
  821. """
  822. offset = self._get_provider_offset(name)
  823. self.providers.insert(offset + 1, credential_provider)
  824. def remove(self, name):
  825. """
  826. Removes a given ``Credentials`` instance from the chain.
  827. :param name: The short name of the credentials instance to remove.
  828. :type name: string
  829. """
  830. available_methods = [p.METHOD for p in self.providers]
  831. if not name in available_methods:
  832. # It's not present. Fail silently.
  833. return
  834. offset = available_methods.index(name)
  835. self.providers.pop(offset)
  836. def get_provider(self, name):
  837. """Return a credential provider by name.
  838. :type name: str
  839. :param name: The name of the provider.
  840. :raises UnknownCredentialError: Raised if no
  841. credential provider by the provided name
  842. is found.
  843. """
  844. return self.providers[self._get_provider_offset(name)]
  845. def _get_provider_offset(self, name):
  846. try:
  847. return [p.METHOD for p in self.providers].index(name)
  848. except ValueError:
  849. raise UnknownCredentialError(name=name)
  850. def load_credentials(self):
  851. """
  852. Goes through the credentials chain, returning the first ``Credentials``
  853. that could be loaded.
  854. """
  855. # First provider to return a non-None response wins.
  856. for provider in self.providers:
  857. logger.debug("Looking for credentials via: %s", provider.METHOD)
  858. creds = provider.load()
  859. if creds is not None:
  860. return creds
  861. # If we got here, no credentials could be found.
  862. # This feels like it should be an exception, but historically, ``None``
  863. # is returned.
  864. #
  865. # +1
  866. # -js
  867. return None