Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

凭证管理支持获取默认凭证 #106

Merged
merged 11 commits into from Aug 26, 2021
119 changes: 119 additions & 0 deletions tencentcloud/common/credential.py
Expand Up @@ -14,13 +14,16 @@
# limitations under the License.

import json
import os
import time
try:
# py3
import configparser
from urllib.parse import urlencode
from urllib.request import urlopen
except ImportError:
# py2
import ConfigParser as configparser
from urllib import urlencode
from urllib import urlopen

Expand Down Expand Up @@ -134,6 +137,13 @@ def update_credential(self):
# maybe we should validate token to None as well
pass

def get_credential(self):
if self.secretId is None or self.secretKey is None or self._token is None:
return None
if len(self.secretId) == 0 or len(self.secretKey) == 0 or len(self.token) == 0:
return None
return self


class STSAssumeRoleCredential(object):
"""使用STSAssumeRoleCredential,制动role,
Expand Down Expand Up @@ -226,3 +236,112 @@ def get_sts_tmp_role_arn(self):
self._tmp_secret_key = t_c["Response"]["Credentials"]["TmpSecretKey"]
self._expired_time = t_c["Response"]["ExpiredTime"] - self._duration_seconds*0.9


class EnvironmentVariableCredentialProvider():
def __init__(self):
"""Tencent Cloud EnvironmentVariableCredentialProvider.

Access https://console.cloud.tencent.com/cam/capi to manage your
credentials.

:param secretId: The secret id of your credential, get by environment variable TENCENTCLOUD_SECRET_ID
:type secretId: str
:param secretKey: The secret key of your credential. get by environment variable TENCENTCLOUD_SECRET_KEY
:type secretKey: str
"""
self.secretId = os.environ.get('TENCENTCLOUD_SECRET_ID')
Copy link
Member

@zqfan zqfan Jun 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

secretId => secret_id,其他的也都改一下吧
看下是否需要实时读取

self.secretKey = os.environ.get('TENCENTCLOUD_SECRET_KEY')

def get_credential(self):
if self.secretId is None or self.secretKey is None:
return None
if len(self.secretId) == 0 or len(self.secretKey) == 0:
return None
return Credential(self.secretId, self.secretKey)


class ProfileCredentialProvider():
def __init__(self):
"""Tencent Cloud ProfileVariableCredentialProvider.

Access https://console.cloud.tencent.com/cam/capi to manage your
credentials.

default file position is "~/.tencentcloud/credentials" or "/etc/tencentcloud/credentials", it is ini format.
such as:
[default]
secret_id=""
secret_key=""

:param secretId: The secret id of your credential.
:type secretId: str
:param secretKey: The secret key of your credential.
:type secretKey: str
"""
if os.path.exists(os.environ['HOME'] + "/.tencentcloud/credentials"):
file_path = os.environ['HOME'] + "/.tencentcloud/credentials"
elif os.path.exists("/etc/tencentcloud/credentials"):
file_path = "/etc/tencentcloud/credentials"
else:
file_path = ""
if file_path:
# loads config
conf = configparser.ConfigParser()
conf.read(file_path)
ini_map = dict(conf._sections)
for k in dict(conf._sections):
option = dict(ini_map[k])
for key, value in dict(ini_map[k]).items():
option[key] = value.strip()
ini_map[k] = option
if "default" in ini_map:
client_config = ini_map.get("default")
self.secretId = client_config.get('secret_id', None)
self.secretKey = client_config.get('secret_key', None)
self.role_name = client_config.get('role_name', None)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

role_name => role_arn,因为sts现在没有根据role_name查role_arn的公开接口

else:
self.secretId = None
self.secretKey = None
self.role_name = None

def get_credential(self):
if self.secretId is None or self.secretKey is None:
return None
if len(self.secretId) == 0 or len(self.secretKey) == 0:
return None
return Credential(self.secretId, self.secretKey)


class DefaultCredentialProvider(object):
"""Tencent Cloud DefaultCredentialProvider.

DefaultCredentialProvider will search credential by order EnvironmentVariableCredentialProvider ProfileCredentialProvider
and CVMRoleCredential.
"""

def __init__(self):
self.cred = None

def get_credentials(self):
if self.cred is not None:
return self.cred

e_v_c_p = EnvironmentVariableCredentialProvider()
env_cred = e_v_c_p.get_credential()
self.cred = env_cred
if self.cred is not None:
return self.cred

p_c_p = ProfileCredentialProvider()
prof_cred = p_c_p.get_credential()
self.cred = prof_cred
if self.cred is not None:
return self.cred

c_r_c = CVMRoleCredential()
cvm_role_crd = c_r_c.get_credential()
self.cred = cvm_role_crd
if self.cred is not None:
return self.cred

raise TencentCloudSDKException("no valid credentail.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TencentCloudSDKException("ClientSideError", "no valid credentail.") ,要指明错误码,这种就判定为客户端错误就好了