oauth.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import calendar
  2. import json
  3. import logging
  4. import time
  5. from urllib.parse import urlparse, urlencode
  6. from typing import Callable, Optional
  7. from alibabacloud_credentials.provider.refreshable import Credentials, RefreshResult, RefreshCachedSupplier
  8. from alibabacloud_credentials.http import HttpOptions
  9. from Tea.core import TeaCore
  10. from alibabacloud_credentials_api import ICredentialsProvider
  11. from alibabacloud_credentials.utils import parameter_helper as ph
  12. from alibabacloud_credentials.exceptions import CredentialException
  13. log = logging.getLogger('credentials')
  14. log.setLevel(logging.INFO)
  15. ch = logging.StreamHandler()
  16. log.addHandler(ch)
  17. # OAuth 令牌更新回调函数类型
  18. OAuthTokenUpdateCallback = Callable[[str, str, str, str, str, int, int], None]
  19. OAuthTokenUpdateCallbackAsync = Callable[[str, str, str, str, str, int, int], None]
  20. def _get_stale_time(expiration: int) -> int:
  21. if expiration < 0:
  22. return int(time.mktime(time.localtime())) + 60 * 60
  23. # OAuth STS credentials are persisted in the CLI profile and should be
  24. # reused for their complete lifetime. Using an earlier stale time causes
  25. # every credentials lookup near expiration to enter the refresh path even
  26. # though the persisted STS credential is still valid.
  27. return expiration
  28. class OAuthCredentialsProvider(ICredentialsProvider):
  29. DEFAULT_CONNECT_TIMEOUT = 5000
  30. DEFAULT_READ_TIMEOUT = 10000
  31. def __init__(self, *,
  32. client_id: str = None,
  33. sign_in_url: str = None,
  34. access_token: str = None,
  35. access_token_expire: int = 0,
  36. refresh_token: str = None,
  37. access_key_id: str = None,
  38. access_key_secret: str = None,
  39. security_token: str = None,
  40. sts_expiration: int = None,
  41. http_options: HttpOptions = None,
  42. token_update_callback: Optional[OAuthTokenUpdateCallback] = None,
  43. token_update_callback_async: Optional[OAuthTokenUpdateCallbackAsync] = None):
  44. if not client_id:
  45. raise ValueError('the ClientId is empty')
  46. if not sign_in_url:
  47. raise ValueError('the url for sign-in is empty')
  48. self._client_id = client_id
  49. self._sign_in_url = sign_in_url
  50. self._access_token = access_token
  51. self._access_token_expire = access_token_expire
  52. self._refresh_token = refresh_token
  53. # Cached STS credential previously obtained from a token exchange and
  54. # persisted alongside the OAuth tokens (e.g. in the CLI config file).
  55. # Reusing it until ``sts_expiration`` avoids exchanging on every fresh
  56. # provider build, matching aliyun-cli's OAuth resolution.
  57. self._sts_access_key_id = access_key_id
  58. self._sts_access_key_secret = access_key_secret
  59. self._sts_security_token = security_token
  60. self._sts_expiration = sts_expiration
  61. self._token_update_callback = token_update_callback
  62. self._token_update_callback_async = token_update_callback_async
  63. self._http_options = http_options if http_options is not None else HttpOptions()
  64. self._runtime_options = {
  65. 'connectTimeout': self._http_options.connect_timeout if self._http_options.connect_timeout is not None else OAuthCredentialsProvider.DEFAULT_CONNECT_TIMEOUT,
  66. 'readTimeout': self._http_options.read_timeout if self._http_options.read_timeout is not None else OAuthCredentialsProvider.DEFAULT_READ_TIMEOUT,
  67. 'httpsProxy': self._http_options.proxy
  68. }
  69. self._credentials_cache = RefreshCachedSupplier(
  70. refresh_callable=self._refresh_credentials,
  71. refresh_callable_async=self._refresh_credentials_async,
  72. )
  73. def get_credentials(self) -> Credentials:
  74. return self._credentials_cache._sync_call()
  75. async def get_credentials_async(self) -> Credentials:
  76. return await self._credentials_cache._async_call()
  77. def _reuse_cached_sts(self) -> Optional[RefreshResult]:
  78. """Return the cached STS credential when it is still valid.
  79. Mirrors aliyun-cli's OAuth handling (config/profile.go): if a previously
  80. exchanged STS credential is present and not yet expired, reuse it instead
  81. of calling ``/v1/exchange``. This keeps a rotating STS AccessKey id stable
  82. across fresh provider builds and, crucially, avoids re-triggering the
  83. token-update callback (which rewrites the config file) on every resolve.
  84. """
  85. if (self._sts_access_key_id and self._sts_access_key_secret
  86. and self._sts_security_token and self._sts_expiration
  87. and self._sts_expiration > int(time.mktime(time.localtime()))):
  88. credentials = Credentials(
  89. access_key_id=self._sts_access_key_id,
  90. access_key_secret=self._sts_access_key_secret,
  91. security_token=self._sts_security_token,
  92. expiration=self._sts_expiration,
  93. provider_name=self.get_provider_name(),
  94. )
  95. return RefreshResult(value=credentials,
  96. stale_time=_get_stale_time(self._sts_expiration))
  97. return None
  98. def _store_exchanged_sts(self, credentials: Credentials, expiration: int) -> None:
  99. """Remember the freshly exchanged STS so later resolves can reuse it."""
  100. self._sts_access_key_id = credentials.get_access_key_id()
  101. self._sts_access_key_secret = credentials.get_access_key_secret()
  102. self._sts_security_token = credentials.get_security_token()
  103. self._sts_expiration = expiration
  104. def _try_refresh_oauth_token(self) -> None:
  105. current_time = int(time.mktime(time.localtime()))
  106. # 构建刷新令牌请求
  107. r = urlparse(self._sign_in_url)
  108. tea_request = ph.get_new_request()
  109. tea_request.headers['host'] = r.hostname
  110. tea_request.port = r.port
  111. tea_request.protocol = r.scheme
  112. tea_request.method = 'POST'
  113. tea_request.pathname = '/v1/token'
  114. # 设置请求体
  115. body_data = {
  116. 'grant_type': 'refresh_token',
  117. 'refresh_token': self._refresh_token,
  118. 'client_id': self._client_id,
  119. 'Timestamp': ph.get_iso_8061_date()
  120. }
  121. tea_request.body = urlencode(body_data)
  122. tea_request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  123. response = TeaCore.do_action(tea_request, self._runtime_options)
  124. if response.status_code != 200:
  125. raise CredentialException(f"failed to refresh OAuth token, status code: {response.status_code}, response: {response.body.decode('utf-8')}")
  126. # 解析响应
  127. dic = json.loads(response.body.decode('utf-8'))
  128. if 'access_token' not in dic or 'refresh_token' not in dic:
  129. raise CredentialException(f"failed to refresh OAuth token: {response.body.decode('utf-8')}")
  130. # 更新令牌
  131. new_access_token = dic.get('access_token')
  132. new_refresh_token = dic.get('refresh_token')
  133. expires_in = dic.get('expires_in', 3600)
  134. new_access_token_expire = current_time + expires_in
  135. self._access_token = new_access_token
  136. self._refresh_token = new_refresh_token
  137. self._access_token_expire = new_access_token_expire
  138. async def _try_refresh_oauth_token_async(self) -> None:
  139. current_time = int(time.mktime(time.localtime()))
  140. # 构建刷新令牌请求
  141. r = urlparse(self._sign_in_url)
  142. tea_request = ph.get_new_request()
  143. tea_request.headers['host'] = r.hostname
  144. tea_request.port = r.port
  145. tea_request.protocol = r.scheme
  146. tea_request.method = 'POST'
  147. tea_request.pathname = '/v1/token'
  148. # 设置请求体
  149. body_data = {
  150. 'grant_type': 'refresh_token',
  151. 'refresh_token': self._refresh_token,
  152. 'client_id': self._client_id,
  153. 'Timestamp': ph.get_iso_8061_date()
  154. }
  155. tea_request.body = urlencode(body_data)
  156. tea_request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  157. response = await TeaCore.async_do_action(tea_request, self._runtime_options)
  158. if response.status_code != 200:
  159. raise CredentialException(f"failed to refresh OAuth token, status code: {response.status_code}, response: {response.body.decode('utf-8')}")
  160. # 解析响应
  161. dic = json.loads(response.body.decode('utf-8'))
  162. if 'access_token' not in dic or 'refresh_token' not in dic:
  163. raise CredentialException(f"failed to refresh OAuth token: {response.body.decode('utf-8')}")
  164. # 更新令牌
  165. new_access_token = dic.get('access_token')
  166. new_refresh_token = dic.get('refresh_token')
  167. expires_in = dic.get('expires_in', 3600)
  168. new_access_token_expire = current_time + expires_in
  169. self._access_token = new_access_token
  170. self._refresh_token = new_refresh_token
  171. self._access_token_expire = new_access_token_expire
  172. def _refresh_credentials(self) -> RefreshResult[Credentials]:
  173. cached = self._reuse_cached_sts()
  174. if cached is not None:
  175. return cached
  176. if self._refresh_token and (
  177. self._access_token is None or self._access_token_expire <= 0 or self._access_token_expire - int(
  178. time.mktime(time.localtime())) <= 1200):
  179. self._try_refresh_oauth_token()
  180. r = urlparse(self._sign_in_url)
  181. tea_request = ph.get_new_request()
  182. tea_request.headers['host'] = r.hostname
  183. tea_request.port = r.port
  184. tea_request.protocol = r.scheme
  185. tea_request.method = 'POST'
  186. tea_request.pathname = '/v1/exchange'
  187. tea_request.headers['Content-Type'] = 'application/json'
  188. tea_request.headers['Authorization'] = f'Bearer {self._access_token}'
  189. response = TeaCore.do_action(tea_request, self._runtime_options)
  190. if response.status_code != 200:
  191. raise CredentialException(
  192. f"error refreshing credentials from OAuth, http_code: {response.status_code}, result: {response.body.decode('utf-8')}")
  193. dic = json.loads(response.body.decode('utf-8'))
  194. if 'error' in dic:
  195. raise CredentialException(
  196. f"error retrieving credentials from OAuth result: {response.body.decode('utf-8')}")
  197. if 'AccessKeyId' not in dic or 'AccessKeySecret' not in dic or 'SecurityToken' not in dic:
  198. raise CredentialException(
  199. f"error retrieving credentials from OAuth result: {response.body.decode('utf-8')}")
  200. # 先转换为时间数组
  201. time_array = time.strptime(dic.get('Expiration'), '%Y-%m-%dT%H:%M:%SZ')
  202. # 转换为时间戳
  203. expiration = calendar.timegm(time_array)
  204. credentials = Credentials(
  205. access_key_id=dic.get('AccessKeyId'),
  206. access_key_secret=dic.get('AccessKeySecret'),
  207. security_token=dic.get('SecurityToken'),
  208. expiration=expiration,
  209. provider_name=self.get_provider_name()
  210. )
  211. self._store_exchanged_sts(credentials, expiration)
  212. # 调用令牌更新回调函数
  213. if self._token_update_callback:
  214. try:
  215. self._token_update_callback(
  216. self._refresh_token,
  217. self._access_token,
  218. credentials.get_access_key_id(),
  219. credentials.get_access_key_secret(),
  220. credentials.get_security_token(),
  221. self._access_token_expire,
  222. expiration
  223. )
  224. except Exception as e:
  225. log.warning(f'failed to update OAuth tokens in config file: {e}')
  226. return RefreshResult(value=credentials,
  227. stale_time=_get_stale_time(expiration))
  228. async def _refresh_credentials_async(self) -> RefreshResult[Credentials]:
  229. cached = self._reuse_cached_sts()
  230. if cached is not None:
  231. return cached
  232. if self._refresh_token and (
  233. self._access_token is None or self._access_token_expire <= 0 or self._access_token_expire - int(
  234. time.mktime(time.localtime())) <= 1200):
  235. await self._try_refresh_oauth_token_async()
  236. r = urlparse(self._sign_in_url)
  237. tea_request = ph.get_new_request()
  238. tea_request.headers['host'] = r.hostname
  239. tea_request.port = r.port
  240. tea_request.protocol = r.scheme
  241. tea_request.method = 'POST'
  242. tea_request.pathname = '/v1/exchange'
  243. tea_request.headers['Content-Type'] = 'application/json'
  244. tea_request.headers['Authorization'] = f'Bearer {self._access_token}'
  245. response = await TeaCore.async_do_action(tea_request, self._runtime_options)
  246. if response.status_code != 200:
  247. raise CredentialException(
  248. f"error refreshing credentials from OAuth, http_code: {response.status_code}, result: {response.body.decode('utf-8')}")
  249. dic = json.loads(response.body.decode('utf-8'))
  250. if 'error' in dic:
  251. raise CredentialException(
  252. f"error retrieving credentials from OAuth result: {response.body.decode('utf-8')}")
  253. if 'AccessKeyId' not in dic or 'AccessKeySecret' not in dic or 'SecurityToken' not in dic:
  254. raise CredentialException(
  255. f"error retrieving credentials from OAuth result: {response.body.decode('utf-8')}")
  256. # 先转换为时间数组
  257. time_array = time.strptime(dic.get('Expiration'), '%Y-%m-%dT%H:%M:%SZ')
  258. # 转换为时间戳
  259. expiration = calendar.timegm(time_array)
  260. credentials = Credentials(
  261. access_key_id=dic.get('AccessKeyId'),
  262. access_key_secret=dic.get('AccessKeySecret'),
  263. security_token=dic.get('SecurityToken'),
  264. expiration=expiration,
  265. provider_name=self.get_provider_name()
  266. )
  267. self._store_exchanged_sts(credentials, expiration)
  268. if self._token_update_callback_async:
  269. try:
  270. await self._token_update_callback_async(
  271. self._refresh_token,
  272. self._access_token,
  273. credentials.get_access_key_id(),
  274. credentials.get_access_key_secret(),
  275. credentials.get_security_token(),
  276. self._access_token_expire,
  277. expiration
  278. )
  279. except Exception as e:
  280. log.warning(f'failed to update OAuth tokens in config file: {e}')
  281. return RefreshResult(value=credentials,
  282. stale_time=_get_stale_time(expiration))
  283. def _get_client_id(self) -> str:
  284. """获取客户端ID"""
  285. return self._client_id
  286. def get_provider_name(self) -> str:
  287. return 'oauth'