Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/specs/cli-output-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,8 @@ The `isolated-launch.v1` capability indicates that `aspire run` accepts the `--i

### `aspire sdk dump`

The SDK commands (`sdk generate`, `sdk dump`, and `sdk export`) create their scanner working directories under `<ASPIRE_HOME>/tmp/sdk/<unique-id>`, 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
Expand Down
3 changes: 2 additions & 1 deletion eng/pipelines/azure-pipelines-unofficial.yml
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,8 @@ extends:
ne(dependencies.build.outputs['Windows.computeChannel.installerChannel'], 'stable'),
or(
eq(variables['Build.SourceBranch'], 'refs/heads/main'),
startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')
startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'),
startsWith(variables['Build.SourceBranch'], 'refs/heads/internal/release/')
)
)
)
Expand Down
3 changes: 2 additions & 1 deletion eng/pipelines/azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -822,7 +822,8 @@ extends:
ne(dependencies.build_sign_native.outputs['BuildNative_linux_x64.ComputeVars.installerChannel'], 'stable'),
or(
eq(variables['Build.SourceBranch'], 'refs/heads/main'),
startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')
startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'),
startsWith(variables['Build.SourceBranch'], 'refs/heads/internal/release/')
)
)
)
Expand Down
14 changes: 0 additions & 14 deletions src/Aspire.Cli/Agents/DeprecatedMcpCommandScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,37 +41,26 @@ public Task ScanAsync(AgentEnvironmentScanContext context, CancellationToken can
{
_logger.LogDebug("Scanning for deprecated MCP command usage in agent configurations");

// Debug: Write scanning info to temp file for diagnostics
var debugPath = Path.Combine(Path.GetTempPath(), "aspire-deprecated-scan.log");
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] Scanning context.RepositoryRoot: {context.RepositoryRoot.FullName}\n");

foreach (var location in s_configLocations)
{
var configPath = Path.Combine(context.RepositoryRoot.FullName, location.RelativePath);
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] Checking {location.AgentName}: {configPath}\n");

if (!File.Exists(configPath))
{
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> File does not exist\n");
continue;
}

File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> File EXISTS!\n");

try
{
var content = File.ReadAllText(configPath);
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> Content: {content.Substring(0, Math.Min(200, content.Length))}\n");
var config = JsonNode.Parse(content)?.AsObject();

if (config is null)
{
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> JSON parse returned null\n");
continue;
}

var hasDeprecated = HasDeprecatedMcpCommand(config, location);
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> HasDeprecatedMcpCommand: {hasDeprecated}\n");

if (hasDeprecated)
{
Expand All @@ -80,17 +69,14 @@ public Task ScanAsync(AgentEnvironmentScanContext context, CancellationToken can
// Create an applicator to update this config
var applicator = CreateUpdateApplicator(location, configPath, config);
context.AddApplicator(applicator);
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> Added applicator\n");
}
}
catch (JsonException ex)
{
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> JsonException: {ex.Message}\n");
_logger.LogDebug(ex, "Failed to parse {AgentName} config at {Path}", location.AgentName, configPath);
}
catch (IOException ex)
{
File.AppendAllText(debugPath, $"[{DateTime.UtcNow:O}] -> IOException: {ex.Message}\n");
_logger.LogDebug(ex, "Failed to read {AgentName} config at {Path}", location.AgentName, configPath);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/Aspire.Cli/Commands/Sdk/SdkDumpCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ protected override async Task<CommandResult> ExecuteAsync(ParseResult parseResul
private Task<IAppHostServerProject> 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<int> DumpCapabilitiesAsync(
Expand All @@ -173,7 +173,7 @@ private async Task<int> DumpCapabilitiesAsync(
OutputFormat format,
CancellationToken cancellationToken)
{
var tempDirectory = Directory.CreateTempSubdirectory("aspire-sdk-dump-");
var tempDirectory = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory);
var tempDir = tempDirectory.FullName;

try
Expand Down Expand Up @@ -272,7 +272,7 @@ private async Task<int> DumpCapabilitiesToDirectoryAsync(
OutputFormat format,
CancellationToken cancellationToken)
{
var tempDirectory = Directory.CreateTempSubdirectory("aspire-sdk-dump-");
var tempDirectory = CliPathHelper.CreateSdkWorkingDirectory(ExecutionContext.AspireHomeDirectory);
var tempDir = tempDirectory.FullName;

try
Expand Down
5 changes: 3 additions & 2 deletions src/Aspire.Cli/Commands/Sdk/SdkExportCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,14 @@ private async Task<int> ExportApiAsync(
IReadOnlyList<IntegrationReference> 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(
Expand Down
6 changes: 3 additions & 3 deletions src/Aspire.Cli/Commands/Sdk/SdkGenerateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -111,12 +112,11 @@ private async Task<int> 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);
Expand Down
15 changes: 15 additions & 0 deletions src/Aspire.Cli/DotNet/DotNetCliRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ internal sealed class ProcessInvocationOptions
public Action<string>? StandardErrorCallback { get; set; }

public bool NoLaunchProfile { get; set; }

/// <summary>
/// Disables automatic MSBuild response files for CLI-generated projects without changing user project builds.
/// </summary>
public bool NoAutoResponse { get; set; }

public string? LaunchProfile { get; set; }
public bool StartDebugSession { get; set; }
public bool Debug { get; set; }
Expand Down Expand Up @@ -157,6 +163,7 @@ internal sealed class ProcessInvocationOptions
StandardOutputCallback = StandardOutputCallback,
StandardErrorCallback = StandardErrorCallback,
NoLaunchProfile = NoLaunchProfile,
NoAutoResponse = NoAutoResponse,
LaunchProfile = LaunchProfile,
StartDebugSession = StartDebugSession,
Debug = Debug,
Expand Down Expand Up @@ -1268,6 +1275,10 @@ public async Task<int> RestoreAsync(FileInfo projectFilePath, ProcessInvocationO
using var activity = telemetry.StartDiagnosticActivity();

string[] cliArgs = ["restore", projectFilePath.FullName];
if (options.NoAutoResponse)
{
cliArgs = [.. cliArgs, "-noAutoResponse"];
}

return await ExecuteAsync(
args: cliArgs,
Expand All @@ -1289,6 +1300,10 @@ public async Task<int> 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.
Expand Down
18 changes: 18 additions & 0 deletions src/Aspire.Cli/Projects/AppHostServerProject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ internal interface IAppHostServerProjectFactory
{
Task<IAppHostServerProject> CreateAsync(string appPath, CancellationToken cancellationToken = default);
Task<IAppHostServerProject> CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken);
Task<IAppHostServerProject> CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken);
}

/// <summary>
Expand All @@ -39,6 +40,20 @@ public Task<IAppHostServerProject> CreateAsync(string appPath, CancellationToken
=> CreateAsync(appPath, restoreRootConfigDirectory: null, cancellationToken);

public async Task<IAppHostServerProject> CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken)
=> await CreateAsync(
appPath,
restoreRootConfigDirectory,
temporary: false,
cancellationToken).ConfigureAwait(false);

public Task<IAppHostServerProject> CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken)
=> CreateAsync(appPath, restoreRootConfigDirectory, temporary: true, cancellationToken);

private async Task<IAppHostServerProject> CreateAsync(
string appPath,
string? restoreRootConfigDirectory,
bool temporary,
CancellationToken cancellationToken)
{
var socketPath = CliPathHelper.CreateGuestAppHostSocketPath("apphost.sock");

Expand All @@ -55,6 +70,9 @@ public async Task<IAppHostServerProject> CreateAsync(string appPath, string? res
processExecutionFactory,
environment,
loggerFactory.CreateLogger<DotNetBasedAppHostServerProject>(),
// 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ private static string ComputeScaffoldFingerprint(Dictionary<string, string> scaf

var options = new ProcessInvocationOptions
{
NoAutoResponse = true,
StandardOutputCallback = outputCollector.AppendOutput,
StandardErrorCallback = outputCollector.AppendError
};
Expand Down
1 change: 1 addition & 0 deletions src/Aspire.Cli/Projects/PrebuiltAppHostServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,7 @@ internal static string GetIntegrationBuildFailureMessage(OutputCollector buildOu
noRestore,
new ProcessInvocationOptions
{
NoAutoResponse = true,
StandardOutputCallback = buildOutput.AppendOutput,
StandardErrorCallback = buildOutput.AppendError
},
Expand Down
33 changes: 33 additions & 0 deletions src/Aspire.Cli/Utils/CliPathHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,39 @@ internal static string GetDefaultAspireHomeDirectory(string? configuredAspireHom
return AspireHomeDirectory.GetDefault(configuredAspireHome, userProfileDirectory);
}

// Accept the execution context's already-resolved Aspire home rather than resolving it
// from process state again, so tests using an isolated home never write to the user's home.
internal static DirectoryInfo CreateSdkWorkingDirectory(DirectoryInfo aspireHomeDirectory)
{
// Keep generated scanner projects out of the shared OS temp hierarchy, where
// ancestor build configuration can affect restore and build.
var tempRoot = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(aspireHomeDirectory.FullName, "tmp"));
var sdkRoot = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(tempRoot.FullName, "sdk"));
var directory = DirectoryHelper.CreateWithOwnerOnlyPermissions(Path.Combine(sdkRoot.FullName, Guid.NewGuid().ToString("N")));
try
{
// Anchor configuration discovery here so global or ancestor settings cannot move
// integration caches outside this invocation's cleanup boundary.
File.WriteAllText(Path.Combine(directory.FullName, Configuration.AspireConfigFile.FileName), "{}");
return directory;
}
catch (Exception initializationException) when (initializationException is IOException or UnauthorizedAccessException)
{
// The caller cannot enter its cleanup scope until this method returns.
try
{
directory.Delete(recursive: true);
}
catch (Exception cleanupException) when (cleanupException is IOException or UnauthorizedAccessException)
{
throw new AggregateException("SDK working directory initialization and cleanup both failed.",
initializationException, cleanupException);
}

throw;
}
}

/// <summary>
/// Returns the absolute path to the staging NuGet package cache root
/// (<c>&lt;ASPIRE_HOME&gt;/.nugetpackages</c>). Producers (the
Expand Down
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// Double-checks authentication state inside the dashboard as a defense-in-depth measure.
/// Use in main layouts and infrastructure that launches UI.
/// </summary>
public static async Task EnsureAuthenticatedAsync(
DashboardOptions dashboardOptions,
Task<AuthenticationState>? 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.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
@if (DashboardOptions.Value.Frontend.AuthMode != FrontendAuthMode.BrowserToken)
{
@Loc[nameof(Resources.Routes.NotAuthorized)]
}
Original file line number Diff line number Diff line change
@@ -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> DashboardOptions { get; init; }

[Inject]
public required IStringLocalizer<Resources.Routes> 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 });
}
}
}
Loading
Loading