托管凭证注入

更新时间:
复制 MD 格式

将 API Key 托管在 Agent Identity,沙箱发请求时由出网网关自动注入真实 Key,Key 不进入沙箱。

概述

许多服务使用 API Key 认证,例如模型服务、搜索服务、企业内部 API。

真实 Key 不应写入沙箱代码。将 Key 托管在 Agent Identity 后,沙箱内正常发起请求(不带认证 Header),出网时由出网网关注入真实 Key,Key 不进入沙箱。

建议先阅读凭证注入,了解整体框架。

适用场景

适用于使用 API Key 认证的目标服务,常见认证 Header 格式如下:

  • Authorization: Bearer <api-key>

  • Authorization: Token <api-key>

  • X-API-Key: <api-key>

如果 Key 是用户自己持有的静态值,也可以用自带凭证注入的整 Header 注入直接配置;两种方式注入效果相同,区别仅在于 Key 存储位置。

前提条件

在阿里云Agent Identity 控制台里先准备好:

  1. 创建 Workload Identity,并关联一个可用的 RAM Role(未关联会导致创建失败);

  2. 给这个 Role 授予 agentidentitydata:GetResourceAPIKey 权限(缺少该权限将无法获取 API Key);

  3. 创建 API Key 凭证提供商,把真实 API Key 存入;

  4. 允许该 Workload Identity 使用这个凭证提供商;

  5. 确认目标服务的域名、Header 名称和认证格式。

配置沙箱

示例中的 my-agent 是前提条件中创建的 Workload Identity 名称,model-provider 是 API Key 凭证提供商名称,api.example.com 是目标服务域名。下面把 Agent Identity 里名为 model-provider 的 API Key,注入到发往 api.example.com 请求的 Authorization Header:

Node.js

import { Sandbox } from "e2b";

const sandbox = await Sandbox.create("code-interpreter-v1", {
  metadata: {
    "fc.sandbox.identity.name": "my-agent",
  },
  network: {
    allowOut: ["api.example.com"],
    denyOut: ["0.0.0.0/0"],
    rules: {
      "api.example.com": [{
        transform: {
          headers: {
            Authorization: "Bearer ${fc.sandbox.identity.apiKey:model-provider}",
          },
        },
      }],
    },
  },
});

Python

from e2b import Sandbox

sandbox = Sandbox.create(
    template="code-interpreter-v1",
    metadata={"fc.sandbox.identity.name": "my-agent"},
    network={
        "allow_out": ["api.example.com"],
        "deny_out": ["0.0.0.0/0"],
        "rules": {
            "api.example.com": [{
                "transform": {
                    "headers": {
                        "Authorization":
                            "Bearer ${fc.sandbox.identity.apiKey:model-provider}"
                    }
                }
            }]
        },
    },
)

引用表达式 ${fc.sandbox.identity.apiKey:<提供商名>} 指向 Agent Identity 中的 API Key,并可与 Bearer 、Token 等固定前缀拼接。

验证凭证注入

在沙箱内直接请求目标服务,无需设置认证 Header:

curl -i https://api.example.com/v1/inference \
  -H 'Content-Type: application/json' \
  -d '{"input":"hello"}'

请求出网时,出网网关会注入 Authorization: Bearer <真实 API Key>。如果 SDK 强制要求传入 Key,可使用占位值,出网网关会覆盖对应 Header。

更新配置

沙箱运行期间可通过 updateNetwork 更换凭证提供商或修改注入规则,具体操作见更新网络配置。

使用限制

通用限制和安全要求见凭证使用限制。