Skip to content

Commit 2d60006

Browse files
authored
msal: restore visible console parenting on Windows (#2464)
Windows authentication dialogs need an appropriate parent window, but Git is not always launched from a visible terminal. GUI applications and background processes can retain a hidden console with a valid HWND. Automatically selecting that invisible owner can leave authentication UI out of view, making the operation appear stalled while it waits for credentials. GCM 3.0 also accidentally reversed the parent-selection preference used in 2.x: interactive Windows broker authentication creates a progress window before considering an existing console owner. This introduces unnecessary temporary UI and disconnects authentication dialogs from the terminal that initiated the operation. This PR restores console-first parenting while rejecting invisible automatically discovered owners. The selection order becomes: 1. An explicit HWND supplied through `GCM_MODAL_PARENTHWND`. 2. The console’s root-owner HWND, provided `IsWindowVisible` returns true. 3. A GCM-created progress window, if a parent is required. 4. No parent otherwise. The visibility check applies **after** walking the window parent/owner chain. This matters for ConPTY, where the console HWND may be a hidden compatibility window while its root owner is the visible terminal. Explicit HWNDs remain the caller’s responsibility and are not visibility-filtered. Minimised owners also remain eligible: this change deliberately does not add an `IsIconic` check or replace a minimised owner with an independent progress window. The series adds regression coverage for parent precedence, hidden or missing owners, and progress-window cleanup, and documents `GCM_MODAL_PARENTHWND` for applications integrating Git into their own GUI.
2 parents 9c3b25d + 8413a8f commit 2d60006

4 files changed

Lines changed: 215 additions & 12 deletions

File tree

‎docs/environment.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,40 @@ Defaults to enabled.
173173

174174
---
175175

176+
### GCM_MODAL_PARENTHWND
177+
178+
Specify the parent window handle (`HWND`) for modal dialogs on Windows.
179+
180+
> [!NOTE]
181+
> This is intended for use by application developers who are calling Git and/or
182+
> GCM from their application and wish to correctly parent authentication dialogs
183+
> to an existing window.
184+
>
185+
> Do **not** set this manually.
186+
187+
#### Example
188+
189+
##### Windows
190+
191+
```csharp
192+
public static int Example(IntPtr myWindowHandle)
193+
{
194+
using var process = new Process();
195+
process.StartInfo = new ProcessStartInfo("git.exe", "pull")
196+
{
197+
Environment =
198+
{
199+
["GCM_MODAL_PARENTHWND"] = myWindowHandle.ToString("d")
200+
}
201+
};
202+
process.Start();
203+
process.WaitForExit();
204+
return process.ExitCode;
205+
}
206+
```
207+
208+
---
209+
176210
### GCM_PROVIDER
177211

178212
Define the host provider to use when authenticating.
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
using System;
2+
using System.Threading;
3+
using GitCredentialManager.Authentication.Entra;
4+
using Xunit;
5+
6+
namespace GitCredentialManager.Tests.Authentication.Entra;
7+
8+
public class MsalParentWindowAdapterTests
9+
{
10+
[Theory]
11+
[InlineData(42, false)]
12+
[InlineData(42, true)]
13+
[InlineData(-1, false)]
14+
[InlineData(-1, true)]
15+
public void GetWindow_ExplicitParent_TakesPrecedence(int parentValue, bool createIfMissing)
16+
{
17+
object parentWindow = new IntPtr(parentValue);
18+
using var adapter = new MsalParentWindowAdapter(parentWindow, createIfMissing,
19+
() => throw new InvalidOperationException("Console lookup should not be called."),
20+
_ => throw new InvalidOperationException("Visibility should not be checked."),
21+
_ => throw new InvalidOperationException("A progress window should not be created."));
22+
23+
object result = adapter.GetWindow();
24+
Assert.Same(parentWindow, result);
25+
}
26+
27+
[Theory]
28+
[InlineData(false)]
29+
[InlineData(true)]
30+
public void GetWindow_VisibleConsoleRoot_PrecedesProgressWindow(bool createIfMissing)
31+
{
32+
var consoleRoot = new IntPtr(42);
33+
bool visibilityChecked = false;
34+
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, createIfMissing,
35+
() => consoleRoot,
36+
hwnd =>
37+
{
38+
Assert.Equal(consoleRoot, hwnd);
39+
visibilityChecked = true;
40+
return true;
41+
},
42+
_ => throw new InvalidOperationException("A progress window should not be created."));
43+
44+
IntPtr result = Assert.IsType<IntPtr>(adapter.GetWindow());
45+
46+
Assert.Equal(consoleRoot, result);
47+
Assert.True(visibilityChecked);
48+
}
49+
50+
[Theory]
51+
[InlineData(0)]
52+
[InlineData(42)]
53+
public void GetWindow_NoVisibleConsoleRoot_CreatesProgressWhenRequired(int consoleRootValue)
54+
{
55+
var consoleRoot = new IntPtr(consoleRootValue);
56+
var progressWindow = new IntPtr(84);
57+
int visibilityChecks = 0;
58+
var windowToken = CancellationToken.None;
59+
using (var adapter = new MsalParentWindowAdapter(IntPtr.Zero, true,
60+
() => consoleRoot,
61+
hwnd =>
62+
{
63+
Assert.Equal(consoleRoot, hwnd);
64+
visibilityChecks++;
65+
return false;
66+
},
67+
ct =>
68+
{
69+
windowToken = ct;
70+
return progressWindow;
71+
}))
72+
{
73+
IntPtr result = Assert.IsType<IntPtr>(adapter.GetWindow());
74+
75+
Assert.Equal(progressWindow, result);
76+
Assert.Equal(consoleRootValue == 0 ? 0 : 1, visibilityChecks);
77+
Assert.True(windowToken.CanBeCanceled);
78+
Assert.False(windowToken.IsCancellationRequested);
79+
}
80+
81+
Assert.True(windowToken.IsCancellationRequested);
82+
}
83+
84+
[Theory]
85+
[InlineData(0)]
86+
[InlineData(42)]
87+
public void GetWindow_NoVisibleConsoleRoot_ReturnsNullWhenParentNotRequired(int consoleRootValue)
88+
{
89+
var consoleRoot = new IntPtr(consoleRootValue);
90+
int visibilityChecks = 0;
91+
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, false,
92+
() => consoleRoot,
93+
hwnd =>
94+
{
95+
Assert.Equal(consoleRoot, hwnd);
96+
visibilityChecks++;
97+
return false;
98+
},
99+
_ => throw new InvalidOperationException("A progress window should not be created."));
100+
101+
object result = adapter.GetWindow();
102+
103+
Assert.Null(result);
104+
Assert.Equal(consoleRootValue == 0 ? 0 : 1, visibilityChecks);
105+
}
106+
107+
[Fact]
108+
public void GetWindow_VisibilityCheckThrows_PropagatesException()
109+
{
110+
var exception = new InvalidOperationException("Visibility check failed.");
111+
using var adapter = new MsalParentWindowAdapter(IntPtr.Zero, true,
112+
() => new IntPtr(42),
113+
_ => throw exception,
114+
_ => throw new InvalidOperationException("A progress window should not be created."));
115+
116+
var thrown = Assert.Throws<InvalidOperationException>(adapter.GetWindow);
117+
Assert.Same(exception, thrown);
118+
}
119+
120+
[Fact]
121+
public void Create_ExplicitParent_IsReturned()
122+
{
123+
object parentWindow = new IntPtr(42);
124+
using var adapter = MsalParentWindowAdapter.Create(parentWindow, true);
125+
126+
object result = adapter.GetWindow();
127+
Assert.Same(parentWindow, result);
128+
}
129+
130+
[PosixFact]
131+
public void Create_NoExplicitParent_Posix_ReturnsNull()
132+
{
133+
using var adapter = MsalParentWindowAdapter.Create(IntPtr.Zero);
134+
135+
object result = adapter.GetWindow();
136+
Assert.Null(result);
137+
}
138+
}

‎src/Core/Authentication/Entra/MsalAdaptors.cs‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,30 @@ internal class MsalParentWindowAdapter : IDisposable
3131
private readonly bool _createIfMissing;
3232
private readonly CancellationTokenSource _cts = new();
3333

34+
private readonly Func<IntPtr> _getConsoleParentWindow;
35+
private readonly Func<IntPtr, bool> _isWindowVisible;
36+
private readonly Func<CancellationToken, IntPtr> _createWindow;
37+
3438
public static MsalParentWindowAdapter Create(object parentWindow, bool createIfMissing = false)
3539
{
36-
return new MsalParentWindowAdapter(parentWindow, createIfMissing);
40+
return new MsalParentWindowAdapter(parentWindow, createIfMissing,
41+
GetConsoleParentWindow, User32.IsWindowVisible, ProgressWindow.ShowAndGetHandle);
3742
}
3843

39-
private MsalParentWindowAdapter(object parentWindow, bool createIfMissing = false)
44+
internal MsalParentWindowAdapter(object parentWindow, bool createIfMissing,
45+
Func<IntPtr> getConsoleParentWindow, Func<IntPtr, bool> isWindowVisible,
46+
Func<CancellationToken, IntPtr> createWindow)
4047
{
48+
EnsureArgument.NotNull(getConsoleParentWindow, nameof(getConsoleParentWindow));
49+
EnsureArgument.NotNull(isWindowVisible, nameof(isWindowVisible));
50+
EnsureArgument.NotNull(createWindow, nameof(createWindow));
51+
4152
_parentWindow = parentWindow;
4253
_createIfMissing = createIfMissing;
54+
55+
_getConsoleParentWindow = getConsoleParentWindow;
56+
_isWindowVisible = isWindowVisible;
57+
_createWindow = createWindow;
4358
}
4459

4560
public object GetWindow()
@@ -49,25 +64,38 @@ public object GetWindow()
4964
return _parentWindow;
5065
}
5166

67+
// See if we can use the console window as a parent.
68+
// We only consider the window if it is valid and visible.
69+
IntPtr consoleParent = _getConsoleParentWindow();
70+
if (consoleParent != IntPtr.Zero && _isWindowVisible(consoleParent))
71+
{
72+
return consoleParent;
73+
}
74+
5275
// Create a stub window to use as a parent
5376
if (_createIfMissing)
5477
{
55-
return ProgressWindow.ShowAndGetHandle(_cts.Token);
78+
return _createWindow(_cts.Token);
5679
}
5780

81+
return null;
82+
}
83+
84+
private static IntPtr GetConsoleParentWindow()
85+
{
5886
// On Windows we can try and get the console window parent handle if that exists
59-
if (PlatformUtils.IsWindows())
87+
if (!PlatformUtils.IsWindows())
6088
{
61-
IntPtr consoleHandle = Kernel32.GetConsoleWindow();
62-
IntPtr parentHandle = User32.GetAncestor(consoleHandle, GetAncestorFlags.GetRootOwner);
63-
64-
if (parentHandle != IntPtr.Zero)
65-
{
66-
return parentHandle;
67-
}
89+
return IntPtr.Zero;
6890
}
6991

70-
return null;
92+
IntPtr consoleHandle = Kernel32.GetConsoleWindow();
93+
94+
// When the parent is using ConPTY (pseudo-terminals) the console
95+
// window may be a fake/stub (as is the case with Windows Terminal).
96+
// This means we need to walk up the ancestor chain to get the actual
97+
// root owner (typically the terminal emulator's window).
98+
return User32.GetAncestor(consoleHandle, GetAncestorFlags.GetRootOwner);
7199
}
72100

73101
public void Dispose()

‎src/Core/Interop/Windows/Native/User32.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ public static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr value)
3636
[DllImport(LibraryName, SetLastError = true)]
3737
public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect);
3838

39+
[DllImport(LibraryName)]
40+
public static extern bool IsWindowVisible(IntPtr hwnd);
41+
3942
/// <summary>
4043
/// Retrieves the handle to the ancestor of the specified window.
4144
/// </summary>

0 commit comments

Comments
 (0)