Use API Key credentials stored in KMS Secrets Manager by configuring a CredentialProvider

Updated at:

Configure a CredentialProvider to centrally manage API keys in Key Management Service (KMS) Secrets Manager. A CredentialProvider centrally manages API keys in Key Management Service (KMS) Secrets Manager. The ack-agent-identity add-on retrieves them through OpenID Connect (OIDC) and delivers them on demand to AI Agent workloads by Agent identity. Neither applications nor business Pods contain plaintext keys or connect to KMS.

Feature overview

In AI Agent scenarios, Agents often need API keys to call third-party services, such as OpenAI and Tongyi Qianwen large language model (LLM) services. Storing API keys directly in application code, images, or environment variables creates credential-leakage risks and makes key rotation difficult.

CredentialProvider is a credential-source custom resource (CR) provided by the ack-agent-identity add-on. When its type is APIKey and its source is KMS, it reads the value of a specified credential from KMS Secrets Manager as an API key. It provides the following capabilities:

  • The actual API key is hosted in KMS Secrets Manager. KMS provides central management, rotation, and auditing for the key. Applications and business Pods neither access the plaintext key nor connect to KMS directly. The ack-agent-identity add-on retrieves the key through OIDC on their behalf.

  • The AgentRole and AgentRoleBinding authorization mechanism controls exactly which CredentialProvider credentials each Agent identity can obtain.

  • secretName supports template variables that dynamically reference different KMS credentials according to context, such as the Agent identity. One configuration can therefore retrieve different credentials for different identities.

Compared with the Kubernetes source, the KMS source moves key hosting from in-cluster Secrets to KMS Secrets Manager. It is suitable for scenarios that require centralized key hosting, rotation, and auditing.

CredentialProvider supports types such as APIKey and RAM. This topic covers only the type: APIKey source for OIDC (ACK) access to a dedicated KMS instance. For other types and sources, see the relevant documentation.

Resource objects involved

A working KMS credential-delivery configuration usually involves the following CRs, which the procedure in this topic creates:

Resource object

Description

ExternalSecretService

Carries the KMS instance access information, including the instance endpoint, the application access point (AAP) used for authentication, and the instance CA certificate. It is independent of the credential to retrieve.

AgentIdentity

Defines an Agent identity, which is the subject of authorization and credential delivery.

CredentialProvider

Defines the credential source. In this topic, type: APIKey references an ExternalSecretService through serviceRef to read a specified credential from KMS.

AgentRole

Defines permission rules that specify which CredentialProvider credentials an Agent can obtain.

AgentRoleBinding

Binds an AgentRole to a specified AgentIdentity to complete authorization.

Prerequisites

  • The cluster version is 1.28 or later.

  • The ack-agent-identity add-on version is 0.5.0 or later. Check the add-on version on the cluster's Add-ons page.

  • The CoreDNS add-on is installed in the cluster.

  • A dedicated KMS instance is purchased and enabled, and its image version is dkms-4.0.0 or later. If the version is earlier than dkms-4.0.0, upgrade it first. For more information, see Upgrade the image version of a KMS instance.

  • RAM Roles for Service Accounts (RRSA) OIDC is enabled on the Basic Information tab of the Cluster Information page. OIDC (ACK) authentication depends on this feature.

  • If the cluster and the dedicated KMS instance are in the same region but in different Virtual Private Clouds (VPCs), VPC sharing (binding) must be configured for the cluster VPC on the KMS side. Otherwise, the cluster cannot access KMS through the instance endpoint. For more information, see Configure Multi-VPC access to KMS instances within the same region.

  • If the cluster and the dedicated KMS instance are in different regions, cross-region access to KMS must be configured. For more information, see Configure cross-region access to KMS instances for applications.

Prepare dedicated KMS instance access

Before you create resources in the cluster, complete the OIDC (ACK) access configuration for the dedicated instance on the KMS side. This configuration provides the application access point, instance endpoint, and instance CA certificate that the add-on needs to access KMS.

An AAP is the identity that KMS uses for cloud-native access. It binds an authentication method to a set of Role-Based Access Control (RBAC) permissions. In this topic, the authentication method is OIDC (ACK), which trusts the JSON Web Token (JWT) of a specified cluster ServiceAccount. The add-on exchanges the cluster ServiceAccount token for temporary credentials and then accesses credentials in the instance with the identity and permissions of that AAP.

  • Log on to the Key Management Service console. In the left-side navigation pane, choose Application Access > Cloud-native Access, and then switch to Container > ACK.

  • Find the target cluster in the cluster list and click Configure ACK Access to its right. Set Authentication Method to OIDC (ACK), and configure the following settings to create an application access point:

Configuration item

Value

Namespace

Enter the fixed value ack-agent-identity.

ServiceAccount

Enter the fixed value credential-provider.

Scope

Select the specified KMS instance, which is this dedicated instance.

RBAC Permissions

Select CryptoServiceSecretUser, which grants read access to the credentials in the instance.

Accessible Resources

Select the credentials and keys that the application needs to access, including keys used to encrypt and decrypt credentials.

For the complete OIDC (ACK) console procedure, including enabling RRSA OIDC and creating an AAP, see Quick access from ACK.

Namespace and ServiceAccount must use the preceding fixed values because the identity presented to KMS is the ack-agent-identity add-on. Its ServiceAccount is the ack-agent-identity namespace's credential-provider, not the ServiceAccount of a business Pod. Business Pods never connect to KMS directly.

  • After configuration is complete, record the following information for creating the ExternalSecretService:

  • Application access point (AAP): Use its short name, such as my-aap, or its full Alibaba Cloud Resource Name (ARN), such as acs:kms:cn-hangzhou:123456789012:applicationaccesspoint/my-aap.

  • Instance endpoint: The dedicated instance gateway domain name, in the format kst-hzz00example.cryptoservice.kms.aliyuncs.com.

  • Instance CA certificate: The CA certificate of the dedicated instance gateway. This is public PEM information used to verify the gateway TLS certificate.

  • Create or confirm the KMS Secrets Manager credential that stores the API key, and record its credential name (secretName).

Configure KMS credential delivery

Create the following in-cluster resources in the same namespace: AgentIdentity, ExternalSecretService, CredentialProvider, AgentRole, and AgentRoleBinding.

  • Follow the instructions in Use ACS with kubectl.

  • Save the following content as kms-external-secret-service.yaml and run kubectl apply -f kms-external-secret-service.yaml to create an ExternalSecretService that carries dedicated KMS instance access information. Replace endpoint, aap.name, and caBundle with the actual values that you recorded in the Prepare dedicated KMS instance access section.

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: ExternalSecretService
metadata:
  name: kms-dedicated-instance
  namespace: <YOUR-NAMESPACE>
spec:
  provider: KMS
  kms:
    endpoint: kst-hzz00example.cryptoservice.kms.aliyuncs.com   # Dedicated instance gateway endpoint
    auth:
      type: AAP                                                 # AAP OIDC authentication
      aap:
        name: my-aap                                            # AAP short name
    # Required CA certificate of the dedicated instance gateway. Accepts base64-encoded PEM (such as `base64 -w0 ca.pem`) or raw PEM.
    caBundle: REPLACE_WITH_BASE64_ENCODED_PEM_OF_YOUR_DEDICATED_KMS_INSTANCE_CA

When an ExternalSecretService is created, it synchronously validates that caBundle is a valid PEM and probes network connectivity to endpoint. If caBundle is invalid or the instance endpoint is unreachable, the apply request is rejected. Confirm connectivity between the cluster and the dedicated KMS instance. See the VPC sharing instructions in Prerequisites.

  • Save the following content as agent-identity.yaml and run kubectl apply -f agent-identity.yaml to create an AgentIdentity that defines an Agent identity.

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: AgentIdentity
metadata:
  name: my-agent          # Agent identity name, referenced during later authorization
  namespace: <YOUR-NAMESPACE>
spec:
  description: "Sample AI Agent identity"
  • Save the following content as credential-provider-kms.yaml and run kubectl apply -f credential-provider-kms.yaml to create a CredentialProvider. It references the preceding ExternalSecretService and specifies the KMS credential to read.

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: CredentialProvider
metadata:
  name: llm-api-key
  namespace: <YOUR-NAMESPACE>
spec:
  type: APIKey
  apiKey:
    source:
      provider: KMS
      kms:
        secretName: my-kms-secret-name        # Credential name in KMS Secrets Manager
        serviceRef:
          name: kms-dedicated-instance        # Name of the ExternalSecretService created in the preceding step
        # versionStage: ACSCurrent            # Optional credential version stage. Default: ACSCurrent
        # versionId: ""                       # Optional specified credential version ID
        # maxCacheValidity: 15m                # Optional maximum credential-value cache period. Default: 15m

secretName supports template variables that dynamically reference different KMS credentials according to context. For more information, see the secretName template variables section.

  • Save the following content as agent-role-kms.yaml and run kubectl apply -f agent-role-kms.yaml to create an AgentRole and an AgentRoleBinding that authorize the Agent identity to obtain credentials from this CredentialProvider.

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: AgentRole
metadata:
  name: get-llm-key
  namespace: <YOUR-NAMESPACE>
spec:
  rules:
  - effect: Allow
    action: "GetResourceCredential"
    resource: "CredentialProvider/llm-api-key"   # Name of the CredentialProvider created in the preceding step
---
apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: AgentRoleBinding
metadata:
  name: my-agent-get-llm-key
  namespace: <YOUR-NAMESPACE>
spec:
  agentRoleRef:
    apiGroup: agentidentity.alibabacloud.com
    kind: AgentRole
    name: get-llm-key
  subjects:
  - authorizationType: "Agent"
    agentAuthorizationConfiguration:
      agentName: my-agent                        # Must match the AgentIdentity name
  • Confirm that the resources are ready. For an ExternalSecretService, Available indicates that its spec is valid and the endpoint network probe succeeded. For a CredentialProvider, Available indicates that its serviceRef resolved to an existing ExternalSecretService.

kubectl get externalsecretservice kms-dedicated-instance -n <YOUR-NAMESPACE>
kubectl get credentialprovider llm-api-key -n <YOUR-NAMESPACE>

Expected output:

NAME                     PROVIDER   AVAILABLE   AGE
kms-dedicated-instance   KMS        True        30s

NAME          AVAILABLE   AGE
llm-api-key   True        30s

Available=True for a CredentialProvider means only that serviceRef resolved. It does not mean that the credential has been retrieved from KMS. Problems such as insufficient AAP permissions, a mismatched instance CA, a nonexistent credential, or an unreachable VPC network surface only when a credential is actually retrieved. For more information, see the Status and troubleshooting section.

Consume credentials

Created and authorized API key credentials are usually consumed through egress traffic credential injection for Agent Sandbox. Reference the CredentialProvider in the tokenTransformation rule of a SecurityProfile. The Sandbox application sends requests with a placeholder token, and the egress gateway replaces it with the actual API key retrieved from KMS when forwarding the requests. For the complete end-to-end configuration of SecurityProfile, SandboxSet, and SandboxClaim, and for the verification steps, see Configure credential injection for Agent Sandbox egress traffic.

secretName template variables

In addition to a fixed credential name, secretName can embed ${ack:agent-identity/...} template variables. During credential retrieval, the system renders the actual credential name from the current request identity context, so it can retrieve different KMS credentials for different identities. For example, llm-api-key-${ack:agent-identity/agent-name} resolves to llm-api-key-my-agent according to the Agent name.

The following template variables are supported:

Template variable

Description

${ack:agent-identity/agent-name}

The name of the AgentIdentity associated with the current Agent identity.

${ack:agent-identity/metadata/<key>}

The value of the specified key in custom metadata written when the identity token was issued. Replace <key> with the actual key name.

The following example dynamically references different KMS credentials for different tenants. Each tenant's API key is stored in a KMS credential named llm-api-key-<tenant-id>. The CredentialProvider resolves the matching credential name through ${ack:agent-identity/metadata/tenant-id} when it retrieves credentials.

Metadata values originate in custom metadata written when the identity token is issued. In Agent Sandbox scenarios, pass the value in the SandboxClaim security.agents.kruise.io/<key> Kubernetes Annotation. The part after this prefix is the metadata key:

apiVersion: agents.kruise.io/v1alpha1
kind: SandboxClaim
metadata:
  name: my-claim
  namespace: <YOUR-NAMESPACE>
spec:
  templateName: my-sandbox-set
  replicas: 1
  annotations:
    # After removing the prefix, this Annotation can be referenced through ${ack:agent-identity/metadata/tenant-id}.
    security.agents.kruise.io/tenant-id: acme
    security.agents.kruise.io/agent-name: my-agent

The corresponding CredentialProvider is as follows:

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: CredentialProvider
metadata:
  name: llm-api-key
  namespace: <YOUR-NAMESPACE>
spec:
  type: APIKey
  apiKey:
    source:
      provider: KMS
      kms:
        secretName: 'llm-api-key-${ack:agent-identity/metadata/tenant-id}'   # Resolves to llm-api-key-acme
        serviceRef:
          name: kms-dedicated-instance

With this configuration, when the request identity metadata tenant-id is acme, secretName resolves to llm-api-key-acme, so the retrieval returns the KMS credential dedicated to that tenant.

If a template variable cannot be resolved in the current request context, the credential-retrieval request fails with an explicit error message instead of silently returning an empty value. For example, resolution fails when the referenced metadata key does not exist.

Field descriptions

ExternalSecretService

The spec structure for provider: KMS is as follows:

spec:
  provider: KMS                      # Required ExternalSecretService provider type. Cannot be changed after creation.
  kms:
    endpoint: <instance-endpoint>    # Required KMS instance access domain name.
    auth:
      type: AAP                      # Required authentication method. Use AAP (OIDC) in this topic.
      aap:
        arn: <aap-arn>               # Use either arn or name. Full AAP ARN.
        # name: <aap-name>           # Use either arn or name. AAP short name.
    caBundle: <ca-pem-or-base64>     # Required CA certificate of the dedicated instance gateway.

The following table describes the key fields:

Field

Required

Description

spec.provider

Yes

The ExternalSecretService provider type. Use KMS in this topic. It cannot be changed after creation.

spec.kms.endpoint

Yes

The endpoint used to access the KMS instance. A dedicated instance gateway endpoint has the format <instance-id>.cryptoservice.kms.aliyuncs.com.

spec.kms.auth.type

Yes

The KMS authentication method. Use AAP for AAP-based OIDC authentication in this topic.

spec.kms.auth.aap.arn

Either

The full AAP ARN, in the format acs:kms:<region>:<uid>:applicationaccesspoint/<name>. It is mutually exclusive with aap.name.

spec.kms.auth.aap.name

Either

The AAP short name. The add-on builds the full ARN from the region and account ID. It is mutually exclusive with aap.arn.

spec.kms.caBundle

Yes

The CA certificate of the dedicated instance gateway. This is public information. The field accepts base64-encoded PEM or raw PEM.

CredentialProvider

The spec structure for type: APIKey with a KMS source is as follows:

spec:
  type: APIKey                       # Required credential type. Cannot be changed after creation.
  apiKey:
    source:
      provider: KMS                  # Required credential source.
      kms:
        secretName: <secret-name>    # Required KMS credential name. Supports template variables.
        serviceRef:
          name: <ess-name>           # Required name of an ExternalSecretService in the same namespace.
        versionStage: ACSCurrent     # Optional credential version stage. Default: ACSCurrent.
        versionId: <version-id>      # Optional specified credential version ID.
        maxCacheValidity: 15m        # Optional maximum credential-value cache period. Default: 15m.

The following table describes the key fields:

Field

Required

Description

spec.type

Yes

The credential type. Use APIKey in this topic. It cannot be changed after creation; validation rejects changes.

spec.apiKey.source.provider

Yes

The credential source. Use KMS in this topic.

spec.apiKey.source.kms.secretName

Yes

The credential name in KMS Secrets Manager. Its value is delivered as the API key. It supports template variables.

spec.apiKey.source.kms.serviceRef.name

Yes

The referenced ExternalSecretService name. It must be in the same namespace as the CredentialProvider. Cross-namespace references are not supported.

spec.apiKey.source.kms.versionStage

No

The credential version stage to read. The default is ACSCurrent.

spec.apiKey.source.kms.versionId

No

Reads the credential value for a specified version ID. Use it with versionStage.

spec.apiKey.source.kms.maxCacheValidity

No

The maximum cache period for credential values. The default is 15m, allowing KMS key rotation or revocation to be detected within one cache period.

Status and troubleshooting

The runtime status of ExternalSecretService and CredentialProvider is recorded in their respective status.conditions fields. Run kubectl describe to view them.

The following table lists common ExternalSecretService Conditions and Reasons:

Condition / Reason

Description

Available = True, Reason = SpecValid

The spec is valid and the instance endpoint network probe succeeded.

Degraded, Reason = EndpointUnreachable

The instance endpoint is unreachable. Check VPC sharing and network connectivity, and verify the endpoint and CA.

The following table lists common CredentialProvider Conditions and Reasons for a KMS source:

Condition / Reason

Description

Available = True, Reason = AllRefsResolved

serviceRef resolved to an existing ExternalSecretService.

Degraded, Reason = RefNotFound

The ExternalSecretService referenced by serviceRef.name does not exist. Check that its name and namespace are consistent.

The CredentialProvider reconciliation phase only checks whether serviceRefexists. It does not check whether KMS can retrieve the credential. Consequently, KMS access errors do not appear in CredentialProvider status and are exposed only when a credential is actually retrieved. The following table lists common runtime errors and how to troubleshoot them:

Symptom

Troubleshooting

Credential retrieval returns a permission or authentication error

Check the KMS OIDC (ACK) AAP configuration: Namespace must beack-agent-identity; ServiceAccount must becredential-provider; the scope must be the dedicated instance; RBAC must include CryptoServiceSecretUser; and the target credential must be included in Accessible Resources.

Credential retrieval returns a TLS or certificate error

Confirm that the ExternalSecretService caBundle matches the dedicated instance gateway CA and that endpoint is correct.

Credential retrieval reports that a credential does not exist

Confirm that secretName, or the name rendered from a template variable, exists in KMS Secrets Manager, and that versionStage or versionId, if specified, references an existing version.

Credential retrieval returns a network disconnection or timeout error

Check whether the cluster VPC differs from the KMS instance VPC without VPC sharing, and whether a security group or Network Policy blocks traffic. See the VPC sharing instructions in Prerequisites.

Limits

Limit

Description

Same-namespace references

A CredentialProvider can reference only an ExternalSecretService in the same namespace. Cross-namespace references are not supported.

Dedicated instance OIDC scope only

This topic covers only OIDC (ACK) access to a dedicated KMS instance.

Instance image version

The dedicated KMS instance image version must be dkms-4.0.0 or later.

Credential value caching

The KMS source caches credential values. maxCacheValidity defaults to 15m; KMS rotation or revocation can take up to one cache period to be detected.

FAQ

CredentialProvider is Available, but the Sandbox cannot retrieve a KMS credential

A CredentialProvider Available status means only that serviceRef resolved. It does not mean that the credential can be retrieved from KMS. Check the following:

  • Verify the KMS OIDC (ACK) AAP configuration: Namespace must beack-agent-identity; ServiceAccount must becredential-provider—the add-on ServiceAccount, not a business Pod ServiceAccount. The scope must be the target dedicated instance, RBAC must include CryptoServiceSecretUser, and the target credential must be included in Accessible Resources.

  • Confirm that the ExternalSecretService endpoint and caBundle match the dedicated instance gateway, and that kubectl describe externalsecretservice does not show a Reason of EndpointUnreachable in status.conditions.

  • Confirm that secretName, or its rendered value, exists in KMS Secrets Manager.

  • If the cluster VPC differs from the KMS instance VPC, confirm that the VPC sharing requirement in Prerequisites is met.

ExternalSecretService creation fails with no such host

The add-on cannot resolve the instance endpoint. Confirm that endpoint is correct and that the cluster VPC meets the VPC sharing requirement in Prerequisites.

ExternalSecretService remains EndpointUnreachable

The add-on cannot connect to the instance endpoint. Confirm that endpoint is correct and caBundle is the CA for that instance gateway, and check whether the cluster VPC meets the VPC sharing requirement in Prerequisites.

An Agent is denied when retrieving credentials

Confirm that an AgentRole with action: GetResourceCredential and resource: CredentialProvider/<name>, together with a corresponding AgentRoleBinding, have been created. The AgentRoleBinding agentName must match the target AgentIdentity name, and all related resources must be in the same namespace.

References