File: Dcp\MsBuildNodeReuseIsolation.cs
Web Access
Project: src\src\Aspire.Hosting\Aspire.Hosting.csproj (Aspire.Hosting)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Backchannel;
using Aspire.Hosting.Dcp.Model;
using Aspire.Hosting.Internal;
using Aspire.Hosting.Lifecycle;
 
namespace Aspire.Hosting.Dcp;
 
/// <summary>
/// Keeps DCP-managed MSBuild workers in a pool associated with the current DCP run.
/// </summary>
/// <remarks>
/// Isolation is enabled only on Windows. There, DCP places the processes it launches in a job object that is
/// terminated when the run ends, which also terminates any MSBuild worker nodes spawned by Aspire-managed builds.
/// A build in the next run can connect to one of those workers while it is still shutting down and fail with
/// MSB4166. Giving each run its own handshake salt prevents connections to workers from another run.
/// On Linux and macOS, workers outlive DCP and remain usable, so that race does not occur. Salting there would only
/// hide the workers from <c>dotnet build-server shutdown --msbuild</c> (which uses the caller's salt) and leave them
/// running until MSBuild's idle timeout, so the build environment is left unchanged.
/// </remarks>
internal sealed class MsBuildNodeReuseIsolation
{
    internal const string HandshakeSaltEnvironmentVariable = MsBuildNodeHandshakeSalt.EnvironmentVariableName;
 
    private static readonly StringComparer s_environmentVariableComparer = StringComparers.CurrentOSEnvironmentVariableName;
 
    private RunState? _runState;
 
    public static MsBuildNodeReuseIsolation? CreateForCurrentPlatform() =>
        MsBuildNodeHandshakeSalt.IsPerRunIsolationEnabled ? new MsBuildNodeReuseIsolation() : null;
 
    public void StartDcpRun(IEnumerable<KeyValuePair<string, string>> environment)
    {
        string? inheritedSalt = null;
        foreach (var (name, value) in environment)
        {
            if (s_environmentVariableComparer.Equals(name, HandshakeSaltEnvironmentVariable))
            {
                inheritedSalt = value;
            }
        }
 
        Volatile.Write(ref _runState, new RunState(inheritedSalt, Guid.NewGuid().ToString("N")));
    }
 
    public void Apply(IResource resource, ExecutableSpec spec, SecretRedactionHistory secretRedactionHistory)
    {
        if (!DotnetBuildCommandEventingSubscriber.IsAspireManagedDotnetBuild(resource))
        {
            return;
        }
 
        var runState = Volatile.Read(ref _runState) ??
            throw new InvalidOperationException("The DCP run must start before configuring an Aspire-managed .NET build.");
        var environment = spec.Env ??= [];
        var originalSalt = runState.InheritedSalt;
        foreach (var variable in environment)
        {
            if (s_environmentVariableComparer.Equals(variable.Name, HandshakeSaltEnvironmentVariable))
            {
                originalSalt = variable.Value ?? throw new InvalidOperationException(
                    $"The {HandshakeSaltEnvironmentVariable} environment variable must have a value.");
            }
        }
 
        // The rendered environment can already contain the salt (for example from WithBuildEnvironment), and on
        // Windows names that differ only by case refer to the same variable. Remove every match so DCP receives a
        // single, unambiguous entry carrying the composed value instead of relying on which duplicate wins.
        environment.RemoveAll(variable => s_environmentVariableComparer.Equals(variable.Name, HandshakeSaltEnvironmentVariable));
 
        // MSBuild incorporates this undocumented environment variable into its node handshake:
        // https://github.com/dotnet/msbuild/blob/660964a8e2106dbb77329ad7807242b64a7bd86c/src/Framework/BackEnd/Handshake.cs
        // Append the run identity after resolution so callbacks, build properties, and IDE metadata keep their values.
        var effectiveSalt = $"{originalSalt}:{runState.Nonce}";
 
        // MSBuild also exposes every environment variable as a project property, so the composed salt would leak into
        // evaluation as $(MSBUILDNODEHANDSHAKESALT). Pin the original value as a global property, which takes precedence
        // over environment-derived properties, so the build evaluates the original value instead. A global property
        // also overrides values assigned by the project or its imports, so DotnetProjectRunPropertiesResolver applies
        // the same pin when it queries the built project's TargetPath; otherwise such a project could be launched from
        // a different output path than the one the build wrote. The handshake reads the environment variable directly,
        // so the composed salt still isolates the workers.
        // https://learn.microsoft.com/visualstudio/msbuild/how-to-use-environment-variables-in-a-build
        var propertyArgument = MsBuildNodeHandshakeSalt.CreateOriginalValuePropertyArgument(originalSalt);
        (spec.Args ??= []).Add(propertyArgument);
 
        // Backchannel redaction matches complete values, and the original salt might contain a secret.
        secretRedactionHistory.AddValues(string.IsNullOrEmpty(originalSalt) ? [effectiveSalt] : [effectiveSalt, propertyArgument]);
        environment.Add(new EnvVar { Name = HandshakeSaltEnvironmentVariable, Value = effectiveSalt });
    }
 
    private sealed record RunState(string? InheritedSalt, string Nonce);
}