Skip to content

Commit c1fd4b5

Browse files
JanProvaznikCopilot
andcommitted
Scope MSBuild server and coordinator resource names to the current user
Named pipes and named mutexes live in machine-wide namespaces, but MSBuild creates its pipes current-user-only. Where the derived names carry no user discriminator, two users on the same machine (Remote Desktop, shared CI agent) collide: the second user sees the first user's mutex, concludes a server or coordinator is already running, skips launching its own, and then cannot connect to the pipe. It also cannot create a pipe under that name, so it is locked out of the feature entirely. MSBuild server derived every such name from ServerNodeHandshake.ComputeHash(), which is built from handshake options, salt and file version only (includeSessionId is false), so all users on a machine computed the same names. Mix the user into ComputeHash() so the server pipe, the running/busy/launch mutexes and the RAR node pipes are all per-user. This changes generated names only; the handshake exchanged over the wire comes from RetrieveHandshakeComponents() and is untouched, so protocol compatibility is unaffected. The coordinator already carried the user in its default pipe name, but an explicit MSBUILDCOORDINATORPIPENAME override dropped it from the mutex names too. Mix the user into the mutex derivation unconditionally so the mutex is never scoped more broadly than the pipe it guards. Add EnvironmentUtilities.CurrentUserName as the single cached accessor for both call sites. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 2adbaa15-8edf-4e50-99b9-4732331c60c8
1 parent 6ee486e commit c1fd4b5

5 files changed

Lines changed: 169 additions & 10 deletions

File tree

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Security.Cryptography;
6+
using System.Text;
7+
using Microsoft.Build.Experimental;
8+
using Microsoft.Build.Internal;
9+
using Shouldly;
10+
using Xunit;
11+
12+
namespace Microsoft.Build.UnitTests.BackEnd
13+
{
14+
/// <summary>
15+
/// Tests that the names MSBuild server derives from <see cref="ServerNodeHandshake"/> are scoped
16+
/// to the current user. Named pipes and named mutexes live in machine-wide namespaces, but the
17+
/// server pipes are created current-user-only, so user-agnostic names would let one user's server
18+
/// lock every other user on the machine out of the feature.
19+
/// </summary>
20+
public class ServerNodeHandshake_Tests
21+
{
22+
[Fact]
23+
public void ComputeHash_IncludesCurrentUser()
24+
{
25+
ServerNodeHandshake handshake = new(HandshakeOptions.None);
26+
27+
// The user name must participate in the hash, otherwise every user on the machine
28+
// computes the same pipe and mutex names.
29+
handshake.ComputeHash().ShouldBe(Hash($"{handshake.GetKey()} {Environment.UserName}"));
30+
handshake.ComputeHash().ShouldNotBe(Hash(handshake.GetKey()));
31+
}
32+
33+
[Fact]
34+
public void ComputeHash_IsStableAcrossInstances()
35+
{
36+
// A client and the server it launches are separate processes that must agree on the
37+
// derived names, so the hash has to depend only on the handshake and the user.
38+
ServerNodeHandshake first = new(HandshakeOptions.None);
39+
ServerNodeHandshake second = new(HandshakeOptions.None);
40+
41+
first.ComputeHash().ShouldBe(second.ComputeHash());
42+
}
43+
44+
[Fact]
45+
public void ComputeHash_DoesNotChangeHandshakeSentOverTheWire()
46+
{
47+
// The user discriminator is a naming concern only. Adding it to the wire handshake would
48+
// be a protocol change, so the exchanged components must stay derived from the key alone.
49+
ServerNodeHandshake handshake = new(HandshakeOptions.None);
50+
51+
HandshakeComponents components = handshake.RetrieveHandshakeComponents();
52+
53+
components.Options.ShouldBe(CommunicationsUtilities.AvoidEndOfHandshakeSignal(components.Options));
54+
handshake.GetKey().ShouldNotContain(Environment.UserName, Case.Insensitive);
55+
}
56+
57+
[Fact]
58+
public void ServerNames_AreAllDerivedFromTheUserScopedHash()
59+
{
60+
ServerNodeHandshake handshake = new(HandshakeOptions.None);
61+
string hash = handshake.ComputeHash();
62+
63+
// Every machine-wide name the server uses must carry the user-scoped hash.
64+
OutOfProcServerNode.GetPipeName(handshake).ShouldContain(hash);
65+
OutOfProcServerNode.GetRunningServerMutexName(handshake).ShouldContain(hash);
66+
OutOfProcServerNode.GetBusyServerMutexName(handshake).ShouldContain(hash);
67+
}
68+
69+
private static string Hash(string input)
70+
{
71+
byte[] utf8 = Encoding.UTF8.GetBytes(input);
72+
#if NET
73+
byte[] bytes = SHA256.HashData(utf8);
74+
#else
75+
using SHA256 sha = SHA256.Create();
76+
byte[] bytes = sha.ComputeHash(utf8);
77+
#endif
78+
79+
return Convert.ToBase64String(bytes)
80+
.Replace("/", "_")
81+
.Replace("=", string.Empty);
82+
}
83+
}
84+
}

‎src/Framework/BackEnd/ServerNodeHandshake.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Globalization;
66
using System.Security.Cryptography;
77
using System.Text;
8+
using Microsoft.Build.Framework;
89

910
namespace Microsoft.Build.Internal;
1011

@@ -36,11 +37,20 @@ public override string GetKey() => $"{_handshakeComponents.Options} {_handshakeC
3637
/// <summary>
3738
/// Computes Handshake stable hash string representing whole state of handshake.
3839
/// </summary>
40+
/// <remarks>
41+
/// The current user is mixed in because every name derived from this hash — the MSBuild server
42+
/// and RAR node pipe names, and the server running/busy/launch mutexes — lives in a machine-wide
43+
/// namespace, while the pipes themselves are created current-user-only. Without the discriminator
44+
/// a second user on the same machine sees the first user's mutex, concludes a server is already
45+
/// running, and then can neither connect to that user's pipe nor create one under the same name.
46+
/// This affects generated names only; the handshake exchanged over the wire is unchanged (see
47+
/// <see cref="RetrieveHandshakeComponents"/>), so it does not alter protocol compatibility.
48+
/// </remarks>
3949
public string ComputeHash()
4050
{
4151
if (_computedHash == null)
4252
{
43-
var input = GetKey();
53+
var input = $"{GetKey()} {EnvironmentUtilities.CurrentUserName}";
4454
byte[] utf8 = Encoding.UTF8.GetBytes(input);
4555
#if NET
4656
Span<byte> bytes = stackalloc byte[SHA256.HashSizeInBytes];

‎src/Framework/Coordinator/CoordinatorSettings.cs‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ internal sealed record class CoordinatorSettings()
2525
public const int DefaultShutdownTimeoutMs = 60_000;
2626
public const int MaxHeartbeatIntervalMs = 300_000;
2727

28-
private static string DefaultPipeName => $"{PipeNameBase}-{Environment.UserName}";
28+
private static string DefaultPipeName => $"{PipeNameBase}-{EnvironmentUtilities.CurrentUserName}";
2929

3030
private int? _heartbeatIntervalMs;
3131
private int? _missedHeartbeatsThreshold;
@@ -134,32 +134,43 @@ public static CoordinatorSettings FromEnvironment()
134134
}
135135

136136
/// <summary>
137-
/// Generates a platform-appropriate mutex name by combining the pipe name with a purpose suffix.
137+
/// Generates a platform-appropriate mutex name by combining the pipe name and the current user
138+
/// with a purpose suffix.
138139
/// </summary>
140+
/// <remarks>
141+
/// The mutex must never be scoped more broadly than the pipe it guards. That pipe is created
142+
/// current-user-only, so a machine-wide mutex shared between users would let one user's
143+
/// coordinator convince another user's clients that a coordinator is already running, while
144+
/// those clients cannot use the pipe. <see cref="PipeName"/> carries the user by default, but an
145+
/// explicit <c>MSBUILDCOORDINATORPIPENAME</c> override can drop it, so the user is mixed in here
146+
/// unconditionally.
147+
/// </remarks>
139148
private string GetMutexName(string purpose)
140149
{
150+
string mutexIdentity = $"{PipeName}-{EnvironmentUtilities.CurrentUserName}";
151+
141152
if (NativeMethods.IsWindows)
142153
{
143-
return $"Global\\{PipeName}-{purpose}";
154+
return $"Global\\{mutexIdentity}-{purpose}";
144155
}
145156

146157
// Named mutexes on Unix do not accept path-like names (for example '/tmp/...').
147-
// Hash the pipe name into a stable, compact identifier safe for the runtime.
158+
// Hash the identity into a stable, compact identifier safe for the runtime.
148159
string prefix = $"msbuild-coordinator-{purpose}-";
149160

150161
#if NET
151-
int byteCount = Encoding.UTF8.GetByteCount(PipeName);
152-
using BufferScope<byte> pipeNameBytes = byteCount <= 256
162+
int byteCount = Encoding.UTF8.GetByteCount(mutexIdentity);
163+
using BufferScope<byte> mutexIdentityBytes = byteCount <= 256
153164
? new(stackalloc byte[byteCount])
154165
: new(byteCount);
155166

156-
Encoding.UTF8.GetBytes(PipeName, pipeNameBytes);
167+
Encoding.UTF8.GetBytes(mutexIdentity, mutexIdentityBytes);
157168

158169
Span<byte> hash = stackalloc byte[SHA256.HashSizeInBytes];
159-
SHA256.HashData(pipeNameBytes[..byteCount], hash);
170+
SHA256.HashData(mutexIdentityBytes[..byteCount], hash);
160171
#else
161172
using SHA256 sha256 = SHA256.Create();
162-
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(PipeName));
173+
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(mutexIdentity));
163174
#endif
164175

165176
// We're being a bit clever here by defining PrefixAndHash as a ref struct on modern .NET

‎src/Framework/EnvironmentUtilities.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,29 @@ public static string ProcessName
9696
}
9797
}
9898

99+
/// <summary>
100+
/// Gets the name of the user the current process is running as, used to scope machine-wide
101+
/// resource names to a single user. Returns an empty string when the name is unavailable.
102+
/// </summary>
103+
/// <remarks>
104+
/// Named pipes and named mutexes live in machine-wide namespaces, so names derived only from
105+
/// an MSBuild version or handshake collide between users sharing a machine (Remote Desktop
106+
/// sessions, shared CI agents). Because MSBuild creates those pipes current-user-only, the
107+
/// second user can neither connect to the existing pipe nor create one under the same name,
108+
/// which locks them out of the feature entirely. Mixing this value into such names keeps each
109+
/// user on their own set of resources.
110+
/// <para>
111+
/// Cached because <see cref="Environment.UserName"/> is surprisingly expensive: it queries the
112+
/// OS and allocates a fresh string on every call, measured at roughly 75 microseconds per call
113+
/// on Windows (on a machine that is not even domain-joined) versus a few nanoseconds to read
114+
/// the cached value. Callers read this from polling loops, so it is worth keeping. A race just
115+
/// recomputes an equal string and publishing the reference is atomic, so no synchronization is
116+
/// needed. <see cref="Environment.UserName"/> returns an empty string rather than throwing when
117+
/// the account cannot be resolved.
118+
/// </para>
119+
/// </remarks>
120+
public static string CurrentUserName => field ??= Environment.UserName;
121+
99122
public static bool IsWellKnownEnvironmentDerivedProperty(string propertyName)
100123
=> propertyName.StartsWith("MSBUILD", StringComparison.OrdinalIgnoreCase) ||
101124
propertyName.StartsWith("COMPLUS_", StringComparison.OrdinalIgnoreCase) ||

‎src/MSBuild.Coordinator.UnitTests/CoordinatorSettings_Tests.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,35 @@ public void CoordinatorSettings_FromEnvironment_UsesEnvironmentOverrides()
6969
settings.ConnectionTimeoutMs.ShouldBe(CoordinatorSettings.DefaultConnectionTimeoutMs);
7070
settings.ProcessId.ShouldBe(EnvironmentUtilities.CurrentProcessId);
7171
}
72+
73+
[Fact]
74+
public void CoordinatorSettings_MutexNames_DifferByPurpose()
75+
{
76+
CoordinatorSettings settings = CoordinatorSettings.Default;
77+
78+
settings.ServerMutexName.ShouldNotBe(settings.LaunchMutexName);
79+
}
80+
81+
[Fact]
82+
public void CoordinatorSettings_MutexNames_DifferByPipeName()
83+
{
84+
// The mutex guards a specific pipe, so two differently-named coordinators must not contend.
85+
CoordinatorSettings first = CoordinatorSettings.Default with { PipeName = "coordinator-pipe-one" };
86+
CoordinatorSettings second = CoordinatorSettings.Default with { PipeName = "coordinator-pipe-two" };
87+
88+
first.ServerMutexName.ShouldNotBe(second.ServerMutexName);
89+
}
90+
91+
[WindowsOnlyFact]
92+
public void CoordinatorSettings_MutexNames_AreUserScopedEvenWhenPipeNameIsOverridden()
93+
{
94+
// The default pipe name already carries the user, but an explicit override can drop it. The
95+
// mutex lives in the machine-wide Global namespace while the pipe it guards is created
96+
// current-user-only, so without the user another account would see this coordinator's mutex,
97+
// skip launching its own, and then be unable to use the pipe.
98+
CoordinatorSettings settings = CoordinatorSettings.Default with { PipeName = "coordinator-pipe-without-user" };
99+
100+
settings.ServerMutexName.ShouldContain(Environment.UserName);
101+
settings.LaunchMutexName.ShouldContain(Environment.UserName);
102+
}
72103
}

0 commit comments

Comments
 (0)