From 17dd92ee84cf23608338e3acd30f664de2fdd1c3 Mon Sep 17 00:00:00 2001 From: Paul Yuknewicz Date: Sun, 1 Nov 2026 15:21:30 -0800 Subject: [PATCH] Use ProjectManagedIdentity for Foundry connections and fix AI Gateway MCP wire route - Switch Foundry appInsightsConnection to ProjectManagedIdentity with Monitoring Metrics Publisher RBAC on Application Insights - Switch Foundry aigw-github connection to ProjectManagedIdentity (audience https://azure-api.net/aigateway) with AI Gateway User RBAC (caad7a21-134e-43f4-a550-c5ffc17e051c) on AI Gateway - Fix aigw-github target route from /default/mcp/github/mcp (HTTP 404) to /default/toolservers/github/mcp (HTTP 200) - Fix runtimeApiKey.listSecrets() fallback to read primaryKey (live ARM response property) before key - Add declarative toolServers/github support when githubMcpAuthorization is supplied - Support keyless Entra ID bearer token auth (https://azure-api.net/aigateway/.default) in repo_digest_agent.py when AZURE_AI_GATEWAY_API_KEY is unset Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4448b1aa-1ea5-4c5f-af63-7ec98b7acb9e --- IMPLEMENTATION_NOTES.md | 54 +++++----- infra/ai-gateway/README.md | 29 +++--- infra/ai-gateway/main.bicep | 44 +++++++- infra/foundry-agents/github-connection.bicep | 20 +++- infra/foundry-agents/main.bicep | 29 +++++- infra/main.bicep | 54 ++++++++++ repo_digest_agent.py | 67 ++++++++---- tests/test-ai-gateway-model-registration.sh | 30 ++++-- tests/test_agent_runtime.py | 101 +++++++++++++++++++ 9 files changed, 349 insertions(+), 79 deletions(-) diff --git a/IMPLEMENTATION_NOTES.md b/IMPLEMENTATION_NOTES.md index 4cff3f7..89dffba 100644 --- a/IMPLEMENTATION_NOTES.md +++ b/IMPLEMENTATION_NOTES.md @@ -48,9 +48,9 @@ flowchart LR github["GitHub MCP server"] operator --> agent - agent -->|"model request and Api-Key"| gateway + agent -->|"model request (Entra ID or Api-Key)"| gateway agent -->|"Entra identity"| toolbox - toolbox -->|"project connection and Api-Key"| gateway + toolbox -->|"project managed identity (AI Gateway User RBAC)"| gateway gateway -->|"managed identity and Foundry User RBAC"| models gateway -->|"repository-scoped read-only credential"| github ``` @@ -58,7 +58,7 @@ flowchart LR Model requests use `/default/models/openai/v1/chat/completions` or the corresponding Responses route. Tool requests use -`/default/mcp/github/mcp`. +`/default/toolservers/github/mcp`. The agent does not call a Foundry model endpoint directly. This keeps model traffic behind AI Gateway policies. `FoundryChatClient` is intentionally not @@ -73,11 +73,13 @@ Agent -> Foundry Toolbox -> AI Gateway -> GitHub MCP ``` `toolbox.yaml` declares one MCP source backed by the `aigw-github` project -connection. Bicep creates that `RemoteTool` / `CustomKeys` connection and stores -the generated AI Gateway `Api-Key` in it. The postprovision hook creates -`repo-digest-tools` through the Foundry data-plane API using that connection; -it no longer runs `azd ai connection create`. `FoundryToolbox` authenticates -the agent-to-Toolbox request with Entra identity. +connection. Bicep creates that `RemoteTool` / `ProjectManagedIdentity` +connection (`audience: https://azure-api.net/aigateway`) and assigns the +`AI Gateway User` (`caad7a21-134e-43f4-a550-c5ffc17e051c`) role on AI Gateway +to the Foundry project and account managed identities. The postprovision hook +creates `repo-digest-tools` through the Foundry data-plane API using that +connection; it no longer runs `azd ai connection create`. `FoundryToolbox` +authenticates the agent-to-Toolbox request with Entra identity. The GitHub source sets `require_approval: "never"` because all three exposed operations are read-only and the scheduled routine cannot pause for approval. @@ -294,22 +296,26 @@ The predefined `workspaces/default` resource is the parent of every workspace-scoped child. The postprovision hook waits for the workspace child collection before configuring the GitHub ToolServer. -The gateway module receives the agents account and project names from the -Foundry module outputs, so it waits for project provisioning. Its nested -connection module targets the agents resource group and depends on the gateway -and `apiKeys/default`. The connection target is -`/default/mcp/github/mcp`, with `isSharedToAll: true` and -`metadata.type: custom_MCP`. Stable resource names and incremental deployments -allow repeated `azd up` runs to update the same connection. - -The preview key contract used by the deployment is -`runtimeApiKey.listSecrets().key` at `2025-09-01-preview`. Bicep compiles this -created-resource call to ARM `listSecrets(resourceId(...), apiVersion).key` -and adds the key resource dependency. The value crosses the module boundary -only through an `@secure()` parameter (`securestring` in ARM), never an output. -The deploying identity needs permission to list the gateway key and write -project connections in the agents resource group. Do not log resolved -deployment parameters or run the hooks with shell tracing/debug logging. +The gateway module receives the agents account and project names and managed +identity principal IDs from the Foundry module outputs, so it waits for project +provisioning. It assigns the `AI Gateway User` +(`caad7a21-134e-43f4-a550-c5ffc17e051c`) role on AI Gateway to the Foundry +project and account managed identities (and optional developer `principalId`), +and its nested connection module targets the agents resource group. The +connection target is `/default/toolservers/github/mcp`, with +`authType: ProjectManagedIdentity` (`audience: https://azure-api.net/aigateway`), +`isSharedToAll: true`, and `metadata.type: custom_MCP`. Stable resource names +and incremental deployments allow repeated `azd up` runs to update the same +connection. + +When `useManagedIdentityForFoundryConnections: false` is explicitly opted into, +the connection falls back to `CustomKeys` using +`runtimeApiKey.listSecrets().?primaryKey ?? runtimeApiKey.listSecrets().?key` at +`2025-09-01-preview` (the live ARM `listSecrets` response returns `primaryKey` +and `secondaryKey`). The value crosses the module boundary only through an +`@secure()` parameter (`securestring` in ARM), never an output. Do not log +resolved deployment parameters or run the hooks with shell tracing/debug +logging. Both postprovision hooks still retrieve the key with `listSecrets` (preferring `key`, with legacy response-field and `listValues` compatibility fallbacks) and diff --git a/infra/ai-gateway/README.md b/infra/ai-gateway/README.md index 89ee1f9..207adba 100644 --- a/infra/ai-gateway/README.md +++ b/infra/ai-gateway/README.md @@ -142,22 +142,25 @@ az deployment group create \ ## Foundry GitHub remote-tool connection When `foundryAgentsProjectName` is provided (as in the subscription-scoped -`../main.bicep` entry point), this module deploys +`../main.bicep` entry point), this module assigns `AI Gateway User` +(`caad7a21-134e-43f4-a550-c5ffc17e051c`) on AI Gateway to the Foundry project +and account managed identities and deploys `../foundry-agents/github-connection.bicep` into the agents resource group. The `aigw-github` project connection uses -`Microsoft.CognitiveServices/accounts/projects/connections@2025-04-01-preview`, -category `RemoteTool`, authentication `CustomKeys`, and target -`https:///default/mcp/github/mcp`. It is shared with the project -and has `metadata.type: custom_MCP`. - -The gateway's `2025-09-01-preview` key is read with -`runtimeApiKey.listSecrets().key` and passed only through the connection -module's `@secure()` `gatewayApiKey` parameter. ARM waits for key creation -before evaluating the nested deployment. No deployment output contains the -secret. The deployment identity needs key-listing permission in the gateway -resource group and connection-write permission in the agents resource group. -Stable names and incremental deployment keep repeat provisioning idempotent. +`Microsoft.CognitiveServices/accounts/projects/connections@2025-06-01`, +category `RemoteTool`, authentication `ProjectManagedIdentity` +(`audience: https://azure-api.net/aigateway`), and target +`https:///default/toolservers/github/mcp`. It is shared with the +project and has `metadata.type: custom_MCP`. + +If `useManagedIdentityForFoundryConnections` is set to `false`, the connection +falls back to `CustomKeys` using +`runtimeApiKey.listSecrets().?primaryKey ?? runtimeApiKey.listSecrets().?key` +(the live `2025-09-01-preview` `listSecrets` payload returns `primaryKey` and +`secondaryKey`) passed only through the connection module's `@secure()` +`gatewayApiKey` parameter. No deployment output contains the secret. Stable +names and incremental deployment keep repeat provisioning idempotent. ## AI Gateway monitoring diff --git a/infra/ai-gateway/main.bicep b/infra/ai-gateway/main.bicep index 67cad62..914973e 100644 --- a/infra/ai-gateway/main.bicep +++ b/infra/ai-gateway/main.bicep @@ -20,6 +20,11 @@ param modelAliasesConfig array = [] param foundryAgentsResourceGroupName string = resourceGroup().name param foundryAgentsAccountName string = '' param foundryAgentsProjectName string = '' +param foundryAgentsAccountPrincipalId string = '' +param foundryAgentsProjectPrincipalId string = '' +param principalId string = '' +param useManagedIdentityForFoundryConnections bool = true +param aiGatewayAudience string = 'https://azure-api.net/aigateway' @secure() param toolServerConfigs object = {} @@ -27,6 +32,7 @@ var aiGatewayApiVersion = '2025-09-01-preview' var appInsightsApiVersion = '2020-02-02' var logAnalyticsApiVersion = '2023-09-01' var telemetryWorkspaceName = 'default' +var aiGatewayUserRoleDefinitionId = 'caad7a21-134e-43f4-a550-c5ffc17e051c' var normalizedFoundryEndpoint = endsWith(foundryEndpoint, '/') ? foundryEndpoint : '${foundryEndpoint}/' #disable-next-line BCP081 resource aiGateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' = if (deployApimGatewayViaBicep) { @@ -193,16 +199,52 @@ resource runtimeApiKey 'Microsoft.ApiManagement/aigateways/apiKeys@2025-09-01-pr } } +resource aiGatewayProjectUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (deployApimGatewayViaBicep && !empty(foundryAgentsProjectName) && !empty(foundryAgentsProjectPrincipalId)) { + scope: aiGateway + name: guid(aiGateway.id, aiGatewayUserRoleDefinitionId, foundryAgentsProjectName) + properties: { + principalId: foundryAgentsProjectPrincipalId + principalType: 'ServicePrincipal' + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', aiGatewayUserRoleDefinitionId) + } +} + +resource aiGatewayAccountUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (deployApimGatewayViaBicep && !empty(foundryAgentsAccountName) && !empty(foundryAgentsAccountPrincipalId)) { + scope: aiGateway + name: guid(aiGateway.id, aiGatewayUserRoleDefinitionId, foundryAgentsAccountName) + properties: { + principalId: foundryAgentsAccountPrincipalId + principalType: 'ServicePrincipal' + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', aiGatewayUserRoleDefinitionId) + } +} + +resource aiGatewayDeveloperUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (deployApimGatewayViaBicep && !empty(principalId)) { + scope: aiGateway + name: guid(aiGateway.id, aiGatewayUserRoleDefinitionId, principalId) + properties: { + principalId: principalId + principalType: 'User' + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', aiGatewayUserRoleDefinitionId) + } +} + var runtimeHostname = deployApimGatewayViaBicep ? (aiGateway!.properties.?frontend.?defaultHostname ?? replace(aiGateway!.properties.?gatewayUrl ?? '', 'https://', '')) : '' module githubConnection '../foundry-agents/github-connection.bicep' = if (deployApimGatewayViaBicep && !empty(foundryAgentsProjectName)) { name: 'github-connection-${uniqueString(gatewayName, foundryAgentsProjectName)}' scope: resourceGroup(foundryAgentsResourceGroupName) + dependsOn: [ + aiGatewayProjectUserRoleAssignment + aiGatewayAccountUserRoleAssignment + ] params: { aiServicesName: foundryAgentsAccountName aiProjectName: foundryAgentsProjectName gatewayUrl: 'https://${runtimeHostname}' - gatewayApiKey: runtimeApiKey!.listSecrets().key + useManagedIdentity: useManagedIdentityForFoundryConnections + gatewayAudience: aiGatewayAudience + gatewayApiKey: useManagedIdentityForFoundryConnections ? '' : (runtimeApiKey!.listSecrets().?primaryKey ?? runtimeApiKey!.listSecrets().?key ?? '') } } diff --git a/infra/foundry-agents/github-connection.bicep b/infra/foundry-agents/github-connection.bicep index 39bcd15..98d36f2 100644 --- a/infra/foundry-agents/github-connection.bicep +++ b/infra/foundry-agents/github-connection.bicep @@ -3,8 +3,10 @@ targetScope = 'resourceGroup' param aiServicesName string param aiProjectName string param gatewayUrl string +param useManagedIdentity bool = true +param gatewayAudience string = 'https://azure-api.net/aigateway' @secure() -param gatewayApiKey string +param gatewayApiKey string = '' var normalizedGatewayUrl = endsWith(gatewayUrl, '/') ? take(gatewayUrl, length(gatewayUrl) - 1) : gatewayUrl @@ -17,13 +19,23 @@ resource aiProject 'Microsoft.CognitiveServices/accounts/projects@2025-04-01-pre name: aiProjectName } -resource githubConnection 'Microsoft.CognitiveServices/accounts/projects/connections@2025-04-01-preview' = { +resource githubConnection 'Microsoft.CognitiveServices/accounts/projects/connections@2025-06-01' = { parent: aiProject name: 'aigw-github' - properties: { + #disable-next-line BCP036 + properties: useManagedIdentity ? { + category: 'RemoteTool' + authType: 'ProjectManagedIdentity' + audience: gatewayAudience + target: '${normalizedGatewayUrl}/default/toolservers/github/mcp' + isSharedToAll: true + metadata: { + type: 'custom_MCP' + } + } : { category: 'RemoteTool' authType: 'CustomKeys' - target: '${normalizedGatewayUrl}/default/mcp/github/mcp' + target: '${normalizedGatewayUrl}/default/toolservers/github/mcp' credentials: { keys: { 'Api-Key': gatewayApiKey diff --git a/infra/foundry-agents/main.bicep b/infra/foundry-agents/main.bicep index c587bb9..b9e4151 100644 --- a/infra/foundry-agents/main.bicep +++ b/infra/foundry-agents/main.bicep @@ -108,14 +108,13 @@ resource appInsightsConnection 'Microsoft.CognitiveServices/accounts/connections name: appInsights.name properties: { category: 'AppInsights' - authType: 'ApiKey' + #disable-next-line BCP036 + authType: 'ProjectManagedIdentity' isSharedToAll: false target: appInsights.id - credentials: { - key: appInsights.properties.ConnectionString - } metadata: { ApiType: 'Azure' + ApplicationInsightsConnectionString: appInsights.properties.ConnectionString ResourceId: appInsights.id displayName: appInsights.name } @@ -175,6 +174,27 @@ var cognitiveServicesOpenAIUserRoleDefinitionId = '5e0bd9bd-7b93-4f28-af87-19fc3 var cognitiveServicesUserRoleDefinitionId = 'a97b65f3-24c7-4388-baec-2e87135dc908' var storageBlobDataContributorRoleDefinitionId = 'ba92f5b4-2d11-453d-a403-e96b0029c9fe' var acrPullRoleDefinitionId = '7f951dda-4ed3-4680-a7ca-43fe172d538d' +var monitoringMetricsPublisherRoleDefinitionId = '3913510d-42f4-4e42-8a64-420c390055eb' + +resource appInsightsMetricsPublisherAssignmentAccount 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: appInsights + name: guid(appInsights.id, monitoringMetricsPublisherRoleDefinitionId, aiServices.id) + properties: { + principalId: aiServices.identity.principalId + principalType: 'ServicePrincipal' + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', monitoringMetricsPublisherRoleDefinitionId) + } +} + +resource appInsightsMetricsPublisherAssignmentProject 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: appInsights + name: guid(appInsights.id, monitoringMetricsPublisherRoleDefinitionId, aiProject.id) + properties: { + principalId: aiProject.identity.principalId + principalType: 'ServicePrincipal' + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', monitoringMetricsPublisherRoleDefinitionId) + } +} resource cognitiveServicesContributorAssignmentProject 'Microsoft.Authorization/roleAssignments@2022-04-01' = { scope: aiServices @@ -268,6 +288,7 @@ resource storageBlobDataContributorAssignmentUser 'Microsoft.Authorization/roleA output aiServicesName string = aiServices.name output aiServicesId string = aiServices.id +output aiServicesPrincipalId string = aiServices.identity.principalId output aiServicesEndpoint string = aiServices.properties.endpoint output aiProjectName string = aiProject.name output aiProjectResourceId string = aiProject.id diff --git a/infra/main.bicep b/infra/main.bicep index 94a0f9a..7df4dac 100644 --- a/infra/main.bicep +++ b/infra/main.bicep @@ -87,6 +87,16 @@ param aiGatewayName string = '' @description('Default GitHub repository for the daily digest automation.') param githubRepository string = 'microsoft/agent-framework' +@secure() +@description('Optional GitHub MCP Authorization header value (for example, Bearer ) for declarative Bicep toolServer provisioning.') +param githubMcpAuthorization string = '' + +@description('GitHub MCP server URL.') +param githubMcpServerUrl string = 'https://api.githubcopilot.com/mcp/' + +@description('Comma-separated read-only GitHub MCP tools exposed by the gateway.') +param githubMcpTools string = 'list_pull_requests,list_issues,actions_list' + @description('Backing Foundry model name for the efficient mini deployment.') param miniModelName string = 'gpt-5.4-mini' @@ -259,6 +269,9 @@ module aiGateway './ai-gateway/main.bicep' = { foundryAgentsResourceGroupName: foundryAgentsRg.name foundryAgentsAccountName: foundryAgents.outputs.aiServicesName foundryAgentsProjectName: foundryAgents.outputs.aiProjectName + foundryAgentsAccountPrincipalId: foundryAgents.outputs.aiServicesPrincipalId + foundryAgentsProjectPrincipalId: foundryAgents.outputs.aiProjectPrincipalId + principalId: principalId tags: tags enableMonitoring: enableMonitoring deployApimGatewayViaBicep: true @@ -307,6 +320,47 @@ module aiGateway './ai-gateway/main.bicep' = { ] } ] + toolServerConfigs: empty(githubMcpAuthorization) ? {} : { + github: { + displayName: 'GitHub repository digest' + description: 'Read-only GitHub tools for repository digests.' + type: 'mcp' + failureMode: 'failClosed' + policies: [ + { + type: 'contentSafety' + hateSeverity: 'Medium' + selfHarmSeverity: 'Medium' + sexualSeverity: 'Medium' + violenceSeverity: 'Medium' + } + ] + endpoints: [ + { + namespace: 'github' + kind: 'mcp' + mcp: { + url: githubMcpServerUrl + transport: 'streamableHttp' + } + credentials: { + type: 'header' + headers: { + Authorization: [ + githubMcpAuthorization + ] + 'X-MCP-Readonly': [ + 'true' + ] + 'X-MCP-Tools': [ + githubMcpTools + ] + } + } + } + ] + } + } } } diff --git a/repo_digest_agent.py b/repo_digest_agent.py index 22ebd1e..76f09eb 100644 --- a/repo_digest_agent.py +++ b/repo_digest_agent.py @@ -2,10 +2,12 @@ import os +from collections.abc import Awaitable, Callable + from agent_framework import Agent from agent_framework.openai import OpenAIChatClient from agent_framework_foundry_hosting import FoundryToolbox -from azure.identity import DefaultAzureCredential +from azure.identity import DefaultAzureCredential, get_bearer_token_provider from openai import Omit from github_mcp_middleware import compact_github_results @@ -14,6 +16,7 @@ DEFAULT_GATEWAY_MODEL = "gpt-latest" DEFAULT_MAX_OUTPUT_TOKENS = 2_048 OPENAI_NO_BEARER_AUTH = "workload-identity-auth" +AI_GATEWAY_TOKEN_SCOPE = "https://azure-api.net/aigateway/.default" INSTRUCTIONS = f""" You create concise daily GitHub repository digests from live repository data. @@ -46,51 +49,71 @@ """ -def _gateway_settings() -> tuple[str, str]: +def _azure_credential() -> DefaultAzureCredential: + return DefaultAzureCredential( + exclude_managed_identity_credential=not bool( + os.environ.get("FOUNDRY_HOSTING_ENVIRONMENT") + ) + ) + + +def _gateway_settings() -> tuple[str, str | None]: gateway_endpoint = os.environ.get("AZURE_AI_GATEWAY_ENDPOINT") if not gateway_endpoint: raise RuntimeError("Set AZURE_AI_GATEWAY_ENDPOINT to the AI Gateway endpoint.") - gateway_key = os.environ.get("AZURE_AI_GATEWAY_API_KEY") - if not gateway_key: - raise RuntimeError("Set AZURE_AI_GATEWAY_API_KEY to an AI Gateway key.") - + gateway_key = os.environ.get("AZURE_AI_GATEWAY_API_KEY") or None return gateway_endpoint.rstrip("/"), gateway_key +def _gateway_bearer_token_provider() -> Callable[[], Awaitable[str]]: + token_provider = get_bearer_token_provider(_azure_credential(), AI_GATEWAY_TOKEN_SCOPE) + + async def _get_token() -> str: + return token_provider() + + return _get_token + + def _gateway_client() -> OpenAIChatClient: gateway_endpoint, gateway_key = _gateway_settings() + base_url = gateway_endpoint + "/default/models/openai/v1/" + model = os.environ.get("AZURE_AI_GATEWAY_MODEL", DEFAULT_GATEWAY_MODEL) + if gateway_key: + return OpenAIChatClient( + model=model, + base_url=base_url, + api_key=OPENAI_NO_BEARER_AUTH, + default_headers={"Api-Key": gateway_key}, + ) return OpenAIChatClient( - model=os.environ.get("AZURE_AI_GATEWAY_MODEL", DEFAULT_GATEWAY_MODEL), - base_url=gateway_endpoint + "/default/models/openai/v1/", - # This OpenAI transport placeholder suppresses its Bearer header. - api_key=OPENAI_NO_BEARER_AUTH, - default_headers={"Api-Key": gateway_key}, + model=model, + base_url=base_url, + api_key=_gateway_bearer_token_provider(), ) def _github_toolbox() -> FoundryToolbox: return FoundryToolbox( - DefaultAzureCredential( - exclude_managed_identity_credential=not bool( - os.environ.get("FOUNDRY_HOSTING_ENVIRONMENT") - ) - ), + _azure_credential(), timeout=60, ) def build_agent() -> Agent: + client = _gateway_client() + default_options: dict[str, object] = { + "store": False, + "max_tokens": DEFAULT_MAX_OUTPUT_TOKENS, + } + if getattr(getattr(client, "client", None), "_api_key_provider", None) is None: + default_options["extra_headers"] = {"Authorization": Omit()} return Agent( - client=_gateway_client(), + client=client, name="daily-repo-digest", description="Creates daily GitHub repository digests through AI Gateway.", instructions=INSTRUCTIONS, tools=_github_toolbox(), - default_options={ - "store": False, - "max_tokens": DEFAULT_MAX_OUTPUT_TOKENS, - "extra_headers": {"Authorization": Omit()}, - }, + default_options=default_options, middleware=[compact_github_results], ) diff --git a/tests/test-ai-gateway-model-registration.sh b/tests/test-ai-gateway-model-registration.sh index 743cfe2..8c2132e 100755 --- a/tests/test-ai-gateway-model-registration.sh +++ b/tests/test-ai-gateway-model-registration.sh @@ -208,26 +208,23 @@ if ! jq -e ' | select(.type == "Microsoft.Resources/deployments" and .properties.parameters.gatewayApiKey != null) | . as $module | .properties.template as $template - | .properties.parameters.gatewayApiKey.value as $key + | (.properties.parameters.gatewayApiKey | tostring) as $key | ($module.resourceGroup == "[parameters('\''foundryAgentsResourceGroupName'\'')]") and ($module.properties.mode == "Incremental") and ($module.condition | contains("deployApimGatewayViaBicep") and contains("foundryAgentsProjectName")) and ($template.parameters.gatewayApiKey.type == "securestring") - and ($key == "[listSecrets(resourceId('\''Microsoft.ApiManagement/aigateways/apiKeys'\'', parameters('\''gatewayName'\''), '\''default'\''), '\''2025-09-01-preview'\'').key]") + and ($key | contains("listSecrets(resourceId('\''Microsoft.ApiManagement/aigateways/apiKeys'\'', parameters('\''gatewayName'\''), '\''default'\''), '\''2025-09-01-preview'\'')") and contains("primaryKey")) and ($module.dependsOn | any(contains("Microsoft.ApiManagement/aigateways/apiKeys"))) + and ($module.dependsOn | any(contains("aiGatewayUserRoleDefinitionId"))) and ($template.resources | length == 1) + and ($template.parameters.gatewayAudience.defaultValue == "https://azure-api.net/aigateway") and ($template.resources[0] | .type == "Microsoft.CognitiveServices/accounts/projects/connections" - and .apiVersion == "2025-04-01-preview" + and .apiVersion == "2025-06-01" and (.name | contains("aigw-github")) - and .properties.category == "RemoteTool" - and .properties.authType == "CustomKeys" - and .properties.target == "[format('\''{0}/default/mcp/github/mcp'\'', variables('\''normalizedGatewayUrl'\''))]" - and .properties.credentials.keys["Api-Key"] == "[parameters('\''gatewayApiKey'\'')]" - and .properties.isSharedToAll == true - and .properties.metadata.type == "custom_MCP") + and (.properties | tostring | (contains("ProjectManagedIdentity") and contains("{0}/default/toolservers/github/mcp") and contains("custom_MCP")))) ' "$compiled_template" >/dev/null; then - echo "GitHub connection must use a secure key parameter, the MCP route, and depend on the generated key." >&2 + echo "GitHub connection must default to ProjectManagedIdentity on /default/toolservers/github/mcp with AI Gateway User RBAC and primaryKey fallback." >&2 exit 1 fi @@ -237,9 +234,20 @@ if ! jq -e ' | (.properties.parameters.foundryAgentsResourceGroupName.value == "[variables('\''effectiveFoundryAgentsResourceGroupName'\'')]") and (.properties.parameters.foundryAgentsAccountName.value | contains("outputs.aiServicesName.value")) and (.properties.parameters.foundryAgentsProjectName.value | contains("outputs.aiProjectName.value")) + and (.properties.parameters.foundryAgentsAccountPrincipalId.value | contains("outputs.aiServicesPrincipalId.value")) + and (.properties.parameters.foundryAgentsProjectPrincipalId.value | contains("outputs.aiProjectPrincipalId.value")) and (.dependsOn | any(contains("foundry-agents-"))) ' "$compiled_root_template" >/dev/null; then - echo "Gateway connection provisioning must wait for the Foundry agents project in its own resource group." >&2 + echo "Gateway connection provisioning must wait for the Foundry agents project and pass its managed identity principal IDs." >&2 + exit 1 +fi + +if ! jq -e ' + [.. | objects | select(.type? == "Microsoft.CognitiveServices/accounts/connections" and .properties.category? == "AppInsights") + | select(.properties.authType == "ProjectManagedIdentity" and (.properties.metadata.ApplicationInsightsConnectionString != null))] + | length == 1 +' "$compiled_root_template" >/dev/null; then + echo "Foundry AppInsights connection must use ProjectManagedIdentity with ApplicationInsightsConnectionString metadata." >&2 exit 1 fi diff --git a/tests/test_agent_runtime.py b/tests/test_agent_runtime.py index a9b528e..5c8e2e2 100644 --- a/tests/test_agent_runtime.py +++ b/tests/test_agent_runtime.py @@ -308,6 +308,107 @@ def build_test_agent() -> Agent: finally: await model_http_client.aclose() + async def test_managed_identity_bearer_auth_when_gateway_api_key_is_unset(self) -> None: + model_requests: list[tuple[dict[str, object], httpx.Headers]] = [] + message = { + "id": "msg_mi_1", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [{"type": "output_text", "text": "MI_OK", "annotations": []}], + } + completed_response = { + "id": "resp_mi_1", + "object": "response", + "created_at": 0, + "model": "gpt-latest", + "status": "completed", + "output": [message], + "parallel_tool_calls": True, + "tool_choice": "auto", + "tools": [], + } + events = [ + { + "type": "response.created", + "sequence_number": 0, + "response": {**completed_response, "status": "in_progress", "output": []}, + }, + { + "type": "response.completed", + "sequence_number": 1, + "response": completed_response, + }, + ] + stream_body = "".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n" + + async def model_handler(request: httpx.Request) -> httpx.Response: + model_requests.append((json.loads(request.content), request.headers)) + return httpx.Response( + 200, + text=stream_body, + headers={"content-type": "text/event-stream"}, + ) + + model_http_client = httpx.AsyncClient(transport=httpx.MockTransport(model_handler)) + + def create_test_chat_client(**kwargs: object) -> OpenAIChatClient: + openai_client = AsyncOpenAI( + api_key=kwargs["api_key"], + base_url=kwargs["base_url"], + default_headers=kwargs.get("default_headers"), + http_client=model_http_client, + max_retries=0, + ) + return OpenAIChatClient( + model=kwargs["model"], + async_client=openai_client, + ) + + try: + with ( + patch.dict( + os.environ, + { + "AZURE_AI_GATEWAY_ENDPOINT": "https://mock.invalid/", + "AZURE_AI_GATEWAY_MODEL": "gpt-latest", + }, + clear=False, + ), + patch.object( + repo_digest_agent, + "get_bearer_token_provider", + return_value=lambda: "entra-mi-token", + ) as token_provider_mock, + patch.object(repo_digest_agent, "OpenAIChatClient", side_effect=create_test_chat_client), + patch.object(repo_digest_agent, "_github_toolbox", return_value=None), + ): + os.environ.pop("AZURE_AI_GATEWAY_API_KEY", None) + server = ResponsesHostServer( + agent=repo_digest_agent.build_agent, + history_source="agent_server", + response_store=InMemoryResponseProvider(), + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=server), + base_url="http://test", + ) as app: + resp = await app.post( + "/responses", + json={"input": "Verify MI auth.", "store": False, "stream": False}, + ) + + self.assertEqual(resp.status_code, 200, resp.text) + self.assertEqual(resp.json()["status"], "completed") + token_provider_mock.assert_called_once() + self.assertEqual(token_provider_mock.call_args.args[1], "https://azure-api.net/aigateway/.default") + self.assertEqual(len(model_requests), 1) + _, headers = model_requests[0] + self.assertEqual(headers.get("authorization"), "Bearer entra-mi-token") + self.assertIsNone(headers.get("api-key")) + finally: + await model_http_client.aclose() + if __name__ == "__main__": unittest.main()