第七章:安全与认证

7.1 概述

安全机制是协议的重要组成部分,确保技能提供者能够控制谁可以发现和调用其技能。协议支持多种认证方式和访问控制策略,在开放性与安全性之间取得平衡。

7.2 访问控制策略

三级访问控制

级别发现可见性调用权限适用场景
public所有人可见无需认证即可调用开放 API、公共知识库
restricted所有人可见需认证后调用商业 API、付费服务
private仅认证后可见需认证后调用内部工具、私有服务

访问控制与发现的关系

  • 未认证请求访问 Well-Known URI 时:
    • 返回所有 publicrestricted 技能
    • 不返回 private 技能
  • 认证后请求访问 Well-Known URI 时:
    • 返回所有技能(包括 private

7.3 认证方式

API Key 认证

最简单的认证方式,通过 HTTP Header 传递密钥。

描述符声明:

{
  "type": "api_key",
  "description": "通过 HTTP Header 传递 API Key",
  "header": "X-API-Key"
}

调用时附加 Header:

POST /invoke HTTP/1.1
Host: api.example.com
X-API-Key: sk-your-api-key-here
Content-Type: application/json

OAuth 2.0 认证

适用于需要细粒度权限控制的场景。

描述符声明:

{
  "type": "oauth2",
  "oauth2": {
    "authorization_url": "https://example.com/oauth/authorize",
    "token_url": "https://example.com/oauth/token",
    "scopes": {
      "skill:invoke": "调用技能",
      "skill:read": "读取技能信息",
      "skill:admin": "管理技能配置"
    }
  }
}

调用时附加 Bearer Token:

POST /invoke HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
Content-Type: application/json

自定义认证

适用于非标准认证场景,提供者通过 instructions 字段说明认证方式。

描述符声明:

{
  "type": "custom",
  "custom": {
    "instructions": "使用 HMAC-SHA256 对请求体签名,将签名放入 X-Signature header",
    "parameters": [
      {
        "name": "secret_key",
        "type": "string",
        "description": "用于 HMAC 签名的密钥",
        "required": true
      }
    ]
  }
}

无认证

公开技能无需认证:

{
  "type": "none"
}

7.4 认证错误处理

认证失败(401)

未提供有效凭据时:

{
  "error": {
    "code": "AUTH_REQUIRED",
    "message": "Authentication is required to invoke this skill",
    "details": {
      "required_auth_type": "oauth2",
      "authorization_url": "https://example.com/oauth/authorize"
    }
  }
}

权限不足(403)

凭据有效但无权访问:

{
  "error": {
    "code": "PERMISSION_DENIED",
    "message": "Insufficient permissions to invoke this skill",
    "details": {
      "required_scopes": ["skill:invoke"],
      "current_scopes": ["skill:read"]
    }
  }
}

7.5 安全最佳实践

  1. 所有通信应使用 HTTPS
  2. API Key 应通过 Header 传递,避免出现在 URL 中
  3. OAuth 2.0 Token 应设置合理的过期时间
  4. 技能提供者应实施速率限制以防止滥用
  5. 敏感技能应使用 private 访问策略,避免被未授权方发现