diff --git a/.github/workflows/testPython.yml b/.github/workflows/testPython.yml index 0fd3d1f..9f1526c 100644 --- a/.github/workflows/testPython.yml +++ b/.github/workflows/testPython.yml @@ -52,7 +52,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} # required build-win: - runs-on: windows-2019 + runs-on: windows-2025 strategy: matrix: python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12" ] diff --git a/README-CN.md b/README-CN.md index 75311e0..a8f85c6 100644 --- a/README-CN.md +++ b/README-CN.md @@ -19,117 +19,162 @@ 如未安装 `pip`, 请先至pip官网 [pip user guide](https://pip.pypa.io/en/stable/installing/ "pip User Guide") 安装pip . ```bash -# 安装 alibabacloud_credentials -pip install alibabacloud_credentials +# 安装 alibabacloud-credentials +pip install alibabacloud-credentials ``` ## 使用说明 在您开始之前,您需要注册阿里云帐户并获取您的[凭证](https://usercenter.console.aliyun.com/#/manage/ak)。 +### Credentials工具**配置参数**介绍 +---------------------------------------------- + +Credentials工具的配置参数定义在`alibabacloud_credentials.models`模块的`Config`类中,凭据类型由必填参数`type`指定。确定凭据类型后,需根据该凭据类型选择相应的参数。下表将详细介绍`type`的取值范围及各类凭据类型所支持的参数。其中,`√`表示必填参数,`-`表示可选参数,`×`表示不支持参数。 + +**说明** +未在下表中列出的凭据类型及参数表示不建议继续使用。 + + +| **type** | **access_key** | **sts** | **ram_role_arn** | **ecs_ram_role** | **oidc_role_arn** | **credentials_uri** | **bearer** | +| --- | --- | ---- | --- | --- | --- | --- | --- | +| access_key_id:访问凭据ID。 | √ | √ | √ | × | × | × | × | +| access_key_secret:访问凭据密钥。 | √ | √ | √ | × | × | × | × | +| security_token:STS Token。 | × | √ | - | × | × | × | × | +| role_arn:RAM角色的ARN。 | × | × | √ | × | √ | × | × | +| role_session_name:自定义会话名称,默认格式为`credentials-python-当前时间的时间戳`。 | × | × | - | × | - | × | × | +| role_name:RAM角色名称。 | × | × | × | - | × | × | × | +| disable_imds_v1:是否强制使用加固模式,默认值为`false`。 | × | × | × | - | × | × | × | +| bearer_token:bearer token。 | × | × | × | × | × | × | √ | +| policy:自定义权限策略。 | × | × | - | × | - | × | × | +| role_session_expiration:会话过期时间,默认3600秒。 | × | × | - | × | - | × | × | +| oidc_provider_arn:OIDC提供商ARN。 | × | × | × | × | √ | × | × | +| oidc_token_file_path:OIDC Token文件路径。 | × | × | × | × | √ | × | × | +| external_id:角色外部 ID,主要功能是防止混淆代理人问题。 | × | × | - | × | × | × | × | +| credentials_uri:凭证的URI。 | × | × | × | × | × | √ | × | +| sts_endpoint:STS的服务接入点,支持VPC服务接入点和公网服务接入点,默认值为`sts.aliyuncs.com`。 | × | × | - | × | - | × | × | +| timeout:HTTP请求的读超时时间,默认值为5000毫秒。 | × | × | - | - | - | - | × | +| connect_timeout:HTTP请求的连接超时时间,默认值为10000毫秒。 | × | × | - | - | - | - | × | + + +### 初始化凭据客户端 +------------------------- + +Credentials工具支持多种方式初始化凭据客户端,您可根据实际情况选择合适的方式进行凭据客户端初始化。 + +**重要** + +* 在项目中使用明文AccessKey,容易因代码仓库权限管理不当造成AccessKey泄露,会威胁该账号下所有资源的安全。建议通过环境变量、配置文件等方式获取AccessKey。 + +* 在初始化凭据客户端时建议采用单例模式,这不仅可启用SDK的凭证缓存功能,还能有效防止因多次调用接口导致的流量控制问题和性能资源的浪费。 + + ### 凭证类型 -#### Access Key +#### 使用默认凭据链 -通过[用户信息管理](https://usercenter.console.aliyun.com/#/manage/ak)设置 access_key,它们具有该账户完全的权限,请妥善保管。有时出于安全考虑,您不能把具有完全访问权限的主账户 AccessKey 交于一个项目的开发者使用,您可以[创建RAM子账户](https://ram.console.aliyun.com/users)并为子账户[授权](https://ram.console.aliyun.com/permissions),使用RAM子用户的 AccessKey 来进行API调用。 +当您在初始化凭据客户端不传入任何参数时,Credentials工具会使用默认凭据链方式初始化客户端。默认凭据的读取逻辑请参见[默认凭据链](#默认凭证链)。 ```python -from alibabacloud_credentials.client import Client -from alibabacloud_credentials.models import Config +from alibabacloud_credentials.client import Client as CredClient -config = Config( - type='access_key', # 凭证类型 - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret -) -cred = Client(config) +# 不指定参数 +credentialsClient = CredClient() -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -cred_type = cred.get_type() +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -#### STS +#### Access Key -通过安全令牌服务(Security Token Service,简称 STS),申请临时安全凭证(Temporary Security Credentials,简称 TSC),创建临时安全凭证。 +通过[用户信息管理](https://usercenter.console.aliyun.com/#/manage/ak)设置 access_key,它们具有该账户完全的权限,请妥善保管。出于安全考虑,您不能把具有完全访问权限的主账户 AccessKey 交于一个项目的开发者使用,您可以[创建RAM子账户](https://ram.console.aliyun.com/users)并为子账户[授权](https://ram.console.aliyun.com/permissions),使用RAM子用户的 AccessKey 来进行API调用。 ```python +import os from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='sts', # 凭证类型 - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken' # STS Token + type='access_key', + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -#### RAM Role ARN +#### STS -通过指定[RAM角色](https://ram.console.aliyun.com/#/role/list),让凭证自动申请维护 STS Token。你可以通过为 `Policy` 赋值来限制获取到的 STS Token 的权限。 +通过安全令牌服务(Security Token Service,简称 STS),申请临时安全凭证(Temporary Security Credentials,简称 TSC),创建临时安全凭证。 ```python +import os + from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='ram_role_arn', # 凭证类型 - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken', # STS Token - role_arn='roleArn', # 格式: acs:ram::用户ID:role/角色名 - role_session_name='roleSessionName', # 角色会话名称 - policy='policy', # 可选, 限制 STS Token 的权限 - role_session_expiration=3600 # 可选, 限制 STS Token 的有效时间 + type='sts', + # 从环境变量中获取AccessKey ID的值 + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + # 从环境变量中获取AccessKeySecret的值 + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), + # 从环境变量中获取临时SecurityToken的值 + security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN') ) -cred = Client(config) +credClient = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = credClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -#### OIDC Role ARN +#### RAM Role ARN -通过指定[OIDC角色],让凭证自动申请维护 STS Token。你可以通过为 `Policy` 赋值来限制获取到的 STS Token 的权限。 +通过指定[RAM角色](https://ram.console.aliyun.com/#/role/list),Credentials工具可以帮助开发者前往STS换取STS Token。您可以通过为 `Policy` 赋值来限制RAM角色到一个更小的权限集合。 ```python -from alibabacloud_credentials.client import Client -from alibabacloud_credentials.models import Config +import os -config = Config( - type='oidc_role_arn', # 凭证类型 - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken', # STS Token - role_arn='roleArn', # 格式: acs:ram::用户ID:role/角色名 - oidc_provider_arn='oidcProviderArn', # 格式: acs:ram::用户Id:oidc-provider/OIDC身份提供商名称 - oidc_token_file_path='/Users/xxx/xxx',# 格式: path,可不设,但需要通过设置 ALIBABA_CLOUD_OIDC_TOKEN_FILE 来代替 - role_session_name='roleSessionName', # 角色会话名称 - policy='policy', # 可选, 限制 STS Token 的权限 - role_session_expiration=3600 # 可选, 限制 STS Token 的有效时间 +from alibabacloud_credentials.client import Client as CredClient +from alibabacloud_credentials.models import Config as CredConfig + +credentialsConfig = CredConfig( + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), + type='ram_role_arn', + # 要扮演的RAM角色ARN,示例值:acs:ram::123456789012****:role/adminrole,可以通过环境变量ALIBABA_CLOUD_ROLE_ARN设置role_arn + role_arn='', + # 角色会话名称,可以通过环境变量ALIBABA_CLOUD_ROLE_SESSION_NAME设置role_session_name + role_session_name='', + # 设置更小的权限策略,非必填。示例值:{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} + policy='', + role_session_expiration=3600 ) -cred = Client(config) +credentialsClient = CredClient(credentialsConfig) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` #### ECS RAM Role -ECS和ECI实例均支持绑定实例RAM角色,当在实例中使用Credentials工具时,将自动获取实例绑定的RAM角色,并通过访问元数据服务获取RAM角色的STS Token,以完成凭据客户端的初始化。 +ECS和ECI实例均支持绑定实例RAM角色,运行于实例中的程序可通过Credentials工具自动获取该角色的STS Token,从而完成凭据客户端的初始化。 -实例元数据服务器支持加固模式和普通模式两种访问方式,Credentials工具默认使用加固模式(IMDSv2)获取访问凭据。若使用加固模式时发生异常,您可以通过设置disable_imds_v1来执行不同的异常处理逻辑: +Credentials工具将默认采用加固模式(IMDSv2)访问ECS的元数据服务(Meta Data Server),在使用加固模式时若发生异常,将使用普通模式兜底来获取访问凭据。您也可以通过设置参数`disable_imds_v1`或环境变量 *ALIBABA_CLOUD_IMDSV1_DISABLE* ,执行不同的异常处理逻辑: - 当值为false(默认值)时,会使用普通模式继续获取访问凭据。 @@ -137,134 +182,237 @@ ECS和ECI实例均支持绑定实例RAM角色,当在实例中使用Credentials 服务端是否支持IMDSv2,取决于您在服务器的配置。 +另外,您可以通过配置环境变量ALIBABA_CLOUD_ECS_METADATA_DISABLED=true来关闭ECS元数据的凭证访问。 + +**说明** +使用加固模式获取临时身份凭证时,alibabacloud-credentials的版本不低于 **0.3.6** 。 + +```python +from alibabacloud_credentials.client import Client as CredClient +from alibabacloud_credentials.models import Config as CredConfig + +credentialsConfig = CredConfig( + type='ecs_ram_role', + # 选填,该ECS角色的角色名称,不填会自动获取,但是建议加上以减少请求次数,可以通过环境变量ALIBABA_CLOUD_ECS_METADATA设置role_name + role_name='', + # 选填,默认值:False。True:表示强制使用加固模式。False:系统将首先尝试在加固模式下获取凭据。如果失败,则会切换到普通模式(IMDSv1)进行尝试 + # disable_imds_v1=True, +) +credentialsClient = CredClient(credentialsConfig) + +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() +``` + +#### OIDC Role ARN + +为了避免影响云上资源的安全,同时又能让不可信的应用安全地获取所需的 STS Token,实现应用级别的权限最小化,您可以使用[RRSA(RAM Roles for Service Account)]功能。阿里云容器集群会为不同的应用Pod创建和挂载相应的服务账户OIDC Token文件,并将相关配置信息注入到环境变量中,Credentials工具通过获取环境变量的配置信息,调用STS服务的[AssumeRoleWithOIDC]接口换取绑定角色的STS Token。 + +注入的环境变量如下: + +***ALIBABA_CLOUD_ROLE_ARN:*** RAM角色名称ARN; + +***ALIBABA_CLOUD_OIDC_PROVIDER_ARN:*** OIDC提供商ARN; + +***ALIBABA_CLOUD_OIDC_TOKEN_FILE:*** OIDC Token文件路径; + ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='ecs_ram_role', # 凭证类型 - role_name='roleName', # 账户RoleName,非必填,不填则自动获取,建议设置,可以减少请求 - disable_imds_v1=True # 选填,是否强制关闭IMDSv1,即必须使用IMDSv2加固模式,可以通过环境变量ALIBABA_CLOUD_IMDSV1_DISABLED设置 + type='oidc_role_arn', + # RAM角色名称ARN,可以通过环境变量ALIBABA_CLOUD_ROLE_ARN设置role_arn + role_arn='', + # OIDC提供商ARN,可以通过环境变量ALIBABA_CLOUD_OIDC_PROVIDER_ARN设置oidc_provider_arn + oidc_provider_arn='', + # OIDC Token文件路径,可以通过环境变量ALIBABA_CLOUD_OIDC_TOKEN_FILE设置oidc_token_file_path + oidc_token_file_path='', + # 角色会话名称,可以通过环境变量ALIBABA_CLOUD_ROLE_SESSION_NAME设置role_session_name + role_session_name='', + # 设置更小的权限策略,非必填。示例值:{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} + policy='', + # 设置session过期时间 + role_session_expiration=3600 ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` #### Credentials URI -通过指定一个 Credentials 地址,从外部服务申请并自动维护 STS Token +通过在应用内部封装STS Token服务并对外提供自定义URI,其他服务仅能通过该URI获取STS Token,这样能够有效降低AK等信息的暴露风险。Credentials工具支持通过请求该服务的URI来获取STS Token,从而实现凭据客户端的初始化。 ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='credentials_uri', # 凭证类型 - credentials_uri='http://local_or_remote_uri/', # Credentials URI + type='credentials_uri', + # 凭证的 URI,格式为http://local_or_remote_uri/,可以通过环境变量ALIBABA_CLOUD_CREDENTIALS_URI设置credentials_uri + credentials_uri='', ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` +该地址必须满足如下条件: + +* 支持GET请求。 + +* 响应 200 状态码。 + +* 响应体为如下的结构: + + ```json + { + "Code": "Success", + "AccessKeySecret": "AccessKeySecret", + "AccessKeyId": "AccessKeyId", + "Expiration": "2021-09-26T03:46:38Z", + "SecurityToken": "SecurityToken" + } + ``` + #### Bearer -如呼叫中心(CCC)需用此凭证,请自行申请维护 Bearer Token。 +目前只有云呼叫中心[CCC](https://api.aliyun.com/api/CCC/2020-07-01/ListPrivilegesOfUser)这款产品支持Bearer Token的凭据初始化方式。 ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='bearer', # 凭证类型 - bearer_token='bearerToken', # BearerToken + type='bearer', + # 填入您的Bearer Token + bearer_token='', ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -### 使用默认凭证提供链 +### 默认凭证链 -```python -from alibabacloud_credentials.client import Client as CredClient -from alibabacloud_ocr20191230.client import Client as OcrClient -from alibabacloud_ocr20191230.models import GetAsyncJobResultRequest -from alibabacloud_tea_rpc.models import Config -from alibabacloud_tea_util.models import RuntimeOptions +当您的程序开发环境和生产环境采用不同的凭据类型,常见做法是在代码中获取当前环境信息,编写获取不同凭据的分支代码。借助Credentials工具的默认凭据链,您可以用同一套代码,通过程序之外的配置来控制不同环境下的凭据获取方式。当您在不传入参数的情况下,直接使用`cred = CredClient()`初始化凭据客户端时,阿里云SDK将会尝试按照如下顺序查找相关凭据信息。 -cred = CredClient() -config = Config(credential=cred) +1. 使用环境变量 -client = OcrClient(config) + 在环境变量里寻找环境凭证,如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID` 和 `ALIBABA_CLOUD_ACCESS_KEY_SECRET` 环境变量且不为空,程序将使用它们创建默认凭证。如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID`、`ALIBABA_CLOUD_ACCESS_KEY_SECRET` 和 `ALIBABA_CLOUD_SECURITY_TOKEN` 环境变量且不为空,则创建 STS 方式的临时凭证,注意:该 token 存在过期时间,推荐在临时环境中使用。 -request = GetAsyncJobResultRequest( - job_id='' -) +2. 使用OIDC RAM角色 + + 如果未找到更高优先级的凭据信息,Credentials工具会检查以下与OIDC RAM角色相关的环境变量: + + * ***ALIBABA_CLOUD_ROLE_ARN:*** RAM角色名称ARN。 + + * ***ALIBABA_CLOUD_OIDC_PROVIDER_ARN:*** OIDC提供商ARN。 + + * ***ALIBABA_CLOUD_OIDC_TOKEN_FILE:*** OIDC Token文件路径。 + + 如果以上三个变量均被设置且内容有效,Credentials将会使用变量内容调用STS服务的[AssumeRoleWithOIDC]接口换取STS Token作为默认凭据。 + +3. 使用配置文件 + + **说明** + 该功能要求alibabacloud_credentials的版本不低于 **1.0rc3** 。 + + 如果未找到更高优先级的凭据信息,Credentials工具会尝试加载`config.json`配置文件。该文件的默认完整路径如下: + + * Linux/Mac系统:`~/.aliyun/config.json` + + * Windows系统:`C:\Users\USER_NAME\.aliyun\config.json` + + 请注意,这些默认路径不可更改为其他路径。如果您需要通过此方式配置访问凭据,您可以手动在相应路径下创建config.json配置文件,内容格式示例如下: + + ```json + { + "current": "", + "profiles": [ + { + "name": "", + "mode": "AK", + "access_key_id": "", + "access_key_secret": "" + }, + { + "name": "", + "mode": "StsToken", + "access_key_id": "", + "access_key_secret": "", + "sts_token": "" + }, + { + "name": "", + "mode": "RamRoleArn", + "access_key_id": "", + "access_key_secret": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + }, + { + "name": "", + "mode": "EcsRamRole", + "ram_role_name": "" + }, + { + "name": "", + "mode": "OIDC", + "oidc_provider_arn": "", + "oidc_token_file": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + }, + { + "name": "", + "mode": "ChainableRamRoleArn", + "source_profile": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + } + ] + } + ``` + 在config.json配置文件中可以通过mode指定不同的凭据: -runtime_options = RuntimeOptions() -response = client.get_async_job_result(request, runtime_options) -``` + * AK:使用用户的Access Key作为凭据信息; -默认凭证提供程序链查找可用的凭证,寻找顺序如下: + * StsToken:使用STS Token作为凭据信息; -1. 环境凭证 + * RamRoleArn:使用RAM角色的ARN来获取凭据信息; - 在环境变量里寻找环境凭证,如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID` 和 `ALIBABA_CLOUD_ACCESS_KEY_SECRET` 环境变量且不为空,程序将使用它们创建默认凭证。如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID`、`ALIBABA_CLOUD_ACCESS_KEY_SECRET` 和 `ALIBABA_CLOUD_SECURITY_TOKEN` 环境变量且不为空,则创建 STS 方式的临时凭证,注意:该 token 存在过期时间,推荐在临时环境中使用。 + * EcsRamRole:利用ECS绑定的RAM角色来获取凭据信息; -2. 配置文件 - - 如果用户主目录存在默认文件 `~/.alibabacloud/credentials.ini (Windows 为 C:\Users\USER_NAME\.alibabacloud\credentials.ini)`,程序会自动创建指定类型和名称的凭证。默认文件可以不存在,但解析错误会抛出异常。配置名小写。不同的项目、工具之间可以共用这个配置文件,因为不在项目之内,也不会被意外提交到版本控制。\ - - 可以通过定义 `ALIBABA_CLOUD_CREDENTIALS_FILE` 环境变量修改默认文件的路径。不配置则使用默认配置 `default`,也可以设置环境变量 `ALIBABA_CLOUD_PROFILE` 使用配置。 - - ```ini - [default] # 默认配置 - enable = true # 启用,没有该选项默认不启用 - type = access_key # 认证方式为 access_key - access_key_id = foo # Key - access_key_secret = bar # Secret - - [client1] # 命名为 `client1` 的配置 - type = ecs_ram_role # 认证方式为 ecs_ram_role - role_name = EcsRamRoleTest # Role Name - - [client2] # 命名为 `client2` 的配置 - enable = false # 不启用 - type = ram_role_arn # 认证方式为 ram_role_arn - region_id = cn-test # 获取session用的region - policy = test # 选填 指定权限 - access_key_id = foo - access_key_secret = bar - role_arn = role_arn - role_session_name = session_name # 选填 - - [client3] # 命名为 `client3` 的配置 - enable = false # 不启用 - type = oidc_role_arn # 认证方式为 oidc_role_arn - region_id = cn-test # 获取session用的region - policy = test # 选填 指定权限 - access_key_id = foo # 选填 - access_key_secret = bar # 选填 - role_arn = role_arn - oidc_provider_arn = oidc_provider_arn - oidc_token_file_path = /xxx/xxx # 可通过设置环境变量 ALIBABA_CLOUD_OIDC_TOKEN_FILE 来代替 - role_session_name = session_name # 选填 - ``` + * OIDC:通过OIDC ARN和OIDC Token来获取凭据信息; -3. 实例 RAM 角色 + * ChainableRamRoleArn:采用角色链的方式,通过`source_profile`指定`config.json`配置文件中其他凭据的名称,以重新获取新的凭据信息。 - 若不存在优先级更高的凭据信息,Credentials工具将通过环境变量获取ALIBABA_CLOUD_ECS_METADATA(ECS实例RAM角色名称)的值。若该变量的值存在,程序将采用加固模式(IMDSv2)访问ECS的元数据服务(Meta Data Server),以获取ECS实例RAM角色的STS Token作为默认凭据信息。在使用加固模式时若发生异常,将使用普通模式兜底来获取访问凭据。您也可以通过设置环境变量ALIBABA_CLOUD_IMDSV1_DISABLED,执行不同的异常处理逻辑: + 配置完成后,Credentials将根据配置文件中 **current** 所指定的凭据名称,选择对应的凭据初始化凭据客户端。此外,还可以通过环境变量 ***ALIBABA_CLOUD_PROFILE*** 指定具体的凭据名称,例如将 ***ALIBABA_CLOUD_PROFILE*** 的值设置为 **client1** 。 + + +4. 使用ECS实例RAM角色 + + 若不存在优先级更高的凭据信息,Credentials工具将默认采用加固模式(IMDSv2)访问ECS的元数据服务(Meta Data Server),以获取ECS实例RAM角色的STS Token作为默认凭据信息。程序会自动访问ECS的元数据服务拿到RoleName信息,再去获取凭证,也就是两次请求。若想减少一次请求,可以直接在环境变量中配置 ***ALIBABA_CLOUD_ECS_METADATA*** 来指定实例RAM角色名称。在使用加固模式时若发生异常,将使用普通模式兜底来获取访问凭据。您也可以通过设置环境变量 ***ALIBABA_CLOUD_IMDSV1_DISABLED*** ,执行不同的异常处理逻辑: - 当值为false时,会使用普通模式继续获取访问凭据。 @@ -272,9 +420,11 @@ response = client.get_async_job_result(request, runtime_options) 服务端是否支持IMDSv2,取决于您在服务器的配置。 -4. Credentials URI + 另外,您可以通过配置环境变量ALIBABA_CLOUD_ECS_METADATA_DISABLED=true来关闭ECS元数据的凭证访问。 + +5. 使用Credentials工具URI - 如果定义了环境变量 `ALIBABA_CLOUD_CREDENTIALS_URI` 且不为空, 程序会将该环境变量的值作为 Credentials URI 地址,在调用时,获取临时安全凭证。 + 如果上述方式均未找到有效的凭据信息,Credentials工具会检查环境变量 ***ALIBABA_CLOUD_CREDENTIALS_URI*** ,如果该变量存在且指向一个有效的URI地址,Credentials会向该URI发起HTTP请求,获取临时安全凭证作为默认凭据。 ## 问题 diff --git a/README.md b/README.md index 504458e..fdd7507 100644 --- a/README.md +++ b/README.md @@ -19,34 +19,96 @@ English | [简体中文](README-CN.md) Python SDK uses a common package management tool named `pip`. If pip is not installed, see the [pip user guide](https://pip.pypa.io/en/stable/installing/ "pip User Guide") to install pip. ```bash -# Install the alibabacloud_credentials -pip install alibabacloud_credentials +# Install the alibabacloud-credentials +pip install alibabacloud-credentials ``` ## Usage Before you begin, you need to sign up for an Alibaba Cloud account and retrieve your [Credentials](https://usercenter.console.aliyun.com/#/manage/ak). +### **Parameters** of the **Credentials tool** + +----------------------------------------------------------- + +The parameters of the Credentials tool are defined in the `Config` class of the `alibabacloud_credentials.models` module. The credential type is determined by the value of `type`, which is a required parameter in the configurations. After you determine a credential type, configure parameters based on the credential type. The following table describes the valid values of `type` and the parameters supported by each credential type. In the table, a check mark (`✓`) indicates that the parameter is required, a hyphen (`-`) indicates that the parameter is optional, and an X mark (`×`) indicates that the parameter is not supported. + +**Note** + +We recommend that you do not use parameters that are not listed in the following table. + +| **type** | **access_key** | **sts** | **ram_role_arn** | **ecs_ram_role** | **oidc_role_arn** | **credentials_uri** | **bearer** | +| --- | --- | ---- | --- | --- | --- | --- | --- | +| access_key_id: the AccessKey ID. | ✓ | ✓ | ✓ | × | × | × | × | +| access_key_secret: the AccessKey secret. | ✓ | ✓ | ✓ | × | × | × | × | +| security_token: Security Token Service (STS) token. | × | ✓ | - | × | × | × | × | +| role_arn: the Alibaba Cloud Resource Name (ARN) of the Resource Access Management (RAM) role. | × | × | ✓ | × | ✓ | × | × | +| role_session_name: the name of the custom session. The default format is `credentials-java-The current timestamp`. | × | × | - | × | - | × | × | +| role_name: specifies the name of the RAM role. | × | × | × | - | × | × | × | +| disable_imds_v1: specifies whether to forcibly use the security hardening mode (IMDSv2). If you set this parameter to true, the security hardening mode (IMDSv2) is used. Default value: `false`. | × | × | × | - | × | × | × | +| bearer_token: a bearer token. | × | × | × | × | × | × | ✓ | +| policy: a custom policy. | × | × | - | × | - | × | × | +| role_session_expiration: the session timeout period. Default value: 3600. Unit: seconds. | × | × | - | × | - | × | × | +| oidc_provider_arn: the ARN of the OpenID Connect (OIDC) identity provider (IdP). | × | × | × | × | ✓ | × | × | +| oidc_token_file_path: the absolute path to the OIDC token. | × | × | × | × | ✓ | × | × | +| external_id: the external ID of the role, which is used to prevent the confused deputy issue. | × | × | - | × | × | × | × | +| credentials_uri: the URI of the credential. | × | × | × | × | × | ✓ | × | +| sts_endpoint: the endpoint of STS. VPC endpoints and Internet endpoints are supported. Default value: `sts.aliyuncs.com`. | × | × | - | × | - | × | × | +| timeout: the timeout period of HTTP read requests. Default value: 5000. Unit: milliseconds. | × | × | - | - | - | - | × | +| connect_timeout: the timeout period of HTTP connection requests. Default value: 10000. Unit: milliseconds. | × | × | - | - | - | - | × | + + +Initialize a Credentials client +------------------------------------------------ + +You can use one of the following methods to initialize a Credentials client as needed: + +**Important** + +* If you use a plaintext AccessKey pair in a project, the AccessKey pair may be leaked due to improper permission management on the code repository. This may threaten the security of all resources within the account to which the AccessKey pair belongs. We recommend that you store the AccessKey pair in environment variables or configuration files. + +* We recommend that you initialize the Credentials client in single-instance mode. This mode not only enables the credential caching feature of the SDK, but also effectively prevents traffic control issues and waste of performance resources caused by multiple API calls. + ### Credential Type +#### Use the default credential provider chain + +If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see [Default credential provider chain](#default-credential-provider-chain). + +```python +from alibabacloud_credentials.client import Client as CredClient + +# Do not specify a method to initialize a Credentials client. +credentialsClient = CredClient() + +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() +``` + #### Access Key -Setup access_key credential through [User Information Management][ak], it have full authority over the account, please keep it safe. Sometimes for security reasons, you cannot hand over a primary account AccessKey with full access to the developer of a project. You may create a sub-account [RAM Sub-account][ram] , grant its [authorization][permissions],and use the AccessKey of RAM Sub-account. +Setup access_key credential through [User Information Management][ak], it have full authority over the account, please keep it safe. For security reasons, you cannot hand over a primary account AccessKey with full access to the developer of a project. You may create a sub-account [RAM Sub-account][ram] , grant its [authorization][permissions],and use the AccessKey of RAM Sub-account. ```python +import os from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='access_key', # credential type - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret + type='access_key', + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` #### STS @@ -54,225 +116,312 @@ cred_type = cred.get_type() Create a temporary security credential by applying Temporary Security Credentials (TSC) through the Security Token Service (STS). ```python +import os + from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='sts', # credential type - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken' # STS Token + type='sts', + # Obtain the AccessKey ID from the environment variable. + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + # Obtain the AccessKey secret from the environment variable. + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), + # Obtain the temporary STS token from the environment variable. + security_token=os.environ.get('ALIBABA_CLOUD_SECURITY_TOKEN') ) -cred = Client(config) +credClient = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = credClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` #### RAM Role ARN -By specifying [RAM Role][RAM Role], the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions([How to make a policy][policy]) of STS Token, you can assign value for `Policy`. +The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains the security token from STS. You can also use the `policy` parameter to limit the permissions of the RAM role. ```python -from alibabacloud_credentials.client import Client -from alibabacloud_credentials.models import Config +import os -config = Config( - type='ram_role_arn', # credential type - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken', # STS Token - role_arn='roleArn', # Format: acs:ram::USER_ID:role/ROLE_NAME - role_session_name='roleSessionName', # Role Session Name - policy='policy', # Not required, limit the permissions of STS Token - role_session_expiration=3600 # Not required, limit the Valid time of STS Token +from alibabacloud_credentials.client import Client as CredClient +from alibabacloud_credentials.models import Config as CredConfig + +credentialsConfig = CredConfig( + access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), + access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), + type='ram_role_arn', + # Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole. + role_arn='', + # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. + role_session_name='', + # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} + policy='', + role_session_expiration=3600 ) -cred = Client(config) +credentialsClient = CredClient(credentialsConfig) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -#### OIDC Role ARN +#### ECS RAM Role -By specifying [OIDC Role][OIDC Role], the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions([How to make a policy][policy]) of STS Token, you can assign value for `Policy`. +ECS instances and elastic container instances can be assigned RAM roles. Programs that run on the instances can use the Credentials tool to automatically obtain an STS token for the RAM role. The STS token can be used to initialize the Credentials client. -```python -from alibabacloud_credentials.client import Client -from alibabacloud_credentials.models import Config +By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2). If an exception is thrown, the Credentials tool switches to the normal mode (IMDSv1). You can also configure the `disable_imds_v1` parameter or the *ALIBABA_CLOUD_IMDSV1_DISABLE* environment variable to specify the exception handling logic. Valid values: -config = Config( - type='oidc_role_arn', # credential type - access_key_id='accessKeyId', # AccessKeyId - access_key_secret='accessKeySecret', # AccessKeySecret - security_token='securityToken', # STS Token - role_arn='roleArn', # Format: acs:ram::USER_ID:role/ROLE_NAME - oidc_provider_arn='oidcProviderArn', # Format: acs:ram::USER_Id:oidc-provider/OIDC Providers - oidc_token_file_path='/Users/xxx/xxx',# oidc_token_file_path can be replaced by setting environment variable: ALIBABA_CLOUD_OIDC_TOKEN_FILE - role_session_name='roleSessionName', # Role Session Name - policy='policy', # Not required, limit the permissions of STS Token - role_session_expiration=3600 # Not required, limit the Valid time of STS Token +* false (default): The Credentials tool continues to obtain the access credential in normal mode (IMDSv1). + +* true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode. + +The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2). + +In addition, you can specify ALIBABA_CLOUD_ECS_METADATA_DISABLED=true to disable access from the Credentials tool to the metadata server of ECS. + +```python +from alibabacloud_credentials.client import Client as CredClient +from alibabacloud_credentials.models import Config as CredConfig + +credentialsConfig = CredConfig( + type='ecs_ram_role', + # Optional. Specify the name of the RAM role of the ECS instance by specifying the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests. + role_name='', + # Default value: False. This parameter is optional. True: The security hardening mode (IMDSv2) is forcibly used. False: The system preferentially attempts to obtain the access credential in security hardening mode (IMDSv2). If the attempt fails, the system switches to the normal mode (IMDSv1) to obtain access credentials. + # disable_imds_v1=True, ) -cred = Client(config) +credentialsClient = CredClient(credentialsConfig) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = credentialsClient.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -#### ECS RAM Role +#### OIDC Role ARN -Both ECS and ECI instances support binding instance RAM roles. When the Credentials tool is used in an instance, the RAM role bound to the instance will be automatically obtained, and the STS Token of the RAM role will be obtained by accessing the metadata service to complete the initialization of the credential client. +To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the [RAM Roles for Service Accounts (RRSA)] feature to grant minimum necessary permissions to an application. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information from the environment variables and calls the [AssumeRoleWithOIDC] operation of STS to obtain the STS token for attached roles. -The instance metadata server supports two access modes: hardened mode and normal mode. The Credentials tool uses hardened mode (IMDSv2) by default to obtain access credentials. If an exception occurs when using hardened mode, you can set disable_imds_v1 to perform different exception handling logic: +The following environment variables are injected into the pod: -- When the value is false (default value), the normal mode will continue to be used to obtain access credentials. +***ALIBABA_CLOUD_ROLE_ARN*** : the ARN of the RAM role. -- When the value is true, it means that only hardened mode can be used to obtain access credentials, and an exception will be thrown. +***ALIBABA_CLOUD_OIDC_PROVIDER_ARN*** : the ARN of the OIDC identity provider (IdP). -Whether the server supports IMDSv2 depends on your configuration on the server. +***ALIBABA_CLOUD_OIDC_TOKEN_FILE*** : the path of the OIDC token file. ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='ecs_ram_role', # credential type - role_name='roleName', # `role_name` is optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests. - disable_imds_v1=True # Optional, whether to forcibly disable IMDSv1, that is, to use IMDSv2 hardening mode, which can be set by the environment variable ALIBABA_CLOUD_IMDSV1_DISABLED + type='oidc_role_arn', + # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. + role_arn='', + # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. + oidc_provider_arn='', + # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. + oidc_token_file_path='', + # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. + role_session_name='', + # Optional. Specify the minimum permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} + policy='', + # Specify the validity period of the session. + role_session_expiration=3600 ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` #### Credentials URI -By specifying a credentials uri, get credential from the local or remote uri, the credential will be able to automatically request maintenance to keep it update. +This method lets you encapsulate an STS token in your application and provide a custom URI to external resources. Other services can obtain the STS token only through the URI. This minimizes the risk of AccessKey exposure. The Credentials tool lets you obtain the STS token by calling the service URI to initialize the Credentials client. ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='credentials_uri', # credential type - credentials_uri='http://local_or_remote_uri/', # Credentials URI + type='credentials_uri', + # Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. + credentials_uri='', ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` +The URI must meet the following requirements: + +* GET requests are supported. + +* The HTTP 200 status code can be returned. + +* The following response body structure is used: + + ```json + { + "Code": "Success", + "AccessKeySecret": "AccessKeySecret", + "AccessKeyId": "AccessKeyId", + "Expiration": "2021-09-26T03:46:38Z", + "SecurityToken": "SecurityToken" + } + ``` + #### Bearer -If credential is required by the Cloud Call Centre (CCC), please apply for Bearer Token maintenance by yourself. +Only [Cloud Call Center](https://api.aliyun.com/api/CCC/2020-07-01/ListPrivilegesOfUser){#0764d4314be87} lets you use a bearer token to initialize an SDK client. ```python from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config config = Config( - type='bearer', # credential type - bearer_token='bearerToken', # BearerToken + type='bearer', + # Enter the bearer token. + bearer_token='', ) cred = Client(config) -access_key_id = cred.get_access_key_id() -access_key_secret = cred.get_access_key_secret() -security_token = cred.get_security_token() -cred_type = cred.get_type() +credential = cred.get_credential() +access_key_id = credential.get_access_key_id() +access_key_secret = credential.get_access_key_secret() +security_token = credential.get_security_token() +cred_type = credential.get_type() ``` -### Use the default credential provider chain +### Default credential provider chain -```python -from alibabacloud_credentials.client import Client as CredClient -from alibabacloud_ocr20191230.client import Client as OcrClient -from alibabacloud_ocr20191230.models import GetAsyncJobResultRequest -from alibabacloud_tea_rpc.models import Config -from alibabacloud_tea_util.models import RuntimeOptions +If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of Alibaba Cloud Credentials for Java allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use `cred = CredClient()`{#e19090ab80ah6} to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order: -cred = CredClient() -config = Config(credential=cred) +1. btain the credential information from environment variables -client = OcrClient(config) + Look for environment credentials in environment variable. If the `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET` environment variables are defined and are not empty, the program will use them to create default credentials. If the `ALIBABA_CLOUD_ACCESS_KEY_ID`, `ALIBABA_CLOUD_ACCESS_KEY_SECRET` and `ALIBABA_CLOUD_SECURITY_TOKEN` environment variables are defined and are not empty, the program will use them to create temporary security credentials(STS). Note: This token has an expiration time, it is recommended to use it in a temporary environment. -request = GetAsyncJobResultRequest( - job_id='' -) +2. Obtain the credential information by using the RAM role of an OIDC IdP + + If no credentials with a higher priority are found, the Credentials tool checks the following environment variables that are related to the RAM role of the OIDC IdP: + + * ***ALIBABA_CLOUD_ROLE_ARN*** : the ARN of the RAM role. + + * ***ALIBABA_CLOUD_OIDC_PROVIDER_ARN*** : the ARN of the OIDC IdP. + + * ***ALIBABA_CLOUD_OIDC_TOKEN_FILE:*** the file path of the OIDC token. + + If the preceding three environment variables are specified and valid, the Credentials tool uses the environment variables to call the [AssumeRoleWithOIDC] operation of STS to obtain an STS token as the default credential. + +3. Obtain the credential information from a configuration file + + **Note** + Make sure that the version of alibabacloud_credentials is **1.0rc3** or later. + + If no credentials with a higher priority are found, the Credentials tool attempts to load the `config.json`{#d4a26eb196u7q} file. Default file path: + + * Linux/macOS: `~/.aliyun/config.json` + + * Windows: `C:\Users\USER_NAME\.aliyun\config.json` + + Do not change the preceding default paths. If you want to use this method to configure an access credential, manually create a config.json file in the corresponding path. Example: + + ```json + { + "current": "", + "profiles": [ + { + "name": "", + "mode": "AK", + "access_key_id": "", + "access_key_secret": "" + }, + { + "name": "", + "mode": "StsToken", + "access_key_id": "", + "access_key_secret": "", + "sts_token": "" + }, + { + "name": "", + "mode": "RamRoleArn", + "access_key_id": "", + "access_key_secret": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + }, + { + "name": "", + "mode": "EcsRamRole", + "ram_role_name": "" + }, + { + "name": "", + "mode": "OIDC", + "oidc_provider_arn": "", + "oidc_token_file": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + }, + { + "name": "", + "mode": "ChainableRamRoleArn", + "source_profile": "", + "ram_role_arn": "", + "ram_session_name": "", + "expired_seconds": 3600 + } + ] + } + ``` + In the config.json file, you can use mode to specify a type of credential: -runtime_options = RuntimeOptions() -response = client.get_async_job_result(request, runtime_options) -``` + * AK: uses the AccessKey pair of a RAM user to obtain the credential information. -The default credential provider chain looks for available credentials, with following order: + * StsToken: uses the STS token as the credential information. -1. Environment Credentials + * RamRoleArn: uses the ARN of a RAM role to obtain the credential information. - Look for environment credentials in environment variable. If the `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET` environment variables are defined and are not empty, the program will use them to create default credentials. If the `ALIBABA_CLOUD_ACCESS_KEY_ID`, `ALIBABA_CLOUD_ACCESS_KEY_SECRET` and `ALIBABA_CLOUD_SECURITY_TOKEN` environment variables are defined and are not empty, the program will use them to create temporary security credentials(STS). Note: This token has an expiration time, it is recommended to use it in a temporary environment. + * EcsRamRole: uses the RAM role attached to an ECS instance to obtain the credential information. + + * OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information. + + * ChainableRamRoleArn: utilizes a role chaining mechanism. It allows you to assume a new RAM role and acquire a new, temporary credential by referencing another credential profile, which is specified by the `source_profile` parameter. + + After you complete the configurations, the Credentials tool selects the credential specified by the **current** parameter in the configuration file and initialize the client. You can also specify the ***ALIBABA_CLOUD_PROFILE*** environment variable to specify the credential information. For example, you can set the ***ALIBABA_CLOUD_PROFILE*** environment variable to **client1** . -2. Credentials File - - If there is `~/.alibabacloud/credentials.ini default file (Windows shows C:\Users\USER_NAME\.alibabacloud\credentials.ini)`, the program automatically creates credentials with the specified type and name. The default file is not necessarily exist, but a parse error will throw an exception. The name of configuration item is lowercase.This configuration file can be shared between different projects and between different tools. Because it is outside of the project and will not be accidentally committed to the version control. The path to the default file can be modified by defining the `ALIBABA_CLOUD_CREDENTIALS_FILE` environment variable. If not configured, use the default configuration `default`. You can also set the environment variables `ALIBABA_CLOUD_PROFILE` to use the configuration. - - ```ini - [default] # default setting - enable = true # Enable,Enabled by default if this option is not present - type = access_key # Certification type: access_key - access_key_id = foo # Key - access_key_secret = bar # Secret - - [client1] # configuration that is named as `client1` - type = ecs_ram_role # Certification type: ecs_ram_role - role_name = EcsRamRoleTest # Role Name - - [client2] # configuration that is named as `client2` - enable = false # Disable - type = ram_role_arn # Certification type: ram_role_arn - region_id = cn-test - policy = test # optional Specify permissions - access_key_id = foo - access_key_secret = bar - role_arn = role_arn - role_session_name = session_name # optional - - [client3] # configuration that is named as `client3` - enable = false # Disable - type = oidc_role_arn # Certification type: oidc_role_arn - region_id = cn-test - policy = test # optional Specify permissions - access_key_id = foo # optional - access_key_secret = bar # optional - role_arn = role_arn - oidc_provider_arn = oidc_provider_arn - oidc_token_file_path = /xxx/xxx # can be replaced by setting environment variable: ALIBABA_CLOUD_OIDC_TOKEN_FILE - role_session_name = session_name # optional - ``` -3. Instance RAM Role +3. Obtain the credential information by using the RAM role of an ECS instance - If there is no credential information with a higher priority, the Credentials tool will obtain the value of ALIBABA_CLOUD_ECS_METADATA (ECS instance RAM role name) through the environment variable. If the value of this variable exists, the program will use the hardened mode (IMDSv2) to access the metadata service (Meta Data Server) of ECS to obtain the STS Token of the ECS instance RAM role as the default credential information. If an exception occurs when using the hardened mode, the normal mode will be used as a fallback to obtain access credentials. You can also set the environment variable ALIBABA_CLOUD_IMDSV1_DISABLED to perform different exception handling logic: + By default, if no credential that has a higher priority exists, the Credential tool accesses the metadata server of ECS in security hardening mode (IMDSv2) to obtain the STS token of the RAM role used by the ECS instance and uses the STS token as the default credential. The program automatically access the metadata server of ECS to obtain the name of the RAM role (RoleName) and then obtains the credential. Two requests are sent in this process. If you want to send only one request, add the ***ALIBABA_CLOUD_ECS_METADATA*** environment variable to specify the name of the RAM role. If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode. You can also configure the ***ALIBABA_CLOUD_IMDSV1_DISABLED*** environment variable to specify an exception handling logic. Valid values of the environment variable: - - When the value is false, the normal mode will continue to obtain access credentials. + 1. false: The Credentials tool continues to obtain the access credential in normal mode. - - When the value is true, it means that only the hardened mode can be used to obtain access credentials, and an exception will be thrown. + 2. true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode. - Whether the server supports IMDSv2 depends on your configuration on the server. + The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2). + + In addition, you can specify ALIBABA_CLOUD_ECS_METADATA_DISABLED=true to disable access from the Credentials tool to the metadata server of ECS. -4. Credentials URI +4. Obtain the credential information based on a URI - If the environment variable `ALIBABA_CLOUD_CREDENTIALS_URI` is defined and not empty, the program will take the value of the environment variable as credentials uri to get the temporary Security credentials. + If no valid credential is obtained using the preceding methods, the Credentials tool checks the ***ALIBABA_CLOUD_CREDENTIALS_URI*** environment variable. If this environment variable exists and specifies a valid URI, the Credentials tool initiates an HTTP requests to obtain an STS token as the default credential. ## Issues diff --git a/alibabacloud_credentials/provider/ecs_ram_role.py b/alibabacloud_credentials/provider/ecs_ram_role.py index 7b8ef8e..b92e2e3 100644 --- a/alibabacloud_credentials/provider/ecs_ram_role.py +++ b/alibabacloud_credentials/provider/ecs_ram_role.py @@ -14,8 +14,10 @@ from alibabacloud_credentials.utils import parameter_helper as ph from alibabacloud_credentials.exceptions import CredentialException -log = logging.getLogger(__name__) +log = logging.getLogger('credentials') log.setLevel(logging.DEBUG) +ch = logging.StreamHandler() +log.addHandler(ch) class EcsRamRoleCredentialsProvider(ICredentialsProvider): diff --git a/alibabacloud_credentials/provider/refreshable.py b/alibabacloud_credentials/provider/refreshable.py index d7cdf48..4515ee7 100644 --- a/alibabacloud_credentials/provider/refreshable.py +++ b/alibabacloud_credentials/provider/refreshable.py @@ -13,8 +13,10 @@ from alibabacloud_credentials.exceptions import CredentialException from alibabacloud_credentials_api import ICredentials -log = logging.getLogger(__name__) +log = logging.getLogger('credentials') log.setLevel(logging.DEBUG) +ch = logging.StreamHandler() +log.addHandler(ch) T = TypeVar('T') INT64_MAX = 2 ** 63 - 1