fix: let the browser-launched handler reach the elevated companion's callback inbox #9

Merged
james.maes merged 2 commits from fix/browser-callback-inbox-20261105 into main 2026-11-05 16:24:44 +00:00
6 changed files with 135 additions and 11 deletions

No files matched your search

+4 -4
View File
@@ -12,10 +12,10 @@ on:
inputs:
product-version:
type: string
default: '1.1.0'
default: '1.1.1'
release-version:
type: string
default: '1.1.0'
default: '1.1.1'
permissions:
contents: read
@@ -59,8 +59,8 @@ jobs:
./build/Test-PackagingInputs.ps1
- name: Build unsigned prerelease MSI
env:
PRODUCT_VERSION: ${{ inputs.product-version || '1.1.0' }}
RELEASE_VERSION: ${{ inputs.release-version || '1.1.0' }}
PRODUCT_VERSION: ${{ inputs.product-version || '1.1.1' }}
RELEASE_VERSION: ${{ inputs.release-version || '1.1.1' }}
run: |
./build/Build-Installer.ps1 -ProductVersion $env:PRODUCT_VERSION -ReleaseVersion $env:RELEASE_VERSION
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+11
View File
@@ -1,5 +1,16 @@
# Changelog
## 1.1.1
Browser sign-in fix. The companion runs elevated, and its callback inbox pipe was keyed with
PipeOptions.CurrentUserOnly to the elevated token's default owner (the Administrators group), so
the protocol handler the browser launches as the ordinary user was refused with "Access to the
path is denied" and no browser sign-in could ever complete. The inbox is now created with an
explicit descriptor owned by and restricted to the user's own SID, and the handler verifies the
companion by process image instead of the owner comparison. A protocol-handler trace in the
per-user profile, copied into the activity log when a browser sign-in does not complete, makes
the hand-off visible. No wire change.
## 1.1.0
Diagnostics for new accounts and servers. The session client now narrates every step of discovery,
+1 -1
View File
@@ -60,7 +60,7 @@
commit as "+<sha>" on AssemblyInformationalVersion, which the About dialog and the
CLI's version output show as a short hash. -->
<PropertyGroup>
<VersionPrefix>1.1.0</VersionPrefix>
<VersionPrefix>1.1.1</VersionPrefix>
<VersionSuffix></VersionSuffix>
</PropertyGroup>
+2 -2
View File
@@ -4,8 +4,8 @@
[CmdletBinding()]
param(
[string] $ProductVersion = '1.1.0',
[string] $ReleaseVersion = '1.1.0',
[string] $ProductVersion = '1.1.1',
[string] $ReleaseVersion = '1.1.1',
# Assemble artifacts/release from an already built MSI (the signed stable flow builds and signs it in
# separate workflow steps). With ExpectedPublisherSubject the MSI must carry that publisher's signature.
[switch] $AssembleOnly,
@@ -6,6 +6,7 @@
using System.Diagnostics;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
@@ -28,11 +29,31 @@ public sealed partial class QqqBrowserCallback : IDisposable
/// <summary>
/// Creates the one-instance pipe. It is current-user-only and the first instance wins, so a second sign-in attempt or a
/// Creates the one-instance pipe. Only this user may open it and the first instance wins, so a second sign-in attempt or a
/// look-alike server created earlier by another process is refused rather than silently sharing the inbox.
/// </summary>
internal QqqBrowserCallback(string name) => _pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance);
internal QqqBrowserCallback(string name) => _pipe = NamedPipeServerStreamAcl.Create(name, PipeDirection.InOut, 1,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.FirstPipeInstance, 4096, 4096, InboxSecurity());
/// <summary>
/// The inbox's security descriptor. The companion runs elevated, and PipeOptions.CurrentUserOnly would key the pipe to
/// the elevated token's default owner, which is the Administrators group rather than the user; the protocol handler the
/// browser launches runs as the ordinary user with Administrators present only as a deny-only group, so it was refused.
/// The descriptor therefore grants access to the user's own SID (the same single-user restriction, keyed correctly) and
/// names the user as owner, so the unelevated handler can reach the inbox and nobody else can.
/// </summary>
internal static PipeSecurity InboxSecurity()
{
using var identity = WindowsIdentity.GetCurrent();
SecurityIdentifier user = identity.User ?? throw new InvalidOperationException("The current user has no security identifier.");
var security = new PipeSecurity();
security.SetOwner(user);
security.SetGroup(user);
security.AddAccessRule(new PipeAccessRule(user, PipeAccessRights.FullControl, AccessControlType.Allow));
return security;
}
@@ -69,7 +90,9 @@ public sealed partial class QqqBrowserCallback : IDisposable
trace?.Invoke("Callback address accepted: " + validated.GetLeftPart(UriPartial.Path) + " with " + (validated.Query.Length - 1).ToString(System.Globalization.CultureInfo.InvariantCulture) + " characters of query (not logged).");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
await using NamedPipeClientStream pipe = new(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly, TokenImpersonationLevel.Anonymous);
// Not CurrentUserOnly: that client option compares the pipe owner with this token's default owner, which differs
// between an elevated and an unelevated process of the same user. The peer is verified by process image instead.
await using NamedPipeClientStream pipe = new(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Anonymous);
trace?.Invoke("Connecting to the companion's callback inbox (five second limit). If this is the last line, no companion in this user session was waiting for a callback: start the browser sign-in from the app first, and keep the app open.");
await pipe.ConnectAsync(timeout.Token).ConfigureAwait(false);
trace?.Invoke("Inbox connected; verifying that it belongs to the installed companion " + expectedExecutable + ".");
@@ -158,6 +181,11 @@ public sealed partial class QqqBrowserCallback : IDisposable
/// <summary>The security descriptor the operating system holds for the live inbox pipe, for tests that must check what was created rather than what was intended.</summary>
internal PipeSecurity CurrentSecurity() => _pipe.GetAccessControl();
/// <summary>Closes the inbox, which ends the sign-in attempt's ability to receive a callback.</summary>
public void Dispose() => _pipe.Dispose();
@@ -0,0 +1,85 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using Qqq.PrintAgent.Windows;
namespace Qqq.PrintAgent.Cli.Tests;
/// <summary>
/// The browser callback inbox must be reachable by the protocol handler the browser launches at medium integrity even when the
/// companion runs elevated: the pipe is owned by the user, restricted to the user, labelled medium integrity, and a forwarded
/// callback from a same-user process is received and acknowledged.
/// </summary>
public sealed class QqqBrowserCallbackInboxTests
{
/// <summary>The inbox descriptor names the current user (not the token's default owner) as owner and grants access to that user's SID only, so an elevated companion cannot lock out the unelevated handler and no other account can reach the inbox.</summary>
[Fact]
public void InboxSecurity_IsUserOwnedUserOnlyAndMediumIntegrity()
{
using var identity = WindowsIdentity.GetCurrent();
PipeSecurity security = QqqBrowserCallback.InboxSecurity();
Assert.Equal(identity.User, security.GetOwner(typeof(SecurityIdentifier)));
AuthorizationRuleCollection rules = security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier));
AuthorizationRule rule = Assert.Single(rules.Cast<AuthorizationRule>());
Assert.Equal(identity.User, rule.IdentityReference);
Assert.Equal(AccessControlType.Allow, ((PipeAccessRule)rule).AccessControlType);
Assert.Equal(PipeAccessRights.FullControl, ((PipeAccessRule)rule).PipeAccessRights);
}
/// <summary>
/// The pipe the companion actually creates is owned by the user's SID, not by the token's default owner. On an elevated
/// process (hosted CI runs elevated) the default owner is the Administrators group, so this fails there if the inbox ever
/// goes back to PipeOptions.CurrentUserOnly, which is exactly the regression that locked out the browser-launched handler.
/// </summary>
[Fact]
public void CreatedInbox_IsOwnedByTheUserNotTheTokenDefaultOwner()
{
using var identity = WindowsIdentity.GetCurrent();
using QqqBrowserCallback inbox = new("QqqPrintAgent.Auth.Test." + Guid.NewGuid().ToString("N"));
PipeSecurity live = inbox.CurrentSecurity();
Assert.Equal(identity.User, live.GetOwner(typeof(SecurityIdentifier)));
if(identity.Owner is not null && identity.Owner != identity.User)
{
Assert.NotEqual(identity.Owner, live.GetOwner(typeof(SecurityIdentifier)));
}
foreach(AuthorizationRule rule in live.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
Assert.Equal(identity.User, rule.IdentityReference);
}
}
/// <summary>A callback forwarded by a same-user process through the handler's own client path reaches the inbox, is validated, acknowledged, and returned to the waiting sign-in.</summary>
[Fact]
public async Task ForwardedCallback_ReachesTheInboxAndIsAcknowledged()
{
string name = "QqqPrintAgent.Auth.Test." + Guid.NewGuid().ToString("N");
using QqqBrowserCallback inbox = new(name);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
Task<Uri> receiving = inbox.ReceiveAsync(timeout.Token);
var steps = new List<string>();
await QqqBrowserCallback.ForwardAsync(QqqBrowserCallback.RedirectUri + "?code=test-code&state=test-state", name, Environment.ProcessPath!, timeout.Token, steps.Add);
Uri received = await receiving;
Assert.Equal("?code=test-code&state=test-state", received.Query);
Assert.Contains(steps, step => step.StartsWith("Companion verified", StringComparison.Ordinal));
Assert.DoesNotContain(steps, step => step.Contains("test-code", StringComparison.Ordinal));
}
/// <summary>An address that is not this application's redirect, or that carries no query, is refused before anything connects.</summary>
[Theory]
[InlineData("io.qrun.qqq-print-agent:/oauth/callback")]
[InlineData("io.qrun.qqq-print-agent:/other?code=x")]
[InlineData("https://evil.invalid/oauth/callback?code=x")]
public void InvalidCallback_IsRefused(string callback)
=> Assert.Throws<InvalidDataException>(() => QqqBrowserCallback.Validate(callback));
}