搭配 Vertex AI Agent Engine 使用代理程式身分

本頁說明如何使用 Identity Access Management (IAM) 代理程式身分,在使用 Vertex AI Agent Engine Runtime 的代理程式時,提供安全性和存取權管理功能。

總覽

代理程式身分提供每個代理程式的身分,可採用最低權限方法,並與代理程式的生命週期相關聯,因此代理程式身分比服務帳戶更安全。透過 IAM 支援代理程式身分,現有的存取權管理控制項可實現嚴格的控管。

本頁面涵蓋下列主題:

限制

規劃專案時,請注意下列限制:

  • 代理程式身分無法在 Cloud Storage 值區上獲授舊版值區角色 (storage.legacyBucketReaderstorage.legacyBucketWriterstorage.legacyBucketOwner)。

  • 建議僅在測試環境中使用代理程式身分。

建立具有代理程式身分的代理程式

建立 Agent Engine 執行個體時,您可以為部署至 Vertex AI Agent Engine 的代理提供專屬身分。身分識別資訊會與 Vertex AI Agent Engine 的代理程式資源 ID 建立關聯,與您用來開發代理程式的代理程式架構無關。

建立代理程式身分時,您可以選擇下列選項:

  • 建立 Agent Engine 執行個體,但不部署代理程式碼:如要在部署代理程式之前設定 IAM 政策,可以建立代理程式身分,但不部署代理程式碼。如要這麼做,請只使用 identity_type 欄位建立 Agent Engine 執行個體:

    import vertexai
    from vertexai import agent_engines
    from vertexai import types
    
    client = vertexai.Client(
      project=PROJECT_ID,
      location=LOCATION,
      http_options=dict(api_version="v1beta1")
    )
    remote_app = client.agent_engines.create(
      config={"identity_type": types.IdentityType.AGENT_IDENTITY}
    )
    

    使用代理身分建立 Agent Engine 執行個體後,即可使用 agent_engine.update(...) 新增代理程式碼。

  • 部署代理程式碼時建立 Agent Engine 執行個體:如要在部署代理程式碼時佈建代理身分,請使用 Vertex AI SDK for Python 和 identity_type=AGENT_IDENTITY 旗標:

    import vertexai
    from vertexai import agent_engines
    from vertexai import types
    
    client = vertexai.Client(
      project=PROJECT_ID,
      location=LOCATION,
      http_options=dict(api_version="v1beta1")
    )
    remote_app = client.agent_engines.create(
          agent=app,
          config={
              "identity_type": types.IdentityType.AGENT_IDENTITY,
              "requirements": ["google-cloud-aiplatform[adk,agent_engines]"],
              "staging_bucket": f"gs://"BUCKET _NAME",
          },
    )
    

    其中 BUCKET_NAME 是 Cloud Storage bucket 的名稱。

Agent Engine 例項是使用系統認證的唯讀代理身分 (主體 ID) 建立:

# Agent identity Format
principal://TRUST_DOMAIN/NAMESPACE/AGENT_NAME

# Example agent identity
principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID

系統會自動為您佈建下列部分,做為代理程式身分識別的一部分:

  • TRUST_DOMAIN:啟用 Vertex AI API 時,系統會為您佈建信任網域:

    • 如果您有機構,信任網域會在機構層級建立,格式為 agents.global.org-ORGANIZATION_ID.system.id.goog

    • 如果專案沒有機構,系統會在專案層級建立信任網域,格式為 agents.global.project-PROJECT_NUMBER.system.id.goog

  • NAMESPACE:代理程式的不變資源路徑。

  • AGENT_NAME:不可變動的 agent-reasoning-engine-id

代理程式身分是以 SPIFFE 為基礎。我們也會在代理程式上自動佈建及管理具有相同身分的 x509 憑證,確保驗證安全無虞。

您可以透過 Vertex AI Agent Engine Google Cloud 控制台和 API 查看身分

使用代理程式身分存取 Google Cloud API 和服務

使用代理程式身分建立代理程式後,您可以使用下列 IAM 政策,授予或拒絕代理程式存取 Google Cloud API 和服務:

  • 允許政策:授予代理程式資源存取權。 Google Cloud

  • 拒絕政策:拒絕代理人存取 Google Cloud 資源。

授予代理存取權

將 IAM 權限授予代理程式身分。建議您指派下列角色:

  • roles/aiplatform.expressUser:授予執行推論、工作階段和記憶體的存取權。

  • roles/serviceusage.serviceUsageConsumer:授予代理程式使用專案配額和 Vertex AI SDK 的權限。

建立 IAM 允許政策,將 IAM 角色授予代理程式:

  # Example: Grant the agent access to vision API.
  gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID \
  --member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID" \
  --role="ROLE_NAME" \

更改下列內容:

  • ORGANIZATION_ID:貴機構的 ID。

  • PROJECT_NUMBER:您的專案編號。

  • LOCATION:您的區域。請參閱 Vertex AI Agent Engine 的支援區域

  • AGENT_ENGINE_ID:Agent Engine 執行個體的資源 ID。

  • ROLE_NAME 是您要授予的角色名稱。例如:roles/vision.user。如需預先定義角色清單,請參閱「瞭解角色」一文。

設定 IAM 後,Google Cloud SDK 的應用程式預設憑證會自動使用代理程式身分,向Google Cloud 資源執行驗證。

拒絕代理程式存取權

如要拒絕代理程式存取資源,可以使用 IAM 拒絕政策,或設定主體存取邊界政策

  • 使用 IAM 拒絕政策,拒絕代理程式存取特定資源。

    // Deny policy (deny all agents across the org from ability to create or delete buckets)
    
    {
    "displayName": "Deny access to bucket for all agent identities in the org",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principalSet://<org.id>.global.agent.id.goog/*"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create",
            "storage.googleapis.com/buckets.delete"
          ]
        }
      }
    ]
    }
    
  • 設定主體存取邊界,限制代理可存取的資源,即使代理可能擁有其他權限:

    // PAB Policy (Only allow agents to operate within resource boundary)
    
    {
        "name":"organizations/ORGANIZATION_ID/locations/global/principalAccessBoundaryPolicies/example-policy",
        "details": {
        "rules": [
          {
            "description": "Restrict agent identity inside a folder",
            "resources": [
              "//cloudresourcemanager.googleapis.com/folder/0123456789012"
            ],
            "effect": "ALLOW"
          }
        ],
      }
    }
    
    // Bind PAB policy to all identities in the organization (incl agent id)
    
    gcloud iam principal-access-boundary-policies bindings create example-pab-binding \
          --organization=organizations/ORGANIZATION_ID \
          --policy=example-policy \ --target-principal-set=cloudresourcemanager.googleapis.com/organizations/ORGANIZATION_ID
    

使用 OAuth 透過委派授權存取第三方服務

代理程式身分可與 Secret Manager 整合,讓代理程式代表您存取第三方服務。

如要設定與 Secret Manager 的整合,請先按照下列步驟,將存取第三方服務的輔助憑證 (用戶端 ID 或用戶端密鑰) 儲存至 Secret Manager (在代理程式生命週期管理的消費者專案中):

  1. 在 Secret Manager 中建立新容器。

  2. 向第三方應用程式供應商取得用戶端 ID 或用戶端密鑰。

  3. 將用戶端 ID 或用戶端密鑰新增至 Secret Manager。

  4. 根據代理程式 ID (主體 ID) 限制這些憑證的存取權:

    # Create the secret container
    gcloud secrets create my-app-oauth-secret
    
    # Add the actual client secret to Secret Manager
    gcloud secrets versions add my-app-oauth-secret "gcp-client-secret-1a2b3c4d"
    
    # Grant agent identity access to the secret
    gcloud secrets add-iam-policy-binding my-app-oauth-secret \
    --role='roles/secretmanager.secretAccessor' \
    --member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID" \
    

儲存密鑰後,代理程式就能在執行階段使用主體 ID 和標準Google Cloud 驗證程式庫,自動存取這些憑證,做為應用程式預設憑證的一部分。

# Example: Use agent identity to retrieve third party credentials from Secret Manager
# Use case: Using an agent, the user is trying to post a message on Slack,
# The developer first retrieves secret from Secret Manager using agent identity,
# and then uses it to login to Slack and post a message.

from google.cloud import secretmanager

def access_secret(project_id: str, secret_id: str, version_id: str = "latest") -> str:

      # Application default credential automatically gets token from MDS using agent identity
      agent_identity_credentials = default()

       # Create the Secret Manager client.
       client = secretmanager.SecretManagerServiceClient(credentials=agent_identity_credentials)

       # Build the resource name of the secret version.
       name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}"

       # Access the secret version.
       response = client.access_secret_version(request={"name": name})

       # Decode the payload to get the secret string.
       secret_value = response.payload.data.decode("UTF-8")
       return secret_value

有了用戶端 ID 和用戶端密鑰,您現在可以建構工具並設定 OAuth 型驗證。

以下範例使用 Agent Development Kit (ADK) 開發的代理。以 OAuth 為基礎的驗證會包裝進 authenticationSchemeauthCredential 方法,做為工具建構的一部分:

import os

from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.auth.auth_credential import AuthCredential, AuthCredentialTypes, OAuth2Auth
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
from google.adk.agents.llm_agent import LlmAgent

auth_scheme = OpenIdConnectWithConfig(
   authorization_endpoint="https://your-endpoint.slack.com/oauth2/v1/authorize",
   token_endpoint="https://your-token-endpoint.slack.com/oauth2/v1/token",
   scopes=['openid', 'profile', "email"]
)

auth_credential = AuthCredential(
 auth_type=AuthCredentialTypes.OPEN_ID_CONNECT,
 oauth2=OAuth2Auth(
   client_id=access_secret(project_id: 'foo', secret_id: 'slack_oauth_client_id'),
   client_secret=access_secret(project_id: 'foo', secret_id: 'slack_oauth_client_secret'),
 )
)

# --- Slack Toolset Configuration Based On OpenAPI Specification ---

with open(os.path.join(os.path.dirname(__file__), 'spec.yaml'), 'r') as f:
   spec_content = f.read()

slack_toolset = OpenAPIToolset(
  spec_str=spec_content,
  spec_str_type='yaml',

  # ** Crucially, associate the authentication scheme and credentials with these tools. **
  # This tells the ADK that the tools require the defined OIDC/OAuth2 flow.
  auth_scheme=auth_scheme,
  auth_credential=auth_credential,
)

# Configure and create the main LLM Agent.

root_agent = LlmAgent(
   model='gemini-2.0-flash',
   name='enterprise_assistant',
   instruction='Help user integrate with Slack and post messages to Slack.',
   tools=userinfo_toolset.get_tools(),
)

執行階段會發生下列情況 (如果您透過 ADK 網頁在本機使用 ADK,這些步驟會在 ADK 網頁和 ADK 後端自動執行):

  1. 您存取代理程式,代理程式判斷需要叫用工具 (例如 Slack)。

  2. ADK 內程式設計的工具 (使用 auth_schemeauth_credential) 會將 authConfig 物件傳回前端 (包括重新導向 URI 和用戶端 ID)。

  3. 前端會剖析 authConfig 物件,您會重新導向至第三方授權頁面。登入後,系統會將您重新導向至代理商前端,並將授權碼傳送至 ADK 後端。

  4. 後端會使用授權碼取得第三方服務的存取權杖,並繼續執行工具。

如果將 ADK 代理部署至 Vertex AI Agent Engine Runtime,您需要建構自訂前端,並將 ADK-web 驗證或重新導向程式碼遷移至前端,以執行相同的 OAuth 整合。

使用 API 金鑰存取第三方服務

代理程式身分可讓代理程式存取第三方服務,並使用 API 金鑰代表您執行動作。您必須先將第三方服務的 API 金鑰儲存至 Secret Manager,然後從 Secret Manager 擷取這些憑證。

from google.adk.tools.openapi_tool.auth.auth_helpers import token_to_scheme_credential
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset

WEATHER_DOT_COM_API_KEY = access_secret(project_id: 'foo', secret_id: 'weather_dot_com_api_key')

auth_scheme, auth_credential = token_to_scheme_credential(
   "apikey", "query", "apikey", WEATHER_DOT_COM_API_KEY
)

sample_api_toolset = OpenAPIToolset(
   spec_str="...",
   spec_str_type="yaml",
   auth_scheme=auth_scheme,
   auth_credential=auth_credential,
)

記錄代理程式活動

啟用 Cloud Logging 後,您就能查看記錄,瞭解哪些代理程式和使用者存取了 Google Cloud 資源。

  • 如果服務專員代表使用者執行動作,記錄檔會同時顯示服務專員和使用者的身分。

  • 如果代理程式是自行採取行動,記錄檔只會顯示代理程式的身分。

列出代理程式及其身分

您可以使用 Google Cloud 控制台和指令列,在 Vertex AI Agent Engine 中查看代理程式身分清單。

控制台

  1. 前往 Google Cloud 控制台的「Vertex AI Agent Engine」頁面。

    前往 Agent Engine

    清單中會顯示所選專案的已部署代理程式。您可以使用「篩選」欄位,依指定欄篩選清單。

  2. 每個代理程式的代理程式身分都會列在「身分」欄下方。

REST API

使用 REST API 取得 Agent Engine 執行個體時,可以擷取代理程式身分。

回覆會包含代理程式身分,格式如下:

{
  ...
  spec: {
    "effectiveIdentity": "agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_ID/locations/LOCATION/reasoningEngines/AGENT_ENGINE_ID"
  }
  ...
}

如果 Agent Engine 執行個體未使用代理程式身分,則 effectiveIdentity 欄位會包含與 Agent Engine 執行個體相關聯的服務代理程式或服務帳戶名稱。

後續步驟