From 0b6bfe2f538d4eed8a9ae7e11651c09dbbe886b8 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 20 Oct 2026 18:01:58 +0000 Subject: [PATCH 1/5] Merged PR 66656: [release/13.6] Fix dashboard not-found authentication ## Description Fix dashboard authentication when an unauthenticated user navigates to a missing route. The router's not-found content previously bypassed `AuthorizeRouteView` and could render the main layout and its UI infrastructure. Missing routes now enforce the frontend authorization policy before rendering dashboard UI. In browser-token mode, unauthenticated users are redirected to login with the original route preserved as the return URL. Add defense-in-depth authentication checks before initializing the main layout, dialog provider, interaction provider, and standalone terminal window. Preserve unsecured mode and the release branch's terminal route-change lifecycle. Targets `release/13.6`. Fixes # (issue) ### User-facing usage With browser-token authentication enabled, navigating from the login page to `/this-page-does-not-exist` redirects back to `/login?returnUrl=%2Fthis-page-does-not-exist` instead of rendering the dashboard layout. Authenticated users can still access the not-found page. ### Validation - Focused dashboard component tests: 106 passed, including browser-token redirects, layouts, interactions, and terminal windows. - Authenticated and unauthenticated initialization tests cover browser-token and OpenID Connect modes. - Dashboard integration-test project build: 0 warnings and 0 errors. - Added a Playwright regression test for navigation from login to a missing route. Compiled but not executed because it is an outerloop test. - `git diff --check` passed. ### Security considerations This changes frontend authentication/authorization handling. The route authorization policy remains the primary control; the additional initialization checks reject unauthenticated users in secured modes before starting UI infrastructure. Security review is requested; no threat model or security review has been completed for this change. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - [ ] No - Did you add public API? - [ ] Yes - If yes, did you have an API Review for it? - [ ] Yes - [ ] No - Did you add `` and `` elements on your triple slash comments? - [ ] Yes - [ ] No - [x] No - Does the change make any security assumptions or guarantees? - [x] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [x] No - [ ] No ---- #### AI description (iteration 1) #### PR Classification Bug fix: unauthenticated users hitting a missing (not-found) route in the dashboard bypassed authentication, exposing the NotFound page without login enforcement. #### PR Summary This PR fixes an authentication bypass where navigating to a non-existent route would skip authorization checks, and adds a defense-in-depth authentication guard across key Blazor components. - `src/Aspire.Dashboard/Components/R... --- .../DashboardAuthenticationState.cs | 29 +++ .../Controls/DashboardNotAuthorized.razor | 4 + .../Controls/DashboardNotAuthorized.razor.cs | 37 ++++ .../Interactions/InteractionsProvider.cs | 14 +- .../Layout/DashboardDialogProvider.cs | 12 +- .../Components/Layout/MainLayout.razor.cs | 7 + .../Components/Layout/WindowLayout.razor | 3 + .../Components/Layout/WindowLayout.razor.cs | 27 +++ .../Components/Pages/TerminalWindow.razor | 2 +- src/Aspire.Dashboard/Components/Routes.razor | 36 +++- .../Components/Routes.razor.cs | 9 + .../Resources/Routes.Designer.cs | 9 + src/Aspire.Dashboard/Resources/Routes.resx | 3 + .../Resources/xlf/Routes.cs.xlf | 5 + .../Resources/xlf/Routes.de.xlf | 5 + .../Resources/xlf/Routes.es.xlf | 5 + .../Resources/xlf/Routes.fr.xlf | 5 + .../Resources/xlf/Routes.it.xlf | 5 + .../Resources/xlf/Routes.ja.xlf | 5 + .../Resources/xlf/Routes.ko.xlf | 5 + .../Resources/xlf/Routes.pl.xlf | 5 + .../Resources/xlf/Routes.pt-BR.xlf | 5 + .../Resources/xlf/Routes.ru.xlf | 5 + .../Resources/xlf/Routes.tr.xlf | 5 + .../Resources/xlf/Routes.zh-Hans.xlf | 5 + .../Resources/xlf/Routes.zh-Hant.xlf | 5 + .../Controls/DashboardNotAuthorizedTests.cs | 70 +++++++ .../Interactions/InteractionsProviderTests.cs | 35 ++++ .../Layout/DashboardDialogProviderTests.cs | 16 ++ .../Layout/MainLayoutTests.cs | 12 ++ .../Layout/WindowLayoutTests.cs | 58 ++++++ .../Pages/TerminalWindowTests.cs | 47 +++++ .../RoutesTests.cs | 172 ++++++++++++++++++ .../Shared/TestNavigationManager.cs | 8 + .../BrowserTokenAuthenticationTests.cs | 72 ++++++++ 35 files changed, 734 insertions(+), 13 deletions(-) create mode 100644 src/Aspire.Dashboard/Authentication/DashboardAuthenticationState.cs create mode 100644 src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor create mode 100644 src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor.cs create mode 100644 src/Aspire.Dashboard/Components/Layout/WindowLayout.razor create mode 100644 src/Aspire.Dashboard/Components/Layout/WindowLayout.razor.cs create mode 100644 src/Aspire.Dashboard/Components/Routes.razor.cs create mode 100644 tests/Aspire.Dashboard.Components.Tests/Controls/DashboardNotAuthorizedTests.cs create mode 100644 tests/Aspire.Dashboard.Components.Tests/Layout/WindowLayoutTests.cs create mode 100644 tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs diff --git a/src/Aspire.Dashboard/Authentication/DashboardAuthenticationState.cs b/src/Aspire.Dashboard/Authentication/DashboardAuthenticationState.cs new file mode 100644 index 00000000000..f05c5279936 --- /dev/null +++ b/src/Aspire.Dashboard/Authentication/DashboardAuthenticationState.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Configuration; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Aspire.Dashboard.Authentication; + +internal static class DashboardAuthenticationState +{ + /// + /// Double-checks authentication state inside the dashboard as a defense-in-depth measure. + /// Use in main layouts and infrastructure that launches UI. + /// + public static async Task EnsureAuthenticatedAsync( + DashboardOptions dashboardOptions, + Task? authenticationState) + { + if (dashboardOptions.Frontend.AuthMode is FrontendAuthMode.Unsecured or null) + { + return; + } + + if (authenticationState is null || (await authenticationState.ConfigureAwait(false)).User.Identity?.IsAuthenticated is not true) + { + throw new InvalidOperationException("Dashboard authentication is required, but the current user is not authenticated."); + } + } +} diff --git a/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor b/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor new file mode 100644 index 00000000000..41964b0fc82 --- /dev/null +++ b/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor @@ -0,0 +1,4 @@ +@if (DashboardOptions.Value.Frontend.AuthMode != FrontendAuthMode.BrowserToken) +{ + @Loc[nameof(Resources.Routes.NotAuthorized)] +} diff --git a/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor.cs b/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor.cs new file mode 100644 index 00000000000..27b218b760a --- /dev/null +++ b/src/Aspire.Dashboard/Components/Controls/DashboardNotAuthorized.razor.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Configuration; +using Aspire.Dashboard.Utils; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; + +namespace Aspire.Dashboard.Components.Controls; + +public sealed partial class DashboardNotAuthorized : ComponentBase +{ + [Inject] + public required NavigationManager NavigationManager { get; init; } + + [Inject] + public required IOptions DashboardOptions { get; init; } + + [Inject] + public required IStringLocalizer Loc { get; init; } + + protected override void OnInitialized() + { + if (DashboardOptions.Value.Frontend.AuthMode == FrontendAuthMode.BrowserToken) + { + // Preserve the path base in both URLs, and keep the return URL local so login validation accepts it. + var currentUri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri); + var returnUrl = currentUri.PathAndQuery + currentUri.Fragment; + var loginUri = NavigationManager.ToAbsoluteUri(DashboardUrls.LoginBasePath); + var loginUrl = QueryHelpers.AddQueryString(loginUri.AbsoluteUri, "returnUrl", returnUrl); + + NavigationManager.NavigateTo(loginUrl, new NavigationOptions { ReplaceHistoryEntry = true }); + } + } +} diff --git a/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs b/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs index 682459daa36..eb39423fdf2 100644 --- a/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs +++ b/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs @@ -4,8 +4,10 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Net; +using Aspire.Dashboard.Authentication; using Aspire.Dashboard.Components.Dialogs; using Aspire.Dashboard.Components.Pages; +using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Model; using Aspire.Dashboard.Model.Interaction; using Aspire.Dashboard.Model.Markdown; @@ -13,7 +15,9 @@ using Aspire.Dashboard.Utils; using Aspire.DashboardService.Proto.V1; using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; using MessageIntentDto = Aspire.DashboardService.Proto.V1.MessageIntent; using MessageIntentUI = Microsoft.FluentUI.AspNetCore.Components.MessageBarIntent; @@ -87,11 +91,19 @@ internal async Task GetMessagesProcessedAsync() [Inject] public required ComponentTelemetryContextProvider TelemetryContextProvider { get; init; } + [Inject] + public required IOptions DashboardOptions { get; init; } + [CascadingParameter] public required ViewportInformation ViewportInformation { get; set; } - protected override void OnInitialized() + [CascadingParameter] + public Task? AuthenticationState { get; set; } + + protected override async Task OnInitializedAsync() { + await DashboardAuthenticationState.EnsureAuthenticatedAsync(DashboardOptions.Value, AuthenticationState); + // Exit quickly if the dashboard client is not enabled. For example, the dashboard is running in the standalone container. if (!DashboardClient.IsEnabled) { diff --git a/src/Aspire.Dashboard/Components/Layout/DashboardDialogProvider.cs b/src/Aspire.Dashboard/Components/Layout/DashboardDialogProvider.cs index 8a5c61e0941..fa6fa7231cf 100644 --- a/src/Aspire.Dashboard/Components/Layout/DashboardDialogProvider.cs +++ b/src/Aspire.Dashboard/Components/Layout/DashboardDialogProvider.cs @@ -1,12 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Aspire.Dashboard.Authentication; using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Model; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Routing; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; namespace Aspire.Dashboard.Components.Layout; @@ -23,8 +26,15 @@ public class DashboardDialogProvider : ComponentBase, IDisposable [Inject] public required NavigationDialogService DialogService { get; init; } - protected override void OnInitialized() + [Inject] + public required IOptions DashboardOptions { get; init; } + + [CascadingParameter] + public Task? AuthenticationState { get; set; } + + protected override async Task OnInitializedAsync() { + await DashboardAuthenticationState.EnsureAuthenticatedAsync(DashboardOptions.Value, AuthenticationState); NavigationManager.LocationChanged += OnLocationChanged; } diff --git a/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs b/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs index 0d48970f09c..4b59fee3d3d 100644 --- a/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs +++ b/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs @@ -2,12 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text; +using Aspire.Dashboard.Authentication; using Aspire.Dashboard.Components.Dialogs; using Aspire.Dashboard.Components.Pages; using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Model; using Aspire.Dashboard.Utils; using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; @@ -104,10 +106,15 @@ public partial class MainLayout : IGlobalKeydownListener, IAsyncDisposable [CascadingParameter] public required ViewportInformation ViewportInformation { get; set; } + [CascadingParameter] + public Task? AuthenticationState { get; set; } + private bool IsTerminalDockEnabled => !_isSwitchingRuns && DashboardClient.IsEnabled && !DashboardClient.IsReadOnly; protected override async Task OnInitializedAsync() { + await DashboardAuthenticationState.EnsureAuthenticatedAsync(Options.CurrentValue, AuthenticationState); + if (RunStore.SupportsRunSelection) { var selectedRunResult = await SessionStorage.GetAsync(BrowserStorageKeys.SelectedDashboardRunId); diff --git a/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor b/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor new file mode 100644 index 00000000000..66c5e0c73b9 --- /dev/null +++ b/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor @@ -0,0 +1,3 @@ +@inherits LayoutComponentBase +@Body + diff --git a/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor.cs b/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor.cs new file mode 100644 index 00000000000..e4599f9bd34 --- /dev/null +++ b/src/Aspire.Dashboard/Components/Layout/WindowLayout.razor.cs @@ -0,0 +1,27 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Authentication; +using Aspire.Dashboard.Configuration; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.Extensions.Options; + +namespace Aspire.Dashboard.Components.Layout; + +/// +/// Provides a chromeless layout for dashboard windows that require authentication in secured modes. +/// +public partial class WindowLayout +{ + [Inject] + public required IOptions DashboardOptions { get; init; } + + [CascadingParameter] + public Task? AuthenticationState { get; set; } + + protected override async Task OnInitializedAsync() + { + await DashboardAuthenticationState.EnsureAuthenticatedAsync(DashboardOptions.Value, AuthenticationState); + } +} diff --git a/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor b/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor index a334dded8d9..06533fded28 100644 --- a/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor +++ b/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor @@ -1,7 +1,7 @@ @page "/terminal-window/apphost/{TerminalId}" @page "/terminal-window/resource/{ResourceName}" @page "/terminal-window/resource/{ResourceName}/{ReplicaIndex:int}" -@layout EmptyLayout +@layout WindowLayout @namespace Aspire.Dashboard.Components.Pages @using Aspire.Dashboard.Components.Controls @using Aspire.Dashboard.Components.Layout diff --git a/src/Aspire.Dashboard/Components/Routes.razor b/src/Aspire.Dashboard/Components/Routes.razor index 1b2af60faf4..1fd0db8690c 100644 --- a/src/Aspire.Dashboard/Components/Routes.razor +++ b/src/Aspire.Dashboard/Components/Routes.razor @@ -13,18 +13,34 @@ - - + + + + + + + + + + + + + - @Loc[nameof(Resources.Routes.NotFoundPageTitle)] - - - + + + + @Loc[nameof(Resources.Routes.NotFoundPageTitle)] + + + + + + + + - -@code { - private ViewportInformation? _viewportInformation; -} diff --git a/src/Aspire.Dashboard/Components/Routes.razor.cs b/src/Aspire.Dashboard/Components/Routes.razor.cs new file mode 100644 index 00000000000..20671c70631 --- /dev/null +++ b/src/Aspire.Dashboard/Components/Routes.razor.cs @@ -0,0 +1,9 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Aspire.Dashboard.Components; + +public partial class Routes +{ + private ViewportInformation? _viewportInformation; +} diff --git a/src/Aspire.Dashboard/Resources/Routes.Designer.cs b/src/Aspire.Dashboard/Resources/Routes.Designer.cs index 4405353182a..3b671fb21df 100644 --- a/src/Aspire.Dashboard/Resources/Routes.Designer.cs +++ b/src/Aspire.Dashboard/Resources/Routes.Designer.cs @@ -87,6 +87,15 @@ public static string ErrorHandlerPageTitle { } } + /// + /// Looks up a localized string similar to Not authorized. + /// + public static string NotAuthorized { + get { + return ResourceManager.GetString("NotAuthorized", resourceCulture); + } + } + /// /// Looks up a localized string similar to Not found. /// diff --git a/src/Aspire.Dashboard/Resources/Routes.resx b/src/Aspire.Dashboard/Resources/Routes.resx index 06ce6cfd2af..61439305a1f 100644 --- a/src/Aspire.Dashboard/Resources/Routes.resx +++ b/src/Aspire.Dashboard/Resources/Routes.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Not authorized + Not found diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.cs.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.cs.xlf index 12160a11f30..789f92e7fcd 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.cs.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.cs.xlf @@ -17,6 +17,11 @@ Chyba + + Not authorized + Not authorized + + Not found Nenalezeno diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.de.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.de.xlf index 01db1064342..e153b18ed93 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.de.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.de.xlf @@ -17,6 +17,11 @@ Fehler + + Not authorized + Not authorized + + Not found Nicht gefunden diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.es.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.es.xlf index c6d11cf9551..e1906da085b 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.es.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.es.xlf @@ -17,6 +17,11 @@ Error + + Not authorized + Not authorized + + Not found No encontrado diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.fr.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.fr.xlf index 38d349df090..36afafdf7ad 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.fr.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.fr.xlf @@ -17,6 +17,11 @@ Erreur + + Not authorized + Not authorized + + Not found Introuvable diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.it.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.it.xlf index 40517cf1b0c..2af54a66070 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.it.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.it.xlf @@ -17,6 +17,11 @@ Errore + + Not authorized + Not authorized + + Not found Non trovata diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.ja.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.ja.xlf index 317f99a9a12..50b59ca4500 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.ja.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.ja.xlf @@ -17,6 +17,11 @@ エラー + + Not authorized + Not authorized + + Not found 見つかりません diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.ko.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.ko.xlf index ff7a7d937be..2f9bc2f79ea 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.ko.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.ko.xlf @@ -17,6 +17,11 @@ 오류 + + Not authorized + Not authorized + + Not found 찾을 수 없음 diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.pl.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.pl.xlf index c41d3c4782c..cb3fd339e98 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.pl.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.pl.xlf @@ -17,6 +17,11 @@ Błąd + + Not authorized + Not authorized + + Not found Nie znaleziono diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.pt-BR.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.pt-BR.xlf index 585b1e445af..66f29a8aa58 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.pt-BR.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.pt-BR.xlf @@ -17,6 +17,11 @@ Erro + + Not authorized + Not authorized + + Not found Não encontrado diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.ru.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.ru.xlf index ff68409b273..02f34a0b89a 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.ru.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.ru.xlf @@ -17,6 +17,11 @@ Ошибка + + Not authorized + Not authorized + + Not found Не найдено diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.tr.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.tr.xlf index be229334f77..8b2e76b6dcf 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.tr.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.tr.xlf @@ -17,6 +17,11 @@ Hata + + Not authorized + Not authorized + + Not found Bulunamadı diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hans.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hans.xlf index b029001f585..58dec9ad62b 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hans.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hans.xlf @@ -17,6 +17,11 @@ 错误 + + Not authorized + Not authorized + + Not found 未找到 diff --git a/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hant.xlf b/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hant.xlf index ba27970d6dd..d7de90a7ae8 100644 --- a/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hant.xlf +++ b/src/Aspire.Dashboard/Resources/xlf/Routes.zh-Hant.xlf @@ -17,6 +17,11 @@ 錯誤 + + Not authorized + Not authorized + + Not found 找不到 diff --git a/tests/Aspire.Dashboard.Components.Tests/Controls/DashboardNotAuthorizedTests.cs b/tests/Aspire.Dashboard.Components.Tests/Controls/DashboardNotAuthorizedTests.cs new file mode 100644 index 00000000000..1f4ab092287 --- /dev/null +++ b/tests/Aspire.Dashboard.Components.Tests/Controls/DashboardNotAuthorizedTests.cs @@ -0,0 +1,70 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Components.Controls; +using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; +using Aspire.Dashboard.Utils; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace Aspire.Dashboard.Components.Tests.Controls; + +[UseCulture("en-US")] +public class DashboardNotAuthorizedTests : DashboardTestContext +{ + public DashboardNotAuthorizedTests() + { + Services.AddLocalization(); + } + + [Theory] + [InlineData("http://localhost/", "owned-missing?value=1", "/login", "/owned-missing?value=1")] + [InlineData("http://localhost/aspire/nested/", "owned-missing?value=1", "/aspire/nested/login", "/aspire/nested/owned-missing?value=1")] + [InlineData("http://localhost/aspire/nested/", "owned%20missing?value=a%2Fb&other=x%26y#details", "/aspire/nested/login", "/aspire/nested/owned%20missing?value=a%2Fb&other=x%26y#details")] + public void Render_BrowserToken_RedirectsToLogin(string baseUri, string missingPath, string expectedLoginPath, string expectedReturnUrl) + { + Services.AddSingleton>(Options.Create(CreateDashboardOptions(FrontendAuthMode.BrowserToken))); + var navigationManager = new TestNavigationManager(baseUri); + Services.AddSingleton(navigationManager); + navigationManager.NavigateTo(missingPath); + + var cut = Render(); + + Assert.Equal(string.Empty, cut.Markup); + var redirectedUri = navigationManager.ToAbsoluteUri(navigationManager.Uri); + Assert.Equal(new Uri(baseUri).Authority, redirectedUri.Authority); + Assert.Equal(expectedLoginPath, redirectedUri.AbsolutePath); + var returnUrl = QueryHelpers.ParseQuery(redirectedUri.Query)["returnUrl"].ToString(); + Assert.Equal(expectedReturnUrl, returnUrl); + Assert.True(UrlValidationHelper.IsSafeRedirectUrl(returnUrl)); + Assert.True(navigationManager.LastNavigationOptions is { ReplaceHistoryEntry: true }); + } + + [Theory] + [InlineData(FrontendAuthMode.OpenIdConnect)] + [InlineData(FrontendAuthMode.Unsecured)] + [InlineData(null)] + public void Render_OtherAuthMode_ShowsNotAuthorizedWithoutRedirect(FrontendAuthMode? authMode) + { + Services.AddSingleton>(Options.Create(CreateDashboardOptions(authMode))); + var navigationManager = Services.GetRequiredService(); + navigationManager.NavigateTo("/owned-missing"); + + var cut = Render(); + + Assert.Equal("http://localhost/owned-missing", navigationManager.Uri); + Assert.Equal("Not authorized", cut.Markup); + } + + private static DashboardOptions CreateDashboardOptions(FrontendAuthMode? authMode) + { + var options = new DashboardOptions(); + options.Frontend.AuthMode = authMode; + + return options; + } +} diff --git a/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs b/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs index 58de1b05cf6..d3438f2ecfb 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs @@ -5,6 +5,7 @@ using Aspire.Dashboard.Components.Pages; using Aspire.Dashboard.Components.Resize; using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Model; using Aspire.Dashboard.Model.Interaction; using Aspire.Dashboard.Telemetry; @@ -17,6 +18,7 @@ using Microsoft.AspNetCore.InternalTesting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; using Xunit; @@ -33,6 +35,39 @@ public InteractionsProviderTests(ITestOutputHelper testOutputHelper) _testOutputHelper = testOutputHelper; } + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public void Initialize_SecuredModeUnauthenticatedUser_Throws(FrontendAuthMode authMode) + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetNotAuthorized(); + SetupInteractionProviderServices(new TestDashboardClient(isEnabled: true)); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var exception = Assert.Throws(() => Render()); + Assert.Equal("Dashboard authentication is required, but the current user is not authenticated.", exception.Message); + } + + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public async Task Initialize_SecuredModeAuthenticatedUser_ProviderEnabledAsync(FrontendAuthMode authMode) + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetAuthorized("test-user"); + var interactionsChannel = Channel.CreateUnbounded(); + var dashboardClient = new TestDashboardClient(isEnabled: true, interactionChannelProvider: () => interactionsChannel); + SetupInteractionProviderServices(dashboardClient); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var cut = Render(builder => builder + .Add(p => p.ViewportInformation, new ViewportInformation(IsDesktop: true, IsUltraLowHeight: false, IsUltraLowWidth: false))); + + cut.WaitForAssertion(() => Assert.True(cut.Instance._enabled)); + await cut.Instance.DisposeAsync().DefaultTimeout(); + } + [Fact] public async Task Initialize_DashboardClientNotEnabled_ProviderDisabledAsync() { diff --git a/tests/Aspire.Dashboard.Components.Tests/Layout/DashboardDialogProviderTests.cs b/tests/Aspire.Dashboard.Components.Tests/Layout/DashboardDialogProviderTests.cs index 26f14fcaf3b..7a68a723aea 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Layout/DashboardDialogProviderTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Layout/DashboardDialogProviderTests.cs @@ -3,9 +3,11 @@ using Aspire.Dashboard.Components.Layout; using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; using Bunit; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; using Xunit; @@ -13,6 +15,20 @@ namespace Aspire.Dashboard.Components.Tests.Layout; public class DashboardDialogProviderTests : DashboardTestContext { + [Fact] + public void SecuredMode_UnauthenticatedUser_Throws() + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetNotAuthorized(); + FluentUISetupHelpers.SetupDialogInfrastructure(this); + var options = new DashboardOptions(); + options.Frontend.AuthMode = FrontendAuthMode.BrowserToken; + Services.AddSingleton>(Options.Create(options)); + + var exception = Assert.Throws(() => Render()); + Assert.Equal("Dashboard authentication is required, but the current user is not authenticated.", exception.Message); + } + [Theory] [InlineData("/traces")] [InlineData("/?hiddenTypes=Container")] diff --git a/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs b/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs index 972f5e5f0fc..e8ff4ea3990 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs @@ -29,6 +29,18 @@ public partial class MainLayoutTests : DashboardTestContext { private IRenderedComponent? _messageBarProvider; + [Fact] + public void OnInitialize_SecuredModeUnauthenticatedUser_Throws() + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetNotAuthorized(); + SetupMainLayoutServices(configureOptions: options => options.Frontend.AuthMode = FrontendAuthMode.BrowserToken); + + var exception = Assert.Throws(() => Render(builder => builder + .Add(p => p.ViewportInformation, new ViewportInformation(IsDesktop: true, IsUltraLowHeight: false, IsUltraLowWidth: false)))); + Assert.Equal("Dashboard authentication is required, but the current user is not authenticated.", exception.Message); + } + [Fact] public async Task OnInitialize_UnsecuredOtlp_NotDismissed_DisplayMessageBar() { diff --git a/tests/Aspire.Dashboard.Components.Tests/Layout/WindowLayoutTests.cs b/tests/Aspire.Dashboard.Components.Tests/Layout/WindowLayoutTests.cs new file mode 100644 index 00000000000..063d9bb7aa6 --- /dev/null +++ b/tests/Aspire.Dashboard.Components.Tests/Layout/WindowLayoutTests.cs @@ -0,0 +1,58 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Components.Layout; +using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.FluentUI.AspNetCore.Components; +using Xunit; + +namespace Aspire.Dashboard.Components.Tests.Layout; + +public class WindowLayoutTests : DashboardTestContext +{ + public WindowLayoutTests() + { + FluentUISetupHelpers.AddCommonDashboardServices(this); + } + + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public void Initialize_SecuredModeMissingAuthenticationState_Throws(FrontendAuthMode authMode) + { + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var exception = Assert.Throws(() => Render()); + + Assert.Equal("Dashboard authentication is required, but the current user is not authenticated.", exception.Message); + } + + [Theory] + [InlineData(FrontendAuthMode.BrowserToken, true)] + [InlineData(FrontendAuthMode.OpenIdConnect, true)] + [InlineData(FrontendAuthMode.Unsecured, false)] + [InlineData(null, false)] + public void Initialize_AllowedAuthenticationState_RendersBodyAndTooltipProvider(FrontendAuthMode? authMode, bool authenticated) + { + var authorizationContext = this.AddAuthorization(); + if (authenticated) + { + authorizationContext.SetAuthorized("test-user"); + } + else + { + authorizationContext.SetNotAuthorized(); + } + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var cut = Render(builder => builder + .Add(p => p.Body, bodyBuilder => bodyBuilder.AddMarkupContent(0, "
Window content
"))); + + Assert.Equal("Window content", cut.Find("#window-content").TextContent); + Assert.Single(cut.FindComponents()); + } +} diff --git a/tests/Aspire.Dashboard.Components.Tests/Pages/TerminalWindowTests.cs b/tests/Aspire.Dashboard.Components.Tests/Pages/TerminalWindowTests.cs index f9c1cb94ac6..afce30636a3 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Pages/TerminalWindowTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Pages/TerminalWindowTests.cs @@ -5,6 +5,7 @@ using Aspire.Dashboard.Components.Controls; using Aspire.Dashboard.Components.Pages; using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Tests.Shared; using Aspire.DashboardService.Proto.V1; using Bunit; @@ -12,6 +13,7 @@ using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.InternalTesting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.JSInterop; using Xunit; @@ -19,6 +21,51 @@ namespace Aspire.Dashboard.Components.Tests.Pages; public class TerminalWindowTests : DashboardTestContext { + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public void Initialize_SecuredModeUnauthenticatedUser_Throws(FrontendAuthMode authMode) + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetNotAuthorized(); + var client = new TestDashboardClient(isEnabled: true, + terminalChannelProvider: () => Channel.CreateUnbounded()); + TerminalSetupHelpers.SetupTerminalComponents(this, client); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var exception = Assert.Throws(() => Render(builder => builder + .Add(p => p.RouteData, new RouteData(typeof(TerminalWindow), new Dictionary + { + [nameof(TerminalWindow.TerminalId)] = "shell" + })))); + Assert.Equal("Dashboard authentication is required, but the current user is not authenticated.", exception.Message); + Assert.Equal(0, client.TerminalSubscriptionCount); + Assert.Equal([], JSInterop.Invocations.Where(i => i.Identifier == "initTerminal")); + } + + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public void Initialize_SecuredModeAuthenticatedUser_ShowsTerminal(FrontendAuthMode authMode) + { + var authorizationContext = this.AddAuthorization(); + authorizationContext.SetAuthorized("test-user"); + var client = new TestDashboardClient(isEnabled: true, + terminalChannelProvider: () => Channel.CreateUnbounded()); + TerminalSetupHelpers.SetupTerminalComponents(this, client); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var cut = Render(builder => builder + .Add(p => p.RouteData, new RouteData(typeof(TerminalWindow), new Dictionary + { + [nameof(TerminalWindow.TerminalId)] = "shell" + }))); + + Assert.Equal("api/apphost-terminal?terminalId=shell", cut.FindComponent().Instance.EndpointPathAndQuery); + cut.WaitForAssertion(() => Assert.Equal(1, client.TerminalSubscriptionCount)); + TerminalSetupHelpers.AssertSingleTerminalConnection(this, "ws://localhost/api/apphost-terminal?terminalId=shell"); + } + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs b/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs new file mode 100644 index 00000000000..fda42bc23dd --- /dev/null +++ b/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs @@ -0,0 +1,172 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Dashboard.Components.Controls; +using Aspire.Dashboard.Components.Layout; +using Aspire.Dashboard.Components.Pages; +using Aspire.Dashboard.Components.Resize; +using Aspire.Dashboard.Components.Tests.Shared; +using Aspire.Dashboard.Configuration; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace Aspire.Dashboard.Components.Tests; + +[UseCulture("en-US")] +public class RoutesTests : DashboardTestContext +{ + public RoutesTests() + { + FluentUISetupHelpers.AddCommonDashboardServices(this); + FluentUISetupHelpers.SetupFluentAnchor(this); + FluentUISetupHelpers.SetupFluentTextField(this); + JSInterop.SetupModule("/Components/Pages/Login.razor.js"); + JSInterop.Setup("window.getWindowDimensions").SetResult(new ViewportSize(1440, 1000)); + JSInterop.SetupVoid("window.listenToWindowResize", _ => true).SetVoidResult(); + } + + [Theory] + [InlineData("/")] + [InlineData("/error/404")] + [InlineData("/terminal-window/apphost/shell")] + [InlineData("/owned-missing")] + public void UnauthenticatedBrowserToken_RedirectsWithoutProtectedLayout(string route) + { + this.AddAuthorization().SetNotAuthorized(); + Services.GetRequiredService>().Value.Frontend.AuthMode = FrontendAuthMode.BrowserToken; + var navigation = Services.GetRequiredService(); + navigation.NavigateTo(route); + + var cut = Render(); + + cut.WaitForAssertion(() => + { + var uri = new Uri(navigation.Uri); + Assert.Equal("/login", uri.AbsolutePath); + Assert.Equal(route, QueryHelpers.ParseQuery(uri.Query)["returnUrl"]); + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } + + [Theory] + [InlineData(FrontendAuthMode.OpenIdConnect)] + [InlineData(FrontendAuthMode.Unsecured)] + [InlineData(null)] + public void UnauthenticatedNonBrowserToken_UsesEmptyLayoutAndLocalizedMessage(FrontendAuthMode? authMode) + { + this.AddAuthorization().SetNotAuthorized(); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Single(cut.FindComponents()); + Assert.Equal("Not authorized", string.Concat(cut.FindComponent().Nodes.Select(node => node.TextContent)).Trim()); + }); + } + + [Theory] + [InlineData(FrontendAuthMode.OpenIdConnect)] + [InlineData(FrontendAuthMode.Unsecured)] + [InlineData(null)] + public void UnauthenticatedNonBrowserToken_MissingRouteShowsLocalizedMessageWithoutProtectedLayout(FrontendAuthMode? authMode) + { + this.AddAuthorization().SetNotAuthorized(); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + Services.GetRequiredService().NavigateTo("/owned-missing"); + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Equal("Not authorized", cut.FindComponent().Markup); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } + + [Fact] + public void AuthenticatedUserWithoutFrontendPolicy_DoesNotUseMainLayout() + { + this.AddAuthorization().SetAuthorized("test-user"); + Services.GetRequiredService>().Value.Frontend.AuthMode = FrontendAuthMode.OpenIdConnect; + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Equal(typeof(EmptyLayout), cut.FindComponent().Instance.DefaultLayout); + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } + + [Theory] + [InlineData(FrontendAuthMode.BrowserToken)] + [InlineData(FrontendAuthMode.OpenIdConnect)] + public void PendingAuthorization_DoesNotRenderPageOrProtectedLayout(FrontendAuthMode authMode) + { + this.AddAuthorization().SetAuthorizing(); + Services.GetRequiredService>().Value.Frontend.AuthMode = authMode; + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } + + [Fact] + public void UnauthenticatedErrorPage_UsesEmptyLayout() + { + this.AddAuthorization().SetNotAuthorized(); + Services.GetRequiredService>().Value.Frontend.AuthMode = FrontendAuthMode.BrowserToken; + Services.GetRequiredService().NavigateTo("/error"); + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Single(cut.FindComponents()); + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } + + [Fact] + public void AuthenticatedUser_UsesMainLayoutByDefaultAndPreservesAnonymousPageLayout() + { + var authorization = this.AddAuthorization(); + authorization.SetAuthorized("test-user"); + authorization.SetPolicies(FrontendAuthorizationDefaults.PolicyName); + Services.GetRequiredService>().Value.Frontend.AuthMode = FrontendAuthMode.BrowserToken; + Services.GetRequiredService().NavigateTo("/error"); + + var cut = Render(); + + cut.WaitForAssertion(() => + { + Assert.Equal(typeof(MainLayout), cut.FindComponent().Instance.DefaultLayout); + Assert.Single(cut.FindComponents()); + Assert.Single(cut.FindComponents()); + Assert.Empty(cut.FindComponents()); + }); + } +} diff --git a/tests/Aspire.Dashboard.Components.Tests/Shared/TestNavigationManager.cs b/tests/Aspire.Dashboard.Components.Tests/Shared/TestNavigationManager.cs index 928f0aa401a..57f35e98855 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Shared/TestNavigationManager.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Shared/TestNavigationManager.cs @@ -7,6 +7,8 @@ namespace Aspire.Dashboard.Components.Tests.Shared; internal sealed class TestNavigationManager : NavigationManager { + public NavigationOptions? LastNavigationOptions { get; private set; } + public TestNavigationManager(string baseUri) { Initialize(baseUri, baseUri); @@ -17,4 +19,10 @@ protected override void NavigateToCore(string uri, bool forceLoad) Uri = ToAbsoluteUri(uri).AbsoluteUri; NotifyLocationChanged(isInterceptedLink: false); } + + protected override void NavigateToCore(string uri, NavigationOptions options) + { + LastNavigationOptions = options; + NavigateToCore(uri, options.ForceLoad); + } } diff --git a/tests/Aspire.Dashboard.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs b/tests/Aspire.Dashboard.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs index 69d71fb56be..802f46d1060 100644 --- a/tests/Aspire.Dashboard.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs +++ b/tests/Aspire.Dashboard.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Collections.Concurrent; using Aspire.TestUtilities; using Aspire.Dashboard.Configuration; using Aspire.Dashboard.Resources; @@ -166,6 +167,77 @@ await RunTestAsync(async page => }); } + [Fact] + [OuterloopTest("Resource-intensive Playwright browser test")] + public async Task BrowserToken_LoginPage_NavigateToMissingRoute_RemainsOnLoginPage() + { + const string missingPagePath = "/this-page-does-not-exist"; + + await RunTestAsync(async page => + { + await page.GotoAsync("/login").DefaultTimeout(); + await Assertions.Expect(SubmitButton(page)).ToBeVisibleAsync().DefaultTimeout(); + + await page.EvaluateAsync($"Blazor.navigateTo('{missingPagePath}')").DefaultTimeout(); + + await page.WaitForURLAsync(url => + { + var uri = new Uri(url); + var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query); + return uri.AbsolutePath == "/login" && query["returnUrl"] == missingPagePath; + }).DefaultTimeout(); + await Assertions.Expect(SubmitButton(page)).ToBeVisibleAsync().DefaultTimeout(); + }); + } + + [Theory] + [InlineData("/login", "/")] + [InlineData("/login", "/error/404")] + [InlineData("/login", "/terminal-window/apphost/shell")] + [InlineData("/error", "/")] + [InlineData("/error", "/error/404")] + [InlineData("/error", "/terminal-window/apphost/shell")] + [InlineData("/error", "/this-page-does-not-exist")] + [OuterloopTest("Resource-intensive Playwright browser test")] + public async Task BrowserToken_AnonymousPage_NavigateToProtectedRoute_RedirectsWithoutLayoutError(string initialPath, string destination) + { + await RunTestAsync(async page => + { + var errors = new ConcurrentQueue(); + page.PageError += (_, error) => errors.Enqueue(error); + page.Console += (_, message) => + { + if (message.Type == "error") + { + errors.Enqueue(message.Text); + } + }; + await page.GotoAsync(initialPath).DefaultTimeout(); + if (initialPath == "/login") + { + await Assertions.Expect(SubmitButton(page)).ToBeVisibleAsync().DefaultTimeout(); + } + else + { + await Assertions.Expect(page.GetByRole(AriaRole.Heading, new() { Name = "Error", Exact = true })) + .ToBeVisibleAsync().DefaultTimeout(); + } + + await page.EvaluateAsync("destination => Blazor.navigateTo(destination)", destination).DefaultTimeout(); + + await page.WaitForURLAsync(url => + { + var uri = new Uri(url); + var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query); + return uri.AbsolutePath == "/login" && query["returnUrl"] == destination; + }).DefaultTimeout(); + await Assertions.Expect(SubmitButton(page)).ToBeVisibleAsync().DefaultTimeout(); + await Assertions.Expect(page.Locator(".layout, #dashboard-settings-button, .terminal-window")) + .ToHaveCountAsync(0).DefaultTimeout(); + Assert.Equal([], errors); + }); + } + private static ILocator SubmitButton(IPage page) => page.Locator("fluent-button[name='submit-token']"); } From c408ec5bf44e43203c278990a43aea93145248f3 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Tue, 3 Nov 2026 23:46:22 +0000 Subject: [PATCH 2/5] Merged PR 68060: Remove temporary-file logging from deprecated MCP scanner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description Stop `DeprecatedMcpCommandScanner` from unconditionally writing agent configuration paths, configuration content, and scan diagnostics to the shared temporary file `aspire-deprecated-scan.log`. Remove only the temporary-file diagnostic logging. Preserve the existing structured `ILogger` debug messages, deprecated-command detection, configuration migration prompts, and configuration updates. This is a focused fix for `internal/release/13.6`, not a backport of the broader agent-client selection changes. No new dependencies. Fixes # (issue) ### User-facing usage Running `aspire agent init` continues to detect and offer to update deprecated `aspire mcp start` configurations, without writing the scan diagnostics or configuration content to `aspire-deprecated-scan.log`. ### Validation - `./restore.sh` — passed. - `MSBUILDTERMINALLOGGER=false dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- --filter-class '*.AgentEnvironmentDetectorTests' --filter-class '*.AgentInitCommandTests' --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true'` — passed, 49 tests. - `git diff --check` — passed. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [ ] Yes - [x] No - Did you add public API? - [ ] Yes - If yes, did you have an API Review for it? - [ ] Yes - [ ] No - Did you add `` and `` elements on your triple slash comments? - [ ] Yes - [ ] No - [x] No - Does the change make any security assumptions or guarantees? - [ ] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [ ] No - [x] No ---- #### AI description (iteration 1) #### PR Classification Code cleanup: removal of leftover debug/temporary-file logging code. #### PR Summary Removes debug logging statements that wrote diagnostic information to a temporary file in the deprecated MCP command scanner. - `src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs`: Removed all `File.AppendAllText` debug logging calls to a temp file, keeping only existing `_logger.LogDebug` calls for error handling. --- .../Agents/DeprecatedMcpCommandScanner.cs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs b/src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs index 5e532dc765b..31d134ab2f2 100644 --- a/src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs +++ b/src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs @@ -41,37 +41,26 @@ public Task ScanAsync(AgentEnvironmentScanContext context, CancellationToken can { _logger.LogDebug("Scanning for deprecated MCP command usage in agent configurations"); - // Debug: Write scanning info to temp file for diagnostics - var debugPath = Path.Combine(Path.GetTempPath(), "aspire-deprecated-scan.log"); - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] Scanning context.RepositoryRoot: {context.RepositoryRoot.FullName}\n"); - foreach (var location in s_configLocations) { var configPath = Path.Combine(context.RepositoryRoot.FullName, location.RelativePath); - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] Checking {location.AgentName}: {configPath}\n"); if (!File.Exists(configPath)) { - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> File does not exist\n"); continue; } - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> File EXISTS!\n"); - try { var content = File.ReadAllText(configPath); - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> Content: {content.Substring(0, Math.Min(200, content.Length))}\n"); var config = JsonNode.Parse(content)?.AsObject(); if (config is null) { - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> JSON parse returned null\n"); continue; } var hasDeprecated = HasDeprecatedMcpCommand(config, location); - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> HasDeprecatedMcpCommand: {hasDeprecated}\n"); if (hasDeprecated) { @@ -80,17 +69,14 @@ public Task ScanAsync(AgentEnvironmentScanContext context, CancellationToken can // Create an applicator to update this config var applicator = CreateUpdateApplicator(location, configPath, config); context.AddApplicator(applicator); - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> Added applicator\n"); } } catch (JsonException ex) { - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> JsonException: {ex.Message}\n"); _logger.LogDebug(ex, "Failed to parse {AgentName} config at {Path}", location.AgentName, configPath); } catch (IOException ex) { - File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> IOException: {ex.Message}\n"); _logger.LogDebug(ex, "Failed to read {AgentName} config at {Path}", location.AgentName, configPath); } } From f017f668fd6e0938e23058dc0450a1403f409809 Mon Sep 17 00:00:00 2001 From: Karol Zadora-Przylecki Date: Fri, 6 Nov 2026 20:44:14 +0000 Subject: [PATCH 3/5] Merged PR 68055: Limit automatic dashboard tunnelling to OTLP endpoints Preserves explicit dashboard endpoint references and ordinary host-resource tunneling. Normalizes legacy host URLs into endpoint references at the dependency-discovery boundary. ---- #### AI description (iteration 1) #### PR Classification Bug fix / feature refinement: restricts automatic dashboard container tunnelling to only OTLP endpoints instead of all dashboard endpoints. #### PR Summary Adds extensive test coverage validating that dashboard tunnelling only exposes OTLP endpoints automatically while preserving explicit endpoint references and legacy tunnel behavior, along with new dashboard routing tests for authentication/authorization layout behavior. - `DcpExecutorTests.cs`: Adds many new test cases verifying `DashboardTunnelAutomaticallyExposesOnlyOtlpEndpoints` only tunnels OTLP gRPC/HTTP endpoints, not all dashboard endpoints. - `DcpExecutorTests.cs`: Adds tests ensuring explicit references (environment, arguments, expressions, properties, host-url, reference) to non-OTLP dashboard endpoints are preserved and tunneled correctly. - `DcpExecutorTests.cs`: Adds tests for caching behavior, legacy container tunnel mode compatibility, and multi-consumer endpoint accumulation. - `RoutesTests.cs` (new file): Adds tests validating dashboard routing/layout behavior under various authentication states (browser token, OpenID Connect, unsecured, pending authorization) ensuring correct layout and redirect behavior. --- .../ApplicationModel/HostUrl.cs | 32 +- .../ApplicationModel/ResourceExtensions.cs | 26 ++ src/Aspire.Hosting/Dcp/ContainerCreator.cs | 51 +++ .../Dcp/DcpExecutorTests.cs | 398 ++++++++++++++++++ .../ExecutionConfigurationGathererTests.cs | 99 +++++ 5 files changed, 592 insertions(+), 14 deletions(-) diff --git a/src/Aspire.Hosting/ApplicationModel/HostUrl.cs b/src/Aspire.Hosting/ApplicationModel/HostUrl.cs index 47ff9eefe4b..c827ccbb9f6 100644 --- a/src/Aspire.Hosting/ApplicationModel/HostUrl.cs +++ b/src/Aspire.Hosting/ApplicationModel/HostUrl.cs @@ -62,20 +62,7 @@ public record HostUrl(string Url) : IExpressionValue, IValueProvider, IManifestE // If we're running with the container tunnel enabled, we need to lookup the port on the tunnel that corresponds to the // target port on the host machine. - targetEndpoint = model.Resources.Where(r => !r.IsContainer()) - .OfType() - .Select(r => - { - // Find if the resource has a host endpoint with a port matching the one from the request - if (r.Annotations.OfType().FirstOrDefault(ep => MatchesHostPort(ep, uri.Port)) is EndpointAnnotation ep) - { - // Return the corresponding endpoint for the container network context. This will be used to determine the port to use when connecting from the container to the host machine. - return r.GetEndpoint(ep.Name, networkContext); - } - - return null; - }) - .FirstOrDefault(ep => ep is not null); + targetEndpoint = GetEndpointReference(model, uri.Port, networkContext); } if (targetEndpoint is { }) @@ -147,6 +134,23 @@ internal static bool TryGetLocalHostPort(string url, out int port) } } + /// + /// Finds the first host endpoint matching a port in the requested network context. + /// + internal static EndpointReference? GetEndpointReference(DistributedApplicationModel model, int port, NetworkIdentifier networkContext) + { + foreach (var resource in model.Resources.Where(resource => !resource.IsContainer()).OfType()) + { + var endpoint = resource.Annotations.OfType().FirstOrDefault(endpoint => MatchesHostPort(endpoint, port)); + if (endpoint is not null) + { + return resource.GetEndpoint(endpoint.Name, networkContext); + } + } + + return null; + } + internal static bool MatchesHostPort(EndpointAnnotation endpoint, int port) { return endpoint.DefaultNetworkID == KnownNetworkIdentifiers.LocalhostNetwork && endpoint.Port == port; diff --git a/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs b/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs index a570ed4c9fe..3f7c2b2fd40 100644 --- a/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs +++ b/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs @@ -1825,6 +1825,32 @@ internal static IReadOnlyList GetReferences(this IExecutionConfigurationGa return [.. references]; } + /// + /// Gets endpoint references from unresolved configuration, normalizing legacy host URLs. + /// + internal static IReadOnlyList GetEndpointReferences( + this IExecutionConfigurationGathererContext context, + DistributedApplicationModel model, + NetworkIdentifier networkContext) + { + var references = new List(); + foreach (var reference in context.GetReferences()) + { + if (reference is EndpointReference endpoint) + { + references.Add(endpoint); + } + else if (reference is HostUrl hostUrl && + HostUrl.TryGetLocalHostPort(hostUrl.Url, out var port) && + HostUrl.GetEndpointReference(model, port, networkContext) is { } legacyEndpoint) + { + references.Add(legacyEndpoint); + } + } + + return references; + } + private static IEnumerable GetUnresolvedValues(IExecutionConfigurationGathererContext context) { foreach (var argument in context.Arguments) diff --git a/src/Aspire.Hosting/Dcp/ContainerCreator.cs b/src/Aspire.Hosting/Dcp/ContainerCreator.cs index 77a4ee97e64..9324e38801d 100644 --- a/src/Aspire.Hosting/Dcp/ContainerCreator.cs +++ b/src/Aspire.Hosting/Dcp/ContainerCreator.cs @@ -345,9 +345,60 @@ internal async Task> GetHostDependenciesA } } + if (_options.Value.EnableAspireContainerTunnel) + { + var dashboardIndex = hostDependencies.FindIndex(dependency => + StringComparers.ResourceName.Equals(dependency.Resource.Name, KnownResourceNames.AspireDashboard)); + if (dashboardIndex >= 0) + { + // Telemetry must not implicitly expose the dashboard frontend. Preserve explicit endpoint + // references without narrowing the endpoints exposed for ordinary host dependencies. + var dashboard = hostDependencies[dashboardIndex]; + var endpoints = await GetDashboardTunnelEndpointsAsync(resource, dashboard, cancellationToken).ConfigureAwait(false); + hostDependencies.RemoveAll(dependency => + StringComparers.ResourceName.Equals(dependency.Resource.Name, KnownResourceNames.AspireDashboard)); + if (endpoints.Length > 0) + { + hostDependencies.Add(new HostResourceWithEndpoints(dashboard.Resource, endpoints)); + } + } + } + return hostDependencies; } + private async Task GetDashboardTunnelEndpointsAsync( + IResource resource, + HostResourceWithEndpoints dashboard, + CancellationToken cancellationToken) + { + // Reuse discovery's cached callbacks without resolving values: the container-network + // services needed to resolve endpoint references have not been provisioned yet. + var context = new ExecutionConfigurationGathererContext(); + var resourceLogger = _loggerService.GetLogger(resource); + await new EnvironmentVariablesExecutionConfigurationGatherer() + .GatherAsync(context, resource, resourceLogger, _executionContext, cancellationToken).ConfigureAwait(false); + await new ArgumentsExecutionConfigurationGatherer() + .GatherAsync(context, resource, resourceLogger, _executionContext, cancellationToken).ConfigureAwait(false); + + var endpointNames = new HashSet(StringComparers.EndpointAnnotationName) + { + KnownEndpointNames.OtlpGrpcEndpointName, + KnownEndpointNames.OtlpHttpEndpointName + }; + var callerNetwork = resource.GetDefaultResourceNetwork(); + foreach (var endpoint in context.GetEndpointReferences(_model, callerNetwork)) + { + if (StringComparers.ResourceName.Equals(endpoint.Resource.Name, dashboard.Resource.Name) && + (endpoint.ContextNetworkID ?? callerNetwork) == KnownNetworkIdentifiers.DefaultAspireContainerNetwork) + { + endpointNames.Add(endpoint.EndpointName); + } + } + + return dashboard.Endpoints.Where(endpoint => endpointNames.Contains(endpoint.Name)).ToArray(); + } + internal async Task CreateHostDependentContainerAsync(RenderedModelResource cr, ImmutableArray hostDependencies, ContainerNetworkEndpointContext context, IDcpObjectFactory factory, CancellationToken cToken) { cToken.ThrowIfCancellationRequested(); diff --git a/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs b/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs index a82dab05889..52602191040 100644 --- a/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs +++ b/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs @@ -9471,6 +9471,362 @@ async ValueTask AssertEndpoint(IResourceWithEndpoints resource, string name, Net } } + [Theory] + [InlineData(true, false, false, "aspire-dashboard", OtlpProtocol.Grpc)] + [InlineData(false, true, false, "aspire-dashboard", OtlpProtocol.HttpProtobuf)] + [InlineData(true, true, false, "aspire-dashboard", OtlpProtocol.Grpc)] + [InlineData(true, true, false, "aspire-dashboard", OtlpProtocol.HttpProtobuf)] + [InlineData(true, true, true, "aspire-dashboard", OtlpProtocol.Grpc)] + [InlineData(true, true, false, "ASPIRE-DASHBOARD", OtlpProtocol.Grpc)] + public async Task DashboardTunnelAutomaticallyExposesOnlyOtlpEndpoints(bool includeGrpc, bool includeHttp, bool useProject, string dashboardName, OtlpProtocol protocol) + { + var builder = DistributedApplication.CreateBuilder(); + IResourceBuilder dashboard = useProject + ? builder.AddProject(dashboardName, launchProfileName: null) + : builder.AddExecutable(dashboardName, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc, includeHttp); + builder.AddContainer("telemetry", "image").WithOtlpExporter(protocol); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + var expectedEndpoints = new List(); + if (includeGrpc) + { + expectedEndpoints.Add(KnownEndpointNames.OtlpGrpcEndpointName); + } + if (includeHttp) + { + expectedEndpoints.Add(KnownEndpointNames.OtlpHttpEndpointName); + } + + var tunnelServices = AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, [.. expectedEndpoints]); + var exporterEndpointName = protocol == OtlpProtocol.Grpc + ? KnownEndpointNames.OtlpGrpcEndpointName + : KnownEndpointNames.OtlpHttpEndpointName; + var exporterService = Assert.Single(tunnelServices, service => service.EndpointName == exporterEndpointName); + var container = Assert.Single(kubernetesService.CreatedResources.OfType()); + Assert.NotNull(container.Spec.Env); + Assert.Equal( + $"http://{KnownHostNames.DefaultContainerTunnelHostName}:{exporterService.AllocatedPort}", + Assert.Single(container.Spec.Env, variable => variable.Name == KnownOtelConfigNames.ExporterOtlpEndpoint).Value); + Assert.Equal( + protocol == OtlpProtocol.Grpc ? "grpc" : "http/protobuf", + Assert.Single(container.Spec.Env, variable => variable.Name == KnownOtelConfigNames.ExporterOtlpProtocol).Value); + + var frontendUrl = await dashboard.GetEndpoint("http").GetValueAsync().DefaultTimeout(); + Assert.Equal("http://localhost:18888", frontendUrl); + } + + [Theory] + [InlineData("environment", false)] + [InlineData("environment", true)] + [InlineData("arguments", true)] + [InlineData("expression", true)] + [InlineData("property", true)] + [InlineData("reference", true)] + [InlineData("all-references", true)] + [InlineData("excluded-reference", true)] + [InlineData("host-url", true)] + public async Task DashboardTunnelPreservesExplicitReferences(string referenceKind, bool withExporter) + { + var builder = DistributedApplication.CreateBuilder(); + IResourceBuilder dashboard = referenceKind == "all-references" + ? builder.AddProject(KnownResourceNames.AspireDashboard, launchProfileName: null) + : builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + var container = builder.AddContainer("consumer", "image"); + if (withExporter) + { + container.WithOtlpExporter(); + } + + switch (referenceKind) + { + case "environment": + container.WithEnvironment("DASHBOARD_UI", dashboard.GetEndpoint("http")); + break; + case "arguments": + container.WithArgs(dashboard.GetEndpoint("http")); + break; + case "expression": + container.WithEnvironment("DASHBOARD_UI", ReferenceExpression.Create($"{dashboard.GetEndpoint("http")}/path")); + break; + case "property": + container.WithEnvironment("DASHBOARD_PORT", dashboard.GetEndpoint("http").Property(EndpointProperty.Port)); + break; + case "reference": + container.WithReference(dashboard.GetEndpoint("http")); + break; + case "all-references": + container.WithReference(dashboard); + break; + case "excluded-reference": + container.WithReference(dashboard.GetEndpoint("diagnostics")); + break; + case "host-url": + container.WithEnvironment("DASHBOARD_UI", new HostUrl("http://localhost:18888/path")); + break; + default: + throw new InvalidOperationException($"Unexpected reference kind '{referenceKind}'."); + } + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + var expectedEndpoints = new List + { + KnownEndpointNames.OtlpGrpcEndpointName, + KnownEndpointNames.OtlpHttpEndpointName, + referenceKind == "excluded-reference" ? "diagnostics" : "http" + }; + if (referenceKind == "all-references") + { + expectedEndpoints.Add("https"); + } + + var tunnelServices = AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, [.. expectedEndpoints]); + var referencedEndpointName = referenceKind == "excluded-reference" ? "diagnostics" : "http"; + var referencedService = Assert.Single(tunnelServices, service => service.EndpointName == referencedEndpointName); + var expectedUrl = $"http://{KnownHostNames.DefaultContainerTunnelHostName}:{referencedService.AllocatedPort}"; + var dcpContainer = Assert.Single(kubernetesService.CreatedResources.OfType()); + Assert.NotNull(dcpContainer.Spec.Env); + + switch (referenceKind) + { + case "environment": + Assert.Equal(expectedUrl, Assert.Single(dcpContainer.Spec.Env, variable => variable.Name == "DASHBOARD_UI").Value); + break; + case "arguments": + Assert.Equal([expectedUrl], dcpContainer.Spec.Args); + break; + case "expression": + case "host-url": + Assert.Equal($"{expectedUrl}/path", Assert.Single(dcpContainer.Spec.Env, variable => variable.Name == "DASHBOARD_UI").Value); + break; + case "property": + Assert.Equal(referencedService.AllocatedPort.ToString(), Assert.Single(dcpContainer.Spec.Env, variable => variable.Name == "DASHBOARD_PORT").Value); + break; + case "reference": + case "all-references": + case "excluded-reference": + Assert.Equal( + expectedUrl, + Assert.Single(dcpContainer.Spec.Env, variable => variable.Name == $"services__{dashboard.Resource.Name}__{referencedEndpointName}__0").Value); + break; + } + } + + [Fact] + public async Task DashboardTunnelUsesEffectiveCachedConfiguration() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + var environmentCalls = 0; + var argumentCalls = 0; + builder.AddContainer("telemetry", "image") + .WithOtlpExporter() + .WithEnvironment(context => + { + Interlocked.Increment(ref environmentCalls); + context.EnvironmentVariables["DASHBOARD_UI"] = dashboard.GetEndpoint("http"); + context.EnvironmentVariables["DASHBOARD_STATE"] = "enabled"; + }) + .WithEnvironment(context => context.EnvironmentVariables.Remove("DASHBOARD_UI")) + .WithArgs(context => + { + Interlocked.Increment(ref argumentCalls); + context.Args.Add(dashboard.GetEndpoint("https")); + }) + .WithArgs(context => context.Args.Clear()); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, KnownEndpointNames.OtlpGrpcEndpointName, KnownEndpointNames.OtlpHttpEndpointName); + Assert.Equal(1, environmentCalls); + Assert.Equal(1, argumentCalls); + var container = Assert.Single(kubernetesService.CreatedResources.OfType()); + Assert.NotNull(container.Spec.Env); + Assert.Equal( + [("DASHBOARD_STATE", "enabled")], + container.Spec.Env + .Where(variable => variable.Name is { } name && name.StartsWith("DASHBOARD_", StringComparison.Ordinal)) + .Select(variable => (variable.Name, variable.Value))); + Assert.Empty(container.Spec.Args ?? []); + } + + [Fact] + public async Task DashboardTunnelPreservesExplicitLocalhostReferenceWithoutTunnelingIt() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + builder.AddContainer("telemetry", "image") + .WithOtlpExporter() + .WithEnvironment("DASHBOARD_UI", dashboard.GetEndpoint("http", KnownNetworkIdentifiers.LocalhostNetwork)); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, KnownEndpointNames.OtlpGrpcEndpointName, KnownEndpointNames.OtlpHttpEndpointName); + var container = Assert.Single(kubernetesService.CreatedResources.OfType()); + Assert.NotNull(container.Spec.Env); + Assert.Equal("http://localhost:18888", Assert.Single(container.Spec.Env, variable => variable.Name == "DASHBOARD_UI").Value); + } + + [Fact] + public async Task DashboardTunnelAccumulatesExplicitEndpointsAcrossConsumers() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + builder.AddContainer("telemetry", "image").WithOtlpExporter(); + var consumer = builder.AddContainer("consumer", "image") + .WithExplicitStart() + .WithEnvironment("DASHBOARD_UI", dashboard.GetEndpoint("http")); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, KnownEndpointNames.OtlpGrpcEndpointName, KnownEndpointNames.OtlpHttpEndpointName); + + var reference = executor.GetResource(DcpExecutor.GetDcpInstance(consumer.Resource, instanceIndex: 0).Name); + await executor.StartResourceAsync(reference, CancellationToken.None).DefaultTimeout(); + + var tunnelServices = AssertTunnelEndpoints( + kubernetesService, + dashboard.Resource.Name, + KnownEndpointNames.OtlpGrpcEndpointName, + KnownEndpointNames.OtlpHttpEndpointName, + "http"); + var uiService = Assert.Single(tunnelServices, service => service.EndpointName == "http"); + var dcpConsumer = Assert.Single(kubernetesService.CreatedResources.OfType(), container => container.AppModelResourceName == consumer.Resource.Name); + Assert.NotNull(dcpConsumer.Spec.Env); + Assert.Equal( + $"http://{KnownHostNames.DefaultContainerTunnelHostName}:{uiService.AllocatedPort}", + Assert.Single(dcpConsumer.Spec.Env, variable => variable.Name == "DASHBOARD_UI").Value); + } + + [Fact] + public async Task DashboardTunnelPreservesExplicitExecutableReference() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + builder.AddContainer("container", "image"); + var consumer = builder.AddExecutable("consumer", "command", "") + .WithEnvironment("DASHBOARD_UI", dashboard.GetEndpoint("http", KnownNetworkIdentifiers.DefaultAspireContainerNetwork)); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + var tunnelService = Assert.Single(AssertTunnelEndpoints(kubernetesService, dashboard.Resource.Name, "http")); + var executable = Assert.Single(kubernetesService.CreatedResources.OfType(), resource => resource.AppModelResourceName == consumer.Resource.Name); + Assert.NotNull(executable.Spec.Env); + Assert.Equal( + $"http://{KnownHostNames.DefaultContainerTunnelHostName}:{tunnelService.AllocatedPort}", + Assert.Single(executable.Spec.Env, variable => variable.Name == "DASHBOARD_UI").Value); + } + + [Fact] + public async Task DashboardTunnelDoesNotCreateTunnelWhenNoEndpointsAreSelected() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: false, includeHttp: false); + builder.AddContainer("container", "image").WaitFor(dashboard); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + Assert.Empty(kubernetesService.CreatedResources.OfType()); + Assert.Equal( + ["diagnostics", "http", "https"], + kubernetesService.CreatedResources.OfType() + .Select(service => service.EndpointName) + .Order(StringComparers.EndpointAnnotationName)); + Assert.Single(kubernetesService.CreatedResources.OfType()); + } + + [Fact] + public async Task DashboardTunnelPreservesLegacyMode() + { + var builder = DistributedApplication.CreateBuilder(); + var dashboard = builder.AddExecutable(KnownResourceNames.AspireDashboard, "command", ""); + AddDashboardTunnelEndpoints(dashboard, includeGrpc: true, includeHttp: true); + builder.AddContainer("telemetry", "image").WithOtlpExporter(); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService, + dcpOptions: new DcpOptions { EnableAspireContainerTunnel = false }); + await executor.RunApplicationAsync().DefaultTimeout(); + + Assert.Empty(kubernetesService.CreatedResources.OfType()); + var containerNetworkServices = kubernetesService.CreatedResources.OfType() + .Where(service => service.AppModelResourceName == dashboard.Resource.Name && + service.Metadata.Annotations.ContainsKey(CustomResource.ContainerNetworkAnnotation)); + Assert.Equal( + new[] { "diagnostics", "http", "https", KnownEndpointNames.OtlpGrpcEndpointName, KnownEndpointNames.OtlpHttpEndpointName }.Order(StringComparers.EndpointAnnotationName), + containerNetworkServices.Select(service => service.EndpointName).Order(StringComparers.EndpointAnnotationName)); + Assert.Equal( + "http://host.docker.internal:18888", + await dashboard.GetEndpoint("http", KnownNetworkIdentifiers.DefaultAspireContainerNetwork).GetValueAsync().DefaultTimeout()); + } + + [Fact] + public async Task ContainerTunnelPreservesAllNonDashboardHostEndpoints() + { + var builder = DistributedApplication.CreateBuilder(); + var executable = builder.AddExecutable("program", "command", "") + .WithEndpoint(name: "http", scheme: "http", port: 18888, targetPort: 11888, isProxied: true) + .WithEndpoint(name: "admin", port: 18889, targetPort: 11889, isProxied: true) + .WithEndpoint(name: KnownEndpointNames.OtlpGrpcEndpointName, port: 4317, targetPort: 14317, isProxied: true); + builder.AddContainer("consumer", "image") + .WithEnvironment("PROGRAM_URL", executable.GetEndpoint("http")); + + var kubernetesService = new TestKubernetesService(); + using var app = builder.Build(); + await using var executor = CreateAppExecutor( + app.Services.GetRequiredService(), + kubernetesService: kubernetesService); + await executor.RunApplicationAsync().DefaultTimeout(); + + AssertTunnelEndpoints(kubernetesService, executable.Resource.Name, "http", "admin", KnownEndpointNames.OtlpGrpcEndpointName); + } + [Fact] public async Task ContainerHostUrlWithoutMatchingHostEndpointUsesContainerHostBridge() { @@ -11113,6 +11469,48 @@ public void EnsureContainerVolumesReady_AllowsReadyVolumes() DcpExecutor.EnsureContainerVolumesReady([volume]); } + private static void AddDashboardTunnelEndpoints(IResourceBuilder dashboard, bool includeGrpc, bool includeHttp) where T : IResourceWithEndpoints + { + dashboard + .WithEndpoint(name: "http", scheme: "http", port: 18888, targetPort: 11888, isProxied: true) + .WithEndpoint(name: "https", scheme: "https", port: 18889, targetPort: 11889, isProxied: true) + .WithEndpoint(name: "diagnostics", scheme: "http", port: 18890, targetPort: 11890, isProxied: true) + .WithEndpoint("diagnostics", endpoint => endpoint.ExcludeReferenceEndpoint = true); + if (includeGrpc) + { + dashboard.WithEndpoint(name: KnownEndpointNames.OtlpGrpcEndpointName, scheme: "http", port: 4317, targetPort: 14317, isProxied: true); + } + if (includeHttp) + { + dashboard.WithEndpoint(name: KnownEndpointNames.OtlpHttpEndpointName, scheme: "http", port: 4318, targetPort: 14318, isProxied: true); + } + } + + private static Service[] AssertTunnelEndpoints(TestKubernetesService kubernetesService, string resourceName, params string[] expectedEndpoints) + { + var services = kubernetesService.CreatedResources.OfType() + .Where(service => StringComparers.ResourceName.Equals(service.AppModelResourceName, resourceName) && + service.Metadata.Annotations.ContainsKey(CustomResource.ContainerTunnelInstanceName)) + .ToArray(); + Assert.Equal( + expectedEndpoints.Order(StringComparers.EndpointAnnotationName), + services.Select(service => service.EndpointName).Order(StringComparers.EndpointAnnotationName)); + + var proxy = Assert.Single(kubernetesService.CreatedResources.OfType()); + Assert.NotNull(proxy.Spec.Tunnels); + Assert.Equal( + services.Select(service => service.Metadata.Name).Order(StringComparer.Ordinal), + proxy.Spec.Tunnels.Select(tunnel => tunnel.ClientServiceName).Order(StringComparer.Ordinal)); + foreach (var service in services) + { + var tunnel = Assert.Single(proxy.Spec.Tunnels, tunnel => tunnel.ClientServiceName == service.Metadata.Name); + Assert.Equal(service.Metadata.Name, tunnel.Name); + Assert.Equal(service.Metadata.Annotations[CustomResource.PrimaryServiceNameAnnotation], tunnel.ServerServiceName); + } + + return services; + } + private static DcpExecutor CreateAppExecutor( DistributedApplicationModel distributedAppModel, IHostEnvironment? hostEnvironment = null, diff --git a/tests/Aspire.Hosting.Tests/ExecutionConfigurationGathererTests.cs b/tests/Aspire.Hosting.Tests/ExecutionConfigurationGathererTests.cs index 6b29f98ce51..ca1d9aa093e 100644 --- a/tests/Aspire.Hosting.Tests/ExecutionConfigurationGathererTests.cs +++ b/tests/Aspire.Hosting.Tests/ExecutionConfigurationGathererTests.cs @@ -142,6 +142,105 @@ public async Task GetReferencesFindsEndpointReferencesAcrossExecutionConfigurati Assert.Equal( [argumentReference, environmentReference, launchToolReference], references.OrderBy(reference => reference.EndpointName)); + + var endpointReferences = context.GetEndpointReferences( + new DistributedApplicationModel(builder.Resources), + KnownNetworkIdentifiers.LocalhostNetwork); + Assert.Equal( + [argumentReference, environmentReference, launchToolReference], + endpointReferences.OrderBy(reference => reference.EndpointName)); + } + + [Theory] + [InlineData("http://localhost:17092/path", true)] + [InlineData("http://127.0.0.1:17092/path", true)] + [InlineData("http://[::1]:17092/path", true)] + [InlineData("http://localhost:17093/path", false)] + [InlineData("http://collector.example:17092/path", false)] + [InlineData("Server=localhost;Database=test", false)] + public void GetEndpointReferencesNormalizesLegacyHostUrls(string url, bool matchesEndpoint) + { + using var builder = TestDistributedApplicationBuilder.Create(); + var target = builder.AddExecutable("target", "target.exe", ".") + .WithEndpoint(name: "http", port: 17092, targetPort: 5000); + var hostUrl = new HostUrl(url); + var context = new ExecutionConfigurationGathererContext(); + context.EnvironmentVariables["TARGET_URL"] = ReferenceExpression.Create($"{hostUrl}"); + context.Arguments.Add(ReferenceExpression.Create($"{hostUrl}")); + + var references = context.GetEndpointReferences( + new DistributedApplicationModel(builder.Resources), + KnownNetworkIdentifiers.DefaultAspireContainerNetwork); + + if (matchesEndpoint) + { + var endpoint = Assert.Single(references); + Assert.Same(target.Resource, endpoint.Resource); + Assert.Equal("http", endpoint.EndpointName); + Assert.Equal(KnownNetworkIdentifiers.DefaultAspireContainerNetwork, endpoint.ContextNetworkID); + } + else + { + Assert.Empty(references); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void GetEndpointReferencesPreservesNetworkContext(bool containerNetwork) + { + using var builder = TestDistributedApplicationBuilder.Create(); + var target = builder.AddExecutable("target", "target.exe", ".") + .WithEndpoint(name: "http", port: 17092, targetPort: 5000) + .WithEndpoint(name: "modeled", port: 17093, targetPort: 5001); + var modeledReference = target.GetEndpoint("modeled", KnownNetworkIdentifiers.DefaultAspireContainerNetwork); + var networkContext = containerNetwork + ? KnownNetworkIdentifiers.DefaultAspireContainerNetwork + : KnownNetworkIdentifiers.LocalhostNetwork; + var context = new ExecutionConfigurationGathererContext(); + context.Arguments.Add(modeledReference); + context.EnvironmentVariables["TARGET_URL"] = new HostUrl("http://localhost:17092/path"); + + var references = context.GetEndpointReferences(new DistributedApplicationModel(builder.Resources), networkContext); + + Assert.Collection(references.OrderBy(endpoint => endpoint.EndpointName, StringComparers.EndpointAnnotationName), + endpoint => + { + Assert.Same(target.Resource, endpoint.Resource); + Assert.Equal("http", endpoint.EndpointName); + Assert.Equal(networkContext, endpoint.ContextNetworkID); + }, + endpoint => Assert.Same(modeledReference, endpoint)); + } + + [Fact] + public void GetEndpointReferencesUsesFirstMatchingHostEndpoint() + { + using var builder = TestDistributedApplicationBuilder.Create(); + builder.AddContainer("container", "image") + .WithEndpoint(name: "http", port: 17092, targetPort: 5000); + builder.AddExecutable("non-host", "non-host.exe", ".") + .WithAnnotation(new EndpointAnnotation( + System.Net.Sockets.ProtocolType.Tcp, + KnownNetworkIdentifiers.DefaultAspireContainerNetwork, + name: "internal", + port: 17092, + targetPort: 5001)); + var firstHost = builder.AddExecutable("first-host", "first-host.exe", ".") + .WithEndpoint(name: "first", port: 17092, targetPort: 5002); + builder.AddExecutable("second-host", "second-host.exe", ".") + .WithEndpoint(name: "second", port: 17092, targetPort: 5003); + var context = new ExecutionConfigurationGathererContext(); + context.EnvironmentVariables["TARGET_URL"] = new HostUrl("http://localhost:17092/path"); + + var endpoint = Assert.Single(context.GetEndpointReferences( + new DistributedApplicationModel(builder.Resources), + KnownNetworkIdentifiers.DefaultAspireContainerNetwork)); + + Assert.Same(firstHost.Resource, endpoint.Resource); + Assert.Equal("first", endpoint.EndpointName); + Assert.Equal(KnownNetworkIdentifiers.DefaultAspireContainerNetwork, endpoint.ContextNetworkID); } #endregion From 1ecd7cc70b5a5a5b8571fe3af69faa1646b8de47 Mon Sep 17 00:00:00 2001 From: Sebastien Ros Date: Fri, 6 Nov 2026 20:48:20 +0000 Subject: [PATCH 4/5] Merged PR 67626: [release/13.6] Isolate CLI-generated builds and SDK temporary directories MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description Prevent automatic MSBuild response files from affecting CLI-generated server/integration builds without changing user-authored builds. SDK command working directories move to `/tmp/sdk/`, with owner-only Unix permissions, local configuration isolation, and cleanup on completion or preparation failure. Normal AppHost caches are unchanged. ### User-facing usage ```bash aspire sdk generate ./MyIntegration.csproj --language typescript --output ./generated aspire sdk dump ./MyIntegration.csproj --format json --output capabilities.json aspire sdk export --language typescript > api.json ``` ### Validation Manual validation to check that the `/tmp` folder was not used, all all projects for in `/tmp/sdk`. - `./restore.sh` — passed; existing dependency vulnerability warnings were reported. - Command below — passed, 54 tests, no failures/skips. Includes real SDK commands with adjacent/parent response files. ```bash MSBUILDTERMINALLOGGER=false dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj \ --no-launch-profile -- --filter-method '*.SdkCommandTests.*' \ --filter-method '*.SdkDumpCommandTests.*' \ --filter-method '*.SdkResponseFileTests.*' \ --filter-method '*.ProcessInvocationOptionsTests.*' \ --filter-method '*.DotNetCliRunnerTests.RestoreAsyncRunsDotnetRestoreCommand' \ --filter-method '*.DotNetCliRunnerTests.BuildAndRestoreAsync_ControlAutomaticResponseFiles' \ --filter-method '*.DotNetCliRunnerTests.BuildAsyncRunsDotnetBuildCommand' \ --filter-method '*.AppHostServerProjectTests.BuildAsync_DisablesAutomaticResponseFiles' \ --filter-method '*.PrebuiltAppHostServerTests.PrepareAsync_WithProjectReferencesAndExplicitChannelButNoOverride_UsesAdditionalSourcesNotRestoreConfigFile' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' ``` - `git diff --check` — passed. - Full suite and internal pipelines not run. ### Security considerations Changes generated-process execution and temp placement. Local configuration keeps caches inside the cleanup boundary. Response suppression applies only to generated builds; explicit response files remain supported. Forced termination/cleanup failure can leave directories; no periodic cleanup. Dedicated security review not performed. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - [ ] No - Did you add public API? - [ ] Yes - If yes, did you have an API Review for it? - [ ] Yes - [ ] No - Did you add `` and `` elements on your triple slash comments? - [ ] Yes - [ ] No - [x] No - Does the change make any security assumptions or guarantees? - [x] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [x] No - [ ] No --- docs/specs/cli-output-formats.md | 2 + src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs | 6 +- .../Commands/Sdk/SdkExportCommand.cs | 5 +- .../Commands/Sdk/SdkGenerateCommand.cs | 6 +- src/Aspire.Cli/DotNet/DotNetCliRunner.cs | 15 ++ .../Projects/AppHostServerProject.cs | 18 +++ .../DotNetBasedAppHostServerProject.cs | 1 + .../Projects/PrebuiltAppHostServer.cs | 1 + src/Aspire.Cli/Utils/CliPathHelper.cs | 33 ++++ .../Commands/Sdk/SdkResponseFileTests.cs | 149 ++++++++++++++++++ .../Commands/SdkCommandTests.cs | 78 +++++++++ .../Commands/SdkDumpCommandTests.cs | 2 +- .../DotNet/DotNetCliRunnerTests.cs | 89 +++++++++-- .../DotNet/ProcessInvocationOptionsTests.cs | 1 + .../Projects/AppHostServerProjectTests.cs | 26 +++ .../Projects/PrebuiltAppHostServerTests.cs | 3 +- .../TestAppHostServerProjectFactory.cs | 3 + 17 files changed, 416 insertions(+), 22 deletions(-) create mode 100644 tests/Aspire.Cli.Tests/Commands/Sdk/SdkResponseFileTests.cs diff --git a/docs/specs/cli-output-formats.md b/docs/specs/cli-output-formats.md index 379b59c26c2..19baca07e0d 100644 --- a/docs/specs/cli-output-formats.md +++ b/docs/specs/cli-output-formats.md @@ -580,6 +580,8 @@ The `isolated-launch.v1` capability indicates that `aspire run` accepts the `--i ### `aspire sdk dump` +The SDK commands (`sdk generate`, `sdk dump`, and `sdk export`) create their scanner working directories under `/tmp/sdk/`, not the OS temporary directory. Scanner configuration and build artifacts stay inside that directory, isolated from ancestor workspace settings. Each invocation removes its working directory on completion, including preparation failures. Normal AppHost integration caches remain workspace-local. + `aspire sdk dump --format json` is a hidden SDK-generation command that emits Aspire type-system capabilities: ```json diff --git a/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs index f3ab64e0aab..98ad61b237f 100644 --- a/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs +++ b/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs @@ -164,7 +164,7 @@ protected override async Task ExecuteAsync(ParseResult parseResul private Task CreateCapabilityScannerProjectAsync(string tempDir, CancellationToken cancellationToken) { var repoRoot = AspireRepositoryDetector.DetectRepositoryRoot(tempDir); - return _appHostServerProjectFactory.CreateAsync(tempDir, restoreRootConfigDirectory: repoRoot, cancellationToken); + return _appHostServerProjectFactory.CreateForSdkCommandsAsync(tempDir, restoreRootConfigDirectory: repoRoot, cancellationToken); } private async Task DumpCapabilitiesAsync( @@ -173,7 +173,7 @@ private async Task DumpCapabilitiesAsync( OutputFormat format, CancellationToken cancellationToken) { - var tempDirectory = Directory.CreateTempSubdirectory("aspire-sdk-dump-"); + var tempDirectory = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory); var tempDir = tempDirectory.FullName; try @@ -272,7 +272,7 @@ private async Task DumpCapabilitiesToDirectoryAsync( OutputFormat format, CancellationToken cancellationToken) { - var tempDirectory = Directory.CreateTempSubdirectory("aspire-sdk-dump-"); + var tempDirectory = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory); var tempDir = tempDirectory.FullName; try diff --git a/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs index e6abd804453..2b5539ca1bf 100644 --- a/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs +++ b/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs @@ -179,13 +179,14 @@ private async Task ExportApiAsync( IReadOnlyList integrations, CancellationToken cancellationToken) { - var tempDirectory = Directory.CreateTempSubdirectory("aspire-sdk-export-"); + var tempDirectory = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory); var tempDirectoryPath = tempDirectory.FullName; try { - var appHostServerProject = await _appHostServerProjectFactory.CreateAsync( + var appHostServerProject = await _appHostServerProjectFactory.CreateForSdkCommandsAsync( tempDirectoryPath, + restoreRootConfigDirectory: null, cancellationToken); var prepareResult = await appHostServerProject.PrepareAsync( diff --git a/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs index 10ba5300625..2b4c29fb79a 100644 --- a/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs +++ b/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs @@ -5,6 +5,7 @@ using Aspire.Cli.Configuration; using Aspire.Cli.Interaction; using Aspire.Cli.Projects; +using Aspire.Cli.Utils; using Microsoft.Extensions.Logging; namespace Aspire.Cli.Commands.Sdk; @@ -111,12 +112,11 @@ private async Task GenerateSdkAsync( var integrationAssemblyName = IntegrationAssemblyNameResolver.Resolve(integrationProject); // Use a temporary directory for the AppHost server - var tempDir = Path.Combine(Path.GetTempPath(), "aspire-sdk-gen", Guid.NewGuid().ToString("N")[..8]); - Directory.CreateDirectory(tempDir); + var tempDir = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory).FullName; try { - var appHostServerProject = await _appHostServerProjectFactory.CreateAsync(tempDir, cancellationToken); + var appHostServerProject = await _appHostServerProjectFactory.CreateForSdkCommandsAsync(tempDir, restoreRootConfigDirectory: null, cancellationToken); // Get code generation package for the target language var codeGenPackage = await _languageDiscovery.GetPackageForLanguageAsync(languageInfo.LanguageId, cancellationToken); diff --git a/src/Aspire.Cli/DotNet/DotNetCliRunner.cs b/src/Aspire.Cli/DotNet/DotNetCliRunner.cs index 027304d64b4..6c5e705f131 100644 --- a/src/Aspire.Cli/DotNet/DotNetCliRunner.cs +++ b/src/Aspire.Cli/DotNet/DotNetCliRunner.cs @@ -54,6 +54,12 @@ internal sealed class ProcessInvocationOptions public Action? StandardErrorCallback { get; set; } public bool NoLaunchProfile { get; set; } + + /// + /// Disables automatic MSBuild response files for CLI-generated projects without changing user project builds. + /// + public bool NoAutoResponse { get; set; } + public string? LaunchProfile { get; set; } public bool StartDebugSession { get; set; } public bool Debug { get; set; } @@ -157,6 +163,7 @@ internal sealed class ProcessInvocationOptions StandardOutputCallback = StandardOutputCallback, StandardErrorCallback = StandardErrorCallback, NoLaunchProfile = NoLaunchProfile, + NoAutoResponse = NoAutoResponse, LaunchProfile = LaunchProfile, StartDebugSession = StartDebugSession, Debug = Debug, @@ -1268,6 +1275,10 @@ public async Task RestoreAsync(FileInfo projectFilePath, ProcessInvocationO using var activity = telemetry.StartDiagnosticActivity(); string[] cliArgs = ["restore", projectFilePath.FullName]; + if (options.NoAutoResponse) + { + cliArgs = [.. cliArgs, "-noAutoResponse"]; + } return await ExecuteAsync( args: cliArgs, @@ -1289,6 +1300,10 @@ public async Task BuildAsync(FileInfo projectFilePath, bool noRestore, IDic var noRestoreSwitch = noRestore ? "--no-restore" : string.Empty; string[] cliArgs = ["build", noRestoreSwitch, projectFilePath.FullName]; cliArgs = [.. cliArgs.Where(arg => !string.IsNullOrWhiteSpace(arg))]; + if (options.NoAutoResponse) + { + cliArgs = [.. cliArgs, "-noAutoResponse"]; + } // File-based AppHosts derive their RunCommand during build. Persist suppression into that // generated command so the later dotnet run --no-build cannot recursively invoke Aspire CLI. diff --git a/src/Aspire.Cli/Projects/AppHostServerProject.cs b/src/Aspire.Cli/Projects/AppHostServerProject.cs index 40eabb6b5b5..2678399bacf 100644 --- a/src/Aspire.Cli/Projects/AppHostServerProject.cs +++ b/src/Aspire.Cli/Projects/AppHostServerProject.cs @@ -18,6 +18,7 @@ internal interface IAppHostServerProjectFactory { Task CreateAsync(string appPath, CancellationToken cancellationToken = default); Task CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken); + Task CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken); } /// @@ -39,6 +40,20 @@ public Task CreateAsync(string appPath, CancellationToken => CreateAsync(appPath, restoreRootConfigDirectory: null, cancellationToken); public async Task CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken) + => await CreateAsync( + appPath, + restoreRootConfigDirectory, + temporary: false, + cancellationToken).ConfigureAwait(false); + + public Task CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken) + => CreateAsync(appPath, restoreRootConfigDirectory, temporary: true, cancellationToken); + + private async Task CreateAsync( + string appPath, + string? restoreRootConfigDirectory, + bool temporary, + CancellationToken cancellationToken) { var socketPath = CliPathHelper.CreateGuestAppHostSocketPath("apphost.sock"); @@ -55,6 +70,9 @@ public async Task CreateAsync(string appPath, string? res processExecutionFactory, environment, loggerFactory.CreateLogger(), + // SDK commands do not reuse these server builds. Put the build files in + // the temporary folder so they are deleted when the command finishes. + projectModelPath: temporary ? Path.Combine(appPath, "server") : null, logFilePath: executionContext.LogFilePath, restoreRootConfigDirectory: restoreRootConfigDirectory); } diff --git a/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs b/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs index 50d6248784e..ed9ee700723 100644 --- a/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs +++ b/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs @@ -551,6 +551,7 @@ private static string ComputeScaffoldFingerprint(Dictionary scaf var options = new ProcessInvocationOptions { + NoAutoResponse = true, StandardOutputCallback = outputCollector.AppendOutput, StandardErrorCallback = outputCollector.AppendError }; diff --git a/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs b/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs index a3251a393bd..b5203dcbf82 100644 --- a/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs +++ b/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs @@ -758,6 +758,7 @@ internal static string GetIntegrationBuildFailureMessage(OutputCollector buildOu noRestore, new ProcessInvocationOptions { + NoAutoResponse = true, StandardOutputCallback = buildOutput.AppendOutput, StandardErrorCallback = buildOutput.AppendError }, diff --git a/src/Aspire.Cli/Utils/CliPathHelper.cs b/src/Aspire.Cli/Utils/CliPathHelper.cs index d405d3ea4b6..eadc347190f 100644 --- a/src/Aspire.Cli/Utils/CliPathHelper.cs +++ b/src/Aspire.Cli/Utils/CliPathHelper.cs @@ -57,6 +57,39 @@ internal static string GetDefaultAspireHomeDirectory(string? configuredAspireHom return AspireHomeDirectory.GetDefault(configuredAspireHome, userProfileDirectory); } + // Accept the execution context's already-resolved Aspire home rather than resolving it + // from process state again, so tests using an isolated home never write to the user's home. + internal static DirectoryInfo CreateSdkWorkingDirectory(DirectoryInfo aspireHomeDirectory) + { + // Keep generated scanner projects out of the shared OS temp hierarchy, where + // ancestor build configuration can affect restore and build. + var tempRoot = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(aspireHomeDirectory.FullName, "tmp")); + var sdkRoot = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(tempRoot.FullName, "sdk")); + var directory = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(sdkRoot.FullName, Guid.NewGuid().ToString("N"))); + try + { + // Anchor configuration discovery here so global or ancestor settings cannot move + // integration caches outside this invocation's cleanup boundary. + File.WriteAllText(Path.Combine(directory.FullName, Configuration.AspireConfigFile.FileName), "{}"); + return directory; + } + catch (Exception initializationException) when (initializationException is IOException or UnauthorizedAccessException) + { + // The caller cannot enter its cleanup scope until this method returns. + try + { + directory.Delete(recursive: true); + } + catch (Exception cleanupException) when (cleanupException is IOException or UnauthorizedAccessException) + { + throw new AggregateException("SDK working directory initialization and cleanup both failed.", + initializationException, cleanupException); + } + + throw; + } + } + /// /// Returns the absolute path to the staging NuGet package cache root /// (<ASPIRE_HOME>/.nugetpackages). Producers (the diff --git a/tests/Aspire.Cli.Tests/Commands/Sdk/SdkResponseFileTests.cs b/tests/Aspire.Cli.Tests/Commands/Sdk/SdkResponseFileTests.cs new file mode 100644 index 00000000000..9f35147c781 --- /dev/null +++ b/tests/Aspire.Cli.Tests/Commands/Sdk/SdkResponseFileTests.cs @@ -0,0 +1,149 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text.Json; +using Aspire.Cli.Commands; +using Aspire.Cli.DotNet; +using Aspire.Cli.Interaction; +using Aspire.Cli.Packaging; +using Aspire.Cli.Projects; +using Aspire.Cli.Tests.TestServices; +using Aspire.Cli.Tests.Utils; +using Aspire.Cli.Utils; +using Aspire.Hosting.Utils; +using Microsoft.AspNetCore.InternalTesting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Aspire.Cli.Tests.Commands.Sdk; + +public class SdkResponseFileTests(ITestOutputHelper outputHelper) +{ + [Theory] + [InlineData("generate", false)] + [InlineData("generate", true)] + [InlineData("dump", false)] + [InlineData("dump", true)] + [InlineData("dump-directory", false)] + [InlineData("dump-directory", true)] + [InlineData("export", false)] + [InlineData("export", true)] + public async Task SdkCommands_IgnoreAutomaticResponseFiles(string commandName, bool parentDirectory) + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var repoRoot = AspireRepositoryDetector.DetectRepositoryRoot(AppContext.BaseDirectory); + Assert.NotNull(repoRoot); + // MSBuild's child working directory resolves symlinks. Use that same path spelling + // for project references, particularly /var -> /private/var on macOS. + var modelDirectory = new DirectoryInfo(PathNormalizer.ResolveSymlinks(workspace.CreateDirectory("scanner").FullName)); + var responseFile = Path.Combine( + parentDirectory ? workspace.Path : modelDirectory.FullName, "Directory.Build.rsp"); + const string unexpectedTarget = "ResponseFileMustNotBeLoaded"; + await File.WriteAllTextAsync(responseFile, $"-target:{unexpectedTarget}"); + + var interaction = new TestInteractionService(); + var aspireHome = new DirectoryInfo(PathNormalizer.ResolveSymlinks(workspace.CreateDirectory("custom-aspire-home").FullName)); + // A scanner must not inherit the native-server setting or use this ancestor as + // its integration-cache root, even though it lives underneath Aspire home. + await File.WriteAllTextAsync(Path.Combine(aspireHome.FullName, "aspire.config.json"), + """{"features":{"appHostServerV2":true}}"""); + var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options => + { + options.CliExecutionContextFactory = _ => workspace.CreateExecutionContext(aspireHomeDirectory: aspireHome); + options.InteractionServiceFactory = _ => interaction; + options.DotNetCliExecutionFactoryFactory = provider => + new ProcessExecutionFactory(new HostEnvironment(), provider.GetRequiredService>()); + options.PackagingServiceFactory = _ => new TestPackagingService + { + GetChannelsAsyncCallback = _ => Task.FromResult>([]) + }; + }); + services.AddSingleton(); + var factoryCalls = 0; + string? scannerPath = null; + services.AddSingleton(provider => + { + var realFactory = ActivatorUtilities.CreateInstance(provider); + return new TestAppHostServerProjectFactory + { + // Inject the response file without replacing production scanner creation, + // build, restore, server startup, or RPC. + CreateAsyncCallback = async (appPath, cancellationToken) => + { + factoryCalls++; + scannerPath = appPath; + Assert.Equal(Path.Combine(aspireHome.FullName, "tmp", "sdk"), Directory.GetParent(appPath)?.FullName); + Assert.Equal(appPath, ConfigurationHelper.GetConfigRootDirectory(new DirectoryInfo(appPath)).FullName); + var project = Assert.IsType( + await realFactory.CreateForSdkCommandsAsync(appPath, repoRoot, cancellationToken)); + Assert.Equal(Path.Combine(appPath, "server"), project.ProjectModelPath); + await File.WriteAllTextAsync( + Path.Combine(parentDirectory ? appPath : project.ProjectModelPath, "Directory.Build.rsp"), + $"-target:{unexpectedTarget}", cancellationToken); + return project; + } + }; + }); + using var provider = services.BuildServiceProvider(); + + // Prove the response file would affect an ordinary build from this exact directory. + var probeProject = new FileInfo(Path.Combine(modelDirectory.FullName, "Probe.proj")); + await File.WriteAllTextAsync(probeProject.FullName, ""); + var probeOutput = new OutputCollector(); + var probeExitCode = await provider.GetRequiredService().BuildAsync( + probeProject, noRestore: true, new ProcessInvocationOptions + { + StandardOutputCallback = probeOutput.AppendOutput, + StandardErrorCallback = probeOutput.AppendError + }, TestContext.Current.CancellationToken).DefaultTimeout(); + Assert.NotEqual(0, probeExitCode); + Assert.Contains(probeOutput.GetLines(), line => line.Line.Contains(unexpectedTarget, StringComparison.Ordinal)); + File.Delete(probeProject.FullName); + + var integrationProject = Path.Combine(repoRoot, "src", "Aspire.Hosting", "Aspire.Hosting.csproj"); + var outputPath = Path.Combine(workspace.Path, "output"); + string[] arguments = commandName switch + { + "generate" => ["sdk", "generate", integrationProject, "--language", "typescript", "--output", outputPath], + "dump" => ["sdk", "dump", integrationProject, "--format", "json", "--output", outputPath], + "dump-directory" => ["sdk", "dump", integrationProject, "--format", "ci", "--output-directory", outputPath], + "export" => ["sdk", "export", "--language", "typescript"], + _ => throw new ArgumentOutOfRangeException(nameof(commandName)) + }; + + var exitCode = await provider.GetRequiredService().Parse(arguments).InvokeAsync() + .DefaultTimeout(TestConstants.ExtraLongTimeoutTimeSpan); + + Assert.Equal(CliExitCodes.Success, exitCode); + Assert.Equal(1, factoryCalls); + Assert.NotNull(scannerPath); + Assert.False(Directory.Exists(scannerPath)); + Assert.Equal(["aspire.config.json", "tmp"], + Directory.GetFileSystemEntries(aspireHome.FullName).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Equal($"-target:{unexpectedTarget}", await File.ReadAllTextAsync(responseFile)); + switch (commandName) + { + case "generate": + Assert.NotEmpty(await File.ReadAllTextAsync(Path.Combine(outputPath, "aspire.mts"))); + break; + case "dump": + using (var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath))) + { + Assert.NotEmpty(document.RootElement.GetProperty("Capabilities").EnumerateArray()); + } + break; + case "export": + var stdout = Assert.Single(interaction.DisplayedRawText, + entry => entry.ConsoleOverride == ConsoleOutput.Standard); + using (var document = JsonDocument.Parse(stdout.Text)) + { + Assert.Equal("Aspire.Hosting", document.RootElement.GetProperty("package").GetProperty("name").GetString()); + Assert.NotEmpty(document.RootElement.GetProperty("declarations").EnumerateArray()); + } + break; + case "dump-directory": + Assert.NotEmpty(await File.ReadAllTextAsync(Path.Combine(outputPath, "Aspire.Hosting.ats.txt"))); + break; + } + } +} diff --git a/tests/Aspire.Cli.Tests/Commands/SdkCommandTests.cs b/tests/Aspire.Cli.Tests/Commands/SdkCommandTests.cs index 8492bc4e7b1..211fc9e3770 100644 --- a/tests/Aspire.Cli.Tests/Commands/SdkCommandTests.cs +++ b/tests/Aspire.Cli.Tests/Commands/SdkCommandTests.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using Aspire.Cli.Commands; +using Aspire.Cli.Projects; +using Aspire.Cli.Tests.TestServices; using Aspire.Cli.Tests.Utils; +using Aspire.Cli.Utils; using Microsoft.AspNetCore.InternalTesting; using Microsoft.Extensions.DependencyInjection; @@ -10,6 +13,81 @@ namespace Aspire.Cli.Tests.Commands; public class SdkCommandTests(ITestOutputHelper outputHelper) { + [Theory] + [InlineData("generate")] + [InlineData("dump")] + [InlineData("dump-directory")] + [InlineData("export")] + public async Task SdkCommands_UseUniqueAspireHomeDirectoriesAndCleanUpAfterBuildFailure(string commandName) + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var aspireHome = new DirectoryInfo(Path.Combine(workspace.Path, "custom-aspire-home")); + aspireHome.Create(); + await File.WriteAllTextAsync(Path.Combine(aspireHome.FullName, "aspire.config.json"), + """{"features":{"appHostServerV2":true}}"""); + if (!OperatingSystem.IsWindows()) + { + foreach (var path in new[] { Path.Combine(aspireHome.FullName, "tmp"), Path.Combine(aspireHome.FullName, "tmp", "sdk") }) + { + Directory.CreateDirectory(path); + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | + UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | + UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute); + } + } + var scannerPaths = new List(); + var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options => + { + options.CliExecutionContextFactory = _ => workspace.CreateExecutionContext(aspireHomeDirectory: aspireHome); + }); + services.AddSingleton(new TestAppHostServerProjectFactory + { + CreateAsyncCallback = (appPath, _) => + { + Assert.Equal(Path.Combine(aspireHome.FullName, "tmp", "sdk"), Directory.GetParent(appPath)?.FullName); + Assert.True(Directory.Exists(appPath)); + Assert.Equal(appPath, ConfigurationHelper.GetConfigRootDirectory(new DirectoryInfo(appPath)).FullName); + Assert.Equal(Path.Combine(appPath, ".aspire", "integrations"), + ConfigurationHelper.GetIntegrationCacheDirectory(new DirectoryInfo(appPath)).FullName); + if (!OperatingSystem.IsWindows()) + { + foreach (var directory in new[] { appPath, Path.Combine(aspireHome.FullName, "tmp"), Path.Combine(aspireHome.FullName, "tmp", "sdk") }) + { + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, + File.GetUnixFileMode(directory)); + } + } + scannerPaths.Add(appPath); + return Task.FromResult(new FakeFailingAppHostServerProject(appPath)); + } + }); + using var provider = services.BuildServiceProvider(); + var integrationProject = Path.Combine(workspace.Path, "Integration.csproj"); + await File.WriteAllTextAsync(integrationProject, ""); + var outputPath = Path.Combine(workspace.Path, "output"); + string[] arguments = commandName switch + { + "generate" => ["sdk", "generate", integrationProject, "--language", "typescript", "--output", outputPath], + "dump" => ["sdk", "dump", "--output", outputPath], + "dump-directory" => ["sdk", "dump", integrationProject, "--format", "ci", "--output-directory", outputPath], + "export" => ["sdk", "export", "--language", "typescript"], + _ => throw new ArgumentOutOfRangeException(nameof(commandName)) + }; + var command = provider.GetRequiredService(); + + for (var i = 0; i < 2; i++) + { + var exitCode = await command.Parse(arguments).InvokeAsync().DefaultTimeout(); + + Assert.Equal(CliExitCodes.FailedToBuildArtifacts, exitCode); + Assert.Equal(i + 1, scannerPaths.Count); + Assert.False(Directory.Exists(scannerPaths[i])); + } + + Assert.Equal(2, scannerPaths.Distinct().Count()); + Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(aspireHome.FullName, "tmp", "sdk"))); + } + [Fact] public async Task SdkCommand_WithoutSubcommand_ReturnsInvalidCommand() { diff --git a/tests/Aspire.Cli.Tests/Commands/SdkDumpCommandTests.cs b/tests/Aspire.Cli.Tests/Commands/SdkDumpCommandTests.cs index aa3318ce9ac..d04d7381207 100644 --- a/tests/Aspire.Cli.Tests/Commands/SdkDumpCommandTests.cs +++ b/tests/Aspire.Cli.Tests/Commands/SdkDumpCommandTests.cs @@ -282,7 +282,7 @@ public async Task SdkDump_PassesRepositoryRootAsScannerRestoreConfigDirectory(bo Assert.NotNull(scannerPath); Assert.Equal(repoRoot, factory.RestoreRootConfigDirectory); Assert.NotNull(scannerFiles); - Assert.Empty(scannerFiles); + Assert.Equal([Path.Combine(scannerPath, "aspire.config.json")], scannerFiles); Assert.False(Directory.Exists(scannerPath)); } diff --git a/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs b/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs index c51df92f3d0..f77b4ccaa4c 100644 --- a/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs +++ b/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs @@ -16,6 +16,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using System.Net.Sockets; namespace Aspire.Cli.Tests.DotNet; @@ -405,8 +406,10 @@ public void ShouldForwardProcessPathAsAspireCliPathAllowsAdjacentBundleLayout() Assert.True(DotNetCliRunner.ShouldForwardProcessPathAsAspireCliPath(cliPath)); } - [Fact] - public async Task RestoreAsyncRunsDotnetRestoreCommand() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RestoreAsyncRunsDotnetRestoreCommand(bool noAutoResponse) { using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); var projectFile = new FileInfo(Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.csproj")); @@ -415,7 +418,10 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand() var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper); using var provider = services.BuildServiceProvider(); - var options = new ProcessInvocationOptions(); + var options = new ProcessInvocationOptions + { + NoAutoResponse = noAutoResponse + }; var executionContext = CreateExecutionContext(workspace.WorkspaceRoot); var runner = DotNetCliRunnerTestHelper.Create( @@ -423,8 +429,12 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand() executionContext, (args, _, _, _) => { - Assert.Equal("restore", args[0]); - Assert.Equal(projectFile.FullName, args[1]); + var expected = new List { "restore", projectFile.FullName }; + if (noAutoResponse) + { + expected.Add("-noAutoResponse"); + } + Assert.Equal(expected, args); }, 0); @@ -433,6 +443,49 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand() Assert.Equal(0, exitCode); } + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task BuildAndRestoreAsync_ControlAutomaticResponseFiles(bool build, bool noAutoResponse) + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var projectDirectory = workspace.CreateDirectory("generated"); + var projectFile = new FileInfo(Path.Combine(projectDirectory.FullName, "Generated.csproj")); + var resultPath = Path.Combine(projectDirectory.FullName, "result.txt"); + await File.WriteAllTextAsync(Path.Combine(workspace.WorkspaceRoot.FullName, "Directory.Build.rsp"), + "-property:ResponseFileValue=from-response-file"); + // No SDK or packages are needed: both commands execute a target that records the + // property supplied by the parent response file, or its project-defined default. + await File.WriteAllTextAsync(projectFile.FullName, """ + + + from-project + + + + + + + """); + using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options => + { + options.DotNetCliExecutionFactoryFactory = _ => + new ProcessExecutionFactory(new TestEnvironment(), NullLogger.Instance); + }).BuildServiceProvider(); + var runner = provider.GetRequiredService(); + var options = new ProcessInvocationOptions { NoAutoResponse = noAutoResponse }; + + var exitCode = build + ? await runner.BuildAsync(projectFile, noRestore: false, options, TestContext.Current.CancellationToken).DefaultTimeout() + : await runner.RestoreAsync(projectFile, options, TestContext.Current.CancellationToken).DefaultTimeout(); + + Assert.Equal(0, exitCode); + Assert.Equal(noAutoResponse ? "from-project" : "from-response-file", + (await File.ReadAllTextAsync(resultPath)).Trim()); + } + [Fact] public async Task BuildAsyncDoesNotInjectConfiguredDotnetCliUseMsBuildServer() { @@ -470,8 +523,12 @@ public async Task BuildAsyncDoesNotInjectConfiguredDotnetCliUseMsBuildServer() Assert.Equal(0, exitCode); } - [Fact] - public async Task BuildAsyncIncludesNoRestoreFlagWhenNoRestoreIsTrue() + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task BuildAsyncRunsDotnetBuildCommand(bool noRestore, bool noAutoResponse) { using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); var projectFile = new FileInfo(Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.csproj")); @@ -480,7 +537,7 @@ public async Task BuildAsyncIncludesNoRestoreFlagWhenNoRestoreIsTrue() var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper); using var provider = services.BuildServiceProvider(); - var options = new ProcessInvocationOptions(); + var options = new ProcessInvocationOptions { NoAutoResponse = noAutoResponse }; var executionContext = CreateExecutionContext(workspace.WorkspaceRoot); var runner = DotNetCliRunnerTestHelper.Create( @@ -488,13 +545,21 @@ public async Task BuildAsyncIncludesNoRestoreFlagWhenNoRestoreIsTrue() executionContext, (args, env, _, _) => { - // Verify that --no-restore is included when noRestore is true - Assert.Contains("build", args); - Assert.Contains("--no-restore", args); + var expected = new List { "build" }; + if (noRestore) + { + expected.Add("--no-restore"); + } + expected.Add(projectFile.FullName); + if (noAutoResponse) + { + expected.Add("-noAutoResponse"); + } + Assert.Equal(expected, args); }, 0); - var exitCode = await runner.BuildAsync(projectFile, noRestore: true, options, CancellationToken.None).DefaultTimeout(); + var exitCode = await runner.BuildAsync(projectFile, noRestore, options, CancellationToken.None).DefaultTimeout(); Assert.Equal(0, exitCode); } diff --git a/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs b/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs index 1fbd736c60a..c6099150938 100644 --- a/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs +++ b/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs @@ -20,6 +20,7 @@ public void Clone_CopiesEveryProperty() StandardOutputCallback = _ => { }, StandardErrorCallback = _ => { }, NoLaunchProfile = true, + NoAutoResponse = true, LaunchProfile = "E2E", StartDebugSession = true, Debug = true, diff --git a/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs b/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs index c9b214b9f07..d9d88d696e6 100644 --- a/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs +++ b/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs @@ -45,6 +45,32 @@ private DotNetBasedAppHostServerProject CreateProject(string? appPath = null) return new DotNetBasedAppHostServerProject(appPath, socketPath, repoRoot, runner, packagingService, new TestProcessExecutionFactory(), new TestEnvironment(), logger); } + [Fact] + public async Task BuildAsync_DisablesAutomaticResponseFiles() + { + var buildCount = 0; + var runner = new TestDotNetCliRunner + { + BuildAsyncCallback = (projectFile, noRestore, options, _) => + { + buildCount++; + Assert.Equal(DotNetBasedAppHostServerProject.ProjectFileName, projectFile.Name); + Assert.False(noRestore); + Assert.True(options.NoAutoResponse); + return 0; + } + }; + var project = new DotNetBasedAppHostServerProject( + _workspace.WorkspaceRoot.FullName, "test.sock", _workspace.WorkspaceRoot.FullName, + runner, MockPackagingServiceFactory.Create(), new TestProcessExecutionFactory(), + new TestEnvironment(), NullLogger.Instance); + + var (success, _) = await project.BuildAsync().DefaultTimeout(); + + Assert.True(success); + Assert.Equal(1, buildCount); + } + [Fact] public async Task CreateProjectFiles_RestoreRootConfigDirectory_PreservesRelativeSources() { diff --git a/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs b/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs index 6e2b6fa4463..0e02ac4af4a 100644 --- a/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs +++ b/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs @@ -2007,8 +2007,9 @@ await File.WriteAllTextAsync(aspireConfigPath, """ }; var dotNetCliRunner = new TestDotNetCliRunner { - BuildAsyncCallback = (projectFilePath, _, _, _) => + BuildAsyncCallback = (projectFilePath, _, options, _) => { + Assert.True(options.NoAutoResponse); generatedProject = XDocument.Load(projectFilePath.FullName); WriteClosureInputs(projectFilePath.Directory!, closureFiles, ["MyIntegration"]); return 0; diff --git a/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs b/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs index 5226f386368..90148806faa 100644 --- a/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs +++ b/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs @@ -14,6 +14,9 @@ internal sealed class TestAppHostServerProjectFactory : IAppHostServerProjectFac public Task CreateAsync(string appPath, CancellationToken cancellationToken = default) => CreateAsync(appPath, restoreRootConfigDirectory: null, cancellationToken); + public Task CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken) + => CreateAsync(appPath, restoreRootConfigDirectory, cancellationToken); + public Task CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken) { RestoreRootConfigDirectory = restoreRootConfigDirectory; From b33d222049f1ecc3bc7257ec07b622fe550b2580 Mon Sep 17 00:00:00 2001 From: Jose Perez Rodriguez Date: Mon, 9 Nov 2026 19:03:42 +0000 Subject: [PATCH 5/5] Merged PR 68450: [release/13.6] Prepare stable installers for internal release branches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description Stable source builds from `internal/release/*` currently skip Prepare Installers, unlike `release/*` builds. Include the internal release prefix in the official and unofficial installer-stage conditions so internal servicing builds produce the same WinGet manifests, Homebrew cask, and npm installation validation results. Preserve the existing PR behavior, main/release eligibility, prerelease behavior, and dependency-success requirements. Signing and production-branch recognition already include internal release branches and require no changes. Prepare Installers only generates/validates files and uploads internal build artifacts. It does not submit WinGet manifests, push a Homebrew tap, or publish npm packages. Public publishing remains in the separate, manual release-publish pipeline; this change does not modify it. Fixes # (issue) ### Validation - `git -C 'C:\Users\joperezr\.copilot\session-state\b41fa7f3-1764-4a40-baab-cd20c93df4a7\files\internal-release-installer-fix' diff --check` — passed. - `node 'C:\Users\joperezr\.copilot\session-state\b41fa7f3-1764-4a40-baab-cd20c93df4a7\files\check-installer-gates.cjs' 'C:\Users\joperezr\.copilot\session-state\b41fa7f3-1764-4a40-baab-cd20c93df4a7\files\internal-release-installer-fix'` — passed 168 diagnostic cases using the extracted conditions: branch, channel, reason, and dependency-success combinations. This session-only diagnostic is not an Azure Pipelines integration test. - Official definition 1602 run [3130747](https://dev.azure.com/dnceng/internal/_build/results?buildId=3130747), revision `8f7d36254f531a80f95074b0011de97b2a695c12`, stable CLI override — queued through the ADO pipeline API and currently running. Requested `stagesToSkip: [assemble]` to exclude Assemble + Publish. Initial timeline inspected; no artifacts yet. - Stable installer execution is **unvalidated**: contributor-branch gating still intentionally excludes this personal branch. Verify the installer jobs, logs, and artifacts on `internal/release/13.6` after merge. No public release/publishing run was queued. Unofficial pipeline execution was not run. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [ ] Yes - [x] No - Did you add public API? - [ ] Yes - If yes, did you have an API Review for it? - [ ] Yes - [ ] No - Did you add `` and `` elements on your triple slash comments? - [ ] Yes - [ ] No - [x] No - Does the change make any security assumptions or guarantees? - [ ] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [ ] No - [x] No --- eng/pipelines/azure-pipelines-unofficial.yml | 3 ++- eng/pipelines/azure-pipelines.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/eng/pipelines/azure-pipelines-unofficial.yml b/eng/pipelines/azure-pipelines-unofficial.yml index 42ebe2c5aa0..4758b360be4 100644 --- a/eng/pipelines/azure-pipelines-unofficial.yml +++ b/eng/pipelines/azure-pipelines-unofficial.yml @@ -343,7 +343,8 @@ extends: ne(dependencies.build.outputs['Windows.computeChannel.installerChannel'], 'stable'), or( eq(variables['Build.SourceBranch'], 'refs/heads/main'), - startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') + startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), + startsWith(variables['Build.SourceBranch'], 'refs/heads/internal/release/') ) ) ) diff --git a/eng/pipelines/azure-pipelines.yml b/eng/pipelines/azure-pipelines.yml index 5b2435cbb86..b8a6943c836 100644 --- a/eng/pipelines/azure-pipelines.yml +++ b/eng/pipelines/azure-pipelines.yml @@ -822,7 +822,8 @@ extends: ne(dependencies.build_sign_native.outputs['BuildNative_linux_x64.ComputeVars.installerChannel'], 'stable'), or( eq(variables['Build.SourceBranch'], 'refs/heads/main'), - startsWith(variables['Build.SourceBranch'], 'refs/heads/release/') + startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), + startsWith(variables['Build.SourceBranch'], 'refs/heads/internal/release/') ) ) )