diff --git a/src/Aspire.Cli/Commands/ResourceCommand.cs b/src/Aspire.Cli/Commands/ResourceCommand.cs index 1f4a4ad21fd..127f41264cb 100644 --- a/src/Aspire.Cli/Commands/ResourceCommand.cs +++ b/src/Aspire.Cli/Commands/ResourceCommand.cs @@ -222,7 +222,8 @@ private static async Task LoadCommandArgumentsAsync( private static async Task GetCommandMetadataAsync(IAppHostAuxiliaryBackchannel connection, string resourceName, string commandName, bool includeHidden, CancellationToken cancellationToken) { - var snapshots = await connection.GetResourceSnapshotsAsync(includeHidden, cancellationToken).ConfigureAwait(false); + var effectiveIncludeHidden = includeHidden || !string.IsNullOrEmpty(resourceName); + var snapshots = await connection.GetResourceSnapshotsAsync(effectiveIncludeHidden, cancellationToken).ConfigureAwait(false); var resources = ResourceSnapshotMapper.ResolveResources(resourceName, snapshots); var lookupCommandName = s_legacyCommandNameMap.GetValueOrDefault(commandName, commandName); @@ -233,7 +234,8 @@ private static async Task LoadCommandArgumentsAsync( private static async Task<(string Name, string Description)[]> GetAvailableCommandMetadataAsync(IAppHostAuxiliaryBackchannel connection, string resourceName, bool includeHidden, CancellationToken cancellationToken) { - var snapshots = await connection.GetResourceSnapshotsAsync(includeHidden, cancellationToken).ConfigureAwait(false); + var effectiveIncludeHidden = includeHidden || !string.IsNullOrEmpty(resourceName); + var snapshots = await connection.GetResourceSnapshotsAsync(effectiveIncludeHidden, cancellationToken).ConfigureAwait(false); var resources = ResourceSnapshotMapper.ResolveResources(resourceName, snapshots); return resources diff --git a/src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs b/src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs index ec1e37facc6..f81f5b978cc 100644 --- a/src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs +++ b/src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs @@ -1851,7 +1851,8 @@ passed to the Aspire command line (arguments specified after '--'). Specifying t app_host_file_path (str): The path to the AppHost source file. By default, this will use the ASPIRE_APPHOST_FILEPATH environment variable if set. container_registry_override (str): When containers are used, use this value to override the container registry. - disable_dashboard (bool): Determines whether the dashboard is disabled. + disable_dashboard (bool): Determines whether dashboard auto-start is disabled. + In run mode, the dashboard resource is still added and can be started explicitly later. dashboard_application_name (str): The application name to display in the dashboard. allow_unsecured_transport (bool): Allows the use of HTTP urls for the AppHost resource endpoint. enable_resource_logging (bool): Enables resource logging. diff --git a/src/Aspire.Hosting/Ats/CreateBuilderOptions.cs b/src/Aspire.Hosting/Ats/CreateBuilderOptions.cs index 8dde4329874..b09bdb727f9 100644 --- a/src/Aspire.Hosting/Ats/CreateBuilderOptions.cs +++ b/src/Aspire.Hosting/Ats/CreateBuilderOptions.cs @@ -31,7 +31,8 @@ internal sealed class CreateBuilderOptions public string? ContainerRegistryOverride { get; set; } /// - /// Determines whether the dashboard is disabled. + /// Determines whether dashboard auto-start should be disabled at app host startup. + /// In run mode, the dashboard resource is still added and can be started explicitly later. /// public bool DisableDashboard { get; set; } diff --git a/src/Aspire.Hosting/Backchannel/AppHostRpcTarget.cs b/src/Aspire.Hosting/Backchannel/AppHostRpcTarget.cs index d793888576d..f32724e023c 100644 --- a/src/Aspire.Hosting/Backchannel/AppHostRpcTarget.cs +++ b/src/Aspire.Hosting/Backchannel/AppHostRpcTarget.cs @@ -20,7 +20,6 @@ internal class AppHostRpcTarget( ProfilingTelemetry profilingTelemetry, PipelineActivityReporter activityReporter, IHostApplicationLifetime lifetime, - DistributedApplicationOptions options, AppHostStartupState startupState, IInteractionFileUploadStore fileUploadStore, IConfiguration configuration) @@ -178,13 +177,6 @@ public void CancelInflightRpcCalls() public async Task GetDashboardUrlsAsync(CancellationToken cancellationToken) { using var activity = profilingTelemetry.StartJsonRpcServerCall(nameof(GetDashboardUrlsAsync), streaming: false); - if (!options.DashboardEnabled) - { - logger.LogDebug("Dashboard URL requested but dashboard is disabled."); - activity.SetDashboardHealthy(false); - return new DashboardUrlsState { DashboardHealthy = false }; - } - try { var urls = await DashboardUrlsHelper.GetDashboardUrlsAsync(serviceProvider, logger, cancellationToken).ConfigureAwait(false); diff --git a/src/Aspire.Hosting/Backchannel/DashboardUrlsHelper.cs b/src/Aspire.Hosting/Backchannel/DashboardUrlsHelper.cs index 9522d2d1fa1..7a59527e344 100644 --- a/src/Aspire.Hosting/Backchannel/DashboardUrlsHelper.cs +++ b/src/Aspire.Hosting/Backchannel/DashboardUrlsHelper.cs @@ -31,9 +31,8 @@ public static async Task GetDashboardConnectionInfoAsyn ILogger logger, CancellationToken cancellationToken = default) { - // Check whether the dashboard resource is registered at all. If it isn't (e.g. the user - // called DisableDashboard()), return immediately rather than waiting forever for a resource - // event that will never arrive. + // Check whether the dashboard resource is registered at all. If it isn't, return + // immediately rather than waiting forever for a resource event that will never arrive. var appModel = serviceProvider.GetService(); var dashboardResource = appModel?.Resources.SingleOrDefault( r => string.Equals(r.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName)) as IResourceWithEndpoints; @@ -48,6 +47,26 @@ public static async Task GetDashboardConnectionInfoAsyn using var activity = profilingTelemetry.StartDashboardGetConnectionInfo(); var resourceNotificationService = serviceProvider.GetRequiredService(); + if (dashboardResource.TryGetLastAnnotation(out _)) + { + if (!resourceNotificationService.TryGetCurrentState(KnownResourceNames.AspireDashboard, out var dashboardEvent)) + { + logger.LogDebug("Dashboard resource is explicit-start and has no current state. Returning unavailable state."); + activity.SetDashboardHealthy(false); + return DashboardConnectionInfo.Unhealthy; + } + + var state = dashboardEvent.Snapshot.State?.Text; + var isStarting = state == KnownResourceStates.Starting || state == KnownResourceStates.Building; + var isRunning = state == KnownResourceStates.Running; + if (!isStarting && !isRunning) + { + logger.LogDebug("Dashboard resource is explicit-start and in state '{State}'. Returning unavailable state.", state ?? "(null)"); + activity.SetDashboardHealthy(false); + return DashboardConnectionInfo.Unhealthy; + } + } + // Wait for the dashboard to be healthy using (var waitActivity = profilingTelemetry.StartDashboardWaitHealthy()) { diff --git a/src/Aspire.Hosting/Dashboard/DashboardEventHandlers.cs b/src/Aspire.Hosting/Dashboard/DashboardEventHandlers.cs index bfc2628bd64..8cec5b16a01 100644 --- a/src/Aspire.Hosting/Dashboard/DashboardEventHandlers.cs +++ b/src/Aspire.Hosting/Dashboard/DashboardEventHandlers.cs @@ -17,6 +17,8 @@ using Aspire.Hosting.Devcontainers.Codespaces; using Aspire.Hosting.Eventing; using Aspire.Hosting.Lifecycle; +using Aspire.Hosting.Orchestrator; +using Aspire.Hosting.Resources; using Aspire.Hosting.Utils; using Aspire.Shared; using Aspire.Shared.ConsoleLogs; @@ -34,6 +36,7 @@ internal sealed class DashboardEventHandlers(IConfiguration configuration, ILogger distributedApplicationLogger, IDashboardEndpointProvider dashboardEndpointProvider, DistributedApplicationExecutionContext executionContext, + DistributedApplicationOptions distributedApplicationOptions, ResourceNotificationService resourceNotificationService, ResourceLoggerService resourceLoggerService, ILoggerFactory loggerFactory, @@ -320,7 +323,14 @@ private void AddDashboardResource(DistributedApplicationModel model) if (!File.Exists(dashboardDll)) { - distributedApplicationLogger.LogError("Dashboard DLL not found: {Path}", dashboardDll); + if (distributedApplicationOptions.DisableDashboard) + { + distributedApplicationLogger.LogDebug("Dashboard DLL not found while dashboard auto-start is disabled: {Path}", dashboardDll); + } + else + { + distributedApplicationLogger.LogError("Dashboard DLL not found: {Path}", dashboardDll); + } } dashboardResource = new ExecutableResource(KnownResourceNames.AspireDashboard, "dotnet", dashboardWorkingDirectory ?? ""); @@ -343,9 +353,20 @@ private void AddDashboardResource(DistributedApplicationModel model) private void ConfigureAspireDashboardResource(IResource dashboardResource) { + var isDashboardExplicitStart = distributedApplicationOptions.DisableDashboard; + if (isDashboardExplicitStart && + !dashboardResource.TryGetLastAnnotation(out _)) + { + dashboardResource.Annotations.Add(new ExplicitStartupAnnotation()); + } + // The dashboard resource can be visible during development. We don't want people to be able to stop the dashboard from inside the dashboard. // Exclude the lifecycle commands from the dashboard resource so they're not accidently clicked during development. dashboardResource.Annotations.Add(new ExcludeLifecycleCommandsAnnotation()); + if (isDashboardExplicitStart) + { + AddDisabledDashboardStartCommand(dashboardResource); + } // Add the ContentView icon to the dashboard resource dashboardResource.Annotations.Add(new ResourceIconAnnotation("ContentView")); @@ -502,6 +523,56 @@ private void ConfigureAspireDashboardResource(IResource dashboardResource) eventing.Subscribe(dashboardResource, DashboardStarted); } + private static void AddDisabledDashboardStartCommand(IResource dashboardResource) + { + if (dashboardResource.TryGetAnnotationsOfType(out var commands) && + commands.Any(command => string.Equals(command.Name, KnownResourceCommands.StartCommand, StringComparison.Ordinal))) + { + return; + } + + dashboardResource.Annotations.Add(new ResourceCommandAnnotation( + name: KnownResourceCommands.StartCommand, + displayName: CommandStrings.StartName, + executeCommand: async context => + { + var orchestrator = context.Services.GetRequiredService(); + await orchestrator.StartResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false); + return new ExecuteCommandResult + { + Success = true, + Message = string.Format(CultureInfo.InvariantCulture, CommandStrings.ResourceStarted, dashboardResource.GetResolvedDisplayResourceName(context.ResourceName)) + }; + }, + updateState: context => + { + var state = context.ResourceSnapshot.State?.Text; + if (state == KnownResourceStates.Starting || + state == KnownResourceStates.Building || + state == KnownResourceStates.RuntimeUnhealthy || + string.IsNullOrEmpty(state)) + { + return ResourceCommandState.Disabled; + } + + if (KnownResourceStates.TerminalStates.Contains(state) || + state == KnownResourceStates.NotStarted || + state == KnownResourceStates.Waiting || + state == "Unknown") + { + return ResourceCommandState.Enabled; + } + + return ResourceCommandState.Hidden; + }, + displayDescription: CommandStrings.StartDescription, + arguments: null, + confirmationMessage: null, + iconName: "Play", + iconVariant: IconVariant.Filled, + isHighlighted: true)); + } + private async Task DashboardStarted(ResourceReadyEvent @event, CancellationToken cancellationToken) { var options = dashboardOptions.Value; diff --git a/src/Aspire.Hosting/Dashboard/DashboardServiceHost.cs b/src/Aspire.Hosting/Dashboard/DashboardServiceHost.cs index c2c75e90e01..caccaafa721 100644 --- a/src/Aspire.Hosting/Dashboard/DashboardServiceHost.cs +++ b/src/Aspire.Hosting/Dashboard/DashboardServiceHost.cs @@ -33,13 +33,12 @@ internal sealed class DashboardServiceHost : IHostedService private readonly TaskCompletionSource _resourceServiceUri = new(); /// - /// if is . + /// in publish mode. /// private readonly WebApplication? _app; private readonly ILogger _logger; public DashboardServiceHost( - DistributedApplicationOptions options, DistributedApplicationModel applicationModel, IConfiguration configuration, DistributedApplicationExecutionContext executionContext, @@ -54,9 +53,9 @@ public DashboardServiceHost( { _logger = loggerFactory.CreateLogger(); - if (!options.DashboardEnabled || executionContext.IsPublishMode) + if (executionContext.IsPublishMode) { - _logger.LogDebug("Dashboard is not enabled so skipping hosting the resource service."); + _logger.LogDebug("Skipping hosting the resource service in publish mode."); _resourceServiceUri.SetCanceled(); return; } diff --git a/src/Aspire.Hosting/Dashboard/TransportOptionsValidator.cs b/src/Aspire.Hosting/Dashboard/TransportOptionsValidator.cs index 8e836798ab5..25a6e1ba46a 100644 --- a/src/Aspire.Hosting/Dashboard/TransportOptionsValidator.cs +++ b/src/Aspire.Hosting/Dashboard/TransportOptionsValidator.cs @@ -12,7 +12,7 @@ internal class TransportOptionsValidator(IConfiguration configuration, Distribut { public ValidateOptionsResult Validate(string? name, TransportOptions transportOptions) { - var effectiveAllowUnsecureTransport = transportOptions.AllowUnsecureTransport || distributedApplicationOptions.DisableDashboard || distributedApplicationOptions.AllowUnsecuredTransport; + var effectiveAllowUnsecureTransport = transportOptions.AllowUnsecureTransport || distributedApplicationOptions.AllowUnsecuredTransport; if (executionContext.IsPublishMode || effectiveAllowUnsecureTransport) { diff --git a/src/Aspire.Hosting/DistributedApplication.cs b/src/Aspire.Hosting/DistributedApplication.cs index 2e666a0bca0..b00ae83ff82 100644 --- a/src/Aspire.Hosting/DistributedApplication.cs +++ b/src/Aspire.Hosting/DistributedApplication.cs @@ -36,7 +36,7 @@ namespace Aspire.Hosting; /// /// /// The method provides additional options for -/// constructing the including disabling the Aspire dashboard (see ) or +/// constructing the including disabling Aspire dashboard auto-start in run mode (see ) or /// allowing unsecured communication between the browser and dashboard, and dashboard and app host (see . /// /// @@ -185,7 +185,7 @@ public static IDistributedApplicationBuilder CreateBuilder(string[] args) /// greater control over the behavior of the distributed application at runtime. For example providing /// an argument allows developers to force all container images to be loaded /// from a specified container registry by using the - /// property, or disabling the dashboard by using the + /// property, or disabling dashboard auto-start in run mode by using the /// property. Refer to the class for more details on /// each option that may be provided. /// diff --git a/src/Aspire.Hosting/DistributedApplicationBuilder.cs b/src/Aspire.Hosting/DistributedApplicationBuilder.cs index 4ab06839045..5a9babbf39e 100644 --- a/src/Aspire.Hosting/DistributedApplicationBuilder.cs +++ b/src/Aspire.Hosting/DistributedApplicationBuilder.cs @@ -473,69 +473,66 @@ public DistributedApplicationBuilder(DistributedApplicationOptions options) if (ExecutionContext.IsRunMode) { // Dashboard - if (!options.DisableDashboard) + if (!IsDashboardUnsecured(_innerBuilder.Configuration)) { - if (!IsDashboardUnsecured(_innerBuilder.Configuration)) + // Passed to apps as a standard OTEL attribute to include in OTLP requests and the dashboard to validate. + // Set a random API key for the OTLP exporter if one isn't already present in configuration. + // If a key is generated, it's stored in the user secrets store so that it will be auto-loaded + // on subsequent runs and not recreated. This is important to ensure it doesn't change the state + // of persistent containers (as a new key would be a spec change). + _userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:OtlpApiKey", TokenGenerator.GenerateToken); + + // Set a random API key for the Dashboard Telemetry API if one isn't already present in configuration. + _userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:DashboardApiKey", TokenGenerator.GenerateToken); + + // Determine the frontend browser token. + if (_innerBuilder.Configuration.GetString(KnownConfigNames.DashboardFrontendBrowserToken, + KnownConfigNames.Legacy.DashboardFrontendBrowserToken, fallbackOnEmpty: true) is not { } browserToken) { - // Passed to apps as a standard OTEL attribute to include in OTLP requests and the dashboard to validate. - // Set a random API key for the OTLP exporter if one isn't already present in configuration. - // If a key is generated, it's stored in the user secrets store so that it will be auto-loaded - // on subsequent runs and not recreated. This is important to ensure it doesn't change the state - // of persistent containers (as a new key would be a spec change). - _userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:OtlpApiKey", TokenGenerator.GenerateToken); - - // Set a random API key for the Dashboard Telemetry API if one isn't already present in configuration. - _userSecretsManager.GetOrSetSecret(_innerBuilder.Configuration, "AppHost:DashboardApiKey", TokenGenerator.GenerateToken); - - // Determine the frontend browser token. - if (_innerBuilder.Configuration.GetString(KnownConfigNames.DashboardFrontendBrowserToken, - KnownConfigNames.Legacy.DashboardFrontendBrowserToken, fallbackOnEmpty: true) is not { } browserToken) + // No browser token was specified in configuration, so generate one. + browserToken = TokenGenerator.GenerateToken(); + } + + _innerBuilder.Configuration.AddInMemoryCollection( + new Dictionary { - // No browser token was specified in configuration, so generate one. - browserToken = TokenGenerator.GenerateToken(); + ["AppHost:BrowserToken"] = browserToken } + ); + + // Determine the resource service API key. + var apiKey = _innerBuilder.Configuration.GetString(KnownConfigNames.DashboardResourceServiceClientApiKey, + KnownConfigNames.Legacy.DashboardResourceServiceClientApiKey, fallbackOnEmpty: true); - _innerBuilder.Configuration.AddInMemoryCollection( - new Dictionary - { - ["AppHost:BrowserToken"] = browserToken - } - ); - - // Determine the resource service API key. - var apiKey = _innerBuilder.Configuration.GetString(KnownConfigNames.DashboardResourceServiceClientApiKey, - KnownConfigNames.Legacy.DashboardResourceServiceClientApiKey, fallbackOnEmpty: true); - - // If no API key was specified in configuration, generate one. - apiKey ??= TokenGenerator.GenerateToken(); - - _innerBuilder.Configuration.AddInMemoryCollection( - new Dictionary - { - ["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.ApiKey), - ["AppHost:ResourceService:ApiKey"] = apiKey - } - ); - } - else - { - // The dashboard is enabled but is unsecured. Set auth mode config setting to reflect this state. - _innerBuilder.Configuration.AddInMemoryCollection( - new Dictionary - { - ["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.Unsecured) - } - ); - } + // If no API key was specified in configuration, generate one. + apiKey ??= TokenGenerator.GenerateToken(); - _innerBuilder.Services.AddOptions().ValidateOnStart().PostConfigure(MapTransportOptionsFromCustomKeys); - _innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, TransportOptionsValidator>()); - _innerBuilder.Services.AddSingleton(); - _innerBuilder.Services.AddHostedService(sp => sp.GetRequiredService()); - _innerBuilder.Services.AddSingleton(); - _innerBuilder.Services.AddEventingSubscriber(); - _innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, ConfigureDefaultDashboardOptions>()); + _innerBuilder.Configuration.AddInMemoryCollection( + new Dictionary + { + ["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.ApiKey), + ["AppHost:ResourceService:ApiKey"] = apiKey + } + ); } + else + { + // The dashboard is enabled but is unsecured. Set auth mode config setting to reflect this state. + _innerBuilder.Configuration.AddInMemoryCollection( + new Dictionary + { + ["AppHost:ResourceService:AuthMode"] = nameof(ResourceServiceAuthMode.Unsecured) + } + ); + } + + _innerBuilder.Services.AddOptions().ValidateOnStart().PostConfigure(MapTransportOptionsFromCustomKeys); + _innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, TransportOptionsValidator>()); + _innerBuilder.Services.AddSingleton(); + _innerBuilder.Services.AddHostedService(sp => sp.GetRequiredService()); + _innerBuilder.Services.AddSingleton(); + _innerBuilder.Services.AddEventingSubscriber(); + _innerBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, ConfigureDefaultDashboardOptions>()); if (options.EnableResourceLogging) { diff --git a/src/Aspire.Hosting/DistributedApplicationOptions.cs b/src/Aspire.Hosting/DistributedApplicationOptions.cs index f9465ccf57c..8f9d33666ed 100644 --- a/src/Aspire.Hosting/DistributedApplicationOptions.cs +++ b/src/Aspire.Hosting/DistributedApplicationOptions.cs @@ -58,7 +58,8 @@ public DistributedApplicationOptions() public string? AssemblyName { get; set; } /// - /// Determines whether the dashboard is disabled. + /// Determines whether dashboard auto-start should be disabled at app host startup. + /// In run mode, the dashboard resource is still added and can be started explicitly later. /// public bool DisableDashboard { get; set; } diff --git a/src/Aspire.Hosting/OtlpConfigurationExtensions.cs b/src/Aspire.Hosting/OtlpConfigurationExtensions.cs index 91224058581..f899f4bbeff 100644 --- a/src/Aspire.Hosting/OtlpConfigurationExtensions.cs +++ b/src/Aspire.Hosting/OtlpConfigurationExtensions.cs @@ -292,6 +292,16 @@ private static (EndpointReference Endpoint, string Protocol)? ResolveOtlpEndpoin return null; } + if (dashboardResource.TryGetLastAnnotation(out _)) + { + // The dashboard is present in the model (so its start command works) but won't auto-start, so its + // endpoints are never allocated. Referencing them here would leave the dictionary holding an + // EndpointReference whose value never resolves, hanging any evaluation of this resource's environment + // variables. Fall back to the static configuration-based endpoint instead, as if the dashboard were + // absent from the model. + return null; + } + var grpcEndpoint = dashboardResource.GetEndpoint(KnownEndpointNames.OtlpGrpcEndpointName); var httpEndpoint = dashboardResource.GetEndpoint(KnownEndpointNames.OtlpHttpEndpointName); diff --git a/src/Aspire.Hosting/Pipelines/DistributedApplicationPipeline.cs b/src/Aspire.Hosting/Pipelines/DistributedApplicationPipeline.cs index 2dc64dfb87f..a2d83e05516 100644 --- a/src/Aspire.Hosting/Pipelines/DistributedApplicationPipeline.cs +++ b/src/Aspire.Hosting/Pipelines/DistributedApplicationPipeline.cs @@ -351,7 +351,7 @@ deploymentStateManager.StateFilePath is string existingStateFilePath && Description = "Validates compute resource bindings before startup.", Action = static context => { - ValidateComputeEnvironmentBindings(context.Model); + ValidateComputeEnvironmentBindings(context.Model, context.ExecutionContext); return Task.CompletedTask; }, RequiredBySteps = [WellKnownPipelineSteps.BeforeStart], @@ -379,7 +379,7 @@ deploymentStateManager.StateFilePath is string existingStateFilePath && }); } - private static void ValidateComputeEnvironmentBindings(DistributedApplicationModel model) + private static void ValidateComputeEnvironmentBindings(DistributedApplicationModel model, DistributedApplicationExecutionContext executionContext) { // With multiple compute environments there is no unambiguous default. Surface a clear // error for any compute resource that hasn't been explicitly bound, rather than letting @@ -394,7 +394,14 @@ private static void ValidateComputeEnvironmentBindings(DistributedApplicationMod var unboundResources = model.Resources .OfType() - .Where(resource => resource.GetComputeEnvironment() is null) + .Where(resource => + resource.GetComputeEnvironment() is null && + // When DisableDashboard=true, the dashboard resource remains in the model with + // ExplicitStartupAnnotation so users can start it on demand. It is intentionally + // not auto-assigned to run-mode compute environments and should not block validation. + !(string.Equals(resource.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName) && + executionContext.IsRunMode && + resource.TryGetLastAnnotation(out _))) .ToList(); if (unboundResources.Count == 0) diff --git a/tests/Aspire.Cli.Tests/Commands/ResourceCommandTests.cs b/tests/Aspire.Cli.Tests/Commands/ResourceCommandTests.cs index 3789bee05fd..47143ebea0e 100644 --- a/tests/Aspire.Cli.Tests/Commands/ResourceCommandTests.cs +++ b/tests/Aspire.Cli.Tests/Commands/ResourceCommandTests.cs @@ -1652,6 +1652,36 @@ public async Task ResourceCommand_IncludeHiddenExecutesHiddenResourceCommandWith AssertJsonObject(backchannel.ExecuteResourceCommandArguments, ("message", "from hidden resource")); } + [Fact] + public async Task ResourceCommand_NamedHiddenResourceExecutesCommandWithoutIncludeHidden() + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + + var backchannel = new TestAppHostAuxiliaryBackchannel + { + ExecuteResourceCommandResult = new ExecuteResourceCommandResponse { Success = true }, + ResourceSnapshots = + [ + CreateResourceSnapshot( + "hidden-worker", + "Hidden", + CreateCommand( + "configure", + CreateArgument("message"))) + ] + }; + await using var provider = CreateServiceProvider(workspace, outputHelper, backchannel); + + var command = provider.GetRequiredService(); + var result = command.Parse("resource hidden-worker configure -- --message \"from named hidden resource\""); + + var exitCode = await result.InvokeAsync().DefaultTimeout(); + + Assert.Equal(CliExitCodes.Success, exitCode); + Assert.Equal(1, backchannel.ExecuteResourceCommandCallCount); + AssertJsonObject(backchannel.ExecuteResourceCommandArguments, ("message", "from named hidden resource")); + } + [Fact] public async Task ResourceCommand_DoesNotForwardCommandOptionWithoutDelimiterWhenNameCollidesWithCliOption() { diff --git a/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/AtsGeneratedAspire.verified.py b/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/AtsGeneratedAspire.verified.py index 58710bef30e..95076e97f35 100644 --- a/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/AtsGeneratedAspire.verified.py +++ b/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/AtsGeneratedAspire.verified.py @@ -2997,7 +2997,8 @@ def create_builder( app_host_file_path (str): The path to the AppHost source file. By default, this will use the ASPIRE_APPHOST_FILEPATH environment variable if set. container_registry_override (str): When containers are used, use this value to override the container registry. - disable_dashboard (bool): Determines whether the dashboard is disabled. + disable_dashboard (bool): Determines whether dashboard auto-start is disabled. + In run mode, the dashboard resource is still added and can be started explicitly later. dashboard_application_name (str): The application name to display in the dashboard. allow_unsecured_transport (bool): Allows the use of HTTP urls for the AppHost resource endpoint. enable_resource_logging (bool): Enables resource logging. diff --git a/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.py b/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.py index 387b09fadb4..35fd779341d 100644 --- a/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.py +++ b/tests/Aspire.Hosting.CodeGeneration.Python.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.py @@ -12996,7 +12996,8 @@ def create_builder( app_host_file_path (str): The path to the AppHost source file. By default, this will use the ASPIRE_APPHOST_FILEPATH environment variable if set. container_registry_override (str): When containers are used, use this value to override the container registry. - disable_dashboard (bool): Determines whether the dashboard is disabled. + disable_dashboard (bool): Determines whether dashboard auto-start is disabled. + In run mode, the dashboard resource is still added and can be started explicitly later. dashboard_application_name (str): The application name to display in the dashboard. allow_unsecured_transport (bool): Allows the use of HTTP urls for the AppHost resource endpoint. enable_resource_logging (bool): Enables resource logging. diff --git a/tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.ts b/tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.ts index 2c1a916cb89..b3c9af913da 100644 --- a/tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.ts +++ b/tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Snapshots/TwoPassScanningGeneratedAspire.verified.ts @@ -916,7 +916,7 @@ export interface CreateBuilderOptions { appHostFilePath?: string | null; /** When containers are used, use this value to override the container registry. */ containerRegistryOverride?: string | null; - /** Determines whether the dashboard is disabled. */ + /** Determines whether dashboard auto-start should be disabled at app host startup. In run mode, the dashboard resource is still added and can be started explicitly later. */ disableDashboard?: boolean; /** The application name to display in the dashboard. */ dashboardApplicationName?: string | null; diff --git a/tests/Aspire.Hosting.Testing.Tests/DashboardTestingBuilderTests.cs b/tests/Aspire.Hosting.Testing.Tests/DashboardTestingBuilderTests.cs index a1a4a8284df..6714c99e120 100644 --- a/tests/Aspire.Hosting.Testing.Tests/DashboardTestingBuilderTests.cs +++ b/tests/Aspire.Hosting.Testing.Tests/DashboardTestingBuilderTests.cs @@ -26,14 +26,18 @@ public class DashboardTestingBuilderTests private const string AppHostResourceServiceApiKey = "AppHost:ResourceService:ApiKey"; [Fact] - public void DashboardIsDisabledByDefault() + public async Task DashboardIsDisabledByDefault() { var options = new DistributedApplicationTestingBuilderOptions(); Assert.False(options.EnableDashboard); using var builder = DistributedApplicationTestingBuilder.Create(); - Assert.Null(builder.Services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(DashboardServiceHost))); + + // Dashboard service registration is unconditional in run mode (see DistributedApplicationBuilder), so the + // absence of DashboardServiceHost is no longer a valid signal for "disabled". Instead, the dashboard + // resource is present but marked explicit-start so it does not auto-start. + await AssertDashboardIsExplicitStartAsync(builder); } [Theory] @@ -127,8 +131,13 @@ public async Task ExistingDefaultCallsRemainUnambiguous() await using var typeBuilder = await DistributedApplicationTestingBuilder.CreateAsync(typeof(Projects.TestingAppHost1_AppHost), default); - Assert.Null(genericBuilder.Services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(DashboardServiceHost))); - Assert.Null(typeBuilder.Services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(DashboardServiceHost))); + // Dashboard service registration is unconditional in run mode (see DistributedApplicationBuilder), so the + // absence of DashboardServiceHost is no longer a valid signal for "hardening not applied". These builders + // wrap a real AppHost entry point, and building them would let it run past Build() in the background + // (racing this test's own assertions), so assert against configuration instead of building: the + // EnableDashboard-only hardening in ConfigureDashboardTesting is the only thing that sets this key. + AssertDashboardTestingHardeningNotApplied(genericBuilder); + AssertDashboardTestingHardeningNotApplied(typeBuilder); await using var genericOptionsBuilder = await DistributedApplicationTestingBuilder.CreateAsync( @@ -256,6 +265,23 @@ private static DistributedApplicationTestingBuilderOptions CreateDashboardOption }; } + private static async Task AssertDashboardIsExplicitStartAsync(IDistributedApplicationTestingBuilder builder) + { + var app = await builder.BuildAsync(); + await app.ExecuteBeforeStartHooksAsync(default); + + var model = app.Services.GetRequiredService(); + var dashboard = Assert.Single(model.Resources, r => r.Name == KnownResourceNames.AspireDashboard); + Assert.True(dashboard.TryGetLastAnnotation(out _)); + } + + private static void AssertDashboardTestingHardeningNotApplied(IDistributedApplicationTestingBuilder builder) + { + // Set only by ConfigureDashboardTesting when DistributedApplicationTestingBuilderOptions.EnableDashboard + // is used, so its absence confirms the old-style default overloads did not opt into dashboard hardening. + Assert.Null(builder.Configuration["AppHost:SuppressDashboardLoginUrlInStartupSummary"]); + } + private static void AssertDashboardTestingDefaults(IDistributedApplicationTestingBuilder builder) { Assert.Equal("true", builder.Configuration["DcpPublisher:RandomizePorts"]); diff --git a/tests/Aspire.Hosting.Tests/Backchannel/AuxiliaryBackchannelRpcTargetTests.cs b/tests/Aspire.Hosting.Tests/Backchannel/AuxiliaryBackchannelRpcTargetTests.cs index 8ae06105a93..471630c2e79 100644 --- a/tests/Aspire.Hosting.Tests/Backchannel/AuxiliaryBackchannelRpcTargetTests.cs +++ b/tests/Aspire.Hosting.Tests/Backchannel/AuxiliaryBackchannelRpcTargetTests.cs @@ -252,7 +252,7 @@ await notificationService.PublishUpdateAsync(custom.Resource, s => s with var result = await target.GetResourceSnapshotsAsync().DefaultTimeout(); - var snapshot = Assert.Single(result); + var snapshot = Assert.Single(result, s => s.Name == "myresource"); // State Assert.Equal("Running", snapshot.State); @@ -1273,7 +1273,7 @@ await notificationService.PublishUpdateAsync(custom.Resource, s => s with var result = await target.GetResourceSnapshotsAsync().DefaultTimeout(); - var snapshot = Assert.Single(result); + var snapshot = Assert.Single(result, s => s.Name == "myresource"); Assert.True(snapshot.Version > 0); Assert.Equal("42", Assert.IsAssignableFrom(snapshot.Properties["number"]).GetValue()); Assert.Equal(bool.TrueString, Assert.IsAssignableFrom(snapshot.Properties["flag"]).GetValue()); @@ -1321,7 +1321,7 @@ await notificationService.PublishUpdateAsync(custom.Resource, s => s with ClientCapabilities = [AuxiliaryBackchannelCapabilities.V3] }).DefaultTimeout(); - var snapshot = Assert.Single(response.Resources); + var snapshot = Assert.Single(response.Resources, s => s.Name == "myresource"); Assert.Equal(42, Assert.IsAssignableFrom(snapshot.Properties["number"]).GetValue()); Assert.True(Assert.IsAssignableFrom(snapshot.Properties["flag"]).GetValue()); var list = Assert.IsAssignableFrom(snapshot.Properties["list"]); @@ -1366,7 +1366,7 @@ await notificationService.PublishUpdateAsync(custom.Resource, s => s with var result = await target.GetResourceSnapshotsAsync().DefaultTimeout(); - var snapshot = Assert.Single(result); + var snapshot = Assert.Single(result, s => s.Name == "myapp"); Assert.Equal("true", Assert.IsAssignableFrom(snapshot.Properties["terminal.enabled"]).GetValue()); Assert.Equal("0", Assert.IsAssignableFrom(snapshot.Properties["terminal.replicaIndex"]).GetValue()); Assert.Equal("1", Assert.IsAssignableFrom(snapshot.Properties["terminal.replicaCount"]).GetValue()); @@ -1402,7 +1402,7 @@ await notificationService.PublishUpdateAsync(custom.Resource, s => s with var result = await target.GetResourceSnapshotsAsync().DefaultTimeout(); - var snapshot = Assert.Single(result); + var snapshot = Assert.Single(result, s => s.Name == "myapp"); Assert.DoesNotContain(snapshot.Properties.Keys, k => k.StartsWith("terminal.", StringComparison.Ordinal)); await app.StopAsync().DefaultTimeout(TestConstants.LongTimeoutTimeSpan); @@ -2727,16 +2727,56 @@ public async Task ExecuteResourceCommandAsync_ValidateOnlyWithMissingCommand_Ret } [Fact] - public async Task GetDashboardUrlsAsync_ReturnsUnhealthy_WhenDashboardResourceIsAbsent() + public async Task GetDashboardUrlsAsync_ReturnsUnhealthy_WhenDashboardIsExplicitStart() { - // When the dashboard is disabled, there is no dashboard resource in the app model. - // The method must return promptly rather than waiting forever for a resource event - // that will never arrive. + // When the dashboard auto-start is disabled, use a real NotStarted snapshot. + // URL lookup should still return promptly as unhealthy. using var builder = TestDistributedApplicationBuilder.Create( options => options.DisableDashboard = true, outputHelper); using var app = builder.Build(); + await app.ExecuteBeforeStartHooksAsync(default).DefaultTimeout(); + + var model = app.Services.GetRequiredService(); + var dashboard = Assert.Single(model.Resources, r => r.Name == KnownResourceNames.AspireDashboard); + var notificationService = app.Services.GetRequiredService(); + await notificationService.PublishUpdateAsync(dashboard, snapshot => snapshot with + { + State = new ResourceStateSnapshot(KnownResourceStates.NotStarted, null) + }).DefaultTimeout(); + + var target = new AuxiliaryBackchannelRpcTarget( + NullLogger.Instance, + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services); + + var result = await target.GetDashboardUrlsAsync().DefaultTimeout(); + + Assert.False(result.DashboardHealthy); + Assert.Null(result.BaseUrlWithLoginToken); + } + + [Theory] + [InlineData("Waiting")] + [InlineData("Unknown")] + public async Task GetDashboardUrlsAsync_ReturnsUnhealthy_WhenDashboardIsExplicitStartAndNotRunnable(string state) + { + using var builder = TestDistributedApplicationBuilder.Create( + options => options.DisableDashboard = true, + outputHelper); + + using var app = builder.Build(); + await app.ExecuteBeforeStartHooksAsync(default).DefaultTimeout(); + + var model = app.Services.GetRequiredService(); + var dashboard = Assert.Single(model.Resources, r => r.Name == KnownResourceNames.AspireDashboard); + var notificationService = app.Services.GetRequiredService(); + await notificationService.PublishUpdateAsync(dashboard, snapshot => snapshot with + { + State = new ResourceStateSnapshot(state, null) + }).DefaultTimeout(); var target = new AuxiliaryBackchannelRpcTarget( NullLogger.Instance, @@ -2750,6 +2790,94 @@ public async Task GetDashboardUrlsAsync_ReturnsUnhealthy_WhenDashboardResourceIs Assert.Null(result.BaseUrlWithLoginToken); } + [Fact] + public async Task ExecuteResourceCommandAsync_ValidateOnly_AllowsDashboardStart_WhenDashboardIsExplicitStart() + { + using var builder = TestDistributedApplicationBuilder.Create( + options => options.DisableDashboard = true, + outputHelper); + + using var app = builder.Build(); + await app.StartAsync().DefaultTimeout(); + + var target = new AuxiliaryBackchannelRpcTarget( + NullLogger.Instance, + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services); + + var startResponse = await target.ExecuteResourceCommandAsync(new ExecuteResourceCommandRequest + { + ResourceName = KnownResourceNames.AspireDashboard, + CommandName = KnownResourceCommands.StartCommand, + ValidateOnly = true + }).DefaultTimeout(); + + Assert.True(startResponse.Success); + + var stopResponse = await target.ExecuteResourceCommandAsync(new ExecuteResourceCommandRequest + { + ResourceName = KnownResourceNames.AspireDashboard, + CommandName = KnownResourceCommands.StopCommand, + ValidateOnly = true + }).DefaultTimeout(); + + Assert.False(stopResponse.Success); + Assert.Equal($"Command '{KnownResourceCommands.StopCommand}' not available for resource '{KnownResourceNames.AspireDashboard}'.", stopResponse.Message); + } + + [Fact] + public async Task ExecuteResourceCommandAsync_StartDashboardCommand_TransitionsFromNotStarted_WhenDashboardIsExplicitStart() + { + using var builder = TestDistributedApplicationBuilder.Create( + options => options.DisableDashboard = true, + outputHelper); + + using var app = builder.Build(); + await app.StartAsync().DefaultTimeout(); + + var model = app.Services.GetRequiredService(); + var dashboard = Assert.Single(model.Resources, r => r.Name == KnownResourceNames.AspireDashboard); + var notificationService = app.Services.GetRequiredService(); + await notificationService.PublishUpdateAsync(dashboard, snapshot => snapshot with + { + State = new ResourceStateSnapshot(KnownResourceStates.NotStarted, null) + }).DefaultTimeout(); + + var target = new AuxiliaryBackchannelRpcTarget( + NullLogger.Instance, + app.Services.GetRequiredService(), + app.Services.GetRequiredService(), + app.Services); + + var response = await target.ExecuteResourceCommandAsync(new ExecuteResourceCommandRequest + { + ResourceName = KnownResourceNames.AspireDashboard, + CommandName = KnownResourceCommands.StartCommand, + ValidateOnly = false + }).DefaultTimeout(); + + Assert.True(response.Success, response.Message); + var deadline = DateTime.UtcNow.AddSeconds(5); + string? observedState = null; + while (DateTime.UtcNow < deadline) + { + if (notificationService.TryGetCurrentState(KnownResourceNames.AspireDashboard, out var currentEvent)) + { + observedState = currentEvent.Snapshot.State?.Text; + if (!string.IsNullOrEmpty(observedState) && observedState != KnownResourceStates.NotStarted) + { + break; + } + } + + await Task.Delay(100).DefaultTimeout(); + } + + Assert.False(string.IsNullOrEmpty(observedState)); + Assert.NotEqual(KnownResourceStates.NotStarted, observedState); + } + [Fact] public async Task WaitForResourceAsync_ReturnsNotFound_WhenResourceDoesNotExist() { diff --git a/tests/Aspire.Hosting.Tests/ComputeEnvironmentValidationTests.cs b/tests/Aspire.Hosting.Tests/ComputeEnvironmentValidationTests.cs index 99526e5ed0e..1f6b48239a3 100644 --- a/tests/Aspire.Hosting.Tests/ComputeEnvironmentValidationTests.cs +++ b/tests/Aspire.Hosting.Tests/ComputeEnvironmentValidationTests.cs @@ -45,6 +45,26 @@ public async Task MultipleComputeEnvironments_WithAllResourcesBound_DoesNotThrow await app.ExecuteBeforeStartHooksAsync(default).DefaultTimeout(); } + [Fact] + public async Task PublishMode_MultipleComputeEnvironments_WithExplicitStartAspireDashboard_Throws() + { + using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish); + + builder.AddResource(new TestComputeEnvironmentResource("env1")); + builder.AddResource(new TestComputeEnvironmentResource("env2")); + + var explicitStartDashboard = new TestComputeResource(KnownResourceNames.AspireDashboard); + explicitStartDashboard.Annotations.Add(new ExplicitStartupAnnotation()); + builder.AddResource(explicitStartDashboard); + + using var app = builder.Build(); + + var ex = await Assert.ThrowsAsync( + () => app.ExecuteBeforeStartHooksAsync(default)).DefaultTimeout(); + + Assert.Contains($"'{KnownResourceNames.AspireDashboard}'", ex.Message); + } + [Fact] public async Task SingleComputeEnvironment_AutoBindsUnboundResources() { diff --git a/tests/Aspire.Hosting.Tests/Dashboard/DashboardEventHandlersTests.cs b/tests/Aspire.Hosting.Tests/Dashboard/DashboardEventHandlersTests.cs index 0b0f8e4f20a..fb36805251e 100644 --- a/tests/Aspire.Hosting.Tests/Dashboard/DashboardEventHandlersTests.cs +++ b/tests/Aspire.Hosting.Tests/Dashboard/DashboardEventHandlersTests.cs @@ -199,6 +199,29 @@ public async Task BeforeStartAsync_ExcludeLifecycleCommands_CommandsNotAddedToDa Assert.Empty(dashboardResource.Annotations.OfType()); } + [Fact] + public async Task BeforeStartAsync_DisabledDashboard_AddsOnlyStartLifecycleCommand() + { + var resourceLoggerService = new ResourceLoggerService(); + var resourceNotificationService = ResourceNotificationServiceTestHelpers.Create(); + var configuration = new ConfigurationBuilder().Build(); + var hook = CreateHook( + resourceLoggerService, + resourceNotificationService, + configuration, + distributedApplicationOptions: new DistributedApplicationOptions { DisableDashboard = true }); + + var model = new DistributedApplicationModel(new ResourceCollection()); + + await hook.OnBeforeStartAsync(new BeforeStartEvent(new TestServiceProvider(), model), CancellationToken.None).DefaultTimeout(); + var dashboardResource = model.Resources.Single(r => string.Equals(r.Name, KnownResourceNames.AspireDashboard, StringComparisons.ResourceName)); + dashboardResource.AddLifeCycleCommands(); + + Assert.Single(dashboardResource.Annotations.OfType()); + var commands = Assert.Single(dashboardResource.Annotations.OfType()); + Assert.Equal(KnownResourceCommands.StartCommand, commands.Name); + } + [Theory] [InlineData("localhost:8080", 8080, "1234", "cert", "aspire-extension-run-123-", "aspire-extension-run-123-dashboard", true)] [InlineData("localhost:8080", 8080, "1234", "cert", "aspire-extension-run-123", "aspire-extension-run-123-dashboard", false)] @@ -854,6 +877,7 @@ private static DashboardEventHandlers CreateHook( ILoggerFactory? loggerFactory = null, IOptions? codespacesOptions = null, IOptions? dashboardOptions = null, + DistributedApplicationOptions? distributedApplicationOptions = null, Hosting.Eventing.DistributedApplicationEventing? eventing = null, ILogger? distributedApplicationLogger = null ) @@ -874,6 +898,7 @@ private static DashboardEventHandlers CreateHook( distributedApplicationLogger ?? NullLogger.Instance, new TestDashboardEndpointProvider(), executionContext, + distributedApplicationOptions ?? new DistributedApplicationOptions(), resourceNotificationService, resourceLoggerService, loggerFactory ?? NullLoggerFactory.Instance, diff --git a/tests/Aspire.Hosting.Tests/Dashboard/DashboardResourceTests.cs b/tests/Aspire.Hosting.Tests/Dashboard/DashboardResourceTests.cs index 10d1fee78d1..ad2ebdb38ba 100644 --- a/tests/Aspire.Hosting.Tests/Dashboard/DashboardResourceTests.cs +++ b/tests/Aspire.Hosting.Tests/Dashboard/DashboardResourceTests.cs @@ -647,7 +647,7 @@ public async Task DashboardIsNotAddedInPublishMode() } [Fact] - public async Task DashboardIsNotAddedIfDisabled() + public async Task DashboardIsAddedWithExplicitStartIfDisabled() { using var builder = TestDistributedApplicationBuilder.Create( options => options.DisableDashboard = true, @@ -658,8 +658,9 @@ public async Task DashboardIsNotAddedIfDisabled() await app.ExecuteBeforeStartHooksAsync(default).DefaultTimeout(); var model = app.Services.GetRequiredService(); - - Assert.Empty(model.Resources); + var dashboard = Assert.Single(model.Resources.OfType()); + Assert.Equal(KnownResourceNames.AspireDashboard, dashboard.Name); + Assert.True(dashboard.TryGetLastAnnotation(out _)); } [Fact] diff --git a/tests/Aspire.Hosting.Tests/Dashboard/TransportOptionsValidatorTests.cs b/tests/Aspire.Hosting.Tests/Dashboard/TransportOptionsValidatorTests.cs index 901ecba57a1..15604b7308d 100644 --- a/tests/Aspire.Hosting.Tests/Dashboard/TransportOptionsValidatorTests.cs +++ b/tests/Aspire.Hosting.Tests/Dashboard/TransportOptionsValidatorTests.cs @@ -46,7 +46,7 @@ public void InvalidTransportOptionSucceedValidationInPublishMode() } [Fact] - public void InvalidTransportOptionSucceedValidationWithDashboardDisabled() + public void InvalidTransportOptionFailsValidationWithDashboardDisabled() { var distributedApplicationOptions = new DistributedApplicationOptions() { @@ -60,7 +60,11 @@ public void InvalidTransportOptionSucceedValidationWithDashboardDisabled() var validator = new TransportOptionsValidator(config, executionContext, distributedApplicationOptions); var result = validator.Validate(null, options); - Assert.True(result.Succeeded, result.FailureMessage); + Assert.True(result.Failed); + Assert.Equal( + $"The 'applicationUrl' setting must be an https address unless the '{KnownConfigNames.AllowUnsecuredTransport}' environment variable is set to true. This configuration is commonly set in the launch profile. See https://aka.ms/aspire/allowunsecuredtransport for more details.", + result.FailureMessage + ); } [Fact]