Skip to content

Latest commit

 

History

History
533 lines (425 loc) · 22 KB

1-Credentials.md

File metadata and controls

533 lines (425 loc) · 22 KB

← Overview | Credentials(中文) | Endpoint →


Credentials

The Volcengine Python SDK supports explicit credentials and CredentialProvider-based automatic resolution.

Credential Providers Overview

Provider Purpose Refresh Support Typical Scenario
StaticCredentialProvider Static AK/SK(/Token) No Long-lived server-side credentials
StsCredentialProvider STS AssumeRole Yes Role-based temporary credentials
StsOidcCredentialProvider STS AssumeRoleWithOIDC Yes OIDC federation
StsSamlCredentialProvider STS AssumeRoleWithSAML Yes SAML federation
EnvironmentVariableCredentialProvider Read from env vars No CI/CD and container env injection
CLIConfigCredentialProvider Read from ~/.volcengine/config.json Depends on mode Reuse CLI login/profile
CLIOrDefaultCredentialProvider CLI profile if selected, else default chain Depends on delegated provider Behave like the CLI
EcsRoleCredentialProvider Read from ECS IMDS Yes ECS instance role credentials
DefaultCredentialProvider Chain wrapper Depends on delegated provider No AK/SK in application code

AK/SK

AK/SK is a pair of permanent access keys created in the Volcengine console. The SDK signs each request to authenticate.

⚠️ Notes

  1. Do not embed or expose AK/SK in client-side applications.
  2. Use a configuration center or environment variables.
  3. Follow least privilege principles.

The SDK supports both global configuration and per-request runtime options (RuntimeOption). Runtime options override global configuration.

import volcenginesdkcore, volcenginesdkecs
from volcenginesdkcore.rest import ApiException
from volcenginesdkcore.interceptor import RuntimeOption

# Global configuration
configuration = volcenginesdkcore.Configuration()
configuration.ak = "Your ak"
configuration.sk = "Your sk"
configuration.debug = True
volcenginesdkcore.Configuration.set_default(configuration)

# Per-request runtime options (override global configuration)
runtime_options = RuntimeOption(
    ak="Your ak",
    sk="Your sk",
    client_side_validation=True,
)

api_instance = volcenginesdkecs.ECSApi()
create_command_request = volcenginesdkecs.CreateCommandRequest(
    command_content="ls -l",
    description="Your command description",
    name="Your command name",
    type="command",
    _configuration=runtime_options,
)

try:
    api_instance.create_command(create_command_request)
except ApiException:
    pass

STS Token

STS (Security Token Service) provides temporary credentials (temporary AK/SK and Token).

⚠️ Notes

  1. Least privilege.
  2. Use a reasonable TTL. Shorter is safer; avoid exceeding 1 hour.
import volcenginesdkcore, volcenginesdkecs
from volcenginesdkcore.rest import ApiException
from volcenginesdkcore.interceptor import RuntimeOption

# Global configuration
configuration = volcenginesdkcore.Configuration()
configuration.ak = "Your ak"
configuration.sk = "Your sk"
configuration.session_token = "Your session token"
configuration.debug = True
volcenginesdkcore.Configuration.set_default(configuration)

# Per-request runtime options
runtime_options = RuntimeOption(
    ak="Your ak",
    sk="Your sk",
    session_token="Your session token",
    client_side_validation=True,
)

api_instance = volcenginesdkecs.ECSApi()
create_command_request = volcenginesdkecs.CreateCommandRequest(
    command_content="ls -l",
    description="Your command description",
    name="Your command name",
    type="command",
    _configuration=runtime_options,
)

try:
    api_instance.create_command(create_command_request)
except ApiException:
    pass

STS AssumeRole

STS AssumeRole obtains temporary credentials by assuming an IAM role. Use the role credentials to perform actual API calls.

Reference: https://www.volcengine.com/docs/6257/86374

from __future__ import print_function
import volcenginesdkcore
import volcenginesdkvpc
from volcenginesdkcore.rest import ApiException
from volcenginesdkcore.auth.providers.sts_provider import StsCredentialProvider

if __name__ == '__main__':
    # Do NOT leak credentials in example code.
    configuration = volcenginesdkcore.Configuration()
    configuration.region = "cn-beijing"

    configuration.credential_provider = StsCredentialProvider(
        ak="Your ak",
        sk="Your sk",
        role_name="Your role name",
        account_id="Your account id",
        duration_seconds=3600,
        scheme="https",
        host="sts.volcengineapi.com",
        region="cn-beijing",
        timeout=30,
        expired_buffer_seconds=60,
        policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}',
        proxy_url="http://user:pass@10.0.0.1:8080",  # empty: client fallback, then STS defaults/environment
        ca_file="/path/to/ca.pem",                   # empty: inherited ssl_ca_cert, otherwise certifi
        insecure_skip_verify=False,                  # explicit CA enables verification; True skips it (debugging only)
    )

    volcenginesdkcore.Configuration.set_default(configuration)
    api_instance = volcenginesdkvpc.VPCApi()
    create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
        cidr_block="192.168.0.0/16",
        dns_servers=["10.0.0.1", "10.1.1.2"],
    )

    try:
        api_instance.create_vpc(create_vpc_request)
    except ApiException:
        pass

The proxy/TLS parameters (proxy_url / ca_file / insecure_skip_verify) are documented in full under Proxy & TLS.

STS AssumeRoleWithOidc

STS AssumeRoleWithOidc obtains temporary credentials via an OIDC token.

Reference: https://www.volcengine.com/docs/6257/1494877

The SDK has a single OIDC implementation: StsOidcCredentialProvider.

  • Backward-compatible mode: role_name + account_id + oidc_token (all optional; missing values do NOT read env vars)
  • Env-aware mode: role_trn + oidc_token_file (all optional; missing values fall back to env vars)
  • All parameters are optional. When none are provided, the provider reads entirely from environment variables.

Supported OIDC env vars:

  • VOLCENGINE_OIDC_ROLE_TRN
  • VOLCENGINE_OIDC_TOKEN_FILE
  • VOLCENGINE_OIDC_ROLE_SESSION_NAME
  • VOLCENGINE_OIDC_ROLE_POLICY
  • VOLCENGINE_OIDC_STS_ENDPOINT

Backward-compatible example:

from __future__ import print_function
import volcenginesdkcore
import volcenginesdkvpc
from volcenginesdkcore.rest import ApiException
from volcenginesdkcore.auth.providers.sts_oidc_provider import StsOidcCredentialProvider

if __name__ == '__main__':
    configuration = volcenginesdkcore.Configuration()
    configuration.region = "cn-beijing"

    configuration.credential_provider = StsOidcCredentialProvider(
        role_name="Your role name",
        account_id="Your account id",
        # Alternatively, pass the full role_trn directly (overrides role_name + account_id):
        # role_trn="trn:iam::2110400000:role/role123",
        oidc_token="your oidc token",
        duration_seconds=3600,
        scheme="https",
        host="sts.volcengineapi.com",
        region="cn-beijing",
        timeout=30,
        expired_buffer_seconds=60,
        policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}',
        max_retries=3,     # optional, total HTTP attempts (including the first; min 1), defaults to 3 (initial request plus up to two retries)
        retry_interval=1,  # optional, seconds between retries, defaults to 1
        proxy_url="http://user:pass@10.0.0.1:8080",  # empty: client fallback, then STS defaults/environment
        ca_file="/path/to/ca.pem",                   # empty: inherited ssl_ca_cert, otherwise certifi
        insecure_skip_verify=False,                  # explicit CA enables verification; True skips it (debugging only)
    )

    volcenginesdkcore.Configuration.set_default(configuration)
    api_instance = volcenginesdkvpc.VPCApi()
    create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
        cidr_block="192.168.0.0/16",
        dns_servers=["10.0.0.1", "10.1.1.2"],
    )

    try:
        api_instance.create_vpc(create_vpc_request)
    except ApiException:
        pass

The proxy/TLS parameters (proxy_url / ca_file / insecure_skip_verify) are documented in full under Proxy & TLS.

Env-aware example:

import os
import volcenginesdkcore
from volcenginesdkcore.auth.providers.sts_oidc_provider import StsOidcCredentialProvider

os.environ["VOLCENGINE_OIDC_ROLE_TRN"] = "trn:iam::1234567890:role/oidc-role"
os.environ["VOLCENGINE_OIDC_TOKEN_FILE"] = "/var/run/secrets/oidc/token"

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
configuration.credential_provider = StsOidcCredentialProvider()
volcenginesdkcore.Configuration.set_default(configuration)

STS AssumeRoleWithSaml

STS AssumeRoleWithSaml obtains temporary credentials via a SAML assertion.

Reference: https://www.volcengine.com/docs/6257/1631607

Role TRN resolution (same style as OIDC):

  • role_trn (explicit) takes priority.
  • Otherwise role_name + account_id is assembled into trn:iam::{account_id}:role/{role_name}.

SAML Provider TRN resolution:

  • saml_provider_trn (explicit) takes priority.
  • Otherwise account_id + provider_name is assembled into trn:iam::{account_id}:saml-provider/{provider_name}.
  • When only role_trn + provider_name are passed, account_id is parsed out of role_trn and combined with provider_name.
from __future__ import print_function
import volcenginesdkcore
import volcenginesdkvpc
from volcenginesdkcore.rest import ApiException
from volcenginesdkcore.auth.providers.sts_saml_provider import StsSamlCredentialProvider

if __name__ == '__main__':
    configuration = volcenginesdkcore.Configuration()
    configuration.region = "cn-beijing"

    configuration.credential_provider = StsSamlCredentialProvider(
        role_name="Your role name",
        account_id="Your account id",
        # Alternatively, pass the full role_trn directly (overrides role_name + account_id):
        # role_trn="trn:iam::2110400000:role/role123",
        provider_name="your provider name",
        # Alternatively, pass the full saml_provider_trn directly (overrides account_id + provider_name):
        # saml_provider_trn="trn:iam::2110400000:saml-provider/provider123",
        saml_resp="your saml resp",
        duration_seconds=3600,
        scheme="https",
        host="sts.volcengineapi.com",
        region="cn-beijing",
        timeout=30,
        expired_buffer_seconds=60,
        policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"volc:RequestedRegion":["cn-beijing"]}}}]}',
        max_retries=3,     # optional, total HTTP attempts (including the first; min 1), defaults to 3 (initial request plus up to two retries)
        retry_interval=1,  # optional, seconds between retries, defaults to 1
        proxy_url="http://user:pass@10.0.0.1:8080",  # empty: client fallback, then STS defaults/environment
        ca_file="/path/to/ca.pem",                   # empty: inherited ssl_ca_cert, otherwise certifi
        insecure_skip_verify=False,                  # explicit CA enables verification; True skips it (debugging only)
    )

    volcenginesdkcore.Configuration.set_default(configuration)
    api_instance = volcenginesdkvpc.VPCApi()
    create_vpc_request = volcenginesdkvpc.CreateVpcRequest(
        cidr_block="192.168.0.0/16",
        dns_servers=["10.0.0.1", "10.1.1.2"],
    )

    try:
        api_instance.create_vpc(create_vpc_request)
    except ApiException:
        pass

The proxy/TLS parameters (proxy_url / ca_file / insecure_skip_verify) are documented in full under Proxy & TLS.

Environment Variable Credential Provider

EnvironmentVariableCredentialProvider reads credentials from:

  • VOLCENGINE_ACCESS_KEY
  • VOLCENGINE_SECRET_KEY
  • VOLCENGINE_SESSION_TOKEN (optional)
import os
import volcenginesdkcore
from volcenginesdkcore.auth.providers.env_provider import EnvironmentVariableCredentialProvider

os.environ["VOLCENGINE_ACCESS_KEY"] = "YourAK"
os.environ["VOLCENGINE_SECRET_KEY"] = "YourSK"

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
configuration.credential_provider = EnvironmentVariableCredentialProvider()
volcenginesdkcore.Configuration.set_default(configuration)

CLI Config Credential Provider

CLIConfigCredentialProvider reads ~/.volcengine/config.json by default.

  • Config path priority: constructor config_path > VOLCENGINE_CLI_CONFIG_FILE > ~/.volcengine/config.json
  • Profile priority: constructor profile_name > VOLCENGINE_PROFILE > current in config > default

Supported modes in profile (case-insensitive):

  • AK / empty
  • StsToken
  • iamrole (delegates to StsCredentialProvider)
  • OIDC (delegates to StsOidcCredentialProvider)
  • EcsRole (delegates to EcsRoleCredentialProvider)
  • SSO Reads STS credentials from the CLI sso cache (SDK refreshes the access token in memory by default; refresh_cli_credentials refreshes and writes back to the cache)
  • console-login Reads STS credentials from the CLI console-login cache (SDK refreshes via OAuth refresh_token in memory by default; refresh_cli_credentials refreshes and writes back to the cache)

Example: explicitly use CLI provider with a specified profile and config path.

import os

import volcenginesdkcore
from volcenginesdkcore.auth.providers.cli_config_provider import CLIConfigCredentialProvider

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
configuration.credential_provider = CLIConfigCredentialProvider(
    profile_name="prod",
    config_path=os.path.expanduser("~/.volcengine/config.json"),
)
volcenginesdkcore.Configuration.set_default(configuration)

Runtime Refresh Behavior (sso / console-login)

For sso and console-login modes the SDK offers two ways to refresh:

  • Default (CLIConfigCredentialProvider / default credential chain): in-memory refresh only. Whenever a refresh is needed the SDK re-reads ~/.volcengine/login/cache/*.json (console-login) or ~/.volcengine/sso/cache/*.json (SSO). If the cached access_token is not within its expiry buffer (60 seconds) it is used as is; otherwise the SDK exchanges the cached refresh_token at the OAuth /token endpoint and keeps the result in memory without writing any file. SSO then calls the Portal GetRoleCredentials API for the STS triple.
  • Explicit refresh (refresh_cli_credentials): refresh and write back. Intended for ve and other command-line tools that reuse CLI credentials: call it at the start of each command. When the access_token has expired it is renewed and written back to the cache, so later processes (including the default mode) reuse it instead of refreshing again. The returned CLIRefreshResult carries credentials plus refreshed, persisted and persist_error.

The explicit refresh follows the shared cache protocol used by ve and the SDKs in every language (see token_cache_store.py and cli_config_provider.py):

  • OAuth refreshes are not locked. The write-back holds <cache file>.lock (created atomically with O_EXCL). If the lock exists the write-back is skipped; a lock file older than 10 seconds (by modification time) is treated as stale, removed, and acquisition is retried once. The cache is re-read under the lock.
  • A deleted cache (ve logout / ve sso logout) is not recreated, and a cache already updated by another process is left untouched. In both cases persisted is False and persist_error is None.
  • The write is based on the latest content on disk, updates only the refreshed fields, keeps all other fields verbatim, and replaces the whole file atomically via a temp file in the same directory and rename, so concurrent writers never corrupt it.
  • Right before the rename, the write-back re-checks that the lock is still owned by this process and that the cache is byte-identical to the copy re-read under the lock; otherwise it skips the write-back (credentials are still returned). This narrows, but cannot fully close, the window against a concurrent login / logout: in rare timing, a cache may reappear once after logout, or one new login may be overwritten; simply run ve logout / ve login again.
  • If the write-back fails (read-only directory, disk full, ...), persist_error reports the cause; the returned credentials are still valid, the cache file is left unchanged, and the next process refreshes again. A write-back that finds another process holding the lock is skipped silently.
  • ve login / ve logout take priority: they remove the lock file and then write or delete the cache (save_token_cache_file / remove_token_cache_file).
  • For long-lived credential objects, use PersistentCLIConfigCredentialProvider; later renewals are written back as well, and last_persist_error() reports the latest write-back failure.
  • The SDK never writes config.json; SSO role STS credentials stay in memory.

Behavior common to both modes:

  • Logout: once the cache is deleted, the SDK no longer renews with the in-memory refresh_token; STS credentials already obtained remain usable until they expire.
  • Refresh-token rejection: when the authorization service rejects the refresh_token, the SDK raises an error instructing the user to run ve login (console-login) or ve sso login (SSO).
  • Concurrency: refreshes are serialized within a process.
from volcenginesdkcore.auth.providers.cli_config_provider import refresh_cli_credentials

result = refresh_cli_credentials()  # profile: profile_name > VOLCENGINE_PROFILE > config "current" > "default"; config_path is optional
if result.persist_error is not None:
    pass  # credentials are usable; they just could not be written back
print(result.credentials.ak)

CLI-or-Default Credential Provider

CLIOrDefaultCredentialProvider picks credentials the same way the ve CLI does for a command: use a CLI profile when one is selected, otherwise fall back to the default credential chain. The selection happens once, in the constructor.

  1. Constructor profile_name (whitespace stripped, non-empty): the profile must exist in the config file, otherwise RuntimeError (profile '<name>' not found in config file.).
  2. Otherwise the current field of the config file, then VOLCENGINE_PROFILE, then VOLCSTACK_PROFILE. If that profile exists it is used; if it does not exist the default chain is used (no error).
  3. A selected profile is resolved by CLIConfigCredentialProvider with the profile name passed explicitly, so VOLCENGINE_ACCESS_KEY / VOLCENGINE_SECRET_KEY in the environment do not override it.
  4. Without a selected profile: if VOLCENGINE_DISABLE_DEFAULT_CREDENTIALS=true a RuntimeError is raised; otherwise DefaultCredentialProvider is used.
  • Config path priority: constructor config_path > VOLCENGINE_CLI_CONFIG_FILE > ~/.volcengine/config.json
  • A missing, unreadable or malformed config file is treated as "no config": the default chain is used, and an explicit profile_name raises because the profile cannot be found. (The CLI ignores --profile in that case; the SDK raises instead of silently using other credentials.)
  • Read-only attributes: profile_name (None when the default chain is used), source (explicit, current, env:VOLCENGINE_PROFILE, env:VOLCSTACK_PROFILE or default-chain) and uses_default_chain.
  • sso / console-login tokens are refreshed in memory only; this provider writes no file. Use refresh_cli_credentials to write refreshed tokens back.
import volcenginesdkcore
from volcenginesdkcore.auth.providers import CLIOrDefaultCredentialProvider

provider = CLIOrDefaultCredentialProvider()  # or profile_name="prod", config_path=...
print(provider.profile_name, provider.source, provider.uses_default_chain)

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
configuration.credential_provider = provider
volcenginesdkcore.Configuration.set_default(configuration)

ECS Role Credential Provider

EcsRoleCredentialProvider reads temporary credentials from ECS IMDS.

  • role_name priority: constructor arg > VOLCENGINE_ECS_METADATA > auto-detect from IMDS
  • disable switch: VOLCENGINE_ECS_METADATA_DISABLED=true
import volcenginesdkcore
from volcenginesdkcore.auth.providers.ecs_role_provider import EcsRoleCredentialProvider

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
# Omit role_name to read VOLCENGINE_ECS_METADATA or auto-detect the role name from IMDS.
configuration.credential_provider = EcsRoleCredentialProvider(role_name="your-ecs-role-name")
volcenginesdkcore.Configuration.set_default(configuration)

Default Credential Provider

When ak, sk, and credential_provider are all unset, the SDK automatically uses DefaultCredentialProvider — no manual configuration is needed.

You can also explicitly set it if you need to customize options (e.g., role_name).

Default chain order:

  1. EnvironmentVariableCredentialProvider
  2. StsOidcCredentialProvider
  3. CLIConfigCredentialProvider
  4. EcsRoleCredentialProvider

By default, reuse_last_provider_enabled=True, so the last successful provider is reused first on later calls.

import volcenginesdkcore
from volcenginesdkcore.auth.providers.default_provider import DefaultCredentialProvider

configuration = volcenginesdkcore.Configuration()
configuration.region = "cn-beijing"
configuration.credential_provider = DefaultCredentialProvider()
volcenginesdkcore.Configuration.set_default(configuration)

← Overview | Credentials(中文) | Endpoint →