Skip to content

Resolve cross-compute-environment endpoint references for Foundry hosted agents - #17756

Merged
David Fowler (davidfowl) merged 8 commits into
release/13.4from
davidfowl/foundry-reference-fix
Jun 1, 2026
Merged

David Fowler (davidfowl) merged 8 commits into
release/13.4from
davidfowl/foundry-reference-fix

Conversation

@davidfowl

@davidfowl David Fowler (davidfowl) commented May 31, 2026 •

Copy link
Copy Markdown
Collaborator

Description

This PR fixes two related gaps that surface when a Foundry hosted agent is referenced from a resource deployed to a different compute environment (#17749). Each is independently useful, but together they make the reported scenario deploy and run end-to-end with no manual steps.

1. Cross-compute-environment endpoint resolution

aspire deploy failed when a resource referenced (via WithReference()) an endpoint whose owning resource was deployed to a different compute environment. Each publisher resolved endpoint references against its local endpoint map, which doesn't contain a resource owned by another environment, so resolution threw a "context not found" error and deployment broke.

This isn't specific to one resource type or one environment. The bug affected cross-environment endpoint references in general — across the Azure Container Apps (ACA), Azure App Service, and Kubernetes (AKS) publishers — and the referenced resource can be any resource with endpoints (a Foundry hosted agent referenced from a different environment was just the originally reported repro from #17749).

This change teaches the publishers to detect when a referenced endpoint's owning resource lives in a different compute environment and to delegate endpoint resolution to that owning environment instead of failing against the local map. Same-environment references are unaffected and continue to resolve locally, so existing generated artifacts (bicep/manifests) stay byte-for-byte unchanged.

The fix is entirely publisher-side: it runs at publish/deploy time against the already-resolved application model, so it applies regardless of how the cross-environment reference was introduced into the model. Resolution is implemented in C#, but because it operates on the resolved model it applies equally to C# and TypeScript AppHosts — a TypeScript AppHost that wires the same cross-environment reference benefits from the fix without any TypeScript-side changes.

The shared logic lives in a new internal helper, ComputeEnvironmentEndpointResolver, which the ACA, App Service, and Kubernetes publishers now call. The Foundry hosted agent resource and the previously bespoke Azure Front Door cross-environment handling were refactored onto the same helper so there is a single resolution path.

2. RBAC auto-wiring for hosted-agent consumers

Even after endpoint resolution succeeded, the deployed consumer could not actually call the hosted agent: invoking a Foundry hosted agent requires the caller to authenticate with a managed identity that holds the Azure AI User role on the owning Foundry account. Previously the app model emitted neither the identity nor the role assignment for a consumer that only referenced the agent's node app, so the developer had to run two manual az role assignment create / identity steps after every deploy.

The blocker is structural: AzureResourcePreparer discovers role targets by walking a resource's direct dependencies and acting on the ones that are themselves IAzureResource. A consumer that references a hosted agent references the agent's node app (a plain compute resource), and the owning Foundry account is only a transitive dependency behind it — so the preparer's walk never reaches the account and no identity/role is wired.

This PR closes that gap with a small, sanctioned hook rather than bespoke per-resource logic:

  • A new public experimental annotation, ReferenceRoleAssignmentAnnotation ([Experimental("ASPIREAZURE003")]), expresses "this resource implies these roles on that Azure resource". It is the redirect that the dependency walk cannot derive on its own.
  • AzureResourcePreparer now honors that annotation as a first-class input alongside the existing RoleAssignmentAnnotation path (RunMode → global role assignments; PublishMode → an explicit role-assignment annotation on the consumer), and de-duplicates roles per target so generated bicep contains no duplicate role-assignment identifiers.
  • The Foundry hosted-agent integration stamps exactly one least-privilege role — Azure AI User — on the consumer's reference to the owning account. It deliberately does not fold in the account's default role set: defaults remain owned by the preparer's normal reference walk, and a consumer that declares its own WithRoleAssignments(...) still suppresses them.

The net effect: referencing a hosted agent now auto-provisions the consumer's managed identity and grants Azure AI User on the Foundry account, eliminating the two manual post-deploy steps.

User-facing usage

A service deployed to one compute environment (here, Azure Kubernetes) can now reference a hosted agent hosted in another (the Foundry project environment) and both deploy and invoke it successfully, with the required identity and role assignment generated automatically. This works for both C# and TypeScript AppHosts.

C# AppHost:

var aks = builder.AddAzureKubernetesEnvironment("aks");

var project = builder.AddFoundry("foundry")
                     .AddProject("project");

// The agent app is deployed to the Foundry project compute environment.
var agent = builder.AddProject<Projects.Agent>("agent")
                   .WithHttpEndpoint()
                   .WithExternalHttpEndpoints();
agent.AsHostedAgent(project);

// The web app is deployed to Azure Kubernetes and references the cross-environment agent.
// Endpoint resolution AND the managed identity + Azure AI User role on the Foundry
// account are now wired automatically — no manual `az role assignment create`.
builder.AddProject<Projects.Web>("web")
       .WithHttpEndpoint()
       .WithExternalHttpEndpoints()
       .WithComputeEnvironment(aks)
       .WithReference(agent);

TypeScript AppHost:

import { createBuilder } from './.aspire/modules/aspire.mjs';

const builder = await createBuilder();

const aks = await builder.addAzureKubernetesEnvironment("aks");

const foundry = await builder.addFoundry("foundry");
const project = await foundry.addProject("project");

// The agent app is deployed to the Foundry project compute environment.
const agent = await builder
    .addProject("agent", "../Agent/Agent.csproj")
    .withHttpEndpoint()
    .withExternalHttpEndpoints();
await agent.asHostedAgent(project);

// The web app is deployed to Azure Kubernetes and references the cross-environment agent.
await builder
    .addProject("web", "../Web/Web.csproj")
    .withHttpEndpoint()
    .withExternalHttpEndpoints()
    .withComputeEnvironment(aks)
    .withReference(agent);

await builder.build().run();

Fixes #17749

Validation

  • Added ComputeEnvironmentEndpointResolverTests (7 tests) covering each observable branch of the helper: cross-environment delegation (both the EndpointReference and EndpointReferenceExpression overloads), same-environment via deployment target, binding-backstop, no-environment, bound multi-target (no throw), and unbound multi-target (throws).
  • Added publisher regression tests for ACA, App Service, and Kubernetes that reference a resource across compute environments, with Verify snapshots for generated bicep/JSON.
  • Added AzureResourcePreparerTests coverage for the RBAC hook: that ReferenceRoleAssignmentAnnotation produces the implied identity + role assignment in both Run and Publish modes, that roles are de-duplicated per target, and that the hosted-agent consumer is granted only Azure AI User (account defaults are not silently folded in, and explicit WithRoleAssignments suppression is honored).
  • Added Foundry HostedAgentExtensionTests asserting the consumer stamps the single least-privilege Azure AI User role.
  • All affected publisher projects build; existing same-environment publisher suites continue to pass (cross-env Foundry snapshots were regenerated to include the auto-wired identity/role).
  • Validated end-to-end against a live Azure deploy: a clean deployment to Azure Container Apps (agentweb → apiservice → Foundry hosted agent) returns real agent responses with no manual role-assignment steps — the consumer's managed identity and Azure AI User grant are emitted by the app model.

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • ReferenceRoleAssignmentAnnotation in Aspire.Hosting.Azure, gated behind [Experimental("ASPIREAZURE003")].
      • If yes, did you have an API Review for it?
        • Yes
        • No — experimental; API review to follow before the diagnostic is stabilized.
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • The RBAC auto-wiring grants the consumer's managed identity the Azure AI User role on the referenced Foundry account. This is a deliberate least-privilege grant (not Contributor/Owner), is only emitted when a resource explicitly references a hosted agent, and is suppressible via an explicit WithRoleAssignments(...). No other roles or defaults are folded in.
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No

David Fowler (davidfowl) and others added 5 commits May 31, 2026 08:37
…ed agents

Fixes #17749. When a resource deployed to App Service, Azure Container
Apps, or Kubernetes used WithReference() to reference a Foundry hosted
agent, publishing failed because the publisher resolved the endpoint
against its own local endpoint map, which does not contain the agent
(deployed to the Foundry project compute environment).

Introduce a shared ComputeEnvironmentEndpointResolver that, when an
endpoint's owning resource is deployed to a different compute environment
than the current publisher, delegates resolution to that owning
environment's GetEndpointPropertyExpression. The three compute-environment
publishers now call it in both the EndpointReference and
EndpointReferenceExpression branches. Azure Front Door and the Foundry
hosted-agent resolver are refactored onto the same shared lookup.

AzureCognitiveServicesProjectResource gets a GetEndpointPropertyExpression
override because the agent address is already a full https URL; the
default scheme://host composition would produce a malformed double-scheme
value.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…isleading comment

Add direct unit tests covering each branch of TryGetCrossEnvironmentEndpointExpression:
cross-environment delegation, same-environment deployment target, WithComputeEnvironment
binding backstop, no-compute-environment, bound multi-target (no throw), and unbound
multi-target (throws). Correct the comment on the fast-path loop which incorrectly claimed
it never throws on multi-target resources.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The first foreach loop using GetDeploymentTargetAnnotation(current) was redundant with
TryGetEffectiveComputeEnvironment + the ReferenceEquals backstop for all well-formed inputs,
and did not provide multi-target throw-safety. Remove it and keep the simpler resolve-then-
compare flow. All six branch tests continue to pass.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Replace the params IComputeEnvironmentResource?[] with an explicit
IReadOnlyList parameter placed before the out, so the out parameter
comes last per convention. Kubernetes still passes two current
environments (its environment plus OwningComputeEnvironment) via a
collection expression; ACA and AppService pass a single-element list.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Add an overload taking EndpointReference that uses ep.Property(EndpointProperty.Url)
internally, so the three EndpointReference call sites (ACA, AppService, Kubernetes)
pass the endpoint directly instead of repeating the .Property(Url) projection.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 17756

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 17756"

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds shared cross-compute-environment endpoint resolution so ACA, App Service, and Kubernetes publishers can resolve references to Foundry hosted agents owned by another compute environment.

Changes:

  • Adds ComputeEnvironmentEndpointResolver and wires it into ACA, App Service, Kubernetes, Foundry, and Front Door flows.
  • Adds Foundry project endpoint-property handling for hosted agent URLs.
  • Adds unit and publisher regression tests with snapshots for ACA, App Service, and AKS scenarios.
Show a summary per file
File Description
src/Shared/ComputeEnvironmentEndpointResolver.cs Adds shared helper for delegated endpoint resolution.
src/Aspire.Hosting.Azure.AppContainers/BaseContainerAppContext.cs Uses helper before local ACA endpoint lookup.
src/Aspire.Hosting.Azure.AppContainers/Aspire.Hosting.Azure.AppContainers.csproj Links shared resolver.
src/Aspire.Hosting.Azure.AppService/AzureAppServiceWebsiteContext.cs Uses helper before local App Service endpoint lookup.
src/Aspire.Hosting.Azure.AppService/Aspire.Hosting.Azure.AppService.csproj Links shared resolver.
src/Aspire.Hosting.Kubernetes/KubernetesResource.cs Uses helper before local Kubernetes endpoint lookup.
src/Aspire.Hosting.Kubernetes/Aspire.Hosting.Kubernetes.csproj Links shared resolver.
src/Aspire.Hosting.Foundry/Project/ProjectResource.cs Adds Foundry endpoint property override.
src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs Reuses shared effective-compute-environment lookup.
src/Aspire.Hosting.Foundry/Aspire.Hosting.Foundry.csproj Links shared resolver.
src/Aspire.Hosting.Azure.FrontDoor/AzureFrontDoorExtensions.cs Reuses shared effective-compute-environment lookup.
src/Aspire.Hosting.Azure.FrontDoor/Aspire.Hosting.Azure.FrontDoor.csproj Links shared resolver.
tests/Aspire.Hosting.Tests/ComputeEnvironmentEndpointResolverTests.cs Adds unit coverage for helper behavior.
tests/Aspire.Hosting.Tests/Aspire.Hosting.Tests.csproj Links shared resolver into tests.
tests/Aspire.Hosting.Azure.Tests/AzureContainerAppsTests.cs Adds ACA regression test.
tests/Aspire.Hosting.Azure.Tests/AzureAppServiceTests.cs Adds App Service regression test.
tests/Aspire.Hosting.Azure.Kubernetes.Tests/AzureKubernetesFoundryReferenceTests.cs Adds AKS/Kubernetes regression test.
tests/Aspire.Hosting.Azure.Tests/Snapshots/AzureContainerAppsTests.EndpointReferenceToFoundryHostedAgentIsResolvedAcrossComputeEnvironments.verified.json Adds ACA snapshot manifest.
tests/Aspire.Hosting.Azure.Tests/Snapshots/AzureContainerAppsTests.EndpointReferenceToFoundryHostedAgentIsResolvedAcrossComputeEnvironments.verified.bicep Adds ACA generated Bicep snapshot.
tests/Aspire.Hosting.Azure.Tests/Snapshots/AzureAppServiceTests.EndpointReferenceToFoundryHostedAgentIsResolvedAcrossComputeEnvironments.verified.json Adds App Service snapshot manifest.
tests/Aspire.Hosting.Azure.Tests/Snapshots/AzureAppServiceTests.EndpointReferenceToFoundryHostedAgentIsResolvedAcrossComputeEnvironments.verified.bicep Adds App Service generated Bicep snapshot.

Copilot's findings

  • Files reviewed: 21/21 changed files
  • Comments generated: 1

@davidfowl

Copy link
Copy Markdown
Collaborator Author

PR Testing Report — End-to-End Azure Deploy

PR Information

CLI Version Verification

  • Expected (PR head): be10e706d
  • Installed PR CLI: 13.4.0-pr.17756.gbe10e706
  • Status: ✅ Verified (suffix pr.17756.gbe10e706 matches PR head)

Scenario

Real end-to-end Azure deploy of a TypeScript AppHost exercising the exact bug class the PR fixes: an Azure App Service web frontend (web, Vite) that holds a cross-compute-environment withReference() to a Foundry hosted agent (agent-ha) running in a different compute environment.

  • Subject app: TS AppHost (apphost.mts) — foundry/project/chat; app-svc App Service env; node agent-ha registered as a Foundry hosted agent; Vite web app withComputeEnvironment(appSvc) + withReference(hostedAgent) + publishAsStaticWebsite({ apiTarget: hostedAgent }).
  • Target: Azure subscription "davifowl dev subscription", resource group rg-aspire-foundry01 (swedencentral).
  • Command: aspire deploy (full end-to-end, not just publish), PR build pinned via aspire.config.json (channel: pr-17756, all package versions 13.4.0-pr.17756.gbe10e706).

Result: ✅ Fix VERIFIED (cross-env resolution works end-to-end)

Before this PR, the cross-environment reference threw the "compute environment context not found" error during deploy and the pipeline never reached provisioning (#17749).

With the PR build:

  • ✅ The cross-environment withReference(agent-ha) resolved successfully — no more "context not found".
  • ✅ The model built and the full 28-step deploy pipeline generated (incl. compute-endpoints-project, provision-web-website).
  • ✅ 27 / 29 steps succeeded in ~1m12s. Images built + pushed to ACR; Foundry, identities, App Service plan all provisioned.
  • ✅ The cross-env reference materialized into a concrete service-discovery app setting services__agent-ha__http__0 that was actually submitted to Azure App Service — direct proof the resolver produced a real value across environments.

Downstream blocker (separate from this PR's fix)

The deploy did not fully complete. The final provision-web-website step failed because Azure App Service rejects the app-setting name services__agent-ha__http__0:

Error code = BadRequest
"AppSetting with name 'services__agent-ha__http__0' is not allowed."
ExtendedCode: 04072

Root cause: the app-setting key inherits the hyphen from the referenced resource name agent-ha. Azure App Service strips - from app-setting / env-var names, so names containing - are disallowed.

This is a pre-existing App Service limitation, independent of the cross-env resolution fix — any reference (same-env or cross-env) to a hyphenated resource name on App Service hits it. The repo already has a guard for it: ValidateEnvironmentVariableNames in AzureAppServiceEnvironmentResource.cs is meant to fail early with a friendly message ("use a dash-free connection name" / call SkipEnvironmentVariableNameChecks()).

Gap worth a follow-up

That early validation did not catch the cross-environment-generated services__agent-ha__http__0 key — so the cross-env path bypasses the existing dash-name guard and lets an un-deployable setting reach Azure, surfacing as a raw BadRequest instead of the actionable Aspire validation error. Recommend a follow-up to extend ValidateEnvironmentVariableNames (or the cross-env app-setting emission) to cover cross-environment service-discovery keys.

Workaround for a fully green run

Rename the hosted-agent resource to be dash-free (e.g. agent-ha → agentha). The cross-env reference then emits services__agentha__http__0, which App Service accepts.

Summary

Aspect Status Notes
CLI version matches PR head ✅ 13.4.0-pr.17756.gbe10e706
Cross-env reference resolves (the PR fix) ✅ Old "context not found" gone
Deploy pipeline executes ✅ 27/29 steps; reference submitted to Azure
Full deploy completes ❌ Blocked by App Service - app-setting rule (services__agent-ha__http__0, ExtendedCode 04072)
Early dash-name validation covers cross-env keys ❌ Pre-existing guard bypassed — suggested follow-up

Overall

✅ PR #17756 VERIFIED for its stated scope — cross-compute-environment endpoint references now resolve correctly during aspire deploy and produce a concrete value that reaches Azure. The remaining failure is a separate, pre-existing App Service hyphen-naming limitation (with a known workaround), plus a suggested follow-up to make the existing dash-name validation cover cross-environment service-discovery keys.

Hosted-agent deployment creates the Foundry agent version using the
wrapper AzureHostedAgentResource.Name (e.g. "agent-ha" for a target
named "agent"). The published cross-environment endpoint path was built
from the bare resource name, producing /agents/agent which does not match
the deployed /agents/agent-ha. Resolve the hosted-agent deployment target
and use its name when present, falling back to the resource name for
non-hosted agents.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@davidfowl

Copy link
Copy Markdown
Collaborator Author

/deployment-tests

@davidfowl

Copy link
Copy Markdown
Collaborator Author

/deployment-test

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Deployment tests starting on PR #17756...

This will deploy to real Azure infrastructure. Results will be posted here when complete.

View workflow run

@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:28 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot had a problem deploying to deployment-testing May 31, 2026 21:47 Failure
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions
github-actions Bot temporarily deployed to deployment-testing May 31, 2026 21:47 Inactive
@github-actions

Copy link
Copy Markdown
Contributor

❌ Deployment E2E Tests failed — 36 passed, 4 failed, 0 cancelled

View test results and recordings

View workflow run

Test Result Recording
Deployment.EndToEnd-AzureStorageDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureKeyVaultDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureLogAnalyticsDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AcaCompactNamingDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureServiceBusDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-FrontDoorDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-TypeScriptAzureContainerAppJobDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetSqlServerInfraDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetKeyVaultConnectivityDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-NspStorageKeyVaultDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-TypeScriptVnetSqlServerInfraDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-KubernetesGatewayTlsDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureContainerRegistryDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-TypeScriptJavaScriptHostingDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-KubernetesHelmChartDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetSqlServerConnectivityDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksWithHelmChartDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetKeyVaultInfraDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AcaStarterDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AcaDeploymentErrorOutputTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureEventHubsDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-TypeScriptExpressDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AuthenticationTests ✅ Passed
Deployment.EndToEnd-AcaCustomRegistryDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AcaManagedRedisDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetStorageBlobInfraDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AzureAppConfigDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksAzureKubernetesEnvironmentGatewayDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-VnetStorageBlobConnectivityDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksMultipleNodePoolsDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksAzureKubernetesEnvironmentCertManagerDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksBlazorRedisDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AppServiceReactDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksStarterDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AcaExistingRegistryDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksStarterWithRedisHelmDeploymentTests ✅ Passed ▶️ View Recording
Deployment.EndToEnd-AksVnetWithAzureResourcesDeploymentTests ❌ Failed ▶️ View Recording
Deployment.EndToEnd-AksVnetInfraDeploymentTests ❌ Failed ▶️ View Recording
Deployment.EndToEnd-AksAzureKubernetesEnvironmentCertManagerTypeScriptDeploymentTests ❌ Failed ▶️ View Recording
Deployment.EndToEnd-AksWithAzureResourcesDeploymentTests ❌ Failed ▶️ View Recording

David Fowler (davidfowl) and others added 2 commits May 31, 2026 17:01
When a compute resource references a Foundry hosted agent's node app via
WithReference, automatically grant the consumer the Azure AI User role on the
owning Foundry account and provision a managed identity, removing the two manual
post-deploy `az role assignment create` steps.

Introduces a public, experimental ReferenceRoleAssignmentAnnotation in
Aspire.Hosting.Azure. A resource that "fronts" an Azure resource (without being
an IAzureResource itself) carries this annotation; AzureResourcePreparer folds
its (Target, Roles) into the same role-assignment path used for direct Azure
references. Foundry's AsHostedAgent stamps the annotation on the agent's node
app granting only the least-privilege Azure AI User role; account defaults and
explicit WithRoleAssignments suppression remain owned by the preparer and are
not reintroduced. GetAllRoleAssignments now dedupes roles per target to avoid
colliding bicep role-assignment identifiers.

Adds preparer end-to-end tests (suppression preserved, defaults preserved,
dedup) and Foundry stamp tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The cross-compute-environment Foundry hosted-agent snapshots were committed
before the RBAC auto-wiring change and never regenerated. With the consumer
now receiving a managed identity (web-identity) plus AZURE_CLIENT_ID and
AZURE_TOKEN_CREDENTIALS env vars, the generated bicep/json changed. CI failed
because the verified baselines were stale; local runs masked it because Verify
auto-accepts on developer machines.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. However, I'm not an expert in this area.

A SME in deployment should double check if there is time.

/// This mirrors the inverse-direction logic used by Foundry hosted agents when they reference
/// endpoints owned by App Service/ACA/Kubernetes resources.
/// </remarks>
internal static class ComputeEnvironmentEndpointResolver

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will everyone building hosting/deploy integrations require code like this? Would this be made public sometime in the future?

I want to make sure the design holds up beyond our own bits.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a public API, this makes that public API a little less verbose.

/// </para>
/// </remarks>
[Experimental("ASPIREAZURE003", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
public sealed class ReferenceRoleAssignmentAnnotation(AzureProvisioningResource target, IReadOnlySet<RoleDefinition> roles) : IResourceAnnotation

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: DebuggerDisplay

Most annotations have a DebuggerDisplay. Add one?

(might not be true for annotations in integrations/hosting. Could be fixed up in the future)

/// <summary>
/// Gets the set of roles that resources referencing the annotated resource should be assigned on <see cref="Target"/>.
/// </summary>
public IReadOnlySet<RoleDefinition> Roles { get; } = roles;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Double checking that order will never matter.

RoleDefinition is a record so it should override methods needed for working well in a hash set. Are there tests that exercise this?

// So the minimal, least-privilege grant for a pure agent consumer is "Azure AI User" alone.
var roles = new HashSet<RoleDefinition>
{
new(AzureHostedAgentResource.AzureAIUserRoleDefinitionId, "Azure AI User")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this string have to be "Azure AI User", or is it our description? A comment confirming/denying would be useful.

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Re-running the failed jobs in the CI workflow for this pull request because 1 job was identified as retry-safe transient failures in the CI run attempt.
GitHub was asked to rerun all failed jobs for that attempt, and the rerun is being tracked in the rerun attempt.
The job links below point to the failed attempt jobs that matched the retry-safe transient failure rules.

@davidfowl

Copy link
Copy Markdown
Collaborator Author

Will follow up on the comments. This is for BUILD. Mitch Denny (@mitchdenny) 4 deployment tests were failing but unrelated to these changes.

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

❓ CLI E2E Tests unknown — 110 passed, 0 failed, 2 unknown (commit 177665c)

View all recordings
Status Test Recording Job Artifacts
✅ AddPackageInteractiveWhileAppHostRunningDetached Recording #78773150234 Logs
✅ AddPackageWhileAppHostRunningDetached Recording #78773150234 Logs
✅ AgentCommands_AllHelpOutputs_AreCorrect Recording #78773150603 Logs
✅ AgentInitCommand_DefaultSelection_InstallsDefaultSkills Recording #78773150603 Logs
✅ AgentInitCommand_MigratesDeprecatedConfig Recording #78773150603 Logs
✅ AgentInitCommand_NonInteractive_BundleOnlySkillsBeyondCliCatalog_AreInstallable Recording #78773150603 Logs
✅ AgentMcpListStructuredLogsReturnsLogsFromStarterApp Recording #78773150060 Logs
✅ AgentMcpListStructuredLogsReturnsLogsFromStarterApp_DevLocalhost Recording #78773150060 Logs
✅ AgentMcpListStructuredLogsReturnsLogsFromStarterApp_Isolated Recording #78773150060 Logs
✅ AllPublishMethodsBuildDockerImages Recording #78773150230 Logs
✅ AspireAddAndStartWorkAgainstLegacyAppHostTs Recording #78773150240 Logs
✅ AspireAddPackageVersionToDirectoryPackagesProps Recording #78773150258 Logs
✅ AspireInitSingleFileAppHostRunsViaDotnetRunAppHost Recording #78773150719 Logs
✅ AspireInitWithExistingAppHostDirRecreatesMissingNuGetConfigAndPreservesFiles Recording #78773150162 Logs
❔ AspireInitWithSolutionFileGeneratesAppHostThatBuildsAgainstChannelHive Recording #78773150162 Logs
✅ AspireStartUpdatesStaleTypeScriptAppHostPath Recording #78773150735 Logs
✅ AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps Recording #78773150258 Logs
✅ AspireUpdateRemovesOrphanAppHostPackageVersionWhenSdkAlreadyCurrent Recording #78773150258 Logs
✅ Banner_DisplayedOnFirstRun Recording #78773150493 Logs
✅ Banner_DisplayedWithExplicitFlag Recording #78773150493 Logs
✅ Banner_NotDisplayedWithNoLogoFlag Recording #78773150493 Logs
✅ CertificatesClean_RemovesCertificates Recording #78773150262 Logs
✅ CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate Recording #78773150262 Logs
✅ CertificatesTrust_WithUntrustedCert_TrustsCertificate Recording #78773150262 Logs
✅ ConfigSetGet_CreatesNestedJsonFormat Recording #78773150217 Logs
✅ CreateAndRunAspireStarterProject Recording #78773150462 Logs
✅ CreateAndRunAspireStarterProjectWithBundle Recording #78773150567 Logs
✅ CreateAndRunEmptyAppHostProject Recording #78773150533 Logs
✅ CreateAndRunJavaEmptyAppHostProject Recording #78773150372 Logs
✅ CreateAndRunJsReactProject Recording #78773150467 Logs
✅ CreateAndRunPolyglotAppHostWithDevLocalhostUrls Recording #78773150462 Logs
✅ CreateAndRunPythonReactProject Recording #78773150248 Logs
✅ CreateAndRunTypeScriptEmptyAppHostProject Recording #78773150502 Logs
✅ CreateAndRunTypeScriptStarterProject Recording #78773150710 Logs
✅ CreateJavaAppHostWithViteApp Recording #78773150260 Logs
✅ CreateTypeScriptAppHostWithViteApp_AllowsGuestAppPackageManagerToDiffer Recording #78773150066 Logs
✅ CreateTypeScriptAppHostWithViteApp_UsesConfiguredToolchain Recording #78773150066 Logs
✅ DashboardRunWithAgentMcpListTracesReturnsNoTraces Recording #78773150662 Logs
✅ DashboardRunWithAgentMcpListTracesReturnsNoTraces_DevLocalhost Recording #78773150662 Logs
✅ DashboardRunWithOtelTracesReturnsNoTraces Recording #78773150662 Logs
✅ DashboardRunWithOtelTracesReturnsNoTraces_DevLocalhost Recording #78773150662 Logs
✅ DeployK8sBasicApiService Recording #78773150245 Logs
✅ DeployK8sWithExternalHelmChart Recording #78773150416 Logs
✅ DeployK8sWithGarnet Recording #78773150252 Logs
✅ DeployK8sWithMongoDB Recording #78773150492 Logs
✅ DeployK8sWithMySql Recording #78773150222 Logs
✅ DeployK8sWithPostgres Recording #78773150528 Logs
✅ DeployK8sWithRabbitMQ Recording #78773150597 Logs
✅ DeployK8sWithRedis Recording #78773150232 Logs
✅ DeployK8sWithSqlServer Recording #78773150349 Logs
✅ DeployK8sWithValkey Recording #78773150251 Logs
✅ DeployTypeScriptAppToKubernetes Recording #78773150166 Logs
✅ DescribeCommandResolvesReplicaNames Recording #78773150520 Logs
✅ DescribeCommandShowsRunningResources Recording #78773150520 Logs
✅ DetachFormatJsonProducesValidJson Recording #78773150521 Logs
✅ DetachFormatJsonProducesValidJsonWhenRestartingExistingInstance Recording #78773150521 Logs
✅ DoPublishAndDeployListStepsWork Recording #78773150259 Logs
✅ DocsCommand_RendersInteractiveMarkdownFromLocalSource Recording #78773150261 Logs
✅ DoctorCommand_DetectsDeprecatedAgentConfig Recording #78773150603 Logs
✅ DoctorCommand_TypeScriptAppHostReportsMissingConfiguredToolchain Recording #78773150236 Logs
✅ DoctorCommand_WithSslCertDir_ShowsTrusted Recording #78773150236 Logs
✅ DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted Recording #78773150236 Logs
✅ GatewayWithoutExternalEndpoint_FailsPublishWithGuidance Recording #78773150256 Logs
✅ GeneratedAspireDevScript_StartsWatchMode_WithConfiguredToolchain Recording #78773150066 Logs
✅ GlobalMigration_HandlesCommentsAndTrailingCommas Recording #78773150217 Logs
✅ GlobalMigration_HandlesMalformedLegacyJson Recording #78773150217 Logs
✅ GlobalMigration_PreservesAllValueTypes Recording #78773150217 Logs
✅ GlobalMigration_SkipsWhenNewConfigExists Recording #78773150217 Logs
✅ GlobalSettings_MigratedFromLegacyFormat Recording #78773150217 Logs
✅ IngressWithoutExternalEndpoint_FailsPublishWithGuidance Recording #78773150256 Logs
✅ InitTypeScriptAppHost_AugmentsExistingViteRepoInWorkspaceSubdirectory Recording #78773150066 Logs
✅ InteractiveCSharpInitCreatesExpectedFiles Recording #78773150134 Logs
✅ InvalidAppHostPathWithComments_IsHealedOnRun Recording #78773150243 Logs
✅ JavaScriptHostingApisRunFromTypeScriptAppHost Recording #78773150230 Logs
✅ LatestCliCanStartStableChannelAppHost Recording #78773150462 Logs
✅ LatestCliCanStartStableChannelTypeScriptAppHost Recording #78773150462 Logs
✅ LegacySettingsMigration_AdjustsRelativeAppHostPath Recording #78773150735 Logs
✅ LogsCommandShowsResourceLogs Recording #78773150469 Logs
✅ OtelLogsReturnsStructuredLogsFromStarterApp Recording #78773150587 Logs
✅ OtelLogsReturnsStructuredLogsFromStarterAppIsolated Recording #78773150587 Logs
✅ PsCommandListsRunningAppHost Recording #78773150364 Logs
✅ PsFormatJsonOutputsOnlyJsonToStdout Recording #78773150364 Logs
✅ PublishJavaScriptPatternsGeneratesExpectedDockerComposeArtifacts Recording #78773150227 Logs
✅ PublishWithConfigureEnvFileUpdatesEnvOutput Recording #78773150227 Logs
✅ PublishWithDockerComposeServiceCallbackSucceeds Recording #78773150227 Logs
✅ PublishWithoutOutputPathUsesAppHostDirectoryDefault Recording #78773150227 Logs
✅ ResourceCommand_FailedExecution_DisplaysAppHostLogPathAndLogContainsEntries Recording #78773150247 Logs
✅ ResourceCommand_SetAndDeleteParameterUpdatesDescribeOutput Recording #78773150247 Logs
✅ RestoreGeneratesSdkFiles Recording #78773150123 Logs
✅ RestoreGeneratesSdkFiles_WithConfiguredToolchain Recording #78773150253 Logs
✅ RestoreRefreshesGeneratedSdkAfterAddingIntegration Recording #78773150253 Logs
✅ RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes Recording #78773150506 Logs
✅ RunFromParentDirectory_UsesExistingConfigNearAppHost Recording #78773150377 Logs
✅ RunReportsSyntaxErrorsForDotNetAppHost Recording #78773150255 Logs
✅ RunReportsSyntaxErrorsForTypeScriptAppHost Recording #78773150255 Logs
✅ SecretCrudOnDotNetAppHost Recording #78773150525 Logs
✅ SecretCrudOnTypeScriptAppHost Recording #78773150370 Logs
✅ StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels Recording #78773150505 Logs
✅ StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets Recording #78773150536 Logs
✅ StartReportsSyntaxErrorsForDotNetAppHost Recording #78773150255 Logs
✅ StartReportsSyntaxErrorsForTypeScriptAppHost Recording #78773150255 Logs
✅ StopAllAppHostsFromAppHostDirectory Recording #78773150543 Logs
✅ StopJavaPolyglotAppHostUsingApphostDirectory Recording #78773150599 Logs
✅ StopNonInteractiveSingleAppHost Recording #78773150543 Logs
✅ StopTypeScriptPolyglotAppHostUsingApphostDirectory Recording #78773150479 Logs
✅ StopWithNoRunningAppHostExitsSuccessfully Recording #78773150234 Logs
✅ TypeScriptAppHostRunDoesNotDeadlockWhenLazyOptionsInvokeAsyncCallback Recording #78773150502 Logs
✅ UnAwaitedChainsCompileWithAutoResolvePromises Recording #78773150253 Logs
❔ UpdateProjectChannelToStable_CSharpEmptyAppHost_PreservesAspireConfigChannel Recording #78773150572 Logs
✅ UpdateProjectChannelToStable_CSharpSingleFileInit_PreservesAspireConfigChannel Recording #78773150572 Logs
✅ UpdateProjectChannelToStable_TypeScriptSingleFileInit_PreservesAspireConfigChannel Recording #78773150572 Logs
✅ UpdateProjectChannelToStable_TypeScript_PreviewsStablePackagesAndPreservesChannel Recording #78773150572 Logs

📹 Recordings uploaded automatically from CI run #26729041681

@aspire-repo-bot

Copy link
Copy Markdown
Contributor

Pull request created: #1143

Generated by PR Documentation Check

@aspire-repo-bot

Copy link
Copy Markdown
Contributor

📝 Documentation has been drafted in microsoft/aspire.dev#1143 targeting release/13.4.

Drafted docs PR covering two user-facing changes from this PR:

  • azure-ai-foundry-host.mdx: New section "Reference a hosted agent across compute environments" showing how a resource in one compute environment (e.g., AKS) can reference a Foundry hosted agent in another, with C# and TypeScript examples. Explains both cross-environment endpoint resolution and the auto-wired Azure AI User RBAC grant (ReferenceRoleAssignmentAnnotation, ASPIREAZURE003).
  • aspireazure003.mdx: Updated the ASPIREAZURE003 diagnostic page to cover both Azure Virtual Networks and ReferenceRoleAssignmentAnnotation, with a cross-example for the hosted-agent scenario.

Note

This draft PR needs human review before merging.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants