diff --git a/docs/specs/cli-output-formats.md b/docs/specs/cli-output-formats.md index 0bfe9882965..d1e5a5464fd 100644 --- a/docs/specs/cli-output-formats.md +++ b/docs/specs/cli-output-formats.md @@ -794,6 +794,8 @@ The `agent-mcp.v1` capability indicates that `aspire agent mcp` is supported. To ### `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/eng/pipelines/azure-pipelines-unofficial.yml b/eng/pipelines/azure-pipelines-unofficial.yml index 453719d3057..ce711f7d189 100644 --- a/eng/pipelines/azure-pipelines-unofficial.yml +++ b/eng/pipelines/azure-pipelines-unofficial.yml @@ -338,7 +338,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 52290371ca8..6f14f53ed0f 100644 --- a/eng/pipelines/azure-pipelines.yml +++ b/eng/pipelines/azure-pipelines.yml @@ -676,7 +676,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/') ) ) ) diff --git a/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs index 16e1e38ae0f..610e70a0e5e 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 @@ -254,10 +254,7 @@ private async Task DumpCapabilitiesAsync( // Clean up temp directory try { - if (Directory.Exists(tempDir)) - { - Directory.Delete(tempDir, recursive: true); - } + await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDir, TimeProvider.System, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { @@ -272,7 +269,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 @@ -333,10 +330,7 @@ private async Task DumpCapabilitiesToDirectoryAsync( { try { - if (Directory.Exists(tempDir)) - { - Directory.Delete(tempDir, recursive: true); - } + await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDir, TimeProvider.System, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs index 5c97c6c6bb1..9634eb0d122 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( @@ -256,10 +257,7 @@ private async Task ExportApiAsync( { try { - if (Directory.Exists(tempDirectoryPath)) - { - Directory.Delete(tempDirectoryPath, recursive: true); - } + await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDirectoryPath, TimeProvider.System, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs b/src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs index 82b37fffef6..321f1f9fca9 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); @@ -197,10 +197,7 @@ private async Task GenerateSdkAsync( // Clean up temp directory try { - if (Directory.Exists(tempDir)) - { - Directory.Delete(tempDir, recursive: true); - } + await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDir, TimeProvider.System, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/Aspire.Cli/DotNet/DotNetCliRunner.cs b/src/Aspire.Cli/DotNet/DotNetCliRunner.cs index 5cbeaadfdf0..4734504464d 100644 --- a/src/Aspire.Cli/DotNet/DotNetCliRunner.cs +++ b/src/Aspire.Cli/DotNet/DotNetCliRunner.cs @@ -63,6 +63,11 @@ internal sealed class ProcessInvocationOptions public bool NoLaunchProfile { get; set; } + /// + /// Disables automatic MSBuild response files for CLI-generated projects without changing user project builds. + /// + public bool NoAutoResponse { get; set; } + /// /// Suppresses implicit restore during single-file project property and target queries. /// @@ -182,6 +187,7 @@ internal sealed class ProcessInvocationOptions StandardOutputCallback = StandardOutputCallback, StandardErrorCallback = StandardErrorCallback, NoLaunchProfile = NoLaunchProfile, + NoAutoResponse = NoAutoResponse, NoRestore = NoRestore, ExcludeRestorePackageImports = ExcludeRestorePackageImports, NuGetRestoreTargetsFile = NuGetRestoreTargetsFile, @@ -1259,6 +1265,11 @@ public async Task RestoreAsync(FileInfo projectFilePath, ProcessInvocationO using var activity = telemetry.StartDiagnosticActivity(); string[] cliArgs = ["restore", projectFilePath.FullName]; + if (options.NoAutoResponse) + { + cliArgs = [.. cliArgs, "-noAutoResponse"]; + } + if (options.NuGetRestoreTargetsFile is { } restoreTargets) { cliArgs = [.. cliArgs, $"-property:NuGetRestoreTargets={MSBuildEscaping.Escape(restoreTargets.FullName)}"]; @@ -1284,6 +1295,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 ad8f8afa505..027e77c114d 100644 --- a/src/Aspire.Cli/Projects/AppHostServerProject.cs +++ b/src/Aspire.Cli/Projects/AppHostServerProject.cs @@ -21,6 +21,7 @@ internal interface IAppHostServerProjectFactory Task CreateAsync(string appPath, CancellationToken cancellationToken = default); Task CreateAsync(string appPath, FileInfo appHostFile, CancellationToken cancellationToken); Task CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken); + Task CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken); } /// @@ -53,6 +54,7 @@ public Task CreateAsync(string appPath, CancellationToken appPath, restoreRootConfigDirectory: null, workloadId: AppHostWorkloadId.Create(appPath), + temporary: false, cancellationToken: cancellationToken); public Task CreateAsync( @@ -66,6 +68,7 @@ public Task CreateAsync( appPath, restoreRootConfigDirectory: null, workloadId: AppHostWorkloadId.Create(appHostFile), + temporary: false, cancellationToken: cancellationToken); } @@ -74,12 +77,17 @@ public async Task CreateAsync(string appPath, string? res appPath, restoreRootConfigDirectory, AppHostWorkloadId.Create(appPath), + temporary: false, cancellationToken).ConfigureAwait(false); + public Task CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken) + => CreateAsync(appPath, restoreRootConfigDirectory, AppHostWorkloadId.Create(appPath), temporary: true, cancellationToken); + private async Task CreateAsync( string appPath, string? restoreRootConfigDirectory, string workloadId, + bool temporary, CancellationToken cancellationToken) { if (IsNativeServerEnabled(appPath)) @@ -103,6 +111,9 @@ private async Task CreateAsync( 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 6f9af68335b..0ed3290add2 100644 --- a/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs +++ b/src/Aspire.Cli/Projects/DotNetBasedAppHostServerProject.cs @@ -499,6 +499,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 e5734f0e69c..9a6598015c4 100644 --- a/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs +++ b/src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs @@ -446,6 +446,7 @@ internal static string GetIntegrationBuildFailureMessage(OutputCollector buildOu noRestore, new ProcessInvocationOptions { + NoAutoResponse = true, StandardOutputCallback = buildOutput.AppendOutput, StandardErrorCallback = buildOutput.AppendError, EnvironmentVariableFilter = name => diff --git a/src/Aspire.Cli/Utils/CliPathHelper.cs b/src/Aspire.Cli/Utils/CliPathHelper.cs index 518471459ee..52f0bce3812 100644 --- a/src/Aspire.Cli/Utils/CliPathHelper.cs +++ b/src/Aspire.Cli/Utils/CliPathHelper.cs @@ -59,6 +59,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/src/Aspire.Cli/Utils/FileDeleteHelper.cs b/src/Aspire.Cli/Utils/FileDeleteHelper.cs index 1e4201a88fc..2298443a738 100644 --- a/src/Aspire.Cli/Utils/FileDeleteHelper.cs +++ b/src/Aspire.Cli/Utils/FileDeleteHelper.cs @@ -10,8 +10,8 @@ namespace Aspire.Cli.Utils; /// /// On Windows a running process holds an exclusive lock on its executable, /// so throws -/// . Rather than failing the entire -/// operation, these helpers rename the locked item to +/// . The synchronous deletion helpers +/// rename the locked item to /// {name}.old.{tickcount} and let the caller proceed. The stale /// renamed items are best-effort cleaned up on subsequent invocations via /// . @@ -57,6 +57,48 @@ internal static bool TryDeleteDirectory(string path) return true; } + /// + /// Deletes a directory recursively, retrying transient I/O and access failures + /// for up to two seconds before rethrowing the final failure. + /// Unlike , this does not rename locked content. + /// + internal static async Task DeleteDirectoryWithRetryAsync(string path, TimeProvider timeProvider, CancellationToken cancellationToken) + { + var delay = TimeSpan.FromMilliseconds(20); + var maxDelay = TimeSpan.FromMilliseconds(250); + var retryBudget = TimeSpan.FromSeconds(2); + var start = timeProvider.GetTimestamp(); + + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!Directory.Exists(path)) + { + return; + } + + try + { + Directory.Delete(path, recursive: true); + return; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Windows can briefly reject deletion of a child's loaded DLLs even after + // its exit is observed. Retry deletion without extending shutdown or moving + // scanner content outside the invocation's cleanup boundary. + var remaining = retryBudget - timeProvider.GetElapsedTime(start); + if (remaining <= TimeSpan.Zero) + { + throw; + } + + await Task.Delay(delay < remaining ? delay : remaining, timeProvider, cancellationToken).ConfigureAwait(false); + delay = TimeSpan.FromTicks(Math.Min(delay.Ticks * 2, maxDelay.Ticks)); + } + } + } + /// /// Attempts to delete a file. If deletion fails because the file is locked /// by another process, the file is renamed to {path}.old.{tickcount} 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 98f23b65353..ee15039e8ca 100644 --- a/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs +++ b/src/Aspire.Dashboard/Components/Interactions/InteractionsProvider.cs @@ -5,7 +5,9 @@ using System.Collections.ObjectModel; using System.Diagnostics; using System.Net; +using Aspire.Dashboard.Authentication; using Aspire.Dashboard.Components.Dialogs; +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; @@ -94,11 +98,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 a8c59a8ec54..aa51e1f540d 100644 --- a/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs +++ b/src/Aspire.Dashboard/Components/Layout/MainLayout.razor.cs @@ -2,11 +2,13 @@ // 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.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; @@ -112,12 +114,17 @@ 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; private Task ToggleTerminalDockAsync() => _terminalDock?.ToggleAsync() ?? Task.CompletedTask; protected override async Task OnInitializedAsync() { + await DashboardAuthenticationState.EnsureAuthenticatedAsync(Options.CurrentValue, AuthenticationState); + ViewPreferences.Changed += OnViewPreferencesChanged; await ViewPreferences.EnsureLoadedAsync(); 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 841a70619e2..b4979ded3fe 100644 --- a/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor +++ b/src/Aspire.Dashboard/Components/Pages/TerminalWindow.razor @@ -1,6 +1,6 @@ @page "/terminal-window/apphost/{TerminalId}" @page "/terminal-window/resource/{ResourceName}" -@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 e9e9e42f339..379dbdce8b6 100644 --- a/src/Aspire.Dashboard/Components/Routes.razor +++ b/src/Aspire.Dashboard/Components/Routes.razor @@ -14,33 +14,46 @@ - - + + + + + + + + + + + + + - @Loc[nameof(Resources.Routes.NotFoundPageTitle)] - @if (DashboardExperienceComponents.TryGetLegacyNotFound( - NavigationManager, - out var legacyLayout, - out var legacyNotFound)) - { - - - - } - else - { - - - - } + + + + @Loc[nameof(Resources.Routes.NotFoundPageTitle)] + @if (DashboardExperienceComponents.TryGetLegacyNotFound( + NavigationManager, + out var legacyLayout, + out var legacyNotFound)) + { + + + + } + else + { + + + + } + + + + + - -@code { - private ViewportInformation? _viewportInformation; - - private static Type GetDefaultLayout(RouteData routeData) => - DashboardExperienceComponents.GetDefaultLayout(routeData.PageType); -} diff --git a/src/Aspire.Dashboard/Components/Routes.razor.cs b/src/Aspire.Dashboard/Components/Routes.razor.cs new file mode 100644 index 00000000000..0b0abc8e887 --- /dev/null +++ b/src/Aspire.Dashboard/Components/Routes.razor.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using RouteData = Microsoft.AspNetCore.Components.RouteData; + +namespace Aspire.Dashboard.Components; + +public partial class Routes +{ + private ViewportInformation? _viewportInformation; + + private static Type GetDefaultLayout(RouteData routeData) => + DashboardExperienceComponents.GetDefaultLayout(routeData.PageType); +} diff --git a/src/Aspire.Dashboard/Resources/Routes.Designer.cs b/src/Aspire.Dashboard/Resources/Routes.Designer.cs index 02bb3e628c4..cbcbd1e279d 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/src/Aspire.Hosting/ApplicationModel/HostUrl.cs b/src/Aspire.Hosting/ApplicationModel/HostUrl.cs index d9c3512f430..d216de490e6 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 e7e419ed17a..188b7fc177e 100644 --- a/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs +++ b/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs @@ -1831,6 +1831,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.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 2bee02f9496..a44a1f01646 100644 --- a/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs +++ b/tests/Aspire.Cli.Tests/DotNet/DotNetCliRunnerTests.cs @@ -840,9 +840,11 @@ public void ShouldForwardProcessPathAsAspireCliPathAllowsAdjacentBundleLayout() } [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task RestoreAsyncRunsDotnetRestoreCommand(bool candidate) + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task RestoreAsyncRunsDotnetRestoreCommand(bool noAutoResponse, bool candidate) { using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); var projectFile = new FileInfo(Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.csproj")); @@ -854,6 +856,7 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand(bool candidate) var targets = new FileInfo(Path.Combine(workspace.WorkspaceRoot.FullName, "candidate;targets%('literal')@$?.targets")); var options = new ProcessInvocationOptions { + NoAutoResponse = noAutoResponse, NuGetRestoreTargetsFile = candidate ? targets : null }; @@ -863,9 +866,16 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand(bool candidate) executionContext, (args, _, _, _) => { - Assert.Equal(candidate - ? ["restore", projectFile.FullName, $"-property:NuGetRestoreTargets={MSBuildEscaping.Escape(targets.FullName)}"] - : ["restore", projectFile.FullName], args); + var expected = new List { "restore", projectFile.FullName }; + if (noAutoResponse) + { + expected.Add("-noAutoResponse"); + } + if (candidate) + { + expected.Add($"-property:NuGetRestoreTargets={MSBuildEscaping.Escape(targets.FullName)}"); + } + Assert.Equal(expected, args); }, 0); @@ -874,6 +884,49 @@ public async Task RestoreAsyncRunsDotnetRestoreCommand(bool candidate) 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() { @@ -911,8 +964,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")); @@ -921,7 +978,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( @@ -929,13 +986,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 b4bb73462b9..6e4ffbdf8c9 100644 --- a/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs +++ b/tests/Aspire.Cli.Tests/DotNet/ProcessInvocationOptionsTests.cs @@ -21,6 +21,7 @@ public void Clone_CopiesEveryProperty() StandardOutputCallback = _ => { }, StandardErrorCallback = _ => { }, NoLaunchProfile = true, + NoAutoResponse = true, NoRestore = true, ExcludeRestorePackageImports = true, NuGetRestoreTargetsFile = new FileInfo(Path.Combine(Path.GetFullPath("."), "Candidate.targets")), diff --git a/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs b/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs index 7dd5d4919d6..b3f6a1189d8 100644 --- a/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs +++ b/tests/Aspire.Cli.Tests/Projects/AppHostServerProjectTests.cs @@ -46,6 +46,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 void DiscoveryIdentityMatchesTheExistingProjectPath() { diff --git a/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs b/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs index f5c97e814b0..388eac76b36 100644 --- a/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs +++ b/tests/Aspire.Cli.Tests/Projects/PrebuiltAppHostServerTests.cs @@ -3164,8 +3164,9 @@ public async Task PrepareAsync_WithProjectReferencesAndNoRequestedChannel_UsesAm var dotNetCliRunner = new TestDotNetCliRunner { - BuildAsyncCallback = (projectFilePath, _, _, _) => + BuildAsyncCallback = (projectFilePath, _, options, _) => { + Assert.True(options.NoAutoResponse); generatedProject = XDocument.Load(projectFilePath.FullName); WriteClosureInputs( projectFilePath.Directory!, diff --git a/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs b/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs index 3534d221ae8..8dd9710dd87 100644 --- a/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs +++ b/tests/Aspire.Cli.Tests/TestServices/TestAppHostServerProjectFactory.cs @@ -19,6 +19,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, FileInfo appHostFile, CancellationToken cancellationToken) { AppHostFile = appHostFile; diff --git a/tests/Aspire.Cli.Tests/Utils/FileDeleteHelperTests.cs b/tests/Aspire.Cli.Tests/Utils/FileDeleteHelperTests.cs new file mode 100644 index 00000000000..0f9d2ff5722 --- /dev/null +++ b/tests/Aspire.Cli.Tests/Utils/FileDeleteHelperTests.cs @@ -0,0 +1,56 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Aspire.Cli.Utils; +using Microsoft.AspNetCore.InternalTesting; +using Microsoft.Extensions.Time.Testing; + +namespace Aspire.Cli.Tests.Utils; + +public class FileDeleteHelperTests(ITestOutputHelper outputHelper) +{ + [Fact] + [SkipOnPlatform(TestPlatforms.Linux | TestPlatforms.OSX | TestPlatforms.FreeBSD, "Windows file sharing semantics are required.")] + public async Task DeleteDirectoryWithRetryAsync_DeletesDirectoryOnceTransientLockIsReleased() + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var directory = workspace.CreateDirectory("server").FullName; + var filePath = Path.Combine(directory, "Aspire.Hosting.dll"); + await File.WriteAllTextAsync(filePath, "assembly"); + var timeProvider = new FakeTimeProvider(); + + using var lockingStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None); + var deleteTask = FileDeleteHelper.DeleteDirectoryWithRetryAsync(directory, timeProvider, TestContext.Current.CancellationToken); + + Assert.False(deleteTask.IsCompleted); + Assert.True(Directory.Exists(directory)); + + lockingStream.Dispose(); + timeProvider.Advance(TimeSpan.FromSeconds(1)); + await deleteTask.DefaultTimeout(); + + Assert.False(Directory.Exists(directory)); + } + + [Fact] + [SkipOnPlatform(TestPlatforms.Linux | TestPlatforms.OSX | TestPlatforms.FreeBSD, "Windows file sharing semantics are required.")] + public async Task DeleteDirectoryWithRetryAsync_ThrowsWhenLockOutlastsRetryBudget() + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var directory = workspace.CreateDirectory("server").FullName; + var filePath = Path.Combine(directory, "Aspire.Hosting.dll"); + await File.WriteAllTextAsync(filePath, "assembly"); + var timeProvider = new FakeTimeProvider(); + + using (new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + var deleteTask = FileDeleteHelper.DeleteDirectoryWithRetryAsync(directory, timeProvider, TestContext.Current.CancellationToken); + + timeProvider.Advance(TimeSpan.FromSeconds(2)); + var exception = await Assert.ThrowsAnyAsync(() => deleteTask).DefaultTimeout(); + Assert.True(exception is IOException or UnauthorizedAccessException, exception.ToString()); + } + + Assert.Equal("assembly", await File.ReadAllTextAsync(filePath)); + } +} 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 7e56c5a0429..70efd185438 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Interactions/InteractionsProviderTests.cs @@ -4,6 +4,7 @@ using System.Threading.Channels; 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; @@ -15,6 +16,7 @@ using Microsoft.AspNetCore.InternalTesting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; using Xunit; @@ -31,6 +33,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 69d8fecc98a..444f5c87a30 100644 --- a/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs +++ b/tests/Aspire.Dashboard.Components.Tests/Layout/MainLayoutTests.cs @@ -31,6 +31,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 HeaderHelp_IsSingleActionThatOpensHelpDialog() { 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 f8f85c12258..2e13167cba8 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.Model; using Aspire.Dashboard.Tests.Shared; using Aspire.DashboardService.Proto.V1; @@ -14,6 +15,7 @@ using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.InternalTesting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; using Microsoft.JSInterop; using Xunit; @@ -24,6 +26,28 @@ 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("shell")] [InlineData("shell-instance")] @@ -287,6 +311,29 @@ public void UnavailableInstanceId_DoesNotAttachToAnotherReplica(string resourceN 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(false, false)] [InlineData(true, true)] diff --git a/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs b/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs new file mode 100644 index 00000000000..f51fbfeca38 --- /dev/null +++ b/tests/Aspire.Dashboard.Components.Tests/RoutesTests.cs @@ -0,0 +1,174 @@ +// 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")] + [InlineData("/legacy")] + [InlineData("/legacy/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.Playwright.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs b/tests/Aspire.Dashboard.Playwright.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs index 778849f22d9..40404f830ae 100644 --- a/tests/Aspire.Dashboard.Playwright.Tests/Integration/Playwright/BrowserTokenAuthenticationTests.cs +++ b/tests/Aspire.Dashboard.Playwright.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']"); } diff --git a/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs b/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs index ba2dfac6e26..ea79b3ef9df 100644 --- a/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs +++ b/tests/Aspire.Hosting.Tests/Dcp/DcpExecutorTests.cs @@ -9905,6 +9905,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); + } + [Theory] [InlineData("localhost")] [InlineData("frontend.dev.localhost")] @@ -11578,6 +11934,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 e11cbf570db..38aaa075f24 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