Skip to content

Commit 824a9c8

Browse files
author
BitsAdmin
committed
Merge branch 'feat/assume_role_and_oidc_and_saml' into 'integration_2025-09-25_1059631177986'
feat: [development task] core (1697918) See merge request iaasng/volcengine-python-sdk!834
2 parents 043e8d3 + 269c505 commit 824a9c8

File tree

17 files changed

+909
-22
lines changed

17 files changed

+909
-22
lines changed

SDK_Integration_zh.md

Lines changed: 223 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
- [访问凭据](#访问凭据)
66
- [AK、SK设置](#aksk设置)
77
- [STS Token设置](#sts-token设置)
8+
- [STS AssumeRole示例](#sts-assumerole示例)
9+
- [STS AssumeRoleWithOidc示例](#sts-assumerolewithoidc示例)
10+
- [STS AssumeRoleWithSaml示例](#sts-assumerolewithsaml示例)
811
- [EndPoint配置](#endpoint配置)
912
- [自定义Endpoint](#自定义endpoint)
1013
- [自定义RegionId](#自定义regionid)
@@ -28,6 +31,8 @@
2831
- [自定义退避策略](#自定义退避策略)
2932
- [异常处理](#异常处理)
3033
- [Debug机制](#debug机制)
34+
- [开启Debug模式](#开启debug模式)
35+
- [设置Debug级别](#设置debug级别)
3136
- [指定日志Logger](#指定日志logger)
3237

3338
# 集成SDK
@@ -133,8 +138,190 @@ try:
133138
except ApiException as e:
134139
pass
135140
```
141+
## STS AssumeRole示例
136142

143+
STS AssumeRole(Security Token Service)是火山引擎提供的临时访问凭证机制。开发者通过服务端调用 STS 接口获取临时凭证(临时 AK、SK 和 Token),有效期可配置,适用于安全要求较高的场景。
144+
<br>
145+
此接口使用IAM子账号角色进行 AssumeRole 操作后,获取到IAM子用户的信息后,发起真正的API请求,参考如下
146+
<br>
147+
连接地址:https://www.volcengine.com/docs/6257/86374
148+
> ⚠️ 注意事项
149+
>
150+
> 1. 最小权限: 仅授予调用方访问所需资源的最小权限,避免使用 * 通配符授予全资源、全操作权限。
151+
> 2. 设置合理的有效期: 请根据实际情况设置合理有效期,越短越安全,建议不要超过1小时。
152+
153+
支持`configuration`级别全局配置和接口级别的运行时参数设置`RuntimeOption`;`RuntimeOption`设置会覆盖`configuration`全局配置。
154+
155+
**代码示例:**
137156

157+
```python
158+
from __future__ import print_function
159+
import volcenginesdkcore
160+
import volcenginesdkvpc
161+
from volcenginesdkcore.rest import ApiException
162+
from volcenginesdkcore.auth.providers.sts_provider import StsCredentialProvider
163+
164+
if __name__ == '__main__':
165+
# 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
166+
configuration = volcenginesdkcore.Configuration()
167+
configuration.region = "cn-beijing"
168+
169+
# 这里是使用STS ASSUMEROLE角色的方式
170+
configuration.credential_provider = StsCredentialProvider(
171+
ak="Your ak", # 必填,子账号的ak
172+
sk="Your sk", # 必填,子账号的sk
173+
role_name="Your role name", # 必填,子账号的角色TRN,如trn:iam::2110400000:role/role123 ,此处填写role123
174+
account_id="Your account id", # 必填,子账号的角色TRN,如trn:iam::2110400000:role/role123 ,此处填写2110400000
175+
duration_seconds=3600, # 非必填,有效期默认3600秒
176+
scheme="https", # 非必填,域名前缀,默认https
177+
host="sts.volcengineapi.com", # 非必填,请求域名,默认sts.volcengineapi.com
178+
region="cn-beijing", # 非必填,请求服务器区域地址,默认cn-north-1
179+
timeout=30, # 非必填,请求超时时间,默认30秒
180+
expired_buffer_seconds=60, #非必填,session有效期前多久过期,剩余时间小于这个设置就要请求新的token了,默认60秒
181+
policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}' # 非必填,授权策略,默认为空
182+
)
183+
184+
# set default configuration
185+
volcenginesdkcore.Configuration.set_default(configuration)
186+
# use global default configuration
187+
api_instance = volcenginesdkvpc.VPCApi()
188+
create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
189+
cidr_block="192.168.0.0/16",
190+
dns_servers=["10.0.0.1", "10.1.1.2"],
191+
)
192+
193+
try:
194+
# 复制代码运行示例,请自行打印API返回值。
195+
api_instance.create_vpc(create_vpc_request)
196+
except ApiException as e:
197+
# 复制代码运行示例,请自行打印API错误信息。
198+
# print("Exception when calling api: %s\n" % e)
199+
pass
200+
```
201+
202+
## STS AssumeRoleWithOidc示例
203+
204+
STS AssumeRoleOIDC(Security Token Service)是火山引擎提供的临时访问凭证机制。开发者通过oidc_token在服务端调用 STS 接口获取临时凭证(临时 AK、SK 和 Token),有效期可配置,适用于安全要求较高的场景。
205+
<br>
206+
此接口使用oidc身份提供商角色使用oidc_token进行 AssumeRoleWithOidc 操作后,获取到用户的信息后,发起真正的API请求,参考如下
207+
<br>
208+
连接地址:https://www.volcengine.com/docs/6257/1494877
209+
> ⚠️ 注意事项
210+
>
211+
> 1. 最小权限: 仅授予调用方访问所需资源的最小权限,避免使用 * 通配符授予全资源、全操作权限。
212+
> 2. 设置合理的有效期: 请根据实际情况设置合理有效期,越短越安全,建议不要超过1小时。
213+
214+
支持`configuration`级别全局配置和接口级别的运行时参数设置`RuntimeOption`;`RuntimeOption`设置会覆盖`configuration`全局配置。
215+
216+
**代码示例:**
217+
218+
```python
219+
# Example Code generated by Beijing Volcanoengine Technology.
220+
from __future__ import print_function
221+
import volcenginesdkcore
222+
import volcenginesdkvpc
223+
from volcenginesdkcore.rest import ApiException
224+
from volcenginesdkcore.auth.providers.sts_oidc_provider import StsOidcCredentialProvider
225+
226+
if __name__ == '__main__':
227+
# 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
228+
configuration = volcenginesdkcore.Configuration()
229+
configuration.region = "cn-beijing"
230+
231+
# 这里是使用STS ASSUMEROLE_OIDC角色的方式
232+
configuration.credential_provider = StsOidcCredentialProvider(
233+
role_name="Your role name", # 必填,账号的角色TRN,如trn:iam::2110400000:role/role123 ,此处填写role123
234+
account_id="Your account id", # 必填,账号的角色TRN,如trn:iam::2110400000:role/role123 ,此处填写2110400000
235+
oidc_token="your oidc token", # 必填,生成的oidcToken,如ey********
236+
duration_seconds=3600, # 非必填,有效期默认3600秒
237+
scheme="https", # 非必填,域名前缀,默认https
238+
host="sts.volcengineapi.com", # 非必填,请求域名,默认sts.volcengineapi.com
239+
region="cn-beijing", # 非必填,请求服务器区域地址,默认cn-beijing
240+
timeout=30, # 非必填,请求超时时间,默认30秒
241+
expired_buffer_seconds=60, # 非必填,session有效期前多久过期,剩余时间小于这个设置就要请求新的token了,默认60秒
242+
policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}' # 非必填,授权策略,默认为空
243+
)
244+
245+
# set default configuration
246+
volcenginesdkcore.Configuration.set_default(configuration)
247+
# use global default configuration
248+
api_instance = volcenginesdkvpc.VPCApi()
249+
create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
250+
cidr_block="192.168.0.0/16",
251+
dns_servers=["10.0.0.1", "10.1.1.2"],
252+
)
253+
254+
try:
255+
# 复制代码运行示例,请自行打印API返回值。
256+
api_instance.create_vpc(create_vpc_request)
257+
except ApiException as e:
258+
# 复制代码运行示例,请自行打印API错误信息。
259+
# print("Exception when calling api: %s\n" % e)
260+
pass
261+
262+
```
263+
264+
## STS AssumeRoleWithSaml示例
265+
266+
STS AssumeRoleWithSaml(Security Token Service)是火山引擎提供的临时访问凭证机制。开发者通过saml_token在服务端调用 STS 接口获取临时凭证(临时 AK、SK 和 Token),有效期可配置,适用于安全要求较高的场景。
267+
<br>
268+
此接口使用saml身份提供商角色使用saml_resp进行 AssumeRoleWithSaml 操作后,获取到用户的信息后,发起真正的API请求,参考如下
269+
<br>
270+
连接地址:https://www.volcengine.com/docs/6257/1631607
271+
> ⚠️ 注意事项
272+
>
273+
> 1. 最小权限: 仅授予调用方访问所需资源的最小权限,避免使用 * 通配符授予全资源、全操作权限。
274+
> 2. 设置合理的有效期: 请根据实际情况设置合理有效期,越短越安全,建议不要超过1小时。
275+
276+
支持`configuration`级别全局配置和接口级别的运行时参数设置`RuntimeOption`;`RuntimeOption`设置会覆盖`configuration`全局配置。
277+
278+
**代码示例:**
279+
```python
280+
# Example Code generated by Beijing Volcanoengine Technology.
281+
from __future__ import print_function
282+
import volcenginesdkcore
283+
import volcenginesdkvpc
284+
from volcenginesdkcore.rest import ApiException
285+
from volcenginesdkcore.auth.providers.sts_saml_provider import StsSamlCredentialProvider
286+
287+
if __name__ == '__main__':
288+
# 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
289+
configuration = volcenginesdkcore.Configuration()
290+
configuration.region = "cn-beijing"
291+
292+
# 这里是使用STS ASSUMEROLE_SAML角色的方式
293+
configuration.credential_provider = StsSamlCredentialProvider(
294+
role_name="Your role name", # 必填,账号的角色TRN,如trn:iam::2110400000:role/role123,此处填写role123
295+
account_id="Your account id", # 必填,账号的角色TRN,如trn:iam::2110400000:saml-provider/role123,此处填写2110400000
296+
provider_name="your provider name",# 必填,认证provider的TRN,如trn:iam::2110400000:saml-provider/provider123,此处填写provider123
297+
saml_resp="your saml resp", # 必填,认证获取到的SAML的断言
298+
duration_seconds=3600, # 非必填,有效期默认3600秒
299+
scheme="https", # 非必填,域名前缀,默认https
300+
host="sts.volcengineapi.com", # 非必填,请求域名,默认sts.volcengineapi.com
301+
region="cn-beijing", # 非必填,请求服务器区域地址,默认cn-beijing
302+
timeout=30, # 非必填,请求超时时间,默认30秒
303+
expired_buffer_seconds=60, # 非必填,session有效期前多久过期,剩余时间小于这个设置就要请求新的token了,默认60秒
304+
policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}' # 非必填,授权策略,默认为空
305+
)
306+
307+
# set default configuration
308+
volcenginesdkcore.Configuration.set_default(configuration)
309+
# use global default configuration
310+
api_instance = volcenginesdkvpc.VPCApi()
311+
create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
312+
cidr_block="192.168.0.0/16",
313+
dns_servers=["10.0.0.1", "10.1.1.2"],
314+
)
315+
316+
try:
317+
# 复制代码运行示例,请自行打印API返回值。
318+
api_instance.create_vpc(create_vpc_request)
319+
except ApiException as e:
320+
# 复制代码运行示例,请自行打印API错误信息。
321+
# print("Exception when calling api: %s\n" % e)
322+
pass
323+
324+
```
138325

139326
# EndPoint配置
140327

@@ -293,6 +480,7 @@ except ApiException as e:
293480
## 配置Http(s)代理
294481

295482
```python
483+
import volcenginesdkcore,volcenginesdkecs
296484
configuration = volcenginesdkcore.Configuration()
297485
configuration.ak = "Your AK"
298486
configuration.sk = "Your SK"
@@ -563,6 +751,8 @@ except Exception as e:
563751

564752
为便于客户在处理请求时进行问题排查和调试,SDK 支持日志功能,并提供多种日志级别设置。客户可根据实际需求配置日志级别,获取详细的请求与响应信息,以提升排障效率和系统可 observability(可观测性)。
565753

754+
## 开启Debug模式
755+
566756
> **默认**
567757
> * `debug` - `False`
568758
@@ -576,6 +766,39 @@ configuration.debug = True # 开启debug模式
576766
volcenginesdkcore.Configuration.set_default(configuration)
577767
```
578768

769+
## 设置debug级别
770+
默认情况下开启debug日志后,会输出所有的debug日志;为了按需输出日志,可以调用`configuration.log_level`进行以下设置:
771+
772+
```python
773+
import volcenginesdkcore
774+
from volcenginesdkcore.observability.debugger import LogLevel
775+
configuration = volcenginesdkcore.Configuration()
776+
configuration.ak = "Your AK"
777+
configuration.sk = "Your SK"
778+
configuration.debug = True # 开启debug模式
779+
configuration.log_level = LogLevel.LOG_DEBUG_WITH_CONFIG.mask | LogLevel.LOG_DEBUG_WITH_REQUEST.mask | LogLevel.LOG_DEBUG_WITH_RESPONSE.mask
780+
volcenginesdkcore.Configuration.set_default(configuration)
781+
782+
```
783+
784+
**支持的日志级别**
785+
786+
787+
| 枚举项 | 父级日志(同时打印父级日志) | 打印的内容 |
788+
| -------------------------------- |-----|--------------------------------------|
789+
| `LOG_DEBUG_WITH_REQUEST` || 请求行与基础请求信息:`HTTP方法``URL(含查询参数)``请求头` |
790+
| `LOG_DEBUG_WITH_REQUEST_BODY` | `LOG_DEBUG_WITH_REQUEST` | `请求体` |
791+
| `LOG_DEBUG_WITH_REQUEST_ID` | `LOG_DEBUG_WITH_REQUEST` | `RequestId` |
792+
| `LOG_DEBUG_WITH_RESPONSE` | `LOG_DEBUG_WITH_REQUEST` | `响应状态码` `响应头` |
793+
| `LOG_DEBUG_WITH_RESPONSE_BODY` | `LOG_DEBUG_WITH_RESPONSE` | `响应体` |
794+
| `LOG_DEBUG_WITH_SIGNING` | `LOG_DEBUG_WITH_REQUEST` | `签名过程` |
795+
| `LOG_DEBUG_WITH_ENDPOINT` | `LOG_DEBUG_WITH_REQUEST` | ` Endpoint 选择过程` |
796+
| `LOG_DEBUG_WITH_REQUEST_RETRIES` | `LOG_DEBUG_WITH_REQUEST` | `重试信息` |
797+
| `LOG_DEBUG_WITH_CONFIG` | `LOG_DEBUG_WITH_REQUEST` | `关键配置信息` |
798+
| `LOG_DEBUG_ALL` || `包含上面所有信息` |
799+
800+
801+
579802
# 指定日志Logger
580803

581804
> **默认**

volcenginesdkcore/api_client.py

Lines changed: 73 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import absolute_import
44

55
import datetime
6-
import logging
76
from multiprocessing.pool import ThreadPool
87
from time import sleep
98

@@ -17,9 +16,7 @@
1716
from volcenginesdkcore.interceptor import DeserializedResponseInterceptor
1817
from volcenginesdkcore.interceptor import InterceptorChain, InterceptorContext
1918
from volcenginesdkcore.interceptor import Request, Response
20-
21-
logger = logging.getLogger(__name__)
22-
19+
from volcenginesdkcore.observability.debugger import sdk_core_logger, LogLevel
2320

2421
class ApiClient(object):
2522
"""Generic API client for Swagger client library builds.
@@ -126,6 +123,8 @@ def __call_api(
126123

127124
interceptor_context = self.interceptor_chain.execute_request(interceptor_context)
128125

126+
self._log_config(interceptor_context.get_request())
127+
129128
retry_count = 0
130129
response_data = None
131130
retry_err = None
@@ -145,7 +144,7 @@ def __call_api(
145144
_request_timeout=interceptor_context.request.request_timeout)
146145
self.last_response = response_data
147146
except Exception as e:
148-
logger.warning("request error: {}".format(e))
147+
sdk_core_logger.warning("request error: {}".format(e))
149148
retry_err = e
150149
if retry_count >= num_max_retries:
151150
raise e
@@ -171,7 +170,7 @@ def request_retry(self, response_data, retry_count, retry_err, retryer):
171170
delay = retryer.get_backoff_delay(retry_count)
172171
sleep(delay / 1000)
173172
if self.configuration.debug:
174-
logger.debug(
173+
sdk_core_logger.debug_config(
175174
"retry backoff strategy:%s, retry condition: %s, max retry count:%d, current retry count: %d, retry delay(ms):%f",
176175
type(retryer.backoff_strategy).__name__, type(retryer.retry_condition).__name__,
177176
retryer.num_max_retries, retry_count + 1, delay)
@@ -331,6 +330,74 @@ def select_header_content_type(self, content_types):
331330
else:
332331
return content_types[0]
333332

333+
def _log_config(self, request):
334+
335+
if not sdk_core_logger.is_enabled_for_loglevel(LogLevel.LOG_DEBUG_WITH_CONFIG):
336+
return
337+
338+
sb = []
339+
340+
sb.append("SDK Version : ")
341+
sb.append(self.user_agent + "\n")
342+
343+
# 连接池配置
344+
sb.append("[Connection Pool]" + "\n")
345+
sb.append(" Number of pools : ")
346+
sb.append(str(self.configuration.num_pools) + "\n")
347+
sb.append(" Connection pool maxsize : ")
348+
sb.append(str(self.configuration.connection_pool_maxsize) + "\n")
349+
350+
# SSL设置
351+
sb.append("[Scheme]" + "\n")
352+
sb.append(" Scheme : ")
353+
sb.append(str(request.scheme) + "\n")
354+
355+
# 代理设置(隐藏部分信息避免敏感泄露)
356+
sb.append("[Proxy]" + "\n");
357+
sb.append(" HTTP Proxy : ")
358+
sb.append(str(self.configuration.http_proxy) + "\n")
359+
sb.append(" HTTPS Proxy : ")
360+
sb.append(str(self.configuration.https_proxy) + "\n")
361+
362+
# 超时设置
363+
sb.append("[Timeout]" + "\n");
364+
sb.append(" Connect Timeout(ms) : ")
365+
sb.append(str(self.configuration.connect_timeout) + "\n")
366+
sb.append(" Read Timeout(ms) : ")
367+
sb.append(str(self.configuration.read_timeout) + "\n")
368+
369+
# 重试设置
370+
sb.append("[Retry]" + "\n");
371+
sb.append(" Auto Retry : ")
372+
sb.append(str(request.auto_retry) + "\n")
373+
if request.auto_retry and request.retryer is not None:
374+
sb.append(" Max Retries : ")
375+
sb.append(str(request.retryer.num_max_retries) + "\n")
376+
sb.append(" Min Delay (ms) : ")
377+
sb.append(str(request.retryer.backoff_strategy.min_retry_delay_ms) + "\n")
378+
sb.append(" Max Delay (ms) : ")
379+
sb.append(str(request.retryer.backoff_strategy.max_retry_delay_ms) + "\n")
380+
sb.append(" Retry Condition : ")
381+
sb.append(type(request.retryer.retry_condition).__name__ if request.retryer.retry_condition is not None else "None" + "\n")
382+
sb.append(" Backoff Strategy : ")
383+
sb.append(type(request.retryer.backoff_strategy).__name__ if request.retryer.backoff_strategy is not None else "None" + "\n")
384+
sb.append(" Retry ErrorCodes : ")
385+
sb.append(str(request.retryer.retry_condition.retry_error_codes) + "\n")
386+
387+
# EndpointResolver设置
388+
sb.append("[Endpoint Resolver]" + "\n")
389+
sb.append(" Region : ")
390+
sb.append(str(request.region) + "\n")
391+
sb.append(" Endpoint : ")
392+
sb.append(str(request.host) + "\n")
393+
sb.append(" Use DualStack : ")
394+
sb.append(str(request.use_dual_stack) + "\n")
395+
sb.append(" Bootstrap Region : ")
396+
sb.append(str(request.custom_bootstrap_region) + "\n")
397+
sb.append(" Resolver Class : ")
398+
sb.append(type(request.endpoint_provider).__name__ if request.endpoint_provider is not None else "None" + "\n")
399+
400+
sdk_core_logger.debug_config("".join(sb))
334401

335402
def metadata(self):
336403
return self._metadata

volcenginesdkcore/auth/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
from .credential import Credential
2-
from .providers import StsCredentialProvider, StaticCredentialProvider
2+
from .providers import StsCredentialProvider, StsOidcCredentialProvider,StaticCredentialProvider
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
from .static_provider import StaticCredentialProvider
22
from .sts_provider import StsCredentialProvider
3+
from .sts_oidc_provider import StsOidcCredentialProvider
4+
from .sts_saml_provider import StsSamlCredentialProvider

0 commit comments

Comments
 (0)