diff --git a/src/Aspire.Hosting.Azure.AppContainers/Aspire.Hosting.Azure.AppContainers.csproj b/src/Aspire.Hosting.Azure.AppContainers/Aspire.Hosting.Azure.AppContainers.csproj
index 52e78c556c6..92848c8485c 100644
--- a/src/Aspire.Hosting.Azure.AppContainers/Aspire.Hosting.Azure.AppContainers.csproj
+++ b/src/Aspire.Hosting.Azure.AppContainers/Aspire.Hosting.Azure.AppContainers.csproj
@@ -11,6 +11,7 @@
+
diff --git a/src/Aspire.Hosting.Azure.AppContainers/BaseContainerAppContext.cs b/src/Aspire.Hosting.Azure.AppContainers/BaseContainerAppContext.cs
index c0d14ac555f..e252d0b7705 100644
--- a/src/Aspire.Hosting.Azure.AppContainers/BaseContainerAppContext.cs
+++ b/src/Aspire.Hosting.Azure.AppContainers/BaseContainerAppContext.cs
@@ -222,6 +222,15 @@ BicepValue GetHostValue(string? prefix = null, string? suffix = null)
if (value is EndpointReference ep)
{
+ // The referenced endpoint may belong to a resource deployed to a different compute
+ // environment (for example a Foundry hosted agent). In that case delegate to the owning
+ // compute environment instead of looking it up in this environment's local endpoint map.
+ if (ComputeEnvironmentEndpointResolver.TryGetCrossEnvironmentEndpointExpression(
+ ep, [_containerAppEnvironmentContext.Environment], out var crossExpr))
+ {
+ return ProcessValue(crossExpr, secretType, parent);
+ }
+
var context = ep.Resource == resource
? this
: _containerAppEnvironmentContext.GetContainerAppContext(ep.Resource);
@@ -274,6 +283,12 @@ BicepValue GetHostValue(string? prefix = null, string? suffix = null)
if (value is EndpointReferenceExpression epExpr)
{
+ if (ComputeEnvironmentEndpointResolver.TryGetCrossEnvironmentEndpointExpression(
+ epExpr, [_containerAppEnvironmentContext.Environment], out var crossExpr))
+ {
+ return ProcessValue(crossExpr, secretType, parent);
+ }
+
var context = epExpr.Endpoint.Resource == resource
? this
: _containerAppEnvironmentContext.GetContainerAppContext(epExpr.Endpoint.Resource);
diff --git a/src/Aspire.Hosting.Azure.AppService/Aspire.Hosting.Azure.AppService.csproj b/src/Aspire.Hosting.Azure.AppService/Aspire.Hosting.Azure.AppService.csproj
index 84d433e5124..1570e890831 100644
--- a/src/Aspire.Hosting.Azure.AppService/Aspire.Hosting.Azure.AppService.csproj
+++ b/src/Aspire.Hosting.Azure.AppService/Aspire.Hosting.Azure.AppService.csproj
@@ -13,6 +13,7 @@
+
diff --git a/src/Aspire.Hosting.Azure.AppService/AzureAppServiceWebsiteContext.cs b/src/Aspire.Hosting.Azure.AppService/AzureAppServiceWebsiteContext.cs
index ca89a2faac7..b5d3c774560 100644
--- a/src/Aspire.Hosting.Azure.AppService/AzureAppServiceWebsiteContext.cs
+++ b/src/Aspire.Hosting.Azure.AppService/AzureAppServiceWebsiteContext.cs
@@ -167,6 +167,15 @@ private void ProcessEndpoints()
if (value is EndpointReference ep)
{
+ // The referenced endpoint may belong to a resource deployed to a different compute
+ // environment (for example a Foundry hosted agent). In that case delegate to the owning
+ // compute environment instead of looking it up in this environment's local endpoint map.
+ if (ComputeEnvironmentEndpointResolver.TryGetCrossEnvironmentEndpointExpression(
+ ep, [environmentContext.Environment], out var crossExpr))
+ {
+ return ProcessValue(crossExpr, secretType, parent, isSlot);
+ }
+
var context = environmentContext.GetAppServiceContext(ep.Resource);
return isSlot ?
(GetEndpointValue(context._slotEndpointMapping[ep.EndpointName], EndpointProperty.Url), secretType) :
@@ -206,6 +215,12 @@ private void ProcessEndpoints()
if (value is EndpointReferenceExpression epExpr)
{
+ if (ComputeEnvironmentEndpointResolver.TryGetCrossEnvironmentEndpointExpression(
+ epExpr, [environmentContext.Environment], out var crossExpr))
+ {
+ return ProcessValue(crossExpr, secretType, parent, isSlot);
+ }
+
var context = environmentContext.GetAppServiceContext(epExpr.Endpoint.Resource);
var mapping = isSlot ? context._slotEndpointMapping[epExpr.Endpoint.EndpointName] : context._endpointMapping[epExpr.Endpoint.EndpointName];
var val = GetEndpointValue(mapping, epExpr.Property);
diff --git a/src/Aspire.Hosting.Azure.FrontDoor/Aspire.Hosting.Azure.FrontDoor.csproj b/src/Aspire.Hosting.Azure.FrontDoor/Aspire.Hosting.Azure.FrontDoor.csproj
index 0715429ec9b..f5e42917159 100644
--- a/src/Aspire.Hosting.Azure.FrontDoor/Aspire.Hosting.Azure.FrontDoor.csproj
+++ b/src/Aspire.Hosting.Azure.FrontDoor/Aspire.Hosting.Azure.FrontDoor.csproj
@@ -15,6 +15,10 @@
+
+
+
+
diff --git a/src/Aspire.Hosting.Azure.FrontDoor/AzureFrontDoorExtensions.cs b/src/Aspire.Hosting.Azure.FrontDoor/AzureFrontDoorExtensions.cs
index 167c95f44b3..73e557b2926 100644
--- a/src/Aspire.Hosting.Azure.FrontDoor/AzureFrontDoorExtensions.cs
+++ b/src/Aspire.Hosting.Azure.FrontDoor/AzureFrontDoorExtensions.cs
@@ -201,16 +201,11 @@ public static IResourceBuilder WithOrigin(
private static IComputeEnvironmentResource GetEffectiveComputeEnvironment(IResource resource)
{
- if (resource.GetComputeEnvironment() is { } computeEnvironment)
+ if (ComputeEnvironmentEndpointResolver.TryGetEffectiveComputeEnvironment(resource, out var computeEnvironment))
{
return computeEnvironment;
}
- if (resource.GetDeploymentTargetAnnotation()?.ComputeEnvironment is { } deploymentComputeEnvironment)
- {
- return deploymentComputeEnvironment;
- }
-
throw new InvalidOperationException(
$"Resource '{resource.Name}' does not have a compute environment. " +
"Ensure a compute environment (e.g., Azure Container Apps, Azure App Service) is configured in the application model.");
diff --git a/src/Aspire.Hosting.Azure/AzureResourcePreparer.cs b/src/Aspire.Hosting.Azure/AzureResourcePreparer.cs
index ac76fc957dd..02448c02bb5 100644
--- a/src/Aspire.Hosting.Azure/AzureResourcePreparer.cs
+++ b/src/Aspire.Hosting.Azure/AzureResourcePreparer.cs
@@ -133,7 +133,8 @@ private async Task BuildRoleAssignmentAnnotations(DistributedApplicationModel ap
foreach (var resource in resourceSnapshot)
{
var prerequisiteResources = new HashSet();
- var azureReferences = await GetAzureReferences(resource, cancellationToken).ConfigureAwait(false);
+ var directDependencies = await resource.GetResourceDependenciesAsync(executionContext, ResourceDependencyDiscoveryMode.DirectOnly, cancellationToken).ConfigureAwait(false);
+ var azureReferences = new HashSet(directDependencies.OfType());
var azureReferencesWithRoleAssignments =
(resource.TryGetAnnotationsOfType(out var annotations)
@@ -184,6 +185,42 @@ private async Task BuildRoleAssignmentAnnotations(DistributedApplicationModel ap
}
}
+ // A direct dependency that is not itself an Azure resource can still "front" one
+ // (e.g. a Foundry hosted agent's node app fronts its owning Foundry account). Such a
+ // resource carries ReferenceRoleAssignmentAnnotation(s) declaring that any resource
+ // referencing it should be granted roles on a transitive Azure target the normal
+ // IAzureResource-only reference walk above cannot reach. Fold those implied targets
+ // into the same role-assignment path so the consumer gets an identity + role bicep
+ // exactly as it would for a direct Azure reference.
+ foreach (var dependency in directDependencies)
+ {
+ if (!dependency.TryGetAnnotationsOfType(out var impliedRoleAssignments))
+ {
+ continue;
+ }
+
+ foreach (var impliedRoleAssignment in impliedRoleAssignments)
+ {
+ var target = impliedRoleAssignment.Target;
+ if (target.IsContainer() || target.IsEmulator())
+ {
+ continue;
+ }
+
+ if (executionContext.IsRunMode)
+ {
+ AppendGlobalRoleAssignments(globalRoleAssignments, target, impliedRoleAssignment.Roles);
+ }
+ else
+ {
+ // In PublishMode, materialize as an explicit RoleAssignmentAnnotation so
+ // GetAllRoleAssignments (which groups by target and unions roles) picks it
+ // up alongside any roles the consumer already declares for the same target.
+ resource.Annotations.Add(new RoleAssignmentAnnotation(target, impliedRoleAssignment.Roles));
+ }
+ }
+ }
+
// in PublishMode with SupportsTargetedRoleAssignments, we need to create the identity and role assignment resources
// if the resource references any Azure resources, or has role assignments to Azure resources
if (executionContext.IsPublishMode)
@@ -250,7 +287,12 @@ private static Dictionary
{
foreach (var g in roleAssignments.GroupBy(r => r.Target))
{
- result[g.Key] = g.SelectMany(r => r.Roles);
+ // Deduplicate roles per target. A target can accumulate multiple RoleAssignmentAnnotations
+ // (e.g. an implied ReferenceRoleAssignmentAnnotation from two hosted agents on the same
+ // Foundry account, plus a direct reference). Emitting the same RoleDefinition twice would
+ // produce two RoleAssignment bicep resources with the same identifier ("{prefix}_{roleName}")
+ // and fail bicep compilation. This mirrors the RunMode path, which unions into a HashSet.
+ result[g.Key] = g.SelectMany(r => r.Roles).Distinct();
}
}
return result;
@@ -359,19 +401,6 @@ private sealed class AddRoleAssignmentsContext(
public DistributedApplicationExecutionContext ExecutionContext => executionContext;
}
- private async Task> GetAzureReferences(IResource resource, CancellationToken cancellationToken)
- {
- var dependencies = await resource.GetResourceDependenciesAsync(executionContext, ResourceDependencyDiscoveryMode.DirectOnly, cancellationToken).ConfigureAwait(false);
-
- HashSet azureReferences = [];
- foreach (var azureResource in dependencies.OfType())
- {
- azureReferences.Add(azureResource);
- }
-
- return azureReferences;
- }
-
private static void AppendGlobalRoleAssignments(Dictionary> globalRoleAssignments, AzureProvisioningResource azureResource, IEnumerable newRoles)
{
if (!globalRoleAssignments.TryGetValue(azureResource, out var existingRoles))
diff --git a/src/Aspire.Hosting.Azure/ReferenceRoleAssignmentAnnotation.cs b/src/Aspire.Hosting.Azure/ReferenceRoleAssignmentAnnotation.cs
new file mode 100644
index 00000000000..58720eaad6e
--- /dev/null
+++ b/src/Aspire.Hosting.Azure/ReferenceRoleAssignmentAnnotation.cs
@@ -0,0 +1,43 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Diagnostics.CodeAnalysis;
+using Aspire.Hosting.ApplicationModel;
+
+namespace Aspire.Hosting.Azure;
+
+///
+/// Declares that any compute resource referencing the annotated resource should be granted
+/// on the Azure resource .
+///
+/// The Azure resource that referencing resources should be granted roles on.
+/// The roles that referencing resources should be assigned on .
+///
+///
+/// This annotation is applied to a resource that "fronts" an Azure resource without being an
+/// itself. For example, a Foundry hosted agent's node app is a plain
+/// compute resource, but invoking the agent requires the caller to hold a role on the owning
+/// Foundry account. The account is only a transitive dependency of a consumer, so
+/// 's normal reference walk — which only acts on direct
+/// dependencies — cannot reach it.
+///
+///
+/// When a compute resource takes a direct dependency on a resource carrying this annotation,
+/// folds (Target, Roles) into the same role-assignment
+/// path used for direct Azure references, so the consumer gets a managed identity and the
+/// corresponding role assignment on with no additional wiring.
+///
+///
+[Experimental("ASPIREAZURE003", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
+public sealed class ReferenceRoleAssignmentAnnotation(AzureProvisioningResource target, IReadOnlySet roles) : IResourceAnnotation
+{
+ ///
+ /// Gets the Azure resource that resources referencing the annotated resource should be granted roles on.
+ ///
+ public AzureProvisioningResource Target { get; } = target;
+
+ ///
+ /// Gets the set of roles that resources referencing the annotated resource should be assigned on .
+ ///
+ public IReadOnlySet Roles { get; } = roles;
+}
diff --git a/src/Aspire.Hosting.Foundry/Aspire.Hosting.Foundry.csproj b/src/Aspire.Hosting.Foundry/Aspire.Hosting.Foundry.csproj
index 709af738f3a..d5dd4cae6ad 100644
--- a/src/Aspire.Hosting.Foundry/Aspire.Hosting.Foundry.csproj
+++ b/src/Aspire.Hosting.Foundry/Aspire.Hosting.Foundry.csproj
@@ -23,6 +23,7 @@
+
diff --git a/src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs b/src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs
index 1c4f139d339..a73b8de2ddb 100644
--- a/src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs
+++ b/src/Aspire.Hosting.Foundry/HostedAgent/AzureHostedAgentResource.cs
@@ -25,7 +25,10 @@ namespace Aspire.Hosting.Foundry;
///
public class AzureHostedAgentResource : Resource, IResourceWithEnvironment
{
- private const string AzureAIUserRoleDefinitionId = "53ca6127-db72-4b80-b1b0-d745d6d5456d";
+ // The "Azure AI User" built-in role (data-plane access to Foundry agents/inference). Granted to
+ // the agent's own instance identity below, and to consumers that reference the agent (see
+ // HostedAgentResourceBuilderExtensions.GrantHostedAgentConsumerRoles).
+ internal const string AzureAIUserRoleDefinitionId = "53ca6127-db72-4b80-b1b0-d745d6d5456d";
///
/// Creates a new instance of the class.
@@ -429,8 +432,7 @@ internal static async Task> GetResolvedEnvironmentVar
throw CreateEndpointResolutionException(hostedAgent, resource, environmentVariableName, endpointReference, $"Endpoint '{endpoint.Name}' is internal. Foundry hosted agents can only reference externally exposed endpoints during publish.");
}
- var deploymentTarget = endpointReference.Resource.GetDeploymentTargetAnnotation();
- if (deploymentTarget?.ComputeEnvironment is not { } computeEnvironment)
+ if (!ComputeEnvironmentEndpointResolver.TryGetEffectiveComputeEnvironment(endpointReference.Resource, out var computeEnvironment))
{
var reason = $"Resource '{endpointReference.Resource.Name}' does not have a compute environment deployment target.";
throw CreateEndpointResolutionException(hostedAgent, resource, environmentVariableName, endpointReference, reason);
diff --git a/src/Aspire.Hosting.Foundry/HostedAgent/HostedAgentBuilderExtension.cs b/src/Aspire.Hosting.Foundry/HostedAgent/HostedAgentBuilderExtension.cs
index 60104ccc4d3..ce7a545e47f 100644
--- a/src/Aspire.Hosting.Foundry/HostedAgent/HostedAgentBuilderExtension.cs
+++ b/src/Aspire.Hosting.Foundry/HostedAgent/HostedAgentBuilderExtension.cs
@@ -4,6 +4,7 @@
using System.Net.Http.Json;
using System.Text.Json;
using Aspire.Hosting.ApplicationModel;
+using Aspire.Hosting.Azure;
using Aspire.Hosting.Foundry;
using Microsoft.Extensions.DependencyInjection;
@@ -419,6 +420,35 @@ private static void ConfigurePublishMode(
builder.ApplicationBuilder.AddResource(hostedAgent)
.WithIconName("Agents")
.WithReferenceRelationship(target);
+
+ // Referencing a hosted agent (its node app) only injects the agent's service-discovery URL.
+ // Unlike referencing a first-class Azure resource, it does not give the consumer a managed
+ // identity or any RBAC on the Foundry account, so calls to the agent's invocation endpoint
+ // fail with 401/403 at runtime. Stamp a ReferenceRoleAssignmentAnnotation on the agent's
+ // target so AzureResourcePreparer grants the "Azure AI User" role on the owning Foundry
+ // account to every consumer that references this agent, and provisions the identity that
+ // makes ACA inject AZURE_CLIENT_ID.
+ StampHostedAgentConsumerRoleAnnotation(target, projectResource.Parent);
+ }
+
+ private static void StampHostedAgentConsumerRoleAnnotation(IResourceWithEnvironment target, FoundryResource account)
+ {
+ // Grant only the "Azure AI User" role required to invoke the hosted agent. We deliberately do
+ // not union the account's default data-plane roles here:
+ // - A consumer that also references the account directly still receives those defaults through
+ // AzureResourcePreparer's normal reference walk (they are preserved when GetAllRoleAssignments
+ // unions per target).
+ // - A consumer that declares explicit role assignments on the account intentionally suppresses
+ // the account defaults; folding them back in here would defeat that suppression.
+ // So the minimal, least-privilege grant for a pure agent consumer is "Azure AI User" alone.
+ var roles = new HashSet
+ {
+ new(AzureHostedAgentResource.AzureAIUserRoleDefinitionId, "Azure AI User")
+ };
+
+#pragma warning disable ASPIREAZURE003 // Type is for evaluation purposes only and is subject to change or removal in future updates.
+ target.Annotations.Add(new ReferenceRoleAssignmentAnnotation(account, roles));
+#pragma warning restore ASPIREAZURE003
}
private sealed class HostedAgentRunProtocol
@@ -454,3 +484,4 @@ private sealed class HostedAgentRunProtocol
public required Func CreateRequestContent { get; init; }
}
}
+
diff --git a/src/Aspire.Hosting.Foundry/Project/ProjectResource.cs b/src/Aspire.Hosting.Foundry/Project/ProjectResource.cs
index 8fcabc67d52..ac90f16f99e 100644
--- a/src/Aspire.Hosting.Foundry/Project/ProjectResource.cs
+++ b/src/Aspire.Hosting.Foundry/Project/ProjectResource.cs
@@ -212,9 +212,48 @@ public AzureContainerRegistryResource? ContainerRegistry
/// Get the address for the particular agent's endpoint.
///
ReferenceExpression IComputeEnvironmentResource.GetHostAddressExpression(EndpointReference endpointReference)
+ => GetAgentAddressExpression(endpointReference);
+
+ ///
+ /// Produces the endpoint property expression for a hosted agent endpoint owned by this Foundry project.
+ ///
+ ///
+ /// The agent address is already a fully-qualified https URL
+ /// (for example https://{account}.services.ai.azure.com/.../agents/{name}), so it is
+ /// returned directly for URL-shaped properties. The default
+ /// implementation composes
+ /// {scheme}://{host}, which would produce a malformed double-scheme value
+ /// (for example http://https://...). Only the properties that WithReference emits for a
+ /// hosted agent endpoint are supported.
+ ///
+ ReferenceExpression IComputeEnvironmentResource.GetEndpointPropertyExpression(EndpointReferenceExpression endpointReferenceExpression)
+ {
+ ArgumentNullException.ThrowIfNull(endpointReferenceExpression);
+
+ var property = endpointReferenceExpression.Property;
+ return property switch
+ {
+ EndpointProperty.Url => GetAgentAddressExpression(endpointReferenceExpression.Endpoint),
+ EndpointProperty.Scheme => ReferenceExpression.Create($"https"),
+ _ => throw new InvalidOperationException(
+ $"The endpoint property '{property}' is not supported for Foundry hosted agent endpoints. Only 'Url' and 'Scheme' are supported.")
+ };
+ }
+
+ private ReferenceExpression GetAgentAddressExpression(EndpointReference endpointReference)
{
var resource = endpointReference.Resource;
- return ReferenceExpression.Create($"{Endpoint}/agents/{resource.Name}");
+
+ // For hosted agents, deployment creates the Foundry agent version using the wrapper
+ // AzureHostedAgentResource.Name (e.g. "agent-ha" for a target named "agent"), not the
+ // target resource name. The published cross-environment URL must point at that deployed
+ // agent name, so prefer the hosted-agent deployment target's name when one exists and fall
+ // back to the resource name for plain (non-hosted) agents.
+ var agentName = resource.GetDeploymentTargetAnnotation(this)?.DeploymentTarget is AzureHostedAgentResource hostedAgent
+ ? hostedAgent.Name
+ : resource.Name;
+
+ return ReferenceExpression.Create($"{Endpoint}/agents/{agentName}");
}
///
diff --git a/src/Aspire.Hosting.Kubernetes/Aspire.Hosting.Kubernetes.csproj b/src/Aspire.Hosting.Kubernetes/Aspire.Hosting.Kubernetes.csproj
index 04e87db475a..a7992c280ff 100644
--- a/src/Aspire.Hosting.Kubernetes/Aspire.Hosting.Kubernetes.csproj
+++ b/src/Aspire.Hosting.Kubernetes/Aspire.Hosting.Kubernetes.csproj
@@ -14,6 +14,7 @@
+
diff --git a/src/Aspire.Hosting.Kubernetes/KubernetesResource.cs b/src/Aspire.Hosting.Kubernetes/KubernetesResource.cs
index 66921ab26ad..6f75bf8acfb 100644
--- a/src/Aspire.Hosting.Kubernetes/KubernetesResource.cs
+++ b/src/Aspire.Hosting.Kubernetes/KubernetesResource.cs
@@ -486,6 +486,16 @@ private async Task