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 @@ -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 `<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 @@ -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/')
)
)
)
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 @@ -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/')
)
)
)
Expand Down
16 changes: 5 additions & 11 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 @@ -254,10 +254,7 @@ private async Task<int> 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)
{
Expand All @@ -272,7 +269,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 Expand Up @@ -333,10 +330,7 @@ private async Task<int> DumpCapabilitiesToDirectoryAsync(
{
try
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDir, TimeProvider.System, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
10 changes: 4 additions & 6 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 Expand Up @@ -256,10 +257,7 @@ private async Task<int> ExportApiAsync(
{
try
{
if (Directory.Exists(tempDirectoryPath))
{
Directory.Delete(tempDirectoryPath, recursive: true);
}
await FileDeleteHelper.DeleteDirectoryWithRetryAsync(tempDirectoryPath, TimeProvider.System, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
11 changes: 4 additions & 7 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 Expand Up @@ -197,10 +197,7 @@ private async Task<int> 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)
{
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 @@ -63,6 +63,11 @@ internal sealed class ProcessInvocationOptions

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; }

/// <summary>
/// Suppresses implicit restore during single-file project property and target queries.
/// </summary>
Expand Down Expand Up @@ -182,6 +187,7 @@ internal sealed class ProcessInvocationOptions
StandardOutputCallback = StandardOutputCallback,
StandardErrorCallback = StandardErrorCallback,
NoLaunchProfile = NoLaunchProfile,
NoAutoResponse = NoAutoResponse,
NoRestore = NoRestore,
ExcludeRestorePackageImports = ExcludeRestorePackageImports,
NuGetRestoreTargetsFile = NuGetRestoreTargetsFile,
Expand Down Expand Up @@ -1259,6 +1265,11 @@ public async Task<int> 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)}"];
Expand All @@ -1284,6 +1295,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
11 changes: 11 additions & 0 deletions src/Aspire.Cli/Projects/AppHostServerProject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ internal interface IAppHostServerProjectFactory
Task<IAppHostServerProject> CreateAsync(string appPath, CancellationToken cancellationToken = default);
Task<IAppHostServerProject> CreateAsync(string appPath, FileInfo appHostFile, CancellationToken cancellationToken);
Task<IAppHostServerProject> CreateAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken);
Task<IAppHostServerProject> CreateForSdkCommandsAsync(string appPath, string? restoreRootConfigDirectory, CancellationToken cancellationToken);
}

/// <summary>
Expand Down Expand Up @@ -53,6 +54,7 @@ public Task<IAppHostServerProject> CreateAsync(string appPath, CancellationToken
appPath,
restoreRootConfigDirectory: null,
workloadId: AppHostWorkloadId.Create(appPath),
temporary: false,
cancellationToken: cancellationToken);

public Task<IAppHostServerProject> CreateAsync(
Expand All @@ -66,6 +68,7 @@ public Task<IAppHostServerProject> CreateAsync(
appPath,
restoreRootConfigDirectory: null,
workloadId: AppHostWorkloadId.Create(appHostFile),
temporary: false,
cancellationToken: cancellationToken);
}

Expand All @@ -74,12 +77,17 @@ public async Task<IAppHostServerProject> CreateAsync(string appPath, string? res
appPath,
restoreRootConfigDirectory,
AppHostWorkloadId.Create(appPath),
temporary: false,
cancellationToken).ConfigureAwait(false);

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

private async Task<IAppHostServerProject> CreateAsync(
string appPath,
string? restoreRootConfigDirectory,
string workloadId,
bool temporary,
CancellationToken cancellationToken)
{
if (IsNativeServerEnabled(appPath))
Expand All @@ -103,6 +111,9 @@ private async Task<IAppHostServerProject> CreateAsync(
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 @@ -499,6 +499,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 @@ -446,6 +446,7 @@ internal static string GetIntegrationBuildFailureMessage(OutputCollector buildOu
noRestore,
new ProcessInvocationOptions
{
NoAutoResponse = true,
StandardOutputCallback = buildOutput.AppendOutput,
StandardErrorCallback = buildOutput.AppendError,
EnvironmentVariableFilter = name =>
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 @@ -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;
}
}

/// <summary>
/// Returns the absolute path to the staging NuGet package cache root
/// (<c>&lt;ASPIRE_HOME&gt;/.nugetpackages</c>). Producers (the
Expand Down
46 changes: 44 additions & 2 deletions src/Aspire.Cli/Utils/FileDeleteHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ namespace Aspire.Cli.Utils;
///
/// On Windows a running process holds an exclusive lock on its executable,
/// so <see cref="Directory.Delete(string, bool)"/> throws
/// <see cref="UnauthorizedAccessException"/>. Rather than failing the entire
/// operation, these helpers rename the locked item to
/// <see cref="UnauthorizedAccessException"/>. The synchronous deletion helpers
/// rename the locked item to
/// <c>{name}.old.{tickcount}</c> and let the caller proceed. The stale
/// renamed items are best-effort cleaned up on subsequent invocations via
/// <see cref="TryCleanupOldItems"/>.
Expand Down Expand Up @@ -57,6 +57,48 @@ internal static bool TryDeleteDirectory(string path)
return true;
}

/// <summary>
/// Deletes a directory recursively, retrying transient I/O and access failures
/// for up to two seconds before rethrowing the final failure.
/// Unlike <see cref="TryDeleteDirectory"/>, this does not rename locked content.
/// </summary>
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));
}
}
}

/// <summary>
/// Attempts to delete a file. If deletion fails because the file is locked
/// by another process, the file is renamed to <c>{path}.old.{tickcount}</c>
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)]
}
Loading
Loading