From ba30561d49dafa7ed663f8ce1f585da2865c0d57 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 22:35:12 -0600 Subject: [PATCH 01/27] feat(presentation): log entries can be written as a message template and its values The presentation log took finished strings only, so every caller put its entry together by concatenation (K22-CODE-CS-10 asks for a template and values). IPresentationLog gains one template method per level. Each has a default that renders the template to text and writes it through the level's text method, so a host that keeps text (the companion's CompanionLog, the tests' RecordingLog) needs no change and a host that keeps structured entries can implement them. PresentationLogTemplate fills the holes in the order the values are given, in the invariant culture; a hole without a value stays as written, a value without a hole is left out, and a brace inside a value is never taken for a hole. The wizard-and-tree plan gives these overloads to its step 2 (ManagementClient). They are added here because step 3's new types are the first to need them; the existing callers are not changed. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../IPresentationLog.cs | 24 +++++- .../PresentationLogTemplate.cs | 44 +++++++++++ .../PresentationLogTests.cs | 79 +++++++++++++++++++ 3 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 src/Qqq.PrintAgent.Presentation/PresentationLogTemplate.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/PresentationLogTests.cs diff --git a/src/Qqq.PrintAgent.Presentation/IPresentationLog.cs b/src/Qqq.PrintAgent.Presentation/IPresentationLog.cs index 800b0cb..5e71db0 100644 --- a/src/Qqq.PrintAgent.Presentation/IPresentationLog.cs +++ b/src/Qqq.PrintAgent.Presentation/IPresentationLog.cs @@ -8,7 +8,9 @@ namespace Qqq.PrintAgent.Presentation; /// /// Where presentation logic writes its activity entries. The companion forwards them to the shared activity log with its own /// prefix; tests record them. Keeping this to four levels means the presentation assembly needs no logging package and no -/// log file, and callers must never pass credentials, enrollment codes or document content to it. +/// log file, and callers must never pass credentials, enrollment codes or document content to it. New code writes an +/// entry as a message template and its values (the second set of methods), never as a string it put together itself; +/// a host that keeps structured entries implements those methods, and one that does not gets the entry as text. /// public interface IPresentationLog { @@ -29,4 +31,24 @@ public interface IPresentationLog /// Records request-level detail; the host writes it only while debug logging is switched on. void Debug(string message); + + + + /// Records one step of normal operation from a message template and the values of its holes (see ). + void Info(string template, params object?[] values) => Info(PresentationLogTemplate.Render(template, values)); + + + + /// Records something the operator should notice, from a message template and the values of its holes. + void Warning(string template, params object?[] values) => Warning(PresentationLogTemplate.Render(template, values)); + + + + /// Records a failure the operator has to act on, from a message template and the values of its holes. + void Error(string template, params object?[] values) => Error(PresentationLogTemplate.Render(template, values)); + + + + /// Records request-level detail from a message template and the values of its holes. + void Debug(string template, params object?[] values) => Debug(PresentationLogTemplate.Render(template, values)); } diff --git a/src/Qqq.PrintAgent.Presentation/PresentationLogTemplate.cs b/src/Qqq.PrintAgent.Presentation/PresentationLogTemplate.cs new file mode 100644 index 0000000..6b269f3 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/PresentationLogTemplate.cs @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Globalization; +using System.Text; + +namespace Qqq.PrintAgent.Presentation; + +/// +/// Turns a message template and its values into the text of a log entry, for a host whose log keeps text. A template +/// is fixed text with named holes, "Opened {Server} after {Seconds} s", and the values fill the holes in the order +/// they are given. Writing entries this way keeps what was said apart from what it was said about, so the sentence +/// is the same for every server and a host can keep the values as fields. +/// +public static class PresentationLogTemplate +{ + /// + /// Fills the holes of a template, first hole with the first value. Each value is written in the invariant culture, + /// so an entry reads the same on every computer, and a missing value (null) is written as nothing. A hole that has + /// no value left stays as it was written, which shows in the log that a value was forgotten; a value that has no + /// hole is left out. Only the template is searched for holes, so a brace inside a value is never taken for one. + /// + public static string Render(string template, IReadOnlyList values) + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(values); + StringBuilder text = new(template.Length); + int position = 0; + foreach(object? value in values) + { + int open = template.IndexOf('{', position); + int close = open < 0 ? -1 : template.IndexOf('}', open); + if(close < 0) + { + break; + } + text.Append(template, position, open - position).Append(Convert.ToString(value, CultureInfo.InvariantCulture)); + position = close + 1; + } + return text.Append(template, position, template.Length - position).ToString(); + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/PresentationLogTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/PresentationLogTests.cs new file mode 100644 index 0000000..c638b98 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/PresentationLogTests.cs @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Globalization; +using Qqq.PrintAgent.Presentation.Tests.Fakes; + +namespace Qqq.PrintAgent.Presentation.Tests; + +/// Log entries written as a message template and its values: how a template becomes text, and that each level's template method writes at that level for a host that keeps text. +public sealed class PresentationLogTests +{ + /// The holes of a template are filled in the order the values are given, whatever the holes are called, and the text around them is kept as written. + [Fact] + public void Template_HolesAreFilledInOrder() + { + Assert.Equal("Opened print.example.com after 3 attempts.", PresentationLogTemplate.Render("Opened {Server} after {Attempts} attempts.", ["print.example.com", 3])); + Assert.Equal("first second", PresentationLogTemplate.Render("{A} {B}", ["first", "second"])); + Assert.Equal("No holes here.", PresentationLogTemplate.Render("No holes here.", [])); + } + + + + /// A value is written the same on every computer, whatever language Windows is set to, and a missing value is written as nothing. + [Fact] + public void Template_ValuesAreWrittenInTheInvariantCulture_AndNullAsNothing() + { + CultureInfo before = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); + try + { + Assert.Equal("Took 1.5 s on 11/10/2026 10:00:00; reason: .", PresentationLogTemplate.Render("Took {Seconds} s on {When}; reason: {Reason}.", [1.5, new DateTime(2026, 11, 10, 10, 0, 0, DateTimeKind.Utc), null])); + } + finally + { + CultureInfo.CurrentCulture = before; + } + } + + + + /// A hole that was given no value stays as it was written, so a forgotten value shows in the log; a value that has no hole is left out; and a brace inside a value is never taken for a hole. + [Fact] + public void Template_MissingAndSurplusValues_AndBracesInValues() + { + Assert.Equal("Opened print.example.com after {Attempts} attempts.", PresentationLogTemplate.Render("Opened {Server} after {Attempts} attempts.", ["print.example.com"])); + Assert.Equal("Opened print.example.com.", PresentationLogTemplate.Render("Opened {Server}.", ["print.example.com", "surplus"])); + Assert.Equal("Said {B} and then last.", PresentationLogTemplate.Render("Said {A} and then {B}.", ["{B}", "last"])); + Assert.Equal("An open brace { is text.", PresentationLogTemplate.Render("An open brace { is text.", ["surplus"])); + } + + + + /// A template and its values are both needed. + [Fact] + public void Template_NeedsATemplateAndValues() + { + Assert.Equal("template", Assert.Throws(() => PresentationLogTemplate.Render(null!, [])).ParamName); + Assert.Equal("values", Assert.Throws(() => PresentationLogTemplate.Render("text", null!)).ParamName); + } + + + + /// A host that keeps text and implements only the four text methods gets each templated entry as finished text at the level it was written at. + [Fact] + public void TemplateMethods_WriteTheFinishedTextAtTheirLevel() + { + RecordingLog recording = new(); + IPresentationLog log = recording; + + log.Info("Opened {Server}.", "print.example.com"); + log.Warning("Slow answer from {Server} ({Seconds} s).", "print.example.com", 12); + log.Error("Could not reach {Server}.", "print.example.com"); + log.Debug("Request {Number} to {Server}.", 7, "print.example.com"); + + Assert.Equal(["INFO Opened print.example.com.", "WARN Slow answer from print.example.com (12 s).", "ERROR Could not reach print.example.com.", "DEBUG Request 7 to print.example.com."], recording.Entries); + } +} -- 2.54.0 From 081f900642ce6d3e918dd56f11b2a5208043c822 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 22:35:21 -0600 Subject: [PATCH 02/27] feat(presentation): the companion's own sign-in, one dispatcher for browser callbacks, and the provider's sign-out Step 3 of the wizard-and-tree stage (ADR-0005). Three types for the connection wizard and the per-server Connection page. The window does not use them yet; the connection dialog still runs on SignInFlow, which is not touched. CompanionSignIn is the part of signing in that needs a session: it reads the server's sign-in description as the signed-in Windows user, signs in by password or through the browser and returns the session credential. It hands nothing to the service, enrolls nothing and holds no trust setting; the certificate exception to read under is an argument. It offers the methods the service's check and its own read both found, stops when the description names another sign-in provider than the check reported, and says whose certificate this account refused, the server's or the provider's, keeping the refusal for the wizard to show. A cancelled or timed-out browser attempt keeps its session. BrowserCallbackDispatcher owns the one callback inbox. An exchange registers the OAuth state it sent and awaits a ticket; the dispatcher has an inbox open exactly while a ticket waits, completes the ticket whose state a callback carries and drops every other callback, logging only that one was dropped. A failing inbox fails every waiter once, and the next registration opens a new one. ProviderSignOut is the provider's half of a sign-out: open its page, wait up to two minutes for this sign-out's own state. When Windows cannot start the browser its failure names the whole address it was asked to open (state, or the ID token hint). The new types report only the kind of failure. ISignInSession gains LastCertificateRejection; the companion's adapter passes the session client's through and the test fake scripts it. Every entry the new types log is a template with values, and the tests assert the log's content wherever a secret could have reached it. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 29 + .../SignIn/BrowserCallbackDispatcher.cs | 271 +++++++ .../SignIn/BrowserCallbackTicket.cs | 60 ++ .../SignIn/BrowserLaunch.cs | 39 + .../SignIn/CompanionSignIn.Browser.cs | 139 ++++ .../SignIn/CompanionSignIn.cs | 473 ++++++++++++ .../SignIn/CompanionSignInState.cs | 59 ++ .../SignIn/ISignInSession.cs | 10 + .../SignIn/ProviderSignOut.cs | 72 ++ .../SignIn/SignInOffer.cs | 63 ++ src/Qqq.PrintAgent/QqqSignInSession.cs | 5 + .../Fakes/FakeSession.cs | 58 +- .../Fakes/SignInWorld.cs | 263 +++++++ .../SignIn/BrowserCallbackDispatcherTests.cs | 465 ++++++++++++ .../SignIn/CompanionSignInBrowserTests.cs | 532 +++++++++++++ .../SignIn/CompanionSignInTests.cs | 699 ++++++++++++++++++ .../SignIn/ProviderSignOutTests.cs | 156 ++++ .../SignIn/SignInOfferTests.cs | 81 ++ 18 files changed, 3465 insertions(+), 9 deletions(-) create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/SignInOffer.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInOfferTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 541986d..a967dfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,35 @@ ## Unreleased +Sign-in in the companion, rebuilt for several servers (2.0; not used by the window yet). Three types were added to +the presentation assembly for the connection wizard and the per-server Connection page of +[ADR-0005](docs/adr/0005-connection-wizard-and-server-tree.md). Nothing the operator sees changes in this build: the +connection dialog still runs on the existing flow, which is untouched. + +- `CompanionSignIn` is the part of signing in that needs a session and runs as the signed-in Windows user. It reads + the server's sign-in description, signs in by password or through the browser, and returns the session credential + to its caller. It hands nothing to the service, enrolls nothing and keeps no certificate setting: the exception to + read under is given with each read. It offers only the methods that the service's check and its own read both + found, and logs a difference. It stops when the description names another sign-in provider than the check + reported. When this Windows account refuses a certificate the service accepted, or the sign-in provider's + certificate, it says which of the two it was and keeps the refused certificate for the wizard to show. A cancelled + or timed-out browser sign-in keeps its session, so the next attempt needs no new read. +- `BrowserCallbackDispatcher` owns the one browser callback inbox. A sign-in or a provider sign-out registers the + OAuth state it sent and waits for the callback that carries it, so two servers can be signing in at once. A + callback that carries no state, more than one, or a state nobody waits for is dropped, and the log says only that + one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that waits fails + once and the next registration opens a new inbox. +- `ProviderSignOut` is the identity provider's half of a sign-out: it opens the provider's sign-out page and waits + up to two minutes for the browser to return with that sign-out's own state. +- When Windows cannot start the browser, its failure text names what it could not start, which is the whole sign-in + or sign-out address. The new types report only the kind of failure, so no state and no token hint can reach the + log or the screen that way. +- The sign-in session seen by the presentation assembly (`ISignInSession`) now also gives the certificate it refused + last and the origin that presented it. +- The presentation log (`IPresentationLog`) can be written to with a message template and its values, which the new + types use for every entry. A host that implements only the four text methods, as the companion does, gets the + finished text. + In-app update, service controls and the pipe's identity check (2.0). The installed product behaves as before. This change does not alter the Windows Installer command line, the files, owners and access lists that are checked or the order they are checked in, what an installer exit code means, the calls made to the service control manager, diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs new file mode 100644 index 0000000..34ecb8f --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// Owns the one browser callback inbox. Windows gives each user one redirect address and one inbox, so browser +/// exchanges cannot each have their own: a sign-in or a provider sign-out registers the OAuth state it sent and gets a +/// ticket to await, and this hands each callback to the ticket whose state it carries. Two servers can then be signing +/// in at once, and a late callback for an exchange that has ended is dropped instead of failing another. An inbox is +/// open exactly while at least one ticket waits. Each inbox takes one callback, so after every callback it is closed and, +/// when tickets still wait, a new one is opened. A callback that carries no state, more than one, or a state nobody +/// waits for is dropped, and the log says only that one was dropped: nothing of a callback, its state or its code is +/// ever logged, and a registered state is held only while its ticket waits. When the inbox itself fails, which +/// includes an inbox that refuses what it received as no callback at all, every waiting ticket fails with that +/// failure and the next registration opens a new inbox. Tickets are registered from the window's thread and +/// callbacks arrive on others, so the waiting set is guarded, and this never continues on a caller's thread. +/// +public sealed class BrowserCallbackDispatcher +{ + private readonly IBrowserCallbackSource _callbacks; + private readonly IPresentationLog _log; + private readonly Lock _gate = new(); + private readonly Dictionary _waiting = new(StringComparer.Ordinal); + private IBrowserCallbackInbox? _inbox; + private CancellationTokenSource? _listening; + + + + /// Wires the dispatcher to where callbacks arrive and to the log. + public BrowserCallbackDispatcher(IBrowserCallbackSource callbacks, IPresentationLog log) + { + _callbacks = callbacks ?? throw new ArgumentNullException(nameof(callbacks)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + } + + + + /// + /// Registers the state a browser exchange sent and returns the ticket to await. The inbox is open when this + /// returns, so the caller opens the browser afterwards and a fast redirect is not lost. A state that is already + /// waiting is refused, because two exchanges could not be told apart. When the inbox cannot be opened the failure is + /// thrown to the caller and nothing is registered. The caller disposes the ticket when its exchange ends, however + /// it ends. + /// + public BrowserCallbackTicket Register(string state) + { + ArgumentException.ThrowIfNullOrEmpty(state); + BrowserCallbackTicket ticket = new(this, state); + lock(_gate) + { + if(!_waiting.TryAdd(state, ticket)) + { + throw new InvalidOperationException("A browser exchange with the same state is already waiting for its callback."); + } + if(_inbox is null) + { + try + { + Listen(); + } + catch(Exception) + { + _waiting.Remove(state); + throw; + } + } + } + return ticket; + } + + + + /// + /// Reads the one state parameter of an address's query: the state a sign-in sent, from the authorization + /// address, or the state a callback returns. It is null when the address has none, an empty one or more than one, + /// because a repeated parameter could make two readers disagree about which exchange a callback belongs to. + /// + internal static string? ReadState(Uri address) + { + string? state = null; + if(!address.IsAbsoluteUri) + { + return null; + } + foreach(string entry in address.Query.TrimStart('?').Split('&')) + { + string[] pair = entry.Split('=', 2); + if(pair.Length == 2 && string.Equals(Uri.UnescapeDataString(pair[0].Replace('+', ' ')), "state", StringComparison.Ordinal)) + { + if(state is not null) + { + return null; + } + state = Uri.UnescapeDataString(pair[1].Replace('+', ' ')); + } + } + return string.IsNullOrEmpty(state) ? null : state; + } + + + + /// Ends a ticket's claim. Only the ticket that is waiting under its state is forgotten, so disposing a ticket that already has its callback cannot remove a later one, and the inbox is closed when nothing waits any more. + internal void Release(BrowserCallbackTicket ticket) + { + lock(_gate) + { + bool waited = ((ICollection>)_waiting).Remove(new KeyValuePair(ticket.State, ticket)); + if(waited && _waiting.Count == 0) + { + Close(); + } + } + } + + + + /// Opens an inbox and starts waiting for its one callback. The caller holds the gate. A failure to open is thrown, and no inbox is then open. + private void Listen() + { + IBrowserCallbackInbox inbox = _callbacks.Open(); + CancellationTokenSource listening = new(); + _inbox = inbox; + _listening = listening; + _log.Info("Browser callback inbox open."); + _ = ReceiveAsync(inbox, listening.Token); + } + + + + /// + /// Closes the open inbox. The caller holds the gate. The fields are cleared before the wait is cancelled, because + /// cancelling can run the end of that wait at once, on this thread, and it must then find that its inbox is no + /// longer the open one and do nothing. + /// + private void Close() + { + IBrowserCallbackInbox inbox = _inbox!; + CancellationTokenSource listening = _listening!; + _inbox = null; + _listening = null; + listening.Cancel(); + inbox.Dispose(); + listening.Dispose(); + } + + + + /// + /// Waits for the one callback of an inbox and routes it. Any failure of the wait, whatever its kind, is the inbox + /// failing, and has to reach the tickets that wait: a failure left here would leave every one of them waiting for + /// its own time limit. The wait that ends because the inbox was closed is told apart inside + /// , by the inbox no longer being the open one. + /// + private async Task ReceiveAsync(IBrowserCallbackInbox inbox, CancellationToken listening) + { + Uri callback; + try + { + callback = await inbox.ReceiveAsync(listening).ConfigureAwait(false); + } + catch(Exception exception) + { + Fail(inbox, exception); + return; + } + Route(inbox, callback); + } + + + + /// + /// Hands a received callback to the ticket whose state it carries, or drops it. The inbox that delivered it is + /// closed and, when tickets still wait, the next one is opened in the same step, so an inbox is open exactly while + /// a ticket waits and the gap between two inboxes is as short as it can be. A callback from an inbox that was + /// closed meanwhile (its last ticket ended as the callback arrived) is dropped. The log line for a drop is fixed + /// text, written before the next inbox opens so the log reads in the order things happened. The ticket is + /// completed last, outside the gate. + /// + private void Route(IBrowserCallbackInbox inbox, Uri callback) + { + BrowserCallbackTicket? ticket = null; + BrowserCallbackTicket[] stranded; + Exception? failure; + lock(_gate) + { + if(ReferenceEquals(_inbox, inbox)) + { + Close(); + if(ReadState(callback) is { } state) + { + _waiting.Remove(state, out ticket); + } + } + if(ticket is null) + { + _log.Warning("A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged."); + } + failure = Reopen(out stranded); + } + if(failure is not null) + { + End(stranded, failure); + } + ticket?.Complete(callback); + } + + + + /// Opens the next inbox when tickets wait and none is open. The caller holds the gate. When it cannot be opened, the tickets that wait cannot receive anything: they are taken out for the caller to fail, and the failure is returned. + private Exception? Reopen(out BrowserCallbackTicket[] stranded) + { + stranded = []; + if(_inbox is not null || _waiting.Count == 0) + { + return null; + } + try + { + Listen(); + return null; + } + catch(Exception exception) + { + stranded = TakeWaiting(); + return exception; + } + } + + + + /// Handles a wait that ended without a callback. When the inbox is still the open one it failed: it is closed and every waiting ticket fails. Otherwise it was closed on purpose and nothing waits on it. + private void Fail(IBrowserCallbackInbox inbox, Exception failure) + { + BrowserCallbackTicket[] stranded; + lock(_gate) + { + if(!ReferenceEquals(_inbox, inbox)) + { + return; + } + Close(); + stranded = TakeWaiting(); + } + End(stranded, failure); + } + + + + /// Removes and returns every waiting ticket. The caller holds the gate. + private BrowserCallbackTicket[] TakeWaiting() + { + BrowserCallbackTicket[] waiting = [.. _waiting.Values]; + _waiting.Clear(); + return waiting; + } + + + + /// Fails the tickets a broken inbox left waiting, each once, and logs the kind of failure and how many it ended. The failure's own text is left to each exchange to report, so nothing an inbox put in a message is logged from here. + private void End(BrowserCallbackTicket[] stranded, Exception failure) + { + _log.Error("The browser callback inbox failed ({Failure}); {Waiting} waiting browser exchange(s) were ended and have to be started again.", failure.GetType().Name, stranded.Length); + foreach(BrowserCallbackTicket ticket in stranded) + { + ticket.Fail(failure); + } + } +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs new file mode 100644 index 0000000..c5f0335 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// One browser exchange's claim on the callback inbox: the sign-in or provider sign-out that registered an OAuth state +/// with the waits on this for the callback carrying that state. Disposing it +/// ends the claim, after which a callback with that state is dropped. The state is held only while the ticket waits +/// and is never shown: the ticket has no public member that returns it. +/// +public sealed class BrowserCallbackTicket : IDisposable +{ + private readonly TaskCompletionSource _callback = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly BrowserCallbackDispatcher _dispatcher; + + + + /// Creates the ticket for a state; only the dispatcher does, when the state is registered. + internal BrowserCallbackTicket(BrowserCallbackDispatcher dispatcher, string state) + { + _dispatcher = dispatcher; + State = state; + } + + + + /// The state this ticket waits for, which is how the dispatcher finds it. + internal string State { get; } + + + + /// + /// The callback carrying this ticket's state. It completes with the callback address when the dispatcher receives + /// it, fails with the inbox's failure when the inbox failed while this ticket waited, and is cancelled when the + /// ticket is disposed first. Whoever awaits it continues on its own thread, never inside the dispatcher. + /// + public Task Callback => _callback.Task; + + + + /// Hands the ticket its callback. + internal void Complete(Uri callback) => _callback.TrySetResult(callback); + + + + /// Ends the wait with the inbox's failure. + internal void Fail(Exception failure) => _callback.TrySetException(failure); + + + + /// Ends the claim: the dispatcher forgets the state, closes the inbox when no other ticket waits, and a wait that has no result yet is cancelled. Disposing a ticket that already has its callback changes nothing. + public void Dispose() + { + _dispatcher.Release(this); + _callback.TrySetCanceled(); + } +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs new file mode 100644 index 0000000..b404be2 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Globalization; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// Opens an address in the browser for a sign-in or a provider sign-out, and makes a failure to do so safe to report. +/// The address carries a sign-in state or the provider's ID token hint. When Windows cannot start the browser, its +/// failure names the thing it could not start, which is that whole address, so the failure's own text must never +/// reach a log line or the screen. +/// +internal static class BrowserLaunch +{ + /// + /// Opens the address. Any failure is replaced by one with fixed text that names only the kind of failure and, + /// for a Windows error, its number. The new failure is thrown after the original has been let go, so the original + /// is not attached as its cause: a report of the new failure, whichever way it is written out, then cannot + /// contain the address. + /// + internal static void Open(IBrowserLauncher browser, Uri address) + { + string kind; + try + { + browser.Open(address); + return; + } + catch(Exception exception) + { + kind = exception is Win32Exception windows ? "Windows error " + windows.NativeErrorCode.ToString(CultureInfo.InvariantCulture) : exception.GetType().Name; + } + throw new IOException("The default browser could not be opened (" + kind + ")."); + } +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs new file mode 100644 index 0000000..32f0bc1 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Qqq.PrintAgent.Core.Authentication; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// Browser sign-in: the exchange with the identity provider through the default browser, its time limit and +/// cancellation, and what is recorded when the browser never comes back. The callback is awaited through the one +/// , by the state this attempt sent, so another server's sign-in can be waiting +/// at the same time and a callback that is not this attempt's never reaches it. +/// +public sealed partial class CompanionSignIn +{ + /// How long a browser sign-in waits before it is given up. + public static readonly TimeSpan BrowserSignInLimit = TimeSpan.FromMinutes(3); + + private static readonly TimeSpan s_traceWindow = TimeSpan.FromMinutes(10); + private CancellationTokenSource? _browserCancel; + + + + /// + /// Signs in through the browser, with a three minute limit, and returns the session credential. Nothing happens + /// without a session that offers the browser. The redirect address is the one this application's installer + /// registered, and it is used only when the server also lists it, so a server cannot steer the callback elsewhere. + /// A cancelled, timed-out or failed attempt is reported by state and keeps the session, so the operator can try + /// again: a late callback of the abandoned attempt carries a state nobody waits for and is dropped by the + /// dispatcher. It returns null when no credential was obtained. + /// + public async Task SignInWithBrowserAsync(CancellationToken cancellationToken = default) + { + if(_session is not { } session || _offer is not { Browser: true } || !TryBegin("Browser sign-in")) + { + return null; + } + return await RunAsync("Browser sign-in", CompanionSignInState.WaitingForBrowser, token => TryBrowserSignInAsync(session, token), cancellationToken); + } + + + + /// Cancels the browser sign-in that is running, if one is. It has no effect once the exchange with the browser has ended, however it ended. + public void CancelBrowserSignIn() => _browserCancel?.Cancel(); + + + + /// + /// The exchange under its limit, and what its ending means. The Cancel button reaches the exchange through a + /// field, which is cleared before the exchange's cancellation sources are released, so a Cancel that arrives while + /// a failed exchange is still being reported finds nothing to cancel. An exchange that the operator cancelled or + /// that ran out of time is said to be exactly that. A wait that the caller or disposal ended is left to the + /// runner. Announcing the result is outside the protected part, as it is for a password sign-in. + /// + private async Task TryBrowserSignInAsync(ISignInSession session, CancellationToken token) + { + QqqCertificateRejection? known = session.LastCertificateRejection; + using CancellationTokenSource limit = new(BrowserSignInLimit, _time); + using CancellationTokenSource cancel = new(); + using var exchange = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancel.Token, token); + QqqSessionCredential credential; + _browserCancel = cancel; + try + { + await ExchangeWithBrowserAsync(session, exchange.Token); + exchange.Token.ThrowIfCancellationRequested(); + credential = session.ExportCredential(); + } + catch(OperationCanceledException) when(!token.IsCancellationRequested && (cancel.IsCancellationRequested || limit.IsCancellationRequested)) + { + _log.Info(cancel.IsCancellationRequested ? "Browser sign-in to {Server} was cancelled by the operator." : "Browser sign-in to {Server} was given up after the three minute limit.", QqqOrigin.ShownAuthority(session.Origin)); + ReportCallbackTrace(); + Settle(cancel.IsCancellationRequested ? CompanionSignInState.BrowserCanceled : CompanionSignInState.BrowserTimedOut); + return null; + } + catch(Exception exception) when(Reportable(exception, token) && exception is IOException or InvalidOperationException or HttpRequestException or UnauthorizedAccessException or Win32Exception or InvalidDataException or OperationCanceledException) + { + ReportCallbackTrace(); + Fail("Browser sign-in not completed", CompanionSignInState.BrowserFailed, session, known, exception); + return null; + } + finally + { + _browserCancel = null; + } + return SignedIn(session, credential); + } + + + + /// + /// The browser exchange itself: begin the sign-in on the session, read the state it sent from the address it + /// returned, register that state with the dispatcher (which has an inbox open before the browser is, so a fast + /// redirect is not lost), open the provider's page in the default browser, wait for the callback with that state, + /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Only the + /// provider's host is logged, never the address, its state or the callback. The token is looked at again once the + /// sign-in was begun, so a browser is not opened for a wait that has already ended; completing takes the same + /// token, and a session refuses to complete for a wait that has ended. + /// + private async Task ExchangeWithBrowserAsync(ISignInSession session, CancellationToken cancellationToken) + { + _log.Info("Browser sign-in requested for {Server}; this application's callback is {Callback}.", QqqOrigin.ShownAuthority(session.Origin), _callbacks.RedirectUri); + if(!_redirects.Contains(_callbacks.RedirectUri, StringComparer.Ordinal)) + { + _log.Warning("The server's native grant does not list this application's callback {Callback}; it lists {Count} other address(es). Add the callback to the QQQ native session grant.", _callbacks.RedirectUri, _redirects.Count); + throw new InvalidOperationException("No approved native browser callback is configured."); + } + Uri authorization = await session.BeginBrowserSignInAsync(new Uri(_callbacks.RedirectUri), cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + string state = BrowserCallbackDispatcher.ReadState(authorization) ?? throw new InvalidOperationException("The sign-in address the session prepared carries no state of its own, so its callback could not be told from another."); + using BrowserCallbackTicket ticket = _dispatcher.Register(state); + _log.Info("Opening the identity provider's sign-in page in the default browser ({Provider}).", QqqOrigin.ShownAuthority(authorization)); + BrowserLaunch.Open(_browser, authorization); + Uri callback = await ticket.Callback.WaitAsync(cancellationToken); + _log.Info("Browser callback received; completing the sign-in."); + await session.CompleteBrowserSignInAsync(callback, cancellationToken); + } + + + + /// + /// Copies the protocol handler's recent trace into the activity log, or states that the browser never launched the + /// handler at all, so a hand-off that stops outside the companion is still visible in one place. The handler + /// writes that trace without the query of any callback. + /// + private void ReportCallbackTrace() + { + IReadOnlyList lines = _callbacks.RecentTrace(s_traceWindow); + if(lines.Count == 0) + { + _log.Warning("The browser never launched the sign-in protocol handler in the last 10 minutes (no entries in {TracePath}). Either the identity provider did not redirect to {Callback} (check the provider's allowed redirect URIs and any error page it showed), or the browser blocked opening the QQQ Print Agent sign-in link.", _callbacks.TracePath, _callbacks.RedirectUri); + return; + } + _log.Warning("Protocol handler trace from {TracePath}:{NewLine}{Trace}", _callbacks.TracePath, Environment.NewLine, string.Join(Environment.NewLine, lines)); + } +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs new file mode 100644 index 0000000..90193cb --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -0,0 +1,473 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Windows.Management; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// The part of signing in that needs a session, and runs in the companion as the signed-in Windows user: read the +/// server's sign-in description, sign in by password or through the browser, and return the session credential to the +/// caller. That is all it does. It hands nothing to the service, enrolls nothing and holds no trust setting: the +/// certificate exception to read under is given with each preparation, and what happens to the credential is the +/// caller's business. A password is passed straight to the session and never kept, and the credential is only ever a +/// return value, never a property. One operation runs at a time; a second one is refused and logged. Everything it +/// announces is raised on the thread that called it. Disposing it only cancels: the running operation ends itself, +/// discards the session on its way out, and from then on nothing is announced. +/// +public sealed partial class CompanionSignIn : ObservableObject, IDisposable +{ + private readonly ISignInSessionFactory _sessions; + private readonly IBrowserLauncher _browser; + private readonly IBrowserCallbackSource _callbacks; + private readonly BrowserCallbackDispatcher _dispatcher; + private readonly IPresentationLog _log; + private readonly TimeProvider _time; + private readonly CancellationTokenSource _lifetime = new(); + private ISignInSession? _session; + private IReadOnlyList _redirects = []; + private CancellationTokenSource? _operation; + private CompanionSignInState _state; + private SignInOffer? _offer; + private QqqCertificateRejection? _rejection; + private string? _failure; + private bool _operating; + private bool _discarding; + private bool _disposed; + + + + /// Wires the sign-in to the things it cannot do itself: create a session, open the browser, name this application's callback, and wait for a callback through the one dispatcher. The time provider drives the browser time limit. + public CompanionSignIn(ISignInSessionFactory sessions, IBrowserLauncher browser, IBrowserCallbackSource callbacks, BrowserCallbackDispatcher dispatcher, IPresentationLog log, TimeProvider? time = null) + { + _sessions = sessions ?? throw new ArgumentNullException(nameof(sessions)); + _browser = browser ?? throw new ArgumentNullException(nameof(browser)); + _callbacks = callbacks ?? throw new ArgumentNullException(nameof(callbacks)); + _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + _time = time ?? TimeProvider.System; + } + + + + /// Where the sign-in is, or how its last step ended. + public CompanionSignInState State + { + get => _state; + private set => SetProperty(ref _state, value); + } + + + + /// The methods that can be used on the session that is held; null while none is held. + public SignInOffer? Offer + { + get => _offer; + private set => SetProperty(ref _offer, value); + } + + + + /// The certificate this Windows account refused in the last step, with the origin that presented it; null when the last step did not end over a certificate. It is public certificate data. + public QqqCertificateRejection? Rejection + { + get => _rejection; + private set => SetProperty(ref _rejection, value); + } + + + + /// Why the last step was not completed, in words, when it failed for a reason other than a certificate; null otherwise. It is the session's own explanation, which never says which part of a sign-in was wrong. + public string? Failure + { + get => _failure; + private set => SetProperty(ref _failure, value); + } + + + + /// True while one of the operations is running; any other is refused until it ends. + public bool IsBusy => _operating; + + + + /// True while a session is held, which is what a sign-in needs. + public bool HasSession => _session is not null; + + + + /// + /// Reads the server's sign-in description as the signed-in Windows user and says which methods can be used. Any + /// session held from before is discarded first. The session is created under the certificate exception the caller + /// gives, which is the one the operator accepted or the one stored with the server, and under no other. The methods + /// offered are those the service's check and this read both found; a difference is logged. When the description + /// names another sign-in provider than the check reported, or this account refuses the server's certificate, or the + /// description cannot be read, the state says which and no session is kept. It returns the offer, or null when + /// nothing can be signed in with, when the caller stopped waiting, or when another operation is running. + /// + public async Task PrepareAsync(Uri server, ServerCheckResult check, QqqCertificateExceptionOrigins certificateException, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(check); + ArgumentNullException.ThrowIfNull(certificateException); + if(!TryBegin("Reading the sign-in description")) + { + return null; + } + return await RunAsync("Reading the sign-in description", CompanionSignInState.Preparing, token => ReadDescriptionAsync(server, check, certificateException, token), cancellationToken); + } + + + + /// + /// The read itself. The session it creates becomes the held session only when a method is offered; in every other + /// case, a failure and a cancellation included, it is discarded before this returns or throws. Taking the session + /// over and announcing it are outside the protected part, so a subscriber that throws while the result is + /// announced has not made the read fail. + /// + private async Task ReadDescriptionAsync(Uri server, ServerCheckResult check, QqqCertificateExceptionOrigins certificateException, CancellationToken token) + { + DropSession(); + ISignInSession? session = null; + QqqAuthenticationMetadata? description = null; + SignInOffer? offer = null; + try + { + _log.Info("Reading the sign-in description of {Server} as this Windows account; an untrusted certificate is accepted from {Exception}.", QqqOrigin.ShownAuthority(server), certificateException); + session = _sessions.Create(server, certificateException); + description = await session.DiscoverAsync(token); + token.ThrowIfCancellationRequested(); + offer = Judge(session, description, check); + } + catch(Exception exception) when(Reportable(exception, token) && exception is IOException or ArgumentException or InvalidOperationException or HttpRequestException or OperationCanceledException) + { + Fail("The sign-in description could not be read", CompanionSignInState.PrepareFailed, session, null, exception); + } + finally + { + if(offer is null) + { + session?.Dispose(); + } + } + return offer is null ? null : Adopt(session!, description!, offer); + } + + + + /// + /// Judges a description that was read and returns what is offered, or null when nobody can sign in with it, having + /// said why. The provider it names is compared with the one the service's check reported, by the rule the check + /// applies (a table-based server names none), and a difference stops the sign-in: a certificate exception the + /// operator accepted covers the provider that was shown, not another. Then the methods are settled: those the + /// check and this read both found, with a difference logged. + /// + private SignInOffer? Judge(ISignInSession session, QqqAuthenticationMetadata description, ServerCheckResult check) + { + string server = QqqOrigin.ShownAuthority(session.Origin); + var read = SignInOffer.Read(description); + Uri? provider = read.Password ? null : description.ProviderOrigin; + Uri? reported = Uri.TryCreate(check.ProviderOrigin, UriKind.Absolute, out Uri? named) ? QqqOrigin.Of(named) : null; + if(!Equals(provider, reported)) + { + _log.Warning("The sign-in provider in the sign-in description of {Server} is {Read}, and the service's check reported {Checked}. Nobody is signed in until the server has been checked again.", server, Shown(provider), Shown(reported)); + Settle(CompanionSignInState.ProviderChanged); + return null; + } + var found = SignInOffer.Checked(check); + SignInOffer offer = found.Common(read); + if(found == read) + { + _log.Info("Sign-in methods for {Server}: {Offer}.", server, offer); + } + else + { + _log.Warning("Sign-in methods for {Server}: the service's check found {Checked} and this account's read found {Read}, so {Offer} is offered.", server, found, read, offer); + } + if(!offer.Any) + { + Settle(CompanionSignInState.NothingOffered); + return null; + } + return offer; + } + + + + /// Takes over the session a method is offered on, with the callbacks its description lists for a browser sign-in, and announces that a sign-in can start. + private SignInOffer Adopt(ISignInSession session, QqqAuthenticationMetadata description, SignInOffer offer) + { + _session = session; + _redirects = description.Values?.NativeSessionLogin?.RedirectUris ?? []; + OnPropertyChanged(nameof(HasSession)); + Offer = offer; + Settle(CompanionSignInState.Ready); + return offer; + } + + + + /// + /// Signs in with a user name and password and returns the session credential. Nothing happens without a session + /// that offers a password. The password is passed straight to the session and never kept or logged. A failure is + /// reported by state, with the session's own reason, which does not say which part (name, password, permission) + /// was wrong, and the session stays for another attempt. It returns null when no credential was obtained: the + /// sign-in failed, the caller stopped waiting, or nothing was attempted. + /// + public async Task SignInWithPasswordAsync(string? username, string password, CancellationToken cancellationToken = default) + { + if(_session is not { } session || _offer is not { Password: true } || !TryBegin("Password sign-in")) + { + return null; + } + return await RunAsync("Password sign-in", CompanionSignInState.SigningIn, token => TrySignInWithPasswordAsync(session, (username ?? string.Empty).Trim(), password, token), cancellationToken); + } + + + + /// + /// The server's part of a password sign-in. A failure of it, the server's own time limit included, is reported as + /// not completed. A wait that the caller or disposal ended is not a failure and is left to the runner, and no + /// credential is taken once the wait has ended. Announcing the result is outside the protected part: once the + /// server has accepted the sign-in, a subscriber that throws while it is announced has not made the sign-in fail. + /// + private async Task TrySignInWithPasswordAsync(ISignInSession session, string username, string password, CancellationToken token) + { + QqqCertificateRejection? known = session.LastCertificateRejection; + QqqSessionCredential credential; + try + { + _log.Info("Password sign-in submitted to {Server}.", QqqOrigin.ShownAuthority(session.Origin)); + await session.SignInWithPasswordAsync(username, password, token); + token.ThrowIfCancellationRequested(); + credential = session.ExportCredential(); + } + catch(Exception exception) when(Reportable(exception, token) && exception is IOException or ArgumentException or HttpRequestException or OperationCanceledException or UnauthorizedAccessException) + { + Fail("Password sign-in not completed", CompanionSignInState.PasswordFailed, session, known, exception); + return null; + } + return SignedIn(session, credential); + } + + + + /// + /// Discards the session, if any, so a later sign-in starts with a new preparation. While an operation is running + /// the session is in use, so this cancels the operation instead, and the operation discards the session as it + /// ends: discarding a session under a call that is still using it makes that call fail in ways that look like + /// errors. Either way no session is held once the running operation, if any, has ended. + /// + public void Discard() + { + if(_disposed) + { + return; + } + if(_operating) + { + _discarding = true; + _operation?.Cancel(); + return; + } + DropSession(); + Settle(CompanionSignInState.NotPrepared); + } + + + + /// + /// Ends the sign-in. It only cancels: an operation that is still running sees the cancellation, ends quietly and + /// discards the session itself. When nothing is running the session is discarded here. After this nothing is + /// announced. + /// + public void Dispose() + { + if(_disposed) + { + return; + } + _disposed = true; + _lifetime.Cancel(); + if(!_operating) + { + DropSession(); + } + _lifetime.Dispose(); + } + + + + /// Announces a change, unless the sign-in was disposed: a view that has closed must not be called back by an operation that was still finishing. + protected override void OnPropertyChanged(PropertyChangedEventArgs e) + { + if(!_disposed) + { + base.OnPropertyChanged(e); + } + } + + + + /// Records that the server accepted the user and returns the credential to hand to the caller. + private QqqSessionCredential SignedIn(ISignInSession session, QqqSessionCredential credential) + { + _log.Info("Sign-in accepted by {Server}; the session credential goes to the caller and is not kept here.", QqqOrigin.ShownAuthority(session.Origin)); + Settle(CompanionSignInState.SignedIn); + return credential; + } + + + + /// + /// Claims the sign-in for one operation. After it was disposed it refuses silently. While another operation is + /// running it refuses and logs that, so a request that did nothing is never silent in the log; the caller sees the + /// state of the operation that is running. + /// + private bool TryBegin(string operation) + { + if(_disposed) + { + return false; + } + if(_operating) + { + _log.Warning("{Operation} was not started: another sign-in operation is still running.", operation); + return false; + } + _operating = true; + return true; + } + + + + /// + /// Runs one claimed operation and always releases the sign-in afterwards, whatever the operation or a subscriber + /// does. The operation's token ends when the caller's does, when the session is discarded and when the sign-in is + /// disposed. An operation that ended for one of those reasons is not a failure: it is noted as debug detail and + /// null is returned. + /// + private async Task RunAsync(string operation, CompanionSignInState running, Func> body, CancellationToken cancellationToken) + where T : class + { + CancellationTokenSource? wait = null; + try + { + wait = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token, cancellationToken); + _operation = wait; + OnPropertyChanged(nameof(IsBusy)); + Settle(running); + wait.Token.ThrowIfCancellationRequested(); + return await body(wait.Token); + } + catch(Exception exception) when(_disposed || exception is OperationCanceledException && wait is { IsCancellationRequested: true }) + { + _log.Debug("{Operation} ended early because {Reason} ({Failure}).", operation, _disposed ? "the sign-in was closed" : _discarding ? "the session was discarded" : "its caller stopped waiting", exception.GetType().Name); + return null; + } + finally + { + End(wait); + } + } + + + + /// + /// Releases the sign-in after an operation. A sign-in that was disposed, or whose session was asked to be + /// discarded, while the operation ran discards the session here, now that no call is using it. An operation that + /// ended without an outcome of its own (its caller stopped waiting, or it threw something unexpected) leaves the + /// state that matches what is held. The state is settled first and the sign-in released after it, so a subscriber + /// that starts the next operation when the sign-in becomes free does not have its state overwritten, and the + /// release happens even when a subscriber throws. + /// + private void End(CancellationTokenSource? wait) + { + try + { + _operation = null; + if(_disposed || _discarding) + { + _discarding = false; + DropSession(); + Settle(CompanionSignInState.NotPrepared); + } + else if(_state is CompanionSignInState.Preparing or CompanionSignInState.SigningIn or CompanionSignInState.WaitingForBrowser) + { + Settle(_session is null ? CompanionSignInState.NotPrepared : CompanionSignInState.Ready); + } + } + finally + { + wait?.Dispose(); + _operating = false; + OnPropertyChanged(nameof(IsBusy)); + } + } + + + + /// + /// Whether a failure is one to report. A failure seen after the sign-in was disposed never is, and neither is the + /// cancellation that the operation's own token asked for. A cancellation nobody here asked for, such as the + /// server's own time limit, is a failure like any other. + /// + private bool Reportable(Exception exception, CancellationToken token) + => !_disposed && !(exception is OperationCanceledException && token.IsCancellationRequested); + + + + /// + /// Reports a step that failed. The failure is logged by type and message, with the full exception as debug + /// detail. When the session refused a certificate during the step (its last refusal is not the one known before + /// the step), the certificate is why: the state says whose it was, the server's own or the sign-in provider's, + /// and the refusal is kept for the caller to show. Any other failure settles in the given state with its reason. + /// + private void Fail(string context, CompanionSignInState state, ISignInSession? session, QqqCertificateRejection? known, Exception exception) + { + _log.Error("{Context}: {Failure}", context, QqqSessionDiagnostics.Describe(exception)); + _log.Debug("{Context} detail: {Exception}", context, exception); + if(session?.LastCertificateRejection is not { } rejection || ReferenceEquals(rejection, known)) + { + Settle(state, QqqSessionDiagnostics.Explain(exception)); + return; + } + bool own = Equals(rejection.Origin, QqqOrigin.Of(session.Origin)); + _log.Warning(own + ? "This Windows account refused the certificate presented by the server ({Presenter}; {Errors}). The service checks certificates under its own account, so it can accept one that this account does not." + : "This Windows account refused the certificate presented by the sign-in provider ({Presenter}; {Errors}).", Shown(rejection.Origin), rejection.Errors); + Settle(own ? CompanionSignInState.AccountRefusedCertificate : CompanionSignInState.ProviderCertificateRefused, rejection: rejection); + } + + + + /// Sets how things stand: the reason and the certificate first, the state last, so a subscriber that reacts to the state finds what goes with it. + private void Settle(CompanionSignInState state, string? failure = null, QqqCertificateRejection? rejection = null) + { + Failure = failure; + Rejection = rejection; + State = state; + } + + + + /// Discards the session, if any, and withdraws what it offered, so no half-finished attempt can be continued and nothing is offered that cannot work. + private void DropSession() + { + _session?.Dispose(); + _session = null; + _redirects = []; + Offer = null; + OnPropertyChanged(nameof(HasSession)); + } + + + + /// An origin as a log line names it: its host and port, which an origin holds in plain ASCII, or words when there is none. + private static string Shown(Uri? origin) => origin is null ? "none" : origin.Authority; +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs new file mode 100644 index 0000000..67cace9 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// Where a is, or how its last step ended. It moves between these values and nothing +/// else, so a wizard step can show the right thing for each and a test can assert the path taken. Whether a session +/// is held, which is what another attempt needs, is said by . +/// +public enum CompanionSignInState +{ + /// No session is held: nothing was prepared yet, or the session was discarded. + NotPrepared, + + /// The server's sign-in description is being read as the signed-in Windows user. + Preparing, + + /// The description was read and a session is held; says which methods can be used. + Ready, + + /// The description was read, and no method is one that both the service's check and this read found. No session is kept. + NothingOffered, + + /// The description names another sign-in provider than the service's check reported, so the server has to be checked again before anyone signs in. No session is kept. + ProviderChanged, + + /// This Windows account refused the certificate the server presented, which the service's check had accepted; holds the certificate and who presented it. + AccountRefusedCertificate, + + /// The description could not be read; says why. No session is kept. + PrepareFailed, + + /// A user name and password are being checked by the server. + SigningIn, + + /// A browser sign-in is running: the provider's page is open, or about to be, and its callback is awaited. + WaitingForBrowser, + + /// The server accepted the user and the session credential was returned to the caller. The session is held until it is discarded. + SignedIn, + + /// The password sign-in was not completed; gives the reason, which never says which part was wrong. The session is kept for another attempt. + PasswordFailed, + + /// The operator cancelled the browser sign-in. The session is kept for another attempt. + BrowserCanceled, + + /// The browser sign-in was given up after its time limit. The session is kept for another attempt. + BrowserTimedOut, + + /// The browser sign-in was not completed; gives the reason. The session is kept for another attempt. + BrowserFailed, + + /// This Windows account refused the certificate the sign-in provider presented; holds the certificate and who presented it. + ProviderCertificateRefused, +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ISignInSession.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ISignInSession.cs index c0dae04..21b0b0d 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/ISignInSession.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ISignInSession.cs @@ -41,4 +41,14 @@ public interface ISignInSession : IDisposable /// Returns the session credential, the only secret handed to the service; it fails when no sign-in completed. QqqSessionCredential ExportCredential(); + + + + /// + /// The certificate this session refused most recently, with the origin that presented it, or null when it has + /// refused none. The session runs as the signed-in Windows user, whose certificate store can differ from the + /// service's, and it talks to its server and to the sign-in provider that server names, so this is how a caller + /// learns that a step failed over a certificate and which of the two presented it. It is public certificate data. + /// + QqqCertificateRejection? LastCertificateRejection { get; } } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs new file mode 100644 index 0000000..2ea1d6d --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Qqq.PrintAgent.Core.Authentication; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// The identity provider's half of a sign-out. The provider is meant to be invisible, so when a server's sign-out +/// comes with the provider's own, that is opened in the browser too: staying signed in to the provider would let the +/// next sign-in skip the credential prompt. This opens the provider's page and waits for the browser to come back +/// with this sign-out's own state, through the one , so it can run while a +/// sign-in to another server waits for its callback. Ending the session in the service is the caller's part. The +/// sign-out request carries the provider's ID token hint: it goes to the browser and nowhere else, and neither it +/// nor its state is logged or kept. +/// +public sealed class ProviderSignOut +{ + /// How long the provider is given to confirm its sign-out. + public static readonly TimeSpan Limit = TimeSpan.FromMinutes(2); + + private readonly IBrowserLauncher _browser; + private readonly BrowserCallbackDispatcher _dispatcher; + private readonly IPresentationLog _log; + private readonly TimeProvider _time; + + + + /// Wires the sign-out to the browser, the one callback dispatcher and the log; the time provider drives the limit. + public ProviderSignOut(IBrowserLauncher browser, BrowserCallbackDispatcher dispatcher, IPresentationLog log, TimeProvider? time = null) + { + _browser = browser ?? throw new ArgumentNullException(nameof(browser)); + _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + _time = time ?? TimeProvider.System; + } + + + + /// + /// Opens the provider's end-session page in the default browser and waits up to two minutes for the browser to + /// return to this application's registered callback with this sign-out's own state. The state is registered + /// first, which opens the inbox, so a fast redirect is not lost. It returns whether the provider confirmed: false + /// when it did not come back in time, when the callback with this state is not on the registered address, when + /// the browser or the inbox failed, and when the caller's token ended the wait. Only the provider's host is + /// logged. + /// + public async Task CompleteAsync(QqqProviderLogout logout, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(logout); + try + { + using BrowserCallbackTicket ticket = _dispatcher.Register(logout.State); + using CancellationTokenSource limit = new(Limit, _time); + using var wait = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancellationToken); + _log.Info("Opening the identity provider's sign-out page in the default browser ({Provider}).", QqqOrigin.ShownAuthority(logout.EndSessionUri)); + BrowserLaunch.Open(_browser, logout.EndSessionUri); + Uri callback = await ticket.Callback.WaitAsync(wait.Token); + bool matched = logout.Matches(callback); + _log.Info(matched ? "Identity provider sign-out callback matched." : "Identity provider sign-out callback did not match this sign-out."); + return matched; + } + catch(Exception exception) when(exception is OperationCanceledException or IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception or InvalidOperationException or ArgumentException) + { + _log.Warning("Identity provider sign-out was not confirmed: {Failure}", QqqSessionDiagnostics.Describe(exception)); + return false; + } + } +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInOffer.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInOffer.cs new file mode 100644 index 0000000..1c7c08b --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInOffer.cs @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Windows.Management; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// The sign-in methods on offer for one server. The service checks a server under its own account and the companion +/// reads the server's sign-in description as the signed-in user; a method is offered only when both found it, so a +/// button is never shown for a method that one of the two could not use. +/// +public sealed record SignInOffer(bool Password, bool Browser) +{ + /// True when at least one method is offered. + public bool Any => Password || Browser; + + + + /// The methods the service's check found. A method name this companion does not know is ignored, as the contract asks of a client. + public static SignInOffer Checked(ServerCheckResult check) + { + ArgumentNullException.ThrowIfNull(check); + return new SignInOffer(check.SignInMethods.Contains(ServerCheckResult.Password, StringComparer.Ordinal), check.SignInMethods.Contains(ServerCheckResult.Browser, StringComparer.Ordinal)); + } + + + + /// + /// The methods a sign-in description offers, by the rule the service's check applies: a table-based server takes + /// a user name and password and nothing else, and any other server offers the browser when it publishes the native + /// session grant. Whether that grant lists this application's callback is checked when the browser sign-in starts. + /// + public static SignInOffer Read(QqqAuthenticationMetadata description) + { + ArgumentNullException.ThrowIfNull(description); + bool password = string.Equals(description.Type, "TABLE_BASED", StringComparison.Ordinal); + return new SignInOffer(password, !password && description.Values?.NativeSessionLogin is not null); + } + + + + /// The methods both this offer and another one hold. + public SignInOffer Common(SignInOffer other) + { + ArgumentNullException.ThrowIfNull(other); + return new SignInOffer(Password && other.Password, Browser && other.Browser); + } + + + + /// The offer in words, for a log line: the names the contract gives the methods, or "no method". + public override string ToString() => (Password, Browser) switch + { + (true, true) => ServerCheckResult.Password + " and " + ServerCheckResult.Browser, + (true, false) => ServerCheckResult.Password, + (false, true) => ServerCheckResult.Browser, + _ => "no method", + }; +} diff --git a/src/Qqq.PrintAgent/QqqSignInSession.cs b/src/Qqq.PrintAgent/QqqSignInSession.cs index e47e4cd..99e565d 100644 --- a/src/Qqq.PrintAgent/QqqSignInSession.cs +++ b/src/Qqq.PrintAgent/QqqSignInSession.cs @@ -58,6 +58,11 @@ internal sealed class QqqSignInSession(QqqSessionClient client) : ISignInSession + /// The certificate the session client refused most recently, with the origin that presented it; null when it refused none. + public QqqCertificateRejection? LastCertificateRejection => client.LastCertificateRejection; + + + /// Releases the session client. public void Dispose() => client.Dispose(); } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs index 3777cd1..9c425ce 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs @@ -14,7 +14,8 @@ namespace Qqq.PrintAgent.Presentation.Tests.Fakes; /// step succeeds unless a failure is set for it, can be held open until the test releases it, and records what the flow /// passed in. Disposing it behaves like the real client too: a call that is still in flight fails with "disposed" when /// it finishes, whatever else happened to it, and every later call is refused. A held call resumes on another thread, as -/// the real client's network calls do. It never touches a network. +/// the real client's network calls do. A test can also name the certificate the session refuses when a step fails, +/// which is how the real client reports that a certificate was why. It never touches a network. /// internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins certificateException) : ISignInSession { @@ -65,6 +66,11 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer + /// When set, it runs at the moment a step is about to answer with success. A test uses it to end the caller's wait at the last moment, which is how a real answer can arrive for a wait that has just ended. + internal Action? BeforeAnswer { get; set; } + + + /// When set, discovery fails with this. internal Exception? DiscoverFailure { get; set; } @@ -110,18 +116,38 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer + /// When set, a step that fails records this as the certificate the session refused, as the real client does when a certificate is why a request failed. A step that fails while this is null leaves the last refusal as it was. + internal QqqCertificateRejection? RefusedCertificate { get; set; } + + + + /// The certificate this session refused most recently; null until a step failed while was set. + public QqqCertificateRejection? LastCertificateRejection { get; private set; } + + + + /// What every browser attempt's state begins with, followed by the attempt's number. Two sessions that sign in at the same time are given different stems, as two real sessions have different random states. + internal string StateStem { get; set; } = "secret-state-"; + + + /// The host and port of the provider page, as the server's provider wrote them; a test sets a name outside ASCII to see how it is shown. internal string ProviderAuthority { get; set; } = "id.example.com"; + /// When set, beginning a browser sign-in returns this address in place of the provider page with the attempt's state, as a session that prepared an unusable address would. + internal Uri? AuthorizationOverride { get; set; } + + + /// The provider page of the latest browser attempt; its query stands for that attempt's secret state. - internal Uri Authorization => new("https://" + ProviderAuthority + "/authorize?state=secret-state-" + _attempts); + internal Uri Authorization => AuthorizationOverride ?? new("https://" + ProviderAuthority + "/authorize?state=" + StateStem + _attempts); /// The callback the provider would send the browser to for the latest attempt, carrying that attempt's state and a one-time code. - internal Uri CallbackForLatestAttempt => new(SignInFixture.Callback + "?code=one-time-code&state=secret-state-" + _attempts); + internal Uri CallbackForLatestAttempt => new(SignInFixture.Callback + "?code=one-time-code&state=" + StateStem + _attempts); @@ -133,9 +159,11 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer { if(DiscoverFailure is not null) { - throw DiscoverFailure; + throw Refusing(DiscoverFailure); } - return PendingDiscovery is null ? Metadata : await PendingDiscovery.Task.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + QqqAuthenticationMetadata metadata = PendingDiscovery is null ? Metadata : await PendingDiscovery.Task.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + BeforeAnswer?.Invoke(); + return metadata; } finally { @@ -154,13 +182,14 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer { if(PasswordFailure is not null) { - throw PasswordFailure; + throw Refusing(PasswordFailure); } if(PendingPassword is not null) { await PendingPassword.Task.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.ForceYielding); } _signedIn = true; + BeforeAnswer?.Invoke(); } finally { @@ -179,7 +208,7 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer { if(BeginFailure is not null) { - throw BeginFailure; + throw Refusing(BeginFailure); } if(PendingBegin is not null) { @@ -187,6 +216,7 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer } _attempts++; _attemptOpen = true; + BeforeAnswer?.Invoke(); return Authorization; } finally @@ -212,9 +242,9 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer _attemptOpen = false; if(CompleteFailure is not null) { - throw CompleteFailure; + throw Refusing(CompleteFailure); } - if(!callback.Query.EndsWith("state=secret-state-" + _attempts, StringComparison.Ordinal)) + if(!callback.Query.EndsWith("state=" + StateStem + _attempts, StringComparison.Ordinal)) { throw new QqqSessionException(QqqSessionException.FailureKind.InvalidResponse, "The callback does not belong to this sign-in attempt."); } @@ -223,6 +253,7 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer await PendingComplete.Task.WaitAsync(cancellationToken).ConfigureAwait(ConfigureAwaitOptions.ForceYielding); } _signedIn = true; + BeforeAnswer?.Invoke(); } finally { @@ -245,6 +276,15 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer + /// Records the certificate a failing step refused, when the test named one, and returns the failure to throw. + private Exception Refusing(Exception failure) + { + LastCertificateRejection = RefusedCertificate ?? LastCertificateRejection; + return failure; + } + + + /// Marks the session discarded. From then on a call in flight fails as it finishes and a new call is refused, which is what disposing the real client under a running call does. public void Dispose() => Disposed = true; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs new file mode 100644 index 0000000..682eae1 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Windows.Management; + +namespace Qqq.PrintAgent.Presentation.Tests.Fakes; + +/// +/// Everything a companion sign-in touches, as hand-written fakes around the one real callback dispatcher: scripted +/// sessions, a browser that only records what it was asked to open, callback inboxes a test delivers to by hand, a +/// manual clock and a recording log. Any number of sign-ins and provider sign-outs can be built over one world, which +/// is how a test puts two of them on the one inbox at the same time. Each session gets its own state stem, as two +/// real sessions have different random states. Every value in it is synthetic. +/// +internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBrowserCallbackSource +{ + /// The address tests use for the first server. + internal const string Server = "https://print.example.com"; + + /// The address tests use for a second server. + internal const string OtherServer = "https://labels.example.net"; + + /// The origin of the sign-in provider the fake sessions send the browser to. + internal const string Provider = "https://id.example.com"; + + /// The callback the fake installation has registered. + internal const string Callback = "io.qrun.qqq-print-agent:/oauth/callback"; + + private volatile TaskCompletionSource? _awaitedInbox; + + + + /// Builds the world with its dispatcher over the fake inboxes. + internal SignInWorld() + { + Dispatcher = new BrowserCallbackDispatcher(this, Log); + } + + + + /// The one dispatcher every sign-in and sign-out of this world shares. + internal BrowserCallbackDispatcher Dispatcher { get; } + + + + /// Everything that was logged. + internal RecordingLog Log { get; } = new(); + + + + /// The clock that drives the time limits. + internal ManualTime Time { get; } = new(); + + + + /// Every session that was created, oldest first. + internal List Sessions { get; } = []; + + + + /// Applied to each new session before it is used, to script what the server offers or how it fails. + internal Action? ConfigureSession { get; set; } + + + + /// When set, creating a session fails with this, as the real client does for an address it refuses. + internal Exception? CreateFailure { get; set; } + + + + /// Every address the browser was asked to open. + internal List Opened { get; } = []; + + + + /// How many inboxes were open and waiting each time the browser was asked to open an address, which shows that the inbox was open first. + internal List ListeningAtLaunch { get; } = []; + + + + /// When set, opening the browser fails with this. + internal Exception? BrowserFailure { get; set; } + + + + /// Every inbox that was opened, oldest first. + internal List Inboxes { get; } = []; + + + + /// When set, opening an inbox fails with this. + internal Exception? InboxFailure { get; set; } + + + + /// The protocol handler trace; empty means the browser never launched the handler. + internal List Trace { get; } = []; + + + + /// The window each read of the trace asked for. + internal List TraceWindows { get; } = []; + + + + /// The registered callback. + public string RedirectUri => Callback; + + + + /// Where the fake protocol handler writes its trace. + public string TracePath => "trace/auth-callback.log"; + + + + /// What the service's check reports for a server that takes a user name and password: that method, and no sign-in provider. + internal static ServerCheckResult PasswordCheck { get; } = new([], [ServerCheckResult.Password]); + + + + /// What the service's check reports for a server that signs in through the browser at the fake provider. + internal static ServerCheckResult BrowserCheck { get; } = new([], [ServerCheckResult.Browser], Provider + "/"); + + + + /// A sign-in description for a server that signs in through the browser: the native grant with the given issuer and redirect addresses. + internal static QqqAuthenticationMetadata BrowserDescription(string issuer = Provider, params string[] redirects) => new() + { + Type = "OAUTH2", + Values = new QqqAuthenticationMetadata.ProviderValues { NativeSessionLogin = new QqqAuthenticationMetadata.NativeGrant { Issuer = issuer, RedirectUris = redirects.Length == 0 ? [Callback] : redirects } }, + }; + + + + /// A certificate refusal as the session client records one: an untrusted authority, presented by the given origin. + internal static QqqCertificateRejection Refusal(string origin) => new(System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors, "CN=synthetic.example", "CN=Synthetic Test Authority", + new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), new DateTime(2027, 1, 1, 0, 0, 0, DateTimeKind.Utc), "00112233445566778899AABBCCDDEEFF00112233", new Uri(origin), new DateTimeOffset(2026, 11, 10, 10, 0, 0, TimeSpan.Zero)); + + + + /// A new sign-in over this world. + internal CompanionSignIn NewSignIn() => new(this, this, this, Dispatcher, Log, Time); + + + + /// A new sign-in that has read a password server's description and holds its session, with the log cleared so a test asserts only what its own step wrote. + internal async Task PasswordReadyAsync() + { + CompanionSignIn signIn = NewSignIn(); + Assert.NotNull(await signIn.PrepareAsync(new Uri(Server), PasswordCheck, QqqCertificateExceptionOrigins.None)); + Log.Entries.Clear(); + return signIn; + } + + + + /// A new sign-in that has read a browser server's description and holds its session, with the log cleared. Each call creates the next session, so two calls give two sign-ins with different states. + internal async Task BrowserReadyAsync(string server = Server) + { + ConfigureSession ??= static session => session.Metadata = BrowserDescription(); + CompanionSignIn signIn = NewSignIn(); + Assert.NotNull(await signIn.PrepareAsync(new Uri(server), BrowserCheck, QqqCertificateExceptionOrigins.None)); + Log.Entries.Clear(); + return signIn; + } + + + + /// Records what a sign-in announces from now on, as "Property=value" in order, which is what a view would have been told. + internal static List Watch(CompanionSignIn signIn) + { + List changes = []; + signIn.PropertyChanged += (_, change) => changes.Add(change.PropertyName + "=" + (change.PropertyName switch + { + nameof(CompanionSignIn.State) => signIn.State.ToString(), + nameof(CompanionSignIn.IsBusy) => signIn.IsBusy.ToString(), + nameof(CompanionSignIn.HasSession) => signIn.HasSession.ToString(), + nameof(CompanionSignIn.Offer) => signIn.Offer?.ToString() ?? "null", + nameof(CompanionSignIn.Failure) => signIn.Failure ?? "null", + _ => signIn.Rejection is null ? "null" : "set", + })); + return changes; + } + + + + /// + /// Awaits something that has to end by itself and fails the test, instead of hanging the run, when it does not. The + /// limit is real time, but it only ever runs out when the code under test is broken; a passing test never waits for it. + /// + internal static async Task EndsAsync(Task operation) => await operation.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + + + + /// + /// Completes with the next inbox that is opened, once the dispatcher has started waiting on it. The dispatcher + /// opens the inbox after a callback on another thread's schedule, so a test uses this to hold its next callback + /// until the new inbox is really open, without sleeping. It must be called before that inbox is opened. + /// + internal async Task NextInboxAsync() + { + _awaitedInbox = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + FakeInbox inbox = await _awaitedInbox.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + await inbox.Listening.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false); + return inbox; + } + + + + /// Creates a scripted session with its own state stem, or fails. + public ISignInSession Create(Uri origin, QqqCertificateExceptionOrigins certificateException) + { + if(CreateFailure is not null) + { + throw CreateFailure; + } + FakeSession session = new(origin, certificateException) { StateStem = "synthetic-state-" + (char)('a' + Sessions.Count) + "-" }; + ConfigureSession?.Invoke(session); + Sessions.Add(session); + return session; + } + + + + /// Records the address instead of opening a browser, or fails. + public void Open(Uri address) + { + if(BrowserFailure is not null) + { + throw BrowserFailure; + } + ListeningAtLaunch.Add(Inboxes.Count(inbox => inbox.Waiting && !inbox.Disposed)); + Opened.Add(address); + } + + + + /// Opens a new inbox the test can deliver to, or fails. + IBrowserCallbackInbox IBrowserCallbackSource.Open() + { + if(InboxFailure is not null) + { + throw InboxFailure; + } + FakeInbox inbox = new(); + Inboxes.Add(inbox); + _awaitedInbox?.TrySetResult(inbox); + return inbox; + } + + + + /// Returns the scripted trace and records the window that was asked for. + public IReadOnlyList RecentTrace(TimeSpan window) + { + TraceWindows.Add(window); + return Trace; + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs new file mode 100644 index 0000000..2b65284 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Presentation.Tests.Fakes; + +namespace Qqq.PrintAgent.Presentation.Tests.SignIn; + +/// +/// The one callback inbox shared by every browser exchange: who gets which callback, what is dropped, when an inbox is +/// open, and what happens when it fails. The dispatcher is the only concurrent piece of the sign-in, so each test +/// decides the order of events itself: a callback is delivered by hand, and the next one is held until the inbox it +/// goes to is known to be open. +/// +public sealed class BrowserCallbackDispatcherTests +{ + private const string Dropped = "WARN A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged."; + private const string InboxOpen = "INFO Browser callback inbox open."; + + + + /// A callback on the registered address carrying the given state and a one-time code, as a provider sends it. + private static Uri CallbackFor(string state) => new(SignInWorld.Callback + "?code=synthetic-code&state=" + state); + + + + /// + /// Two servers sign in through the browser at the same time. Both wait on the one inbox, which was open before + /// either browser page was. The second sign-in's callback arrives first and completes the second sign-in only; the + /// inbox is closed and a new one opened for the first, whose callback then completes it. Each session was handed + /// its own callback, and nothing of either reached the log. + /// + [Fact] + public async Task Dispatcher_TwoSignIns_EachGetsItsOwnCallback() + { + SignInWorld world = new(); + using CompanionSignIn first = await world.BrowserReadyAsync(); + using CompanionSignIn second = await world.BrowserReadyAsync(SignInWorld.OtherServer); + FakeSession firstSession = world.Sessions[0]; + FakeSession secondSession = world.Sessions[1]; + + Task firstRunning = first.SignInWithBrowserAsync(); + Task secondRunning = second.SignInWithBrowserAsync(); + FakeInbox inbox = Assert.Single(world.Inboxes); + Assert.Equal([1, 1], world.ListeningAtLaunch); + Assert.Equal([firstSession.Authorization, secondSession.Authorization], world.Opened); + Assert.NotEqual(firstSession.Authorization, secondSession.Authorization); + Task reopened = world.NextInboxAsync(); + inbox.Deliver(secondSession.CallbackForLatestAttempt); + QqqSessionCredential? secondCredential = await SignInWorld.EndsAsync(secondRunning); + FakeInbox next = await reopened; + + Assert.Equal(new Uri(SignInWorld.OtherServer), secondCredential?.Origin); + Assert.Equal(CompanionSignInState.SignedIn, second.State); + Assert.False(firstRunning.IsCompleted); + Assert.Equal(CompanionSignInState.WaitingForBrowser, first.State); + Assert.Null(firstSession.Callback); + Assert.True(inbox.Disposed); + Assert.False(next.Disposed); + + next.Deliver(firstSession.CallbackForLatestAttempt); + QqqSessionCredential? firstCredential = await SignInWorld.EndsAsync(firstRunning); + + Assert.Equal(new Uri(SignInWorld.Server), firstCredential?.Origin); + Assert.Equal(CompanionSignInState.SignedIn, first.State); + Assert.Equal(firstSession.CallbackForLatestAttempt, firstSession.Callback); + Assert.Equal(secondSession.CallbackForLatestAttempt, secondSession.Callback); + Assert.True(next.Disposed); + Assert.Equal(2, world.Inboxes.Count); + Assert.DoesNotContain(Dropped, world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic-state", StringComparison.Ordinal) || entry.Contains("one-time-code", StringComparison.Ordinal) || entry.Contains("synthetic-session-token", StringComparison.Ordinal)); + } + + + + /// + /// One of two sign-ins is cancelled, and its browser page comes back afterwards. That late callback belongs to + /// nobody: it is dropped, the log says only that one was dropped, the session that started it never sees it, and + /// the other sign-in is neither completed nor failed by it. The other sign-in's own callback, held until the new + /// inbox is open, then completes it. + /// + [Fact] + public async Task Dispatcher_LateCallbackForAnEndedSignIn_IsDropped_TheOtherCompletes() + { + SignInWorld world = new(); + using CompanionSignIn ended = await world.BrowserReadyAsync(); + using CompanionSignIn other = await world.BrowserReadyAsync(SignInWorld.OtherServer); + FakeSession endedSession = world.Sessions[0]; + FakeSession otherSession = world.Sessions[1]; + Task endedRunning = ended.SignInWithBrowserAsync(); + Task otherRunning = other.SignInWithBrowserAsync(); + FakeInbox inbox = Assert.Single(world.Inboxes); + ended.CancelBrowserSignIn(); + Assert.Null(await SignInWorld.EndsAsync(endedRunning)); + Assert.False(inbox.Disposed); + world.Log.Entries.Clear(); + + Task reopened = world.NextInboxAsync(); + inbox.Deliver(endedSession.CallbackForLatestAttempt); + FakeInbox next = await reopened; + + Assert.Equal([Dropped, InboxOpen], world.Log.Entries); + Assert.Null(endedSession.Callback); + Assert.Equal(CompanionSignInState.BrowserCanceled, ended.State); + Assert.False(otherRunning.IsCompleted); + Assert.Equal(CompanionSignInState.WaitingForBrowser, other.State); + Assert.True(inbox.Disposed); + + next.Deliver(otherSession.CallbackForLatestAttempt); + QqqSessionCredential? credential = await SignInWorld.EndsAsync(otherRunning); + + Assert.Equal(new Uri(SignInWorld.OtherServer), credential?.Origin); + Assert.Equal(otherSession.CallbackForLatestAttempt, otherSession.Callback); + Assert.True(next.Disposed); + Assert.Equal(2, world.Inboxes.Count); + Assert.Single(world.Log.Entries, entry => string.Equals(entry, Dropped, StringComparison.Ordinal)); + } + + + + /// + /// A callback that cannot be given to anyone is dropped: one with no state, with the state twice, with an empty + /// state, with a parameter whose name only looks like "state", or with a state nobody waits for. The ticket that + /// waits is untouched, a new inbox is opened for it, and the log holds the fixed sentence and nothing of the + /// callback. The ticket's own callback, sent to the new inbox, still reaches it. + /// + [Theory] + [InlineData("?code=synthetic-code")] + [InlineData("?state=synthetic-state-x&state=synthetic-state-x")] + [InlineData("?code=synthetic-code&state=")] + [InlineData("?STATE=synthetic-state-x")] + [InlineData("?state")] + [InlineData("?state=synthetic-state-unknown&code=synthetic-code")] + public async Task Dispatcher_CallbackWithNoStateOrTwo_IsDropped_AndNotLogged(string query) + { + SignInWorld world = new(); + using BrowserCallbackTicket ticket = world.Dispatcher.Register("synthetic-state-x"); + FakeInbox inbox = Assert.Single(world.Inboxes); + + Task reopened = world.NextInboxAsync(); + inbox.Deliver(new Uri(SignInWorld.Callback + query)); + FakeInbox next = await reopened; + + Assert.False(ticket.Callback.IsCompleted); + Assert.True(inbox.Disposed); + Assert.False(next.Disposed); + Assert.Equal([InboxOpen, Dropped, InboxOpen], world.Log.Entries); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic", StringComparison.Ordinal) || entry.Contains("oauth", StringComparison.OrdinalIgnoreCase)); + + next.Deliver(CallbackFor("synthetic-state-x")); + + Assert.Equal(CallbackFor("synthetic-state-x"), await SignInWorld.EndsAsync(ticket.Callback)); + Assert.True(next.Disposed); + Assert.Equal(2, world.Inboxes.Count); + } + + + + /// + /// No inbox exists until something waits. The first ticket opens one and the dispatcher is waiting on it when the + /// registration returns; a second ticket shares it; it stays open while either waits and is closed with the last, + /// without that being logged as a failure. A ticket that ended can be disposed again, and that does not take away + /// a later ticket that waits under the same state. The next registration opens a new inbox. The test runs without + /// a synchronization context, as the dispatcher's own threads do: closing an inbox then ends the dispatcher's wait + /// on it inside the very call that closes it, which is the order of events the closing has to get right. + /// + [Fact] + public void Dispatcher_InboxOpensWithTheFirstTicket_ClosesWithTheLast() + { + using NoContext none = new(); + SignInWorld world = new(); + Assert.Empty(world.Inboxes); + + BrowserCallbackTicket first = world.Dispatcher.Register("synthetic-state-a"); + FakeInbox inbox = Assert.Single(world.Inboxes); + Assert.True(inbox.Waiting); + BrowserCallbackTicket second = world.Dispatcher.Register("synthetic-state-b"); + Assert.Single(world.Inboxes); + + first.Dispose(); + Assert.False(inbox.Disposed); + Assert.True(first.Callback.IsCanceled); + Assert.False(second.Callback.IsCompleted); + second.Dispose(); + Assert.True(inbox.Disposed); + Assert.True(second.Callback.IsCanceled); + Assert.Equal([InboxOpen], world.Log.Entries); + + BrowserCallbackTicket later = world.Dispatcher.Register("synthetic-state-a"); + Assert.Equal(2, world.Inboxes.Count); + Assert.True(world.Inboxes[1].Waiting); + first.Dispose(); + Assert.False(world.Inboxes[1].Disposed); + Assert.False(later.Callback.IsCompleted); + later.Dispose(); + Assert.True(world.Inboxes[1].Disposed); + Assert.Equal([InboxOpen, InboxOpen], world.Log.Entries); + } + + + + /// + /// The inbox breaks while two exchanges wait. Both waits fail with that failure, once: the log has one line for + /// it, which names the kind of failure and how many it ended and nothing of the failure's own text, and the broken + /// inbox is closed. The failed tickets are no longer registered, so disposing them changes nothing. The next + /// registration opens a new inbox, which works. + /// + [Fact] + public async Task Dispatcher_InboxFails_EveryWaiterFailsOnce_TheNextOpensANewOne() + { + SignInWorld world = new(); + using BrowserCallbackTicket first = world.Dispatcher.Register("synthetic-state-a"); + using BrowserCallbackTicket second = world.Dispatcher.Register("synthetic-state-b"); + FakeInbox inbox = Assert.Single(world.Inboxes); + IOException failure = new("synthetic pipe failure"); + + inbox.Fail(failure); + + Assert.Same(failure, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(first.Callback))); + Assert.Same(failure, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(second.Callback))); + Assert.True(inbox.Disposed); + Assert.Equal([InboxOpen, "ERROR The browser callback inbox failed (IOException); 2 waiting browser exchange(s) were ended and have to be started again."], world.Log.Entries); + + first.Dispose(); + second.Dispose(); + Assert.Single(world.Inboxes); + using BrowserCallbackTicket next = world.Dispatcher.Register("synthetic-state-a"); + Assert.Equal(2, world.Inboxes.Count); + Assert.False(next.Callback.IsCompleted); + world.Inboxes[1].Deliver(CallbackFor("synthetic-state-a")); + + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(next.Callback)); + Assert.Single(world.Log.Entries, entry => entry.StartsWith("ERROR", StringComparison.Ordinal)); + } + + + + /// When the inbox cannot be opened for the first ticket, the failure goes to whoever registered and nothing is left registered: the same state can be registered again once the inbox can be opened. + [Fact] + public async Task InboxThatCannotBeOpened_FailsTheRegistration_AndLeavesNothingBehind() + { + SignInWorld world = new() { InboxFailure = new UnauthorizedAccessException("synthetic open failure") }; + + Assert.Same(world.InboxFailure, Assert.Throws(() => world.Dispatcher.Register("synthetic-state-a"))); + Assert.Empty(world.Inboxes); + Assert.Empty(world.Log.Entries); + + world.InboxFailure = null; + using BrowserCallbackTicket ticket = world.Dispatcher.Register("synthetic-state-a"); + Assert.Single(world.Inboxes).Deliver(CallbackFor("synthetic-state-a")); + + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(ticket.Callback)); + } + + + + /// + /// After a callback the inbox has to be opened again for the tickets that still wait. When that fails, the callback + /// that did arrive still completes its own ticket, and the ticket left waiting fails with the failure, because + /// nothing could reach it any more. The next registration tries a new inbox. + /// + [Fact] + public async Task InboxThatCannotBeReopened_CompletesTheCallbackItHas_AndFailsWhoStillWaits() + { + SignInWorld world = new(); + using BrowserCallbackTicket served = world.Dispatcher.Register("synthetic-state-a"); + using BrowserCallbackTicket stranded = world.Dispatcher.Register("synthetic-state-b"); + UnauthorizedAccessException failure = new("synthetic open failure"); + world.InboxFailure = failure; + + world.Inboxes[0].Deliver(CallbackFor("synthetic-state-a")); + + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(served.Callback)); + Assert.Same(failure, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(stranded.Callback))); + Assert.True(world.Inboxes[0].Disposed); + Assert.Equal([InboxOpen, "ERROR The browser callback inbox failed (UnauthorizedAccessException); 1 waiting browser exchange(s) were ended and have to be started again."], world.Log.Entries); + + world.InboxFailure = null; + using BrowserCallbackTicket next = world.Dispatcher.Register("synthetic-state-b"); + Assert.Equal(2, world.Inboxes.Count); + Assert.False(next.Callback.IsCompleted); + } + + + + /// + /// A callback, or a failure, can come out of an inbox at the very moment its last ticket ends and the inbox is + /// closed. The inboxes here ignore being closed and answer when told to, which is that moment made certain, and by + /// then another exchange has registered and a new inbox is open. The late callback is dropped like any other that + /// reached nobody, even though it carries the state that now waits, and the late failure is not reported at all, + /// because the closing caused it. Either way the exchange that waits on the new inbox is untouched, and its own + /// callback completes it. The test runs without a synchronization context, as the dispatcher's own threads do, so + /// the dispatcher deals with each answer inside the call that gives it and the test reads the result straight after. + /// + [Theory] + [InlineData(true, new[] { InboxOpen, InboxOpen, Dropped })] + [InlineData(false, new[] { InboxOpen, InboxOpen })] + public void AnswerFromAnInboxThatWasClosedMeanwhile_DoesNotTouchTheNextExchange(bool callback, string[] entries) + { + using NoContext none = new(); + RecordingLog log = new(); + LateInboxes source = new(); + BrowserCallbackDispatcher dispatcher = new(source, log); + BrowserCallbackTicket ended = dispatcher.Register("synthetic-state-a"); + ended.Dispose(); + Assert.True(source.Inboxes[0].Disposed); + using BrowserCallbackTicket waiting = dispatcher.Register("synthetic-state-a"); + + if(callback) + { + source.Inboxes[0].Answer.SetResult(CallbackFor("synthetic-state-a")); + } + else + { + source.Inboxes[0].Answer.SetException(new IOException("synthetic pipe failure")); + } + + Assert.Equal(entries, log.Entries, StringComparer.Ordinal); + Assert.True(ended.Callback.IsCanceled); + Assert.False(waiting.Callback.IsCompleted); + Assert.Equal(2, source.Inboxes.Count); + Assert.False(source.Inboxes[1].Disposed); + + source.Inboxes[1].Answer.SetResult(CallbackFor("synthetic-state-a")); + + Assert.True(waiting.Callback.IsCompletedSuccessfully); + Assert.True(source.Inboxes[1].Disposed); + Assert.Equal(2, source.Inboxes.Count); + } + + + + /// + /// Two exchanges cannot wait under one state, because a callback could not be told to belong to one of them. The + /// second registration is refused without naming the state, and the first is left as it was. A state of nothing is + /// refused before anything is opened. + /// + [Fact] + public async Task StateThatIsAlreadyWaiting_OrEmpty_IsRefused() + { + SignInWorld world = new(); + Assert.Throws(() => world.Dispatcher.Register("")); + Assert.Empty(world.Inboxes); + using BrowserCallbackTicket ticket = world.Dispatcher.Register("synthetic-state-a"); + + InvalidOperationException refused = Assert.Throws(() => world.Dispatcher.Register("synthetic-state-a")); + + Assert.Equal("A browser exchange with the same state is already waiting for its callback.", refused.Message); + Assert.Single(world.Inboxes).Deliver(CallbackFor("synthetic-state-a")); + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(ticket.Callback)); + } + + + + /// + /// The state of an address is its one "state" parameter, decoded: found wherever it stands in the query, with a + /// plus sign and a percent escape read as the provider wrote them. There is none when the parameter is missing, + /// empty, repeated or named differently, when the address has no query, and when it is not an absolute address. + /// + [Theory] + [InlineData("https://id.example.com/authorize?client_id=synthetic&state=synthetic-state-a&nonce=synthetic", "synthetic-state-a")] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic%2Dstate+a", "synthetic-state a")] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic=state", "synthetic=state")] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=a&state=b", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?mystate=synthetic", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback", null)] + [InlineData("/oauth/callback?state=synthetic-state-a", null)] + public void ReadState_IsTheOneStateParameter(string address, string? state) + { + Assert.Equal(state, BrowserCallbackDispatcher.ReadState(new Uri(address, UriKind.RelativeOrAbsolute))); + } + + + + /// The dispatcher cannot work without a place callbacks arrive and a log, and says which is missing. + [Fact] + public void MissingCollaborator_IsRefused() + { + SignInWorld world = new(); + + Assert.Equal("callbacks", Assert.Throws(() => new BrowserCallbackDispatcher(null!, world.Log)).ParamName); + Assert.Equal("log", Assert.Throws(() => new BrowserCallbackDispatcher(world, null!)).ParamName); + } + + + + /// Removes the test runner's synchronization context from the calling thread until it is disposed. With a context present, .NET never continues an awaiting method inside the call that completes what it awaits; without one it does, which is what happens on the thread-pool threads the dispatcher works on. + private sealed class NoContext : IDisposable + { + private readonly SynchronizationContext? _before = SynchronizationContext.Current; + + + + /// Removes the context. + internal NoContext() => SynchronizationContext.SetSynchronizationContext(null); + + + + /// Puts the context back. + public void Dispose() => SynchronizationContext.SetSynchronizationContext(_before); + } + + + + /// A callback source whose inboxes do not notice being closed and answer when the test says so, on the test's own thread. + private sealed class LateInboxes : IBrowserCallbackSource + { + /// Every inbox that was opened, oldest first. + internal List Inboxes { get; } = []; + + + + /// The registered callback. + public string RedirectUri => SignInWorld.Callback; + + + + /// Not read by the dispatcher. + public string TracePath => "trace/auth-callback.log"; + + + + /// Opens a new inbox. + public IBrowserCallbackInbox Open() + { + LateInbox inbox = new(); + Inboxes.Add(inbox); + return inbox; + } + + + + /// Not read by the dispatcher. + public IReadOnlyList RecentTrace(TimeSpan window) => []; + } + + + + /// An inbox whose wait ends only when the test completes , whatever happens to the token or the inbox meanwhile. The wait's continuation runs inside that completion, so the test continues after the dispatcher has dealt with the answer. + private sealed class LateInbox : IBrowserCallbackInbox + { + /// What the wait ends with; completing it runs the dispatcher's handling at once. + internal TaskCompletionSource Answer { get; } = new(); + + + + /// True once the dispatcher closed the inbox. + internal bool Disposed { get; private set; } + + + + /// Waits for the answer and ignores the token. + public Task ReceiveAsync(CancellationToken cancellationToken) => Answer.Task; + + + + /// Marks the inbox closed. + public void Dispose() => Disposed = true; + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs new file mode 100644 index 0000000..858055f --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Presentation.Tests.Fakes; + +namespace Qqq.PrintAgent.Presentation.Tests.SignIn; + +/// The companion's browser sign-in: the exchange through the default browser and the one callback dispatcher, its time limit and cancellation, what is reported when it does not complete, and the thread everything is announced on. +public sealed class CompanionSignInBrowserTests +{ + private const string Requested = "INFO Browser sign-in requested for print.example.com; this application's callback is io.qrun.qqq-print-agent:/oauth/callback."; + private const string NeverLaunched = "WARN The browser never launched the sign-in protocol handler in the last 10 minutes (no entries in trace/auth-callback.log). Either the identity provider did not redirect to io.qrun.qqq-print-agent:/oauth/callback (check the provider's allowed redirect URIs and any error page it showed), or the browser blocked opening the QQQ Print Agent sign-in link."; + + + + /// True when an entry holds something that must never be logged: a sign-in state, a one-time code or a session token. + private static bool Secret(string entry) + => entry.Contains("synthetic-state", StringComparison.Ordinal) || entry.Contains("one-time-code", StringComparison.Ordinal) || entry.Contains("synthetic-session-token", StringComparison.Ordinal); + + + + /// + /// The exchange begins the sign-in on the session with this application's registered callback, has an inbox open + /// before the provider's page is opened, waits under a three minute limit, completes the sign-in with the callback + /// that carries this attempt's state, closes the inbox and returns the credential. The session stays. Only the + /// provider's host is logged: no state, no code and no token. + /// + [Fact] + public async Task Browser_CompletedExchange_ReturnsTheCredential_AndLogsNoSecrets() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + List changes = SignInWorld.Watch(signIn); + + Task running = signIn.SignInWithBrowserAsync(); + Assert.Equal(CompanionSignInState.WaitingForBrowser, signIn.State); + Assert.True(signIn.IsBusy); + FakeInbox inbox = Assert.Single(world.Inboxes); + Assert.True(inbox.Waiting); + Assert.Equal([1], world.ListeningAtLaunch); + Assert.Equal(session.Authorization, Assert.Single(world.Opened)); + Assert.Equal(new Uri(SignInWorld.Callback), session.Redirect); + inbox.Deliver(session.CallbackForLatestAttempt); + QqqSessionCredential? credential = await SignInWorld.EndsAsync(running); + + Assert.Equal(new Uri(SignInWorld.Server), credential?.Origin); + Assert.Equal("synthetic-session-token", credential?.SessionToken); + Assert.Equal(session.CallbackForLatestAttempt, session.Callback); + Assert.True(inbox.Disposed); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(session.Disposed); + Assert.Equal(["IsBusy=True", "State=WaitingForBrowser", "State=SignedIn", "IsBusy=False"], changes); + Assert.Equal(TimeSpan.FromMinutes(3), Assert.Single(world.Time.RequestedDelays)); + Assert.Equal(TimeSpan.FromMinutes(3), CompanionSignIn.BrowserSignInLimit); + Assert.Equal([Requested, + "INFO Browser callback inbox open.", + "INFO Opening the identity provider's sign-in page in the default browser (id.example.com).", + "INFO Browser callback received; completing the sign-in.", + "INFO Sign-in accepted by print.example.com; the session credential goes to the caller and is not kept here."], world.Log.Entries); + Assert.DoesNotContain(world.Log.Entries, Secret); + } + + + + /// The provider's page is at an address the server's provider wrote. The log names its host by the ASCII name the browser will really go to, so a look-alike letter reads as the "xn--" name, and the browser is given the address exactly as the session returned it. + [Fact] + public async Task Browser_ProviderPageWithALookAlikeHost_IsLoggedByItsAsciiName() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + world.Sessions[0].ProviderAuthority = "l\u043Egin.example.com:9443"; + + Task running = signIn.SignInWithBrowserAsync(); + world.Inboxes[0].Deliver(world.Sessions[0].CallbackForLatestAttempt); + + Assert.NotNull(await SignInWorld.EndsAsync(running)); + Assert.Equal(new Uri("https://l\u043Egin.example.com:9443/authorize?state=synthetic-state-a-1"), Assert.Single(world.Opened)); + Assert.Contains("INFO Opening the identity provider's sign-in page in the default browser (xn--lgin-55d.example.com:9443).", world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains('\u043E', StringComparison.Ordinal) || Secret(entry)); + } + + + + /// + /// A browser sign-in waits, with the inbox open, until the operator cancels it or three minutes pass, and not a + /// second less. Either ending is said to be exactly what it was, the inbox is closed, and the session and its + /// offer stay for another attempt. Cancel has no effect once the exchange has ended. The next attempt on the same + /// session works. + /// + [Theory] + [InlineData(false, CompanionSignInState.BrowserCanceled, "INFO Browser sign-in to print.example.com was cancelled by the operator.")] + [InlineData(true, CompanionSignInState.BrowserTimedOut, "INFO Browser sign-in to print.example.com was given up after the three minute limit.")] + public async Task Browser_WaitsCanBeCancelledAndGivesUpAfterThreeMinutes(bool byLimit, CompanionSignInState ending, string entry) + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + + Task running = signIn.SignInWithBrowserAsync(); + Assert.Equal(CompanionSignInState.WaitingForBrowser, signIn.State); + Assert.True(world.Inboxes[0].Waiting); + world.Time.Advance(TimeSpan.FromMinutes(3) - TimeSpan.FromSeconds(1)); + Assert.False(running.IsCompleted); + Assert.Equal(CompanionSignInState.WaitingForBrowser, signIn.State); + if(byLimit) + { + world.Time.Advance(TimeSpan.FromSeconds(1)); + } + else + { + signIn.CancelBrowserSignIn(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(ending, signIn.State); + Assert.Null(signIn.Failure); + Assert.Null(signIn.Rejection); + Assert.True(signIn.HasSession); + Assert.Equal(new SignInOffer(false, true), signIn.Offer); + Assert.False(session.Disposed); + Assert.Null(session.Callback); + Assert.True(world.Inboxes[0].Disposed); + Assert.False(signIn.IsBusy); + string[] last = [.. world.Log.Entries.TakeLast(2)]; + Assert.Equal([entry, NeverLaunched], last); + Assert.DoesNotContain(world.Log.Entries, line => line.StartsWith("ERROR", StringComparison.Ordinal) || Secret(line)); + + signIn.CancelBrowserSignIn(); + running = signIn.SignInWithBrowserAsync(); + world.Inboxes[1].Deliver(session.CallbackForLatestAttempt); + + Assert.NotNull(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + } + + + + /// + /// An abandoned attempt leaves a browser page behind, and that page can still come back. Its callback carries the + /// abandoned attempt's state, which nobody waits for: it is dropped while the next attempt on the same session + /// waits, and that attempt is completed by its own callback, the only one the session is ever given. + /// + [Fact] + public async Task Browser_AbandonedAttemptsCallback_IsDroppedWhileTheNextAttemptWaits() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + Task abandoned = signIn.SignInWithBrowserAsync(); + Uri late = session.CallbackForLatestAttempt; + signIn.CancelBrowserSignIn(); + Assert.Null(await SignInWorld.EndsAsync(abandoned)); + + Task running = signIn.SignInWithBrowserAsync(); + Task reopened = world.NextInboxAsync(); + world.Inboxes[1].Deliver(late); + FakeInbox next = await reopened; + Assert.False(running.IsCompleted); + Assert.Null(session.Callback); + Assert.NotEqual(late, session.CallbackForLatestAttempt); + next.Deliver(session.CallbackForLatestAttempt); + + Assert.NotNull(await SignInWorld.EndsAsync(running)); + Assert.Equal(session.CallbackForLatestAttempt, session.Callback); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + Assert.Single(world.Log.Entries, entry => entry.StartsWith("WARN A browser callback that belongs to no waiting sign-in or sign-out was dropped.", StringComparison.Ordinal)); + Assert.DoesNotContain(world.Log.Entries, Secret); + } + + + + /// + /// Only the callback this application's installer registered is used, and only when the server lists exactly that + /// address, so a server cannot steer the callback elsewhere. A server that lists other addresses, one that + /// differs only by letter case among them, is refused before the session is asked to begin: no browser is opened + /// and no inbox. The log says how many addresses the server lists and repeats none of them. + /// + [Fact] + public async Task Browser_CallbackTheServerDoesNotList_IsRefused() + { + SignInWorld world = new() { ConfigureSession = session => session.Metadata = SignInWorld.BrowserDescription(SignInWorld.Provider, "https://print.example.com/synthetic-other-callback", "io.qrun.qqq-print-agent:/oauth/Callback") }; + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + + QqqSessionCredential? credential = await SignInWorld.EndsAsync(signIn.SignInWithBrowserAsync()); + + Assert.Null(credential); + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.Equal("No approved native browser callback is configured.", signIn.Failure); + Assert.Empty(world.Opened); + Assert.Empty(world.Inboxes); + Assert.Null(world.Sessions[0].Redirect); + Assert.True(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.Equal("WARN The server's native grant does not list this application's callback io.qrun.qqq-print-agent:/oauth/callback; it lists 2 other address(es). Add the callback to the QQQ native session grant.", world.Log.Entries[1]); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic-other-callback", StringComparison.Ordinal) || entry.Contains("/oauth/Callback", StringComparison.Ordinal)); + } + + + + /// + /// The sign-in provider presents a certificate this Windows account does not trust, so the session cannot read the + /// provider's own description and the sign-in cannot begin. That is reported as the provider's certificate being + /// refused, with the certificate and the origin that presented it, and not as a plain failure; the browser is not + /// opened and the session stays. A later attempt that fails for another reason is not blamed on that certificate. + /// + [Fact] + public async Task Browser_ProvidersCertificateRefused_IsReportedWithTheCertificate() + { + QqqCertificateRejection refusal = SignInWorld.Refusal(SignInWorld.Provider); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + world.Sessions[0].BeginFailure = new HttpRequestException("The SSL connection could not be established, see inner exception."); + world.Sessions[0].RefusedCertificate = refusal; + + QqqSessionCredential? credential = await SignInWorld.EndsAsync(signIn.SignInWithBrowserAsync()); + + Assert.Null(credential); + Assert.Equal(CompanionSignInState.ProviderCertificateRefused, signIn.State); + Assert.Same(refusal, signIn.Rejection); + Assert.Equal(new Uri(SignInWorld.Provider), signIn.Rejection?.Origin); + Assert.Null(signIn.Failure); + Assert.True(signIn.HasSession); + Assert.Empty(world.Opened); + Assert.Empty(world.Inboxes); + Assert.Equal("WARN This Windows account refused the certificate presented by the sign-in provider (id.example.com; RemoteCertificateChainErrors).", world.Log.Entries[^1]); + + world.Sessions[0].RefusedCertificate = null; + world.Sessions[0].BeginFailure = new IOException("synthetic network failure"); + Assert.Null(await SignInWorld.EndsAsync(signIn.SignInWithBrowserAsync())); + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.Null(signIn.Rejection); + Assert.Equal("synthetic network failure", signIn.Failure); + } + + + + /// + /// A failure at any step of the exchange ends it as "not completed" with the reason, keeps the session, closes + /// any inbox that was opened and releases the sign-in: the session cannot begin, it prepares an address without a + /// state, the inbox cannot be opened, the browser cannot be opened, the inbox breaks while waiting, the session + /// refuses the callback, no credential can be taken, or the server's own time limit ends the completion. When + /// the browser cannot be opened the failure Windows gives names the whole sign-in address; the reason shown and + /// logged names only the kind of failure. No state reaches the log or the reason in any of them. + /// + [Theory] + [InlineData("begin", 0, "The server's sign-in configuration is not usable.", "QqqSessionException: The server's sign-in configuration is not usable.")] + [InlineData("no state", 0, "The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.", "InvalidOperationException: The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.")] + [InlineData("no inbox", 0, "synthetic open failure", "IOException: synthetic open failure")] + [InlineData("browser", 0, "The default browser could not be opened (Windows error 2).", "IOException: The default browser could not be opened (Windows error 2).")] + [InlineData("launcher", 0, "The default browser could not be opened (InvalidOperationException).", "IOException: The default browser could not be opened (InvalidOperationException).")] + [InlineData("inbox", 1, "Invalid QQQ browser callback.", "InvalidDataException: Invalid QQQ browser callback.")] + [InlineData("complete", 1, "The server's answer was not usable.", "QqqSessionException: The server's answer was not usable.")] + [InlineData("export", 1, "Sign in before exporting the session.", "QqqSessionException: Sign in before exporting the session.")] + [InlineData("time limit", 1, "The server did not answer in time.", "TaskCanceledException: The server did not answer in time.")] + public async Task Browser_FailureDuringTheExchange_IsReportedWithItsReason(string step, int opened, string reason, string logged) + { + const string address = "https://id.example.com/authorize?state=synthetic-state-a-1"; + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + session.BeginFailure = step is "begin" ? new QqqSessionException(QqqSessionException.FailureKind.ConfigurationRequired, "The server's sign-in configuration is not usable.") : null; + session.AuthorizationOverride = step is "no state" ? new Uri("https://id.example.com/authorize?client_id=synthetic-client") : null; + world.InboxFailure = step is "no inbox" ? new IOException("synthetic open failure") : null; + world.BrowserFailure = step switch + { + "browser" => new Win32Exception(2, "An error occurred trying to start process '" + address + "' with working directory 'C:\\synthetic'. The system cannot find the file specified."), + "launcher" => new InvalidOperationException("synthetic launcher failure for " + address), + _ => null, + }; + session.CompleteFailure = step switch + { + "complete" => new QqqSessionException(QqqSessionException.FailureKind.InvalidResponse, "The server's answer was not usable."), + "time limit" => new TaskCanceledException("The server did not answer in time."), + _ => null, + }; + session.ExportFailure = step is "export" ? new QqqSessionException(QqqSessionException.FailureKind.AuthenticationRequired, "Sign in before exporting the session.") : null; + + Task running = signIn.SignInWithBrowserAsync(); + if(step is "inbox") + { + world.Inboxes[0].Fail(new InvalidDataException("Invalid QQQ browser callback.")); + } + else if(step is "complete" or "export" or "time limit") + { + world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.Equal(reason, signIn.Failure); + Assert.Null(signIn.Rejection); + Assert.True(signIn.HasSession); + Assert.False(session.Disposed); + Assert.False(signIn.IsBusy); + Assert.Equal(opened, world.Opened.Count); + Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); + Assert.Contains(NeverLaunched, world.Log.Entries, StringComparer.Ordinal); + Assert.Contains("ERROR Browser sign-in not completed: " + logged, world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(world.Log.Entries, Secret); + Assert.False(Secret(signIn.Failure!)); + } + + + + /// + /// When a browser sign-in is not completed, what the protocol handler recorded is copied into the log, so a + /// hand-off that stopped outside the companion can be seen in one place; when it recorded nothing in the last ten + /// minutes, the log says the browser never launched the handler and what that usually means. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Browser_NotCompleted_CopiesTheHandlersTrace_OrSaysItNeverRan(bool traced) + { + string[] trace = ["2026-11-10T10:00:00Z Protocol handler started by the browser (process 4242, session 1).", "2026-11-10T10:00:05Z Callback NOT delivered: TimeoutException: synthetic."]; + SignInWorld world = new(); + world.Trace.AddRange(traced ? trace : []); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + + Task running = signIn.SignInWithBrowserAsync(); + world.Time.Advance(TimeSpan.FromMinutes(3)); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(traced ? "WARN Protocol handler trace from trace/auth-callback.log:" + Environment.NewLine + trace[0] + Environment.NewLine + trace[1] : NeverLaunched, world.Log.Entries[^1]); + Assert.Equal(TimeSpan.FromMinutes(10), Assert.Single(world.TraceWindows)); + } + + + + /// + /// A browser sign-in whose caller stops waiting ends quietly: nothing is reported as cancelled or failed, the inbox + /// is closed, and the session stays. When the wait ends at the very moment the session has begun the sign-in, the + /// browser is not opened for it and no inbox is. + /// + [Theory] + [InlineData(true, 1, "TaskCanceledException")] + [InlineData(false, 0, "OperationCanceledException")] + public async Task Browser_CallerStopsWaiting_EndsQuietlyAndKeepsTheSession(bool whileWaiting, int opened, string cancellation) + { + using CancellationTokenSource caller = new(); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + world.Sessions[0].BeforeAnswer = whileWaiting ? null : caller.Cancel; + + Task running = signIn.SignInWithBrowserAsync(caller.Token); + if(whileWaiting) + { + await caller.CancelAsync(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[0].Disposed); + Assert.False(signIn.IsBusy); + Assert.Equal(opened, world.Opened.Count); + Assert.Equal(opened, world.Inboxes.Count); + Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); + Assert.Equal($"DEBUG Browser sign-in ended early because its caller stopped waiting ({cancellation}).", world.Log.Entries[^1]); + Assert.DoesNotContain(world.Log.Entries, entry => entry.StartsWith("WARN", StringComparison.Ordinal) || entry.StartsWith("ERROR", StringComparison.Ordinal)); + } + + + + /// When the operator cancels at the very moment the session completes the sign-in, the wait has ended: no credential is taken, and the attempt ends as cancelled. + [Fact] + public async Task Browser_CompletedAtTheMomentItIsCancelled_TakesNoCredential() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + session.BeforeAnswer = () => + { + if(session.Callback is not null) + { + signIn.CancelBrowserSignIn(); + } + }; + + Task running = signIn.SignInWithBrowserAsync(); + world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.BrowserCanceled, signIn.State); + Assert.NotNull(session.Callback); + } + + + + /// Nothing is attempted without a session, or on a session that does not offer the browser: no credential, no inbox, no browser, nothing announced or logged. + [Fact] + public async Task Browser_WithoutASessionThatOffersIt_NothingIsAttempted() + { + SignInWorld world = new(); + using CompanionSignIn unprepared = world.NewSignIn(); + using CompanionSignIn passwordOnly = await world.PasswordReadyAsync(); + List changes = SignInWorld.Watch(passwordOnly); + + Assert.Null(await unprepared.SignInWithBrowserAsync()); + Assert.Null(await SignInWorld.EndsAsync(passwordOnly.SignInWithBrowserAsync())); + + Assert.Equal(CompanionSignInState.NotPrepared, unprepared.State); + Assert.Equal(CompanionSignInState.Ready, passwordOnly.State); + Assert.Empty(world.Inboxes); + Assert.Empty(world.Opened); + Assert.Null(world.Sessions[0].Redirect); + Assert.Empty(changes); + Assert.Empty(world.Log.Entries); + } + + + + /// + /// Discarding, or disposing, while a browser sign-in waits ends the wait quietly: the inbox is closed, the session + /// is discarded once the exchange has ended, and nothing is reported as cancelled or failed. After a discard the + /// sign-in says so and can be used again; after disposal it announces nothing. + /// + [Theory] + [InlineData(false, "DEBUG Browser sign-in ended early because the session was discarded (TaskCanceledException).")] + [InlineData(true, "DEBUG Browser sign-in ended early because the sign-in was closed (TaskCanceledException).")] + public async Task Browser_DiscardedOrDisposedWhileWaiting_EndsQuietly(bool dispose, string entry) + { + SignInWorld world = new(); + CompanionSignIn signIn = await world.BrowserReadyAsync(); + Task running = signIn.SignInWithBrowserAsync(); + List changes = SignInWorld.Watch(signIn); + + if(dispose) + { + signIn.Dispose(); + } + else + { + signIn.Discard(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.True(world.Inboxes[0].Disposed); + Assert.True(world.Sessions[0].Disposed); + Assert.False(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.Equal(entry, world.Log.Entries[^1]); + Assert.DoesNotContain(world.Log.Entries, line => line.StartsWith("WARN", StringComparison.Ordinal) || line.StartsWith("ERROR", StringComparison.Ordinal)); + string[] announced = dispose ? [] : ["Offer=null", "HasSession=False", "State=NotPrepared", "IsBusy=False"]; + Assert.Equal(announced, changes, StringComparer.Ordinal); + signIn.Dispose(); + } + + + + /// + /// Runs every operation on a single-threaded context, like a window's, while each thing the sign-in waits for is + /// completed from a thread-pool thread: the description, the password check, the start of the browser sign-in, the + /// callback (which the dispatcher receives on a thread of its own) and its completion. Every announcement must + /// arrive on the calling thread with that context current. A view updates its controls in these handlers, so one + /// "do not return to the caller's thread" inside the sign-in fails this test instead of crashing the companion. + /// + [Fact] + public void Announcements_AreRaisedOnTheCallingThread() + { + using PumpContext pump = new(); + int caller = Environment.CurrentManagedThreadId; + List offThread = []; + List announced = []; + SignInWorld world = new() { ConfigureSession = Held(new QqqAuthenticationMetadata { Type = "TABLE_BASED" }) }; + using CompanionSignIn signIn = world.NewSignIn(); + signIn.PropertyChanged += (_, change) => + { + announced.Add(change.PropertyName!); + if(Environment.CurrentManagedThreadId != caller || !ReferenceEquals(SynchronizationContext.Current, pump)) + { + offThread.Add(change.PropertyName!); + } + }; + + pump.Run(() => RunEveryOperationAsync(world, signIn)); + + Assert.Empty(offThread); + Assert.Contains(nameof(CompanionSignIn.State), announced, StringComparer.Ordinal); + Assert.Contains(nameof(CompanionSignIn.IsBusy), announced, StringComparer.Ordinal); + Assert.Contains(nameof(CompanionSignIn.Offer), announced, StringComparer.Ordinal); + Assert.Contains(nameof(CompanionSignIn.HasSession), announced, StringComparer.Ordinal); + Assert.Contains(nameof(CompanionSignIn.Failure), announced, StringComparer.Ordinal); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + } + + + + /// A session script in which every step waits for the test, so each can be completed from another thread. + private static Action Held(QqqAuthenticationMetadata description) => session => + { + session.Metadata = description; + session.PendingDiscovery = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.PendingBegin = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + session.PendingComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + }; + + + + /// Reads a password server's description, fails a password sign-in, discards, reads a browser server's description and signs in through the browser, completing every wait from another thread. + private static async Task RunEveryOperationAsync(SignInWorld world, CompanionSignIn signIn) + { + Task prepare = signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + await Task.Run(() => world.Sessions[0].PendingDiscovery!.SetResult(world.Sessions[0].Metadata)); + Assert.NotNull(await prepare); + Task password = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); + await Task.Run(() => world.Sessions[0].PendingPassword!.SetException(new IOException("synthetic network failure"))); + Assert.Null(await password); + signIn.Discard(); + + world.ConfigureSession = Held(SignInWorld.BrowserDescription()); + prepare = signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.BrowserCheck, QqqCertificateExceptionOrigins.None); + await Task.Run(() => world.Sessions[1].PendingDiscovery!.SetResult(world.Sessions[1].Metadata)); + Assert.NotNull(await prepare); + Task opened = world.NextInboxAsync(); + Task browser = signIn.SignInWithBrowserAsync(); + await Task.Run(() => world.Sessions[1].PendingBegin!.SetResult()); + FakeInbox inbox = await opened; + await Task.Run(() => inbox.Deliver(world.Sessions[1].CallbackForLatestAttempt)); + await world.Sessions[1].CompleteEntered; + await Task.Run(() => world.Sessions[1].PendingComplete!.SetResult()); + Assert.NotNull(await browser); + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs new file mode 100644 index 0000000..fa653b8 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -0,0 +1,699 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Reflection; +using System.Security.Authentication; +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Presentation.Tests.Fakes; +using Qqq.PrintAgent.Windows.Management; + +namespace Qqq.PrintAgent.Presentation.Tests.SignIn; + +/// The companion's own sign-in: reading a server's sign-in description as the signed-in user, signing in by password, and what it holds, announces and logs. Browser sign-in has its own file. +public sealed class CompanionSignInTests +{ + private const string Reading = "INFO Reading the sign-in description of print.example.com as this Windows account; an untrusted certificate is accepted from none."; + + + + /// + /// The methods offered are those the service's check found and this account's read of the description offers too. + /// When the two agree that is logged as information, and when they differ as a warning naming both. A method name + /// the companion does not know is ignored. The session is created for the server that was asked for, under exactly + /// the certificate exception the caller gave, and kept; the view is told in the order things became true. + /// + [Theory] + [InlineData("password", true, true, false, "INFO Sign-in methods for print.example.com: password.")] + [InlineData("password,passkey", true, true, false, "INFO Sign-in methods for print.example.com: password.")] + [InlineData("browser", false, false, true, "INFO Sign-in methods for print.example.com: browser.")] + [InlineData("password,browser", false, false, true, "WARN Sign-in methods for print.example.com: the service's check found password and browser and this account's read found browser, so browser is offered.")] + [InlineData("password,browser", true, true, false, "WARN Sign-in methods for print.example.com: the service's check found password and browser and this account's read found password, so password is offered.")] + public async Task Prepare_OffersOnlyWhatTheCheckAndThisReadBothFound(string found, bool tableBased, bool password, bool browser, string entry) + { + SignInWorld world = new() { ConfigureSession = session => session.Metadata = tableBased ? new QqqAuthenticationMetadata { Type = "TABLE_BASED" } : SignInWorld.BrowserDescription() }; + ServerCheckResult check = new([], found.Split(','), tableBased ? null : SignInWorld.Provider); + var exception = QqqCertificateExceptionOrigins.ForServer(new Uri(SignInWorld.Server), new Uri(SignInWorld.Provider)); + using CompanionSignIn signIn = world.NewSignIn(); + List changes = SignInWorld.Watch(signIn); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), check, exception); + + Assert.Equal(new SignInOffer(password, browser), offer); + Assert.Same(offer, signIn.Offer); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.Null(signIn.Failure); + Assert.Null(signIn.Rejection); + FakeSession session = Assert.Single(world.Sessions); + Assert.False(session.Disposed); + Assert.Equal(new Uri(SignInWorld.Server), session.Origin); + Assert.Same(exception, session.CertificateException); + Assert.Equal(["INFO Reading the sign-in description of print.example.com as this Windows account; an untrusted certificate is accepted from https://print.example.com, https://id.example.com.", entry], world.Log.Entries); + Assert.Equal(["IsBusy=True", "State=Preparing", "HasSession=False", "HasSession=True", "Offer=" + offer, "State=Ready", "IsBusy=False"], changes); + } + + + + /// When no method is one that both the check and this read found, nothing is offered: the state says so, the difference is logged, and the session that was created is discarded, because nobody could sign in on it. + [Fact] + public async Task Prepare_NoMethodBothFound_OffersNothingAndKeepsNoSession() + { + SignInWorld world = new(); + using CompanionSignIn signIn = world.NewSignIn(); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), new ServerCheckResult([], [ServerCheckResult.Browser]), QqqCertificateExceptionOrigins.None); + + Assert.Null(offer); + Assert.Null(signIn.Offer); + Assert.Equal(CompanionSignInState.NothingOffered, signIn.State); + Assert.False(signIn.HasSession); + Assert.True(Assert.Single(world.Sessions).Disposed); + Assert.Equal([Reading, "WARN Sign-in methods for print.example.com: the service's check found browser and this account's read found password, so no method is offered."], world.Log.Entries); + } + + + + /// + /// The service's check accepted the server's certificate under its own account, and this Windows account refuses + /// it. That is reported as exactly that, with the certificate the session refused and the origin that presented + /// it, which is the server's own. It is not reported as an unreadable description, no reason text is given beside + /// the certificate, and no session is kept. + /// + [Fact] + public async Task Prepare_ThisAccountRefusesTheCertificate_ReportsItAndWhoPresentedIt() + { + QqqCertificateRejection refusal = SignInWorld.Refusal(SignInWorld.Server); + SignInWorld world = new() + { + ConfigureSession = session => + { + session.DiscoverFailure = new HttpRequestException("The SSL connection could not be established, see inner exception.", new AuthenticationException("The remote certificate was rejected by the provided RemoteCertificateValidationCallback.")); + session.RefusedCertificate = refusal; + }, + }; + using CompanionSignIn signIn = world.NewSignIn(); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + + Assert.Null(offer); + Assert.Equal(CompanionSignInState.AccountRefusedCertificate, signIn.State); + Assert.Same(refusal, signIn.Rejection); + Assert.Equal(new Uri(SignInWorld.Server), signIn.Rejection?.Origin); + Assert.Null(signIn.Failure); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.True(Assert.Single(world.Sessions).Disposed); + Assert.Equal("ERROR The sign-in description could not be read: HttpRequestException: The SSL connection could not be established, see inner exception. <- AuthenticationException: The remote certificate was rejected by the provided RemoteCertificateValidationCallback.", world.Log.Entries[1]); + Assert.Equal("WARN This Windows account refused the certificate presented by the server (print.example.com; RemoteCertificateChainErrors). The service checks certificates under its own account, so it can accept one that this account does not.", world.Log.Entries[^1]); + } + + + + /// + /// The description this account reads names another sign-in provider than the service's check reported: a + /// different one, one where the check reported none, none where the check reported one, or a look-alike of it. + /// The sign-in stops there, because a certificate exception the operator accepted covers the provider that was + /// shown and not another. Both are named in the log by the ASCII name a connection would really go to, and no + /// session is kept. + /// + [Theory] + [InlineData("https://id.example.com", "https://login.example.org/realms/synthetic", "login.example.org", "id.example.com")] + [InlineData(null, "https://id.example.com", "id.example.com", "none")] + [InlineData("https://id.example.com", "", "none", "id.example.com")] + [InlineData("not an address", "https://id.example.com", "id.example.com", "none")] + [InlineData("https://login.example.com", "https://l\u043Egin.example.com", "xn--lgin-55d.example.com", "login.example.com")] + public async Task Prepare_AnotherProviderThanTheOneChecked_IsRefused(string? reported, string issuer, string read, string shown) + { + SignInWorld world = new() { ConfigureSession = session => session.Metadata = SignInWorld.BrowserDescription(issuer) }; + using CompanionSignIn signIn = world.NewSignIn(); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), new ServerCheckResult([], [ServerCheckResult.Browser], reported), QqqCertificateExceptionOrigins.None); + + Assert.Null(offer); + Assert.Equal(CompanionSignInState.ProviderChanged, signIn.State); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.Null(signIn.Failure); + Assert.True(Assert.Single(world.Sessions).Disposed); + Assert.Equal([Reading, $"WARN The sign-in provider in the sign-in description of print.example.com is {read}, and the service's check reported {shown}. Nobody is signed in until the server has been checked again."], world.Log.Entries); + } + + + + /// + /// The provider is compared as an origin. The check's address and the description's issuer are the same provider + /// when their scheme, host and port are: whatever the letter case, an explicit default port or a path on either + /// side, and whether a name outside ASCII is written in Unicode or in its "xn--" form. + /// + [Theory] + [InlineData("https://ID.example.com:443/", "https://id.example.com/realms/synthetic")] + [InlineData("https://id.example.com/realms/other", "https://id.example.com")] + [InlineData("https://l\u043Egin.example.com", "https://xn--lgin-55d.example.com")] + public async Task Prepare_SameProviderWrittenDifferently_IsTheSameProvider(string reported, string issuer) + { + SignInWorld world = new() { ConfigureSession = session => session.Metadata = SignInWorld.BrowserDescription(issuer) }; + using CompanionSignIn signIn = world.NewSignIn(); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), new ServerCheckResult([], [ServerCheckResult.Browser], reported), QqqCertificateExceptionOrigins.None); + + Assert.Equal(new SignInOffer(false, true), offer); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + } + + + + /// + /// A description that cannot be read is reported with the session's own reason, and no session is kept: a server + /// that does not answer, an address the session client refuses, and the server's own time limit, which is a + /// cancellation nobody here asked for and therefore a failure like any other. + /// + [Theory] + [InlineData("unreachable", "No connection could be made because the target machine actively refused it.", "HttpRequestException: No connection could be made because the target machine actively refused it.")] + [InlineData("refused address", "Use an HTTPS server origin, or explicitly enabled loopback HTTP. (Parameter 'kind')", "ArgumentException: Use an HTTPS server origin, or explicitly enabled loopback HTTP. (Parameter 'kind')")] + [InlineData("time limit", "The server did not answer in time.", "TaskCanceledException: The server did not answer in time.")] + public async Task Prepare_DescriptionThatCannotBeRead_IsReportedWithItsReason(string kind, string reason, string logged) + { + SignInWorld world = new() + { + CreateFailure = string.Equals(kind, "refused address", StringComparison.Ordinal) ? new ArgumentException("Use an HTTPS server origin, or explicitly enabled loopback HTTP.", nameof(kind)) : null, + ConfigureSession = session => session.DiscoverFailure = string.Equals(kind, "unreachable", StringComparison.Ordinal) + ? new HttpRequestException("No connection could be made because the target machine actively refused it.") + : new TaskCanceledException("The server did not answer in time."), + }; + using CompanionSignIn signIn = world.NewSignIn(); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + + Assert.Null(offer); + Assert.Equal(CompanionSignInState.PrepareFailed, signIn.State); + Assert.Equal(reason, signIn.Failure); + Assert.Null(signIn.Rejection); + Assert.False(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.All(world.Sessions, session => Assert.True(session.Disposed)); + Assert.Equal("ERROR The sign-in description could not be read: " + logged, world.Log.Entries[1]); + Assert.StartsWith("DEBUG The sign-in description could not be read detail: System.", world.Log.Entries[2], StringComparison.Ordinal); + } + + + + /// + /// A read whose caller stops waiting ends quietly: nothing is reported as failed, the session it created is + /// discarded once its call has ended, and only a debug entry says what happened. The same holds when the answer + /// arrives at the very moment the wait ends, and a read asked for with a wait that has already ended creates + /// no session at all. + /// + [Theory] + [InlineData("while reading", 1, "TaskCanceledException")] + [InlineData("as the answer arrives", 1, "OperationCanceledException")] + [InlineData("before it starts", 0, "OperationCanceledException")] + public async Task Prepare_CallerStopsWaiting_EndsQuietlyWithoutASession(string moment, int sessions, string cancellation) + { + using CancellationTokenSource caller = new(); + SignInWorld world = new() + { + ConfigureSession = session => + { + session.PendingDiscovery = string.Equals(moment, "while reading", StringComparison.Ordinal) ? new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) : null; + session.BeforeAnswer = caller.Cancel; + }, + }; + using CompanionSignIn signIn = world.NewSignIn(); + if(string.Equals(moment, "before it starts", StringComparison.Ordinal)) + { + await caller.CancelAsync(); + } + + Task running = signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None, caller.Token); + if(string.Equals(moment, "while reading", StringComparison.Ordinal)) + { + Assert.Equal(CompanionSignInState.Preparing, signIn.State); + Assert.True(signIn.IsBusy); + Assert.False(signIn.HasSession); + await caller.CancelAsync(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.False(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.Null(signIn.Failure); + Assert.Equal(sessions, world.Sessions.Count); + Assert.All(world.Sessions, session => Assert.True(session.Disposed)); + Assert.Equal($"DEBUG Reading the sign-in description ended early because its caller stopped waiting ({cancellation}).", world.Log.Entries[^1]); + Assert.DoesNotContain(world.Log.Entries, entry => entry.StartsWith("ERROR", StringComparison.Ordinal) || entry.StartsWith("WARN", StringComparison.Ordinal)); + } + + + + /// Reading again starts clean: the session held from the earlier read is discarded before the new one is created, and the new one is the one that is held. + [Fact] + public async Task Prepare_Again_DiscardsTheEarlierSession() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + + Assert.Equal(2, world.Sessions.Count); + Assert.True(world.Sessions[0].Disposed); + Assert.False(world.Sessions[1].Disposed); + Assert.True(signIn.HasSession); + } + + + + /// + /// A password sign-in passes the trimmed user name and the password to the session once and returns the session + /// credential to the caller. The sign-in keeps neither: no field of it holds the password, the user name or the + /// credential, it has no property that could show a credential, and nothing of them is logged. The session stays, + /// so the caller decides when it is discarded. + /// + [Fact] + public async Task Password_ReturnsTheCredential_KeepsNoPassword() + { + const string password = "synthetic-password-canary"; + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + List changes = SignInWorld.Watch(signIn); + + QqqSessionCredential? credential = await signIn.SignInWithPasswordAsync(" synthetic-operator ", password); + + Assert.Equal(new Uri(SignInWorld.Server), credential?.Origin); + Assert.Equal("synthetic-session-token", credential?.SessionToken); + Assert.Equal(("synthetic-operator", password), world.Sessions[0].PasswordAttempt); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[0].Disposed); + Assert.Null(signIn.Failure); + Assert.Equal(["IsBusy=True", "State=SigningIn", "State=SignedIn", "IsBusy=False"], changes); + Assert.Equal(["INFO Password sign-in submitted to print.example.com.", "INFO Sign-in accepted by print.example.com; the session credential goes to the caller and is not kept here."], world.Log.Entries); + object?[] held = [.. typeof(CompanionSignIn).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select(field => field.GetValue(signIn))]; + Assert.NotEmpty(held); + Assert.DoesNotContain(held, value => value is QqqSessionCredential || value is string text && (text.Contains(password, StringComparison.Ordinal) || text.Contains("synthetic-operator", StringComparison.Ordinal))); + Assert.DoesNotContain(typeof(CompanionSignIn).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), property => property.PropertyType == typeof(QqqSessionCredential)); + } + + + + /// + /// A refused password sign-in ends the same way whatever the server objected to, the credentials or the permission: + /// the same state and the session's own sentence, to which nothing is added that tells the cases apart. Neither + /// the user name nor the password is logged, and the session and its offer stay, so another attempt needs no new + /// read; that attempt succeeds and the reason is gone. + /// + [Theory] + [InlineData(QqqSessionException.FailureKind.AuthenticationRequired)] + [InlineData(QqqSessionException.FailureKind.PermissionDenied)] + public async Task Password_Failure_DoesNotSayWhichPartWasWrong(QqqSessionException.FailureKind kind) + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PasswordFailure = new QqqSessionException(kind, "The server did not accept this sign-in."); + + QqqSessionCredential? credential = await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-wrong-password"); + + Assert.Null(credential); + Assert.Equal(CompanionSignInState.PasswordFailed, signIn.State); + Assert.Equal("The server did not accept this sign-in.", signIn.Failure); + Assert.Null(signIn.Rejection); + Assert.True(signIn.HasSession); + Assert.Equal(new SignInOffer(true, false), signIn.Offer); + Assert.False(world.Sessions[0].Disposed); + Assert.Equal("ERROR Password sign-in not completed: QqqSessionException: The server did not accept this sign-in.", world.Log.Entries[1]); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic-wrong-password", StringComparison.Ordinal) || entry.Contains("synthetic-operator", StringComparison.Ordinal) || entry.Contains(kind.ToString(), StringComparison.Ordinal)); + + world.Sessions[0].PasswordFailure = null; + Assert.NotNull(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + Assert.Null(signIn.Failure); + } + + + + /// The server's own time limit is a cancellation nobody here asked for, so it is a failed sign-in with its reason, not a quiet end. + [Fact] + public async Task Password_ServerTimeLimit_IsAFailedSignIn() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PasswordFailure = new TaskCanceledException("The server did not answer in time."); + + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + + Assert.Equal(CompanionSignInState.PasswordFailed, signIn.State); + Assert.Equal("The server did not answer in time.", signIn.Failure); + Assert.True(signIn.HasSession); + } + + + + /// + /// A certificate this account refuses while a password is being checked is why that step failed: the state says + /// whose certificate it was and the refusal is kept. A later step that fails for another reason is not blamed on + /// the certificate the session refused before. + /// + [Fact] + public async Task Password_CertificateRefusedDuringTheStep_IsReported_AndAnOlderRefusalIsNot() + { + QqqCertificateRejection refusal = SignInWorld.Refusal(SignInWorld.Server); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PasswordFailure = new HttpRequestException("The SSL connection could not be established, see inner exception."); + world.Sessions[0].RefusedCertificate = refusal; + + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.AccountRefusedCertificate, signIn.State); + Assert.Same(refusal, signIn.Rejection); + Assert.Null(signIn.Failure); + Assert.True(signIn.HasSession); + + world.Sessions[0].RefusedCertificate = null; + world.Sessions[0].PasswordFailure = new IOException("synthetic network failure"); + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.PasswordFailed, signIn.State); + Assert.Null(signIn.Rejection); + Assert.Equal("synthetic network failure", signIn.Failure); + } + + + + /// + /// A password sign-in whose caller stops waiting ends quietly and keeps the session for another attempt; nothing + /// is reported as failed. When the server accepts the sign-in at the very moment the wait ends, no credential is + /// taken either. + /// + [Theory] + [InlineData(true, "TaskCanceledException")] + [InlineData(false, "OperationCanceledException")] + public async Task Password_CallerStopsWaiting_EndsQuietlyAndKeepsTheSession(bool whileChecking, string cancellation) + { + using CancellationTokenSource caller = new(); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PendingPassword = whileChecking ? new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) : null; + world.Sessions[0].BeforeAnswer = caller.Cancel; + + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password", caller.Token); + if(whileChecking) + { + Assert.Equal(CompanionSignInState.SigningIn, signIn.State); + await caller.CancelAsync(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[0].Disposed); + Assert.False(signIn.IsBusy); + Assert.Null(signIn.Failure); + Assert.Equal(["INFO Password sign-in submitted to print.example.com.", $"DEBUG Password sign-in ended early because its caller stopped waiting ({cancellation})."], world.Log.Entries); + } + + + + /// Nothing is attempted without a session, or on a session that does not offer a password: the caller gets no credential, the session is not asked, and nothing is announced or logged. + [Fact] + public async Task Password_WithoutASessionThatOffersIt_NothingIsAttempted() + { + SignInWorld world = new(); + using CompanionSignIn unprepared = world.NewSignIn(); + using CompanionSignIn browserOnly = await world.BrowserReadyAsync(); + List changes = SignInWorld.Watch(browserOnly); + + Assert.Null(await unprepared.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Null(await browserOnly.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + + Assert.Equal(CompanionSignInState.NotPrepared, unprepared.State); + Assert.Equal(CompanionSignInState.Ready, browserOnly.State); + Assert.Null(Assert.Single(world.Sessions).PasswordAttempt); + Assert.Empty(changes); + Assert.Empty(world.Log.Entries); + } + + + + /// + /// One operation runs at a time. While a password is being checked, another read and another password sign-in are + /// refused: each returns nothing, each refusal is logged, and the running operation and its state are not + /// disturbed. When it ends the sign-in is free again. + /// + [Fact] + public async Task SecondOperationWhileOneRuns_IsRefusedAndLogged() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + TaskCompletionSource answer = new(TaskCreationOptions.RunContinuationsAsynchronously); + world.Sessions[0].PendingPassword = answer; + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); + List changes = SignInWorld.Watch(signIn); + + Assert.Null(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-other-password")); + + Assert.Equal(["INFO Password sign-in submitted to print.example.com.", + "WARN Reading the sign-in description was not started: another sign-in operation is still running.", + "WARN Password sign-in was not started: another sign-in operation is still running."], world.Log.Entries); + Assert.Empty(changes); + Assert.Equal(CompanionSignInState.SigningIn, signIn.State); + Assert.True(signIn.IsBusy); + Assert.Single(world.Sessions); + Assert.Equal("synthetic-password", world.Sessions[0].PasswordAttempt?.Password); + + answer.SetResult(); + Assert.NotNull(await SignInWorld.EndsAsync(running)); + Assert.False(signIn.IsBusy); + } + + + + /// Discarding when nothing runs lets the session go at once and withdraws what it offered; a sign-in then needs a new read, and until one is made nothing is attempted. + [Fact] + public async Task Discard_WhenNothingRuns_LetsTheSessionGo() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + Assert.NotNull(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + List changes = SignInWorld.Watch(signIn); + + signIn.Discard(); + + Assert.True(world.Sessions[0].Disposed); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.Equal(["Offer=null", "HasSession=False", "State=NotPrepared"], changes); + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + } + + + + /// + /// Discarding while a password is being checked does not pull the session out from under that call: a session + /// that is discarded under a running call makes the call end with "disposed", and here it ends with the + /// cancellation that was asked for. It ends quietly, the session is discarded once it has ended, and nothing is + /// reported as failed. Afterwards the sign-in can read a description again and keeps that session. + /// + [Fact] + public async Task Discard_WhileAnOperationRuns_CancelsIt_AndTheSessionGoesWhenItEnds() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); + + signIn.Discard(); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.True(world.Sessions[0].Disposed); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.False(signIn.IsBusy); + Assert.Equal(["INFO Password sign-in submitted to print.example.com.", "DEBUG Password sign-in ended early because the session was discarded (TaskCanceledException)."], world.Log.Entries); + + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[1].Disposed); + } + + + + /// + /// Disposing while the server checks a password only cancels. The session is not discarded under the running + /// call, which would make the call end with "disposed": it ends with the cancellation, quietly, the session is + /// discarded then, and from the moment of disposal nothing more is announced: a view that has closed is not + /// called back. Only a debug entry records the end. + /// + [Fact] + public async Task Dispose_OnlyCancels_NothingIsAnnouncedAfterwards() + { + SignInWorld world = new(); + CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + List changes = SignInWorld.Watch(signIn); + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); + Assert.Equal(["IsBusy=True", "State=SigningIn"], changes); + + signIn.Dispose(); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.True(world.Sessions[0].Disposed); + Assert.Equal(["IsBusy=True", "State=SigningIn"], changes); + Assert.False(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.Equal(["INFO Password sign-in submitted to print.example.com.", "DEBUG Password sign-in ended early because the sign-in was closed (TaskCanceledException)."], world.Log.Entries); + } + + + + /// + /// Disposing when nothing runs discards the session at once and announces nothing. After that every request does + /// nothing: no read, no sign-in, no discard, and disposing again is harmless. + /// + [Fact] + public async Task Dispose_WhenNothingRuns_DiscardsTheSession_AndEverythingAfterwardsDoesNothing() + { + SignInWorld world = new(); + CompanionSignIn signIn = await world.PasswordReadyAsync(); + List changes = SignInWorld.Watch(signIn); + + signIn.Dispose(); + signIn.Dispose(); + signIn.Discard(); + signIn.CancelBrowserSignIn(); + + Assert.True(world.Sessions[0].Disposed); + Assert.Null(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Null(await signIn.SignInWithBrowserAsync()); + Assert.Single(world.Sessions); + Assert.Empty(changes); + Assert.Empty(world.Log.Entries); + } + + + + /// + /// A subscriber that throws while the sign-in announces that it is busy does not leave it claimed forever: the + /// failure reaches the caller, the sign-in is free again, and the next read works. + /// + [Fact] + public async Task SubscriberThatThrowsAtTheStart_DoesNotLeaveTheSignInClaimed() + { + SignInWorld world = new(); + using CompanionSignIn signIn = world.NewSignIn(); + bool thrown = false; + signIn.PropertyChanged += (_, change) => + { + if(!thrown && string.Equals(change.PropertyName, nameof(CompanionSignIn.IsBusy), StringComparison.Ordinal)) + { + thrown = true; + throw new InvalidOperationException("synthetic subscriber failure"); + } + }; + + await Assert.ThrowsAsync(() => signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + + Assert.False(signIn.IsBusy); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + } + + + + /// + /// A subscriber that throws while a result is announced has not made the step fail. The read still ended ready + /// with its session, and the password sign-in still ended signed in; neither is reported as not completed, the + /// subscriber's failure reaches the caller, and the sign-in is free again. + /// + [Theory] + [InlineData(CompanionSignInState.Ready)] + [InlineData(CompanionSignInState.SignedIn)] + public async Task SubscriberThatThrowsWhileAResultIsAnnounced_HasNotMadeTheStepFail(CompanionSignInState announced) + { + SignInWorld world = new(); + using CompanionSignIn signIn = world.NewSignIn(); + signIn.PropertyChanged += (_, change) => + { + if(string.Equals(change.PropertyName, nameof(CompanionSignIn.State), StringComparison.Ordinal) && signIn.State == announced) + { + throw new IOException("synthetic subscriber failure"); + } + }; + + Task step = announced == CompanionSignInState.Ready + ? signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None) + : PrepareThenSignInAsync(signIn); + + await Assert.ThrowsAsync(() => step); + Assert.Equal(announced, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(Assert.Single(world.Sessions).Disposed); + Assert.Null(signIn.Failure); + Assert.False(signIn.IsBusy); + Assert.DoesNotContain(world.Log.Entries, entry => entry.StartsWith("ERROR", StringComparison.Ordinal)); + } + + + + /// Reads a password server's description and then signs in by password. + private static async Task PrepareThenSignInAsync(CompanionSignIn signIn) + { + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + _ = await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); + } + + + + /// + /// A failure nobody expects (a programming error in a session, say) is not dressed up as a failed sign-in: it + /// reaches the caller. The sign-in is released all the same and its state matches what it holds: no session after + /// a read that threw, and the session still there after a sign-in that threw. + /// + [Fact] + public async Task UnexpectedFailure_ReachesTheCaller_AndTheStateMatchesWhatIsHeld() + { + SignInWorld world = new() { ConfigureSession = session => session.DiscoverFailure = new NotSupportedException("synthetic unexpected failure") }; + using CompanionSignIn signIn = world.NewSignIn(); + + await Assert.ThrowsAsync(() => signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.False(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.True(world.Sessions[0].Disposed); + + world.ConfigureSession = session => session.PasswordFailure = new NotSupportedException("synthetic unexpected failure"); + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + await Assert.ThrowsAsync(() => signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(signIn.IsBusy); + } + + + + /// A sign-in cannot work without its collaborators and says which is missing; a read needs a server, the check's result and a certificate exception, which may be the empty one but not nothing. + [Fact] + public async Task MissingCollaboratorOrArgument_IsRefused() + { + SignInWorld world = new(); + using CompanionSignIn signIn = world.NewSignIn(); + + Assert.Equal("sessions", Assert.Throws(() => new CompanionSignIn(null!, world, world, world.Dispatcher, world.Log)).ParamName); + Assert.Equal("browser", Assert.Throws(() => new CompanionSignIn(world, null!, world, world.Dispatcher, world.Log)).ParamName); + Assert.Equal("callbacks", Assert.Throws(() => new CompanionSignIn(world, world, null!, world.Dispatcher, world.Log)).ParamName); + Assert.Equal("dispatcher", Assert.Throws(() => new CompanionSignIn(world, world, world, null!, world.Log)).ParamName); + Assert.Equal("log", Assert.Throws(() => new CompanionSignIn(world, world, world, world.Dispatcher, null!)).ParamName); + Assert.Equal("server", (await Assert.ThrowsAsync(() => signIn.PrepareAsync(null!, SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None))).ParamName); + Assert.Equal("check", (await Assert.ThrowsAsync(() => signIn.PrepareAsync(new Uri(SignInWorld.Server), null!, QqqCertificateExceptionOrigins.None))).ParamName); + Assert.Equal("certificateException", (await Assert.ThrowsAsync(() => signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, null!))).ParamName); + Assert.False(signIn.IsBusy); + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs new file mode 100644 index 0000000..6be93b8 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Presentation.Tests.Fakes; + +namespace Qqq.PrintAgent.Presentation.Tests.SignIn; + +/// The identity provider's half of a sign-out: its page is opened, its return is recognized by this sign-out's own state within two minutes, and nothing of the request reaches the log. +public sealed class ProviderSignOutTests +{ + private const string Hint = "synthetic-id-token-hint"; + private const string State = "synthetic-sign-out-state"; + + + + /// A provider sign-out as the service returns one: the end-session address with its token hint, the registered callback and this sign-out's state. + private static QqqProviderLogout Logout(string provider = "id.example.com") => new(new Uri("https://" + provider + "/end-session?id_token_hint=" + Hint + "&state=" + State), new Uri(SignInWorld.Callback), State); + + + + /// A provider sign-out over the world's dispatcher, browser, log and clock. + private static ProviderSignOut Over(SignInWorld world) => new(world, world.Dispatcher, world.Log, world.Time); + + + + /// + /// The inbox is open before the provider's page is, the page is the address the service returned, and the wait has + /// a two minute limit. A callback carrying another exchange's state is not this sign-out's: it is dropped and the + /// wait goes on. The callback with this sign-out's state, on the registered address, confirms it. The log names + /// the provider's host and nothing else of the request: no token hint and no state. + /// + [Fact] + public async Task ProviderSignOut_MatchesItsOwnState_WithinTwoMinutes() + { + SignInWorld world = new(); + QqqProviderLogout logout = Logout(); + + Task running = Over(world).CompleteAsync(logout); + FakeInbox inbox = Assert.Single(world.Inboxes); + Assert.Equal([1], world.ListeningAtLaunch); + Assert.Equal(logout.EndSessionUri, Assert.Single(world.Opened)); + Assert.Equal(TimeSpan.FromMinutes(2), Assert.Single(world.Time.RequestedDelays)); + Assert.Equal(TimeSpan.FromMinutes(2), ProviderSignOut.Limit); + Task reopened = world.NextInboxAsync(); + inbox.Deliver(new Uri(SignInWorld.Callback + "?state=synthetic-state-of-another-exchange")); + FakeInbox next = await reopened; + Assert.False(running.IsCompleted); + next.Deliver(new Uri(SignInWorld.Callback + "?state=" + State)); + + Assert.True(await SignInWorld.EndsAsync(running)); + Assert.True(next.Disposed); + Assert.Equal(["INFO Browser callback inbox open.", + "INFO Opening the identity provider's sign-out page in the default browser (id.example.com).", + "WARN A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged.", + "INFO Browser callback inbox open.", + "INFO Identity provider sign-out callback matched."], world.Log.Entries); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic", StringComparison.Ordinal)); + } + + + + /// The provider's page is at an address the server's provider wrote, so the log names its host by the ASCII name the browser will really go to: a look-alike letter reads as the "xn--" name. The browser is given the address unchanged. + [Fact] + public async Task ProviderPageWithALookAlikeHost_IsLoggedByItsAsciiName() + { + SignInWorld world = new(); + QqqProviderLogout logout = Logout("l\u043Egin.example.com:8443"); + + Task running = Over(world).CompleteAsync(logout); + world.Inboxes[0].Deliver(new Uri(SignInWorld.Callback + "?state=" + State)); + + Assert.True(await SignInWorld.EndsAsync(running)); + Assert.Same(logout.EndSessionUri, Assert.Single(world.Opened)); + Assert.Contains("INFO Opening the identity provider's sign-out page in the default browser (xn--lgin-55d.example.com:8443).", world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains('\u043E', StringComparison.Ordinal) || entry.Contains("synthetic", StringComparison.Ordinal)); + } + + + + /// A callback that carries this sign-out's state but is not on the registered address is handed to the sign-out, which does not take it as the provider finishing. + [Fact] + public async Task CallbackWithItsStateOnAnotherAddress_DoesNotConfirm() + { + SignInWorld world = new(); + + Task running = Over(world).CompleteAsync(Logout()); + world.Inboxes[0].Deliver(new Uri("io.qrun.qqq-print-agent:/oauth/other?state=" + State)); + + Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal("INFO Identity provider sign-out callback did not match this sign-out.", world.Log.Entries[^1]); + Assert.True(world.Inboxes[0].Disposed); + } + + + + /// + /// When the provider does not come back within two minutes, the browser cannot be opened, the inbox cannot be + /// opened or breaks, or the caller stops waiting, the sign-out is not confirmed, and the log says so with the kind + /// of failure. Windows names what it could not start in its failure, which is the whole sign-out address with the + /// token hint; none of that reaches the log. + /// + [Theory] + [InlineData("limit", "TaskCanceledException: A task was canceled.")] + [InlineData("token", "TaskCanceledException: A task was canceled.")] + [InlineData("browser", "IOException: The default browser could not be opened (Windows error 2).")] + [InlineData("no inbox", "UnauthorizedAccessException: synthetic open failure")] + [InlineData("inbox", "IOException: synthetic pipe failure")] + public async Task ProviderThatDoesNotReturn_IsNotConfirmed(string ending, string cause) + { + SignInWorld world = new() + { + BrowserFailure = string.Equals(ending, "browser", StringComparison.Ordinal) ? new Win32Exception(2, "An error occurred trying to start process '" + Logout().EndSessionUri.AbsoluteUri + "' with working directory 'C:\\synthetic'. The system cannot find the file specified.") : null, + InboxFailure = string.Equals(ending, "no inbox", StringComparison.Ordinal) ? new UnauthorizedAccessException("synthetic open failure") : null, + }; + using CancellationTokenSource cancellation = new(); + + Task running = Over(world).CompleteAsync(Logout(), cancellation.Token); + if(string.Equals(ending, "limit", StringComparison.Ordinal)) + { + world.Time.Advance(TimeSpan.FromMinutes(2)); + } + else if(string.Equals(ending, "token", StringComparison.Ordinal)) + { + await cancellation.CancelAsync(); + } + else if(string.Equals(ending, "inbox", StringComparison.Ordinal)) + { + world.Inboxes[0].Fail(new IOException("synthetic pipe failure")); + } + + Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal("WARN Identity provider sign-out was not confirmed: " + cause, world.Log.Entries[^1]); + Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); + Assert.Equal(string.Equals(ending, "browser", StringComparison.Ordinal) || string.Equals(ending, "no inbox", StringComparison.Ordinal) ? 0 : 1, world.Opened.Count); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(Hint, StringComparison.Ordinal) || entry.Contains(State, StringComparison.Ordinal)); + } + + + + /// A provider sign-out cannot work without a browser, the dispatcher and a log, and says which is missing; and it needs a sign-out to complete. + [Fact] + public async Task MissingCollaborator_IsRefused() + { + SignInWorld world = new(); + + Assert.Equal("browser", Assert.Throws(() => new ProviderSignOut(null!, world.Dispatcher, world.Log)).ParamName); + Assert.Equal("dispatcher", Assert.Throws(() => new ProviderSignOut(world, null!, world.Log)).ParamName); + Assert.Equal("log", Assert.Throws(() => new ProviderSignOut(world, world.Dispatcher, null!)).ParamName); + Assert.Equal("logout", (await Assert.ThrowsAsync(() => new ProviderSignOut(world, world.Dispatcher, world.Log).CompleteAsync(null!))).ParamName); + } +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInOfferTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInOfferTests.cs new file mode 100644 index 0000000..f1589cd --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInOfferTests.cs @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Core.Authentication; +using Qqq.PrintAgent.Presentation.SignIn; +using Qqq.PrintAgent.Presentation.Tests.Fakes; +using Qqq.PrintAgent.Windows.Management; + +namespace Qqq.PrintAgent.Presentation.Tests.SignIn; + +/// The sign-in methods on offer: what the service's check found, what a sign-in description offers, what both hold, and how an offer reads in a log line. +public sealed class SignInOfferTests +{ + /// The check's methods are read by the names the contract gives them, exactly; a name the companion does not know, or one in another letter case, is ignored. + [Theory] + [InlineData("password", true, false)] + [InlineData("browser", false, true)] + [InlineData("browser,password", true, true)] + [InlineData("passkey,Password,BROWSER", false, false)] + [InlineData("", false, false)] + public void Checked_ReadsTheMethodsTheContractNames(string methods, bool password, bool browser) + { + Assert.Equal(new SignInOffer(password, browser), SignInOffer.Checked(new ServerCheckResult([], methods.Split(',', StringSplitOptions.RemoveEmptyEntries)))); + } + + + + /// A description offers what the service's check would find in it: a table-based server takes a password and nothing else, even when it also publishes a browser grant; any other server offers the browser when it publishes the grant, and nothing without it. + [Fact] + public void Read_FollowsTheRuleOfTheServicesCheck() + { + QqqAuthenticationMetadata grant = SignInWorld.BrowserDescription(); + + Assert.Equal(new SignInOffer(true, false), SignInOffer.Read(new QqqAuthenticationMetadata { Type = "TABLE_BASED" })); + Assert.Equal(new SignInOffer(true, false), SignInOffer.Read(new QqqAuthenticationMetadata { Type = "TABLE_BASED", Values = grant.Values })); + Assert.Equal(new SignInOffer(false, true), SignInOffer.Read(grant)); + Assert.Equal(new SignInOffer(false, false), SignInOffer.Read(new QqqAuthenticationMetadata { Type = "OAUTH2" })); + Assert.Equal(new SignInOffer(false, false), SignInOffer.Read(new QqqAuthenticationMetadata { Type = "OAUTH2", Values = new QqqAuthenticationMetadata.ProviderValues() })); + Assert.Equal(new SignInOffer(false, false), SignInOffer.Read(new QqqAuthenticationMetadata { Type = "table_based" })); + } + + + + /// What two offers have in common is each method both hold, and an offer is something only when it holds a method. + [Fact] + public void Common_IsWhatBothHold() + { + Assert.Equal(new SignInOffer(true, false), new SignInOffer(true, true).Common(new SignInOffer(true, false))); + Assert.Equal(new SignInOffer(false, true), new SignInOffer(false, true).Common(new SignInOffer(true, true))); + Assert.Equal(new SignInOffer(false, false), new SignInOffer(true, false).Common(new SignInOffer(false, true))); + Assert.True(new SignInOffer(true, false).Any); + Assert.True(new SignInOffer(false, true).Any); + Assert.False(new SignInOffer(false, false).Any); + } + + + + /// An offer reads in a log line by the names the contract gives the methods. + [Theory] + [InlineData(true, true, "password and browser")] + [InlineData(true, false, "password")] + [InlineData(false, true, "browser")] + [InlineData(false, false, "no method")] + public void ToString_NamesTheMethods(bool password, bool browser, string text) + { + Assert.Equal(text, new SignInOffer(password, browser).ToString()); + } + + + + /// Each of the three needs what it reads from. + [Fact] + public void MissingArgument_IsRefused() + { + Assert.Equal("check", Assert.Throws(() => SignInOffer.Checked(null!)).ParamName); + Assert.Equal("description", Assert.Throws(() => SignInOffer.Read(null!)).ParamName); + Assert.Equal("other", Assert.Throws(() => new SignInOffer(true, true).Common(null!)).ParamName); + } +} -- 2.54.0 From e37f957cfa724da368c2c3347f8d617444b9ad33 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 22:49:41 -0600 Subject: [PATCH 03/27] fix(companion): a browser that cannot be started no longer puts the sign-in address in the log or the dialog When Windows cannot start the default browser, .NET's failure text names what it could not start: "An error occurred trying to start process '' ...". The connection dialog's flow logged that text and showed it as the reason of "Browser sign-in not completed", so a failed start at sign-in wrote the provider's authorization address, with the attempt's state, nonce and code challenge, to the companion log and the dialog. A failed start at the provider's sign-out logged the end-session address, with the ID token hint. SignInFlow now opens the browser through BrowserLaunch at both places, as CompanionSignIn and ProviderSignOut already do. BrowserLaunch replaces any launcher failure with fixed text: that the default browser could not be opened, the kind of failure (for a Windows error, its number), and what to check. The original failure is not attached as the cause, so no way of writing the new one out can contain the address. The text now ends with the remedy, because it is what the operator reads as the reason. This is a change to SignInFlow, which step 3 of the wizard-and-tree stage was not to touch. It is kept to exactly this: the two calls that start the browser, and the comments beside them. The flow is what ships until the wizard replaces it, so the fix could not wait for that. What the dialog shows at a sign-out whose browser did not start is unchanged (it never showed the failure's text there); only the log line changed. Tests at all four sites use a launcher that fails the way Windows does, with an address carrying marked state, nonce, code challenge and ID token hint, and assert that none of them and no query reaches a log line, a message, or a property a view binds to. The audit records it as U22. Every tag from v0.2.0-rc.1 to v1.2.1 has the sign-in case; the sign-out case is in no tag and is on release/1.2.2. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 14 +++- docs/AUDIT-2026-11-10.md | 6 ++ .../SignIn/BrowserLaunch.cs | 15 ++-- .../SignIn/IBrowserLauncher.cs | 2 +- .../SignIn/SignInFlow.Browser.cs | 6 +- .../SignIn/SignInFlow.SignOut.cs | 6 +- src/Qqq.PrintAgent/DefaultBrowserLauncher.cs | 2 +- .../Fakes/BrowserStartFailure.cs | 75 +++++++++++++++++++ .../SignIn/CompanionSignInBrowserTests.cs | 38 +++++++++- .../SignIn/ProviderSignOutTests.cs | 30 +++++++- .../SignIn/SignInFlowBrowserTests.cs | 44 ++++++++++- .../SignIn/SignInFlowSignOutTests.cs | 39 +++++++++- 12 files changed, 257 insertions(+), 20 deletions(-) create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/Fakes/BrowserStartFailure.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index a967dfe..8c4cbb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,20 @@ ## Unreleased +A failed browser start no longer writes the sign-in address to the companion log or the dialog (2.0). When Windows +could not start the default browser for a browser sign-in, the companion's log entry and the dialog's "Browser +sign-in not completed" message repeated Windows' own error text, and that text names what it could not start: the +whole sign-in address, with that attempt's state, nonce and code challenge. When the browser could not be started +for the identity provider's sign-out, the log entry named the provider's sign-out address the same way, with its ID +token hint. Both now say only that the default browser could not be opened, with the Windows error number, and what +to check: that a default browser is set in Windows Settings under Apps, Default apps. Sign-in and sign-out are +otherwise unchanged. Every release up to 1.2.1 has the sign-in case; the sign-out case was never in a release +([audit](docs/AUDIT-2026-11-10.md), U22). + Sign-in in the companion, rebuilt for several servers (2.0; not used by the window yet). Three types were added to the presentation assembly for the connection wizard and the per-server Connection page of -[ADR-0005](docs/adr/0005-connection-wizard-and-server-tree.md). Nothing the operator sees changes in this build: the -connection dialog still runs on the existing flow, which is untouched. +[ADR-0005](docs/adr/0005-connection-wizard-and-server-tree.md). Nothing the operator sees changes through them in +this build: the connection dialog still runs on the existing flow, whose one change is the entry above. - `CompanionSignIn` is the part of signing in that needs a session and runs as the signed-in Windows user. It reads the server's sign-in description, signs in by password or through the browser, and returns the session credential diff --git a/docs/AUDIT-2026-11-10.md b/docs/AUDIT-2026-11-10.md index eee38ee..d241fe3 100644 --- a/docs/AUDIT-2026-11-10.md +++ b/docs/AUDIT-2026-11-10.md @@ -269,6 +269,12 @@ Found by the retrospective reviews of 2026-11-10 and by the review of the printi | W80 | Nit | When the update session's folder fails its second check, the one made after the folder is created, the empty folder is left under the updates folder (`MsiUpdateService.cs:186-187`): nothing was downloaded into it, and removing it is refused by the same check. `NothingIsDownloadedIntoAFolderThatCannotBeTrusted` pins this. An administrator finds an empty folder with a random name (found by the author of plan step 8 and confirmed by its review) | Open | | W81 | Nit | The link check of the recorded outcome before it is written (`MsiUpdateSteps.Apply.cs:201`, on `last-result.json`) has no refusing test: with the check removed every test passes. The path is a file, so showing the refusal needs a file symbolic link, which Windows lets a test create only with a privilege or in developer mode; the other link checks are shown with junctions, which are folders (review of plan step 8) | Open | +Found while building the companion's sign-in for the connection wizard (2026-11-10), by its author: + +| ID | Severity | Finding | Status | +| --- | --- | --- | --- | +| U22 | Not rated | A browser that cannot be started puts the address it was asked to open into the companion's log and, at sign-in, into the dialog. The companion starts the browser through the Windows shell, and when that fails .NET's failure text names what could not be started: "An error occurred trying to start process '' ..." (seen on .NET 10.0.14 with a shell start of a file that does not exist; no browser was involved). At a browser sign-in the address is the provider's authorization address, with that attempt's `state`, `nonce` and `code_challenge`; the text was logged at error level and shown as the reason of "Browser sign-in not completed", and the whole failure was logged again as debug detail (`SignInFlow.Browser.cs:98-103`, started at `:152`, read at `ebea861`). At a provider sign-out the address is the provider's end-session address, with the `id_token_hint` (the provider's ID token) and the sign-out's `state`; the text was logged as a warning and not shown (`SignInFlow.SignOut.cs:121-125`, started at `:114`). The log file's own redaction removes the value of `state` from such a line in 2.0 and nothing else of it; `id_token_hint=` passes unchanged, which is the gap W40 records, and W40's note that no log line can carry it did not hold for this one. The dialog's message is not redacted at all. It takes a failed browser start to happen: no default browser, or a broken handler for web addresses. Releases: the sign-in case is in every tag from `v0.2.0-rc.1` to `v1.2.1` (introduced by `2c1c5f1`, 2026-10-31; in `v1.2.1` the start is `src/Qqq.PrintAgent/MainWindow.Authentication.cs:339` and the catch that logs and shows the text is at `:294-298`), and 1.2.1's log has no rule for `state`, so installed 1.2.x systems write and show the address whole. The sign-out case came with `5d4b7f4` (2026-11-09), is in no tag, and is on the unreleased `release/1.2.2` branch (`MainWindow.Authentication.cs:303`, `:311`) together with the sign-in case (`:395`, `:354`). Read from the code in each case, not run | Closed for 2.0 by the change that adds this row: every browser start in the presentation assembly goes through `BrowserLaunch`, which replaces the failure with fixed text (that the default browser could not be opened, the kind of failure or the Windows error number, and what to check), in the dialog's flow and in the new `CompanionSignIn` and `ProviderSignOut`. Open for 1.2.x: `release/1.2.2` still has both cases, and 1.2.1 as installed has the sign-in case | + ### Repository | ID | Requirement | Finding | Status | diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs index b404be2..1e8d8d3 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs @@ -16,11 +16,16 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// internal static class BrowserLaunch { + /// What an operator can do about a browser that could not be opened; it follows the kind of failure in the failure's text, which is shown as the reason a sign-in was not completed. + internal const string Remedy = "Check that a default browser is set in Windows Settings under Apps, Default apps, then try again."; + + + /// - /// Opens the address. Any failure is replaced by one with fixed text that names only the kind of failure and, - /// for a Windows error, its number. The new failure is thrown after the original has been let go, so the original - /// is not attached as its cause: a report of the new failure, whichever way it is written out, then cannot - /// contain the address. + /// Opens the address. Any failure is replaced by one with fixed text: that the default browser could not be + /// opened, the kind of failure (for a Windows error, its number) and what to do about it. The new failure is + /// thrown after the original has been let go, so the original is not attached as its cause: a report of the new + /// failure, whichever way it is written out, then cannot contain the address. /// internal static void Open(IBrowserLauncher browser, Uri address) { @@ -34,6 +39,6 @@ internal static class BrowserLaunch { kind = exception is Win32Exception windows ? "Windows error " + windows.NativeErrorCode.ToString(CultureInfo.InvariantCulture) : exception.GetType().Name; } - throw new IOException("The default browser could not be opened (" + kind + ")."); + throw new IOException("The default browser could not be opened (" + kind + "). " + Remedy); } } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/IBrowserLauncher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/IBrowserLauncher.cs index ac6050c..5e2bf46 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/IBrowserLauncher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/IBrowserLauncher.cs @@ -8,6 +8,6 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// Opens an address in the user's default browser. The address can carry a sign-in state or a token hint, so implementations hand it straight to the browser and never log it. public interface IBrowserLauncher { - /// Opens the address; a failure to start the browser is thrown to the caller. + /// Opens the address; a failure to start the browser is thrown to the caller. On Windows that failure's text names what could not be started, which is the whole address, so presentation code opens a browser only through , which replaces the failure with fixed text before anything can log or show it. void Open(Uri address); } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs index 5fe8345..4207a0f 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs @@ -137,7 +137,9 @@ public sealed partial class SignInFlow /// /// The browser exchange itself: open the callback inbox first (so a fast redirect is not lost), begin the login, open the /// provider's page in the default browser, wait for the forwarded callback, and complete the login on the session - /// that started it. The inbox is disposed when the exchange ends. Only the provider's host is logged. A callback that is + /// that started it. The inbox is disposed when the exchange ends. Only the provider's host is logged, and a browser that + /// cannot be started is reported by the kind of failure only, because Windows' own text for it names the whole address + /// with its state (see ). A callback that is /// malformed or too large is refused by the inbox as invalid data, which the caller reports like any other failed exchange. /// The token is looked at again after each wait, so a browser is not opened and a login is not completed for a wait /// that has already ended. @@ -149,7 +151,7 @@ public sealed partial class SignInFlow Uri authorization = await session.BeginBrowserSignInAsync(redirect, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _log.Info("Opening the identity provider's sign-in page in the default browser (" + QqqOrigin.ShownAuthority(authorization) + ")."); - _browser.Open(authorization); + BrowserLaunch.Open(_browser, authorization); Uri callback = await inbox.ReceiveAsync(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _callbackArrived = true; diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs index 2733a77..3824f32 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs @@ -99,7 +99,9 @@ public sealed partial class SignInFlow /// /// Opens the identity provider's end-session page in the default browser and waits up to two minutes for the browser to return /// to this application's registered callback with this sign-out's own state. The inbox is opened first so a fast redirect is not lost. - /// The request carries a sensitive token hint, so only its host is logged. Returns whether the provider confirmed; the wait + /// The request carries a sensitive token hint, so only its host is logged, and a browser that cannot be started is logged by + /// the kind of failure only, because Windows' own text for it names the whole request (see ). + /// Returns whether the provider confirmed; the wait /// also ends when the caller's token does. When the flow is disposed the wait ends without a result, and that is left /// to the runner as a quiet end instead of being reported as an unconfirmed sign-out. /// @@ -111,7 +113,7 @@ public sealed partial class SignInFlow using CancellationTokenSource limit = new(ProviderSignOutLimit, _time); using var wait = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancellationToken); _log.Info("Opening the identity provider's sign-out page in the default browser (" + QqqOrigin.ShownAuthority(logout.EndSessionUri) + ")."); - _browser.Open(logout.EndSessionUri); + BrowserLaunch.Open(_browser, logout.EndSessionUri); Uri callback = await inbox.ReceiveAsync(wait.Token); ThrowIfDisposed(); bool matched = logout.Matches(callback); diff --git a/src/Qqq.PrintAgent/DefaultBrowserLauncher.cs b/src/Qqq.PrintAgent/DefaultBrowserLauncher.cs index e958ed5..c3249b0 100644 --- a/src/Qqq.PrintAgent/DefaultBrowserLauncher.cs +++ b/src/Qqq.PrintAgent/DefaultBrowserLauncher.cs @@ -11,6 +11,6 @@ namespace Qqq.PrintAgent; /// Opens an address in the user's default browser through the Windows shell. The address can carry a sign-in state or a token hint, so it is handed straight to the shell and never logged here. internal sealed class DefaultBrowserLauncher : IBrowserLauncher { - /// Starts the default browser on the address; a failure to start it is thrown to the flow, which reports it. + /// Starts the default browser on the address; a failure to start it is thrown to the presentation assembly. Windows' text for that failure names the whole address, so nothing here logs it, and the presentation assembly reports only the kind of failure. public void Open(Uri address) => _ = Process.Start(new ProcessStartInfo(address.AbsoluteUri) { UseShellExecute = true }); } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/BrowserStartFailure.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/BrowserStartFailure.cs new file mode 100644 index 0000000..9788d2e --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/BrowserStartFailure.cs @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Globalization; +using System.Reflection; + +namespace Qqq.PrintAgent.Presentation.Tests.Fakes; + +/// +/// A browser that cannot be started, failing the way Windows fails: the failure's own text names what could not be +/// started, which is the whole address the browser was asked to open. The addresses here carry marked synthetic values +/// in the places a real sign-in address and a real sign-out address carry their sensitive ones (state, nonce, code +/// challenge, ID token hint), so a test can show that none of them, and no query at all, reaches a log line, a message +/// or a property a view binds to. +/// +internal static class BrowserStartFailure +{ + /// The marked state of both addresses. + internal const string State = "synthetic-state-canary"; + + /// The marked nonce of the sign-in address. + internal const string Nonce = "synthetic-nonce-canary"; + + /// The marked code challenge of the sign-in address. + internal const string Challenge = "synthetic-challenge-canary"; + + /// The marked ID token hint of the sign-out address. + internal const string Hint = "synthetic-id-token-hint-canary"; + + /// What an operator is told to do, which ends every report of a browser that could not be opened. + internal const string Remedy = "Check that a default browser is set in Windows Settings under Apps, Default apps, then try again."; + + /// The whole report of a browser Windows could not start for want of the file (error 2). + internal const string WindowsReport = "The default browser could not be opened (Windows error 2). " + Remedy; + + /// The whole report of a launcher that failed in some other way. + internal const string OtherReport = "The default browser could not be opened (InvalidOperationException). " + Remedy; + + + + /// A provider's authorization address as the session client builds one, with the marked state, nonce and code challenge. + internal static Uri SignInAddress { get; } = new("https://id.example.com/authorize?client_id=synthetic-client&response_type=code&redirect_uri=io.qrun.qqq-print-agent%3A%2Foauth%2Fcallback&scope=openid&state=" + State + + "&nonce=" + Nonce + "&prompt=login&max_age=0&code_challenge_method=S256&code_challenge=" + Challenge); + + + + /// A provider's end-session address as the service returns one, with the marked ID token hint and state. + internal static Uri SignOutAddress { get; } = new("https://id.example.com/end-session?id_token_hint=" + Hint + "&post_logout_redirect_uri=io.qrun.qqq-print-agent%3A%2Foauth%2Fcallback&state=" + State); + + + + /// The failure .NET throws when Windows cannot start what it was asked to open: error 2, with the text .NET gives it, which names the address in full. + internal static Win32Exception AsWindows(Uri address) + => new(2, "An error occurred trying to start process '" + address.AbsoluteUri + "' with working directory 'C:/Program Files/Synthetic'. The system cannot find the file specified."); + + + + /// A launcher failure of another kind whose text also names the address. + internal static InvalidOperationException AsAnotherKind(Uri address) => new("The launcher could not open " + address.AbsoluteUri + "."); + + + + /// True when a text holds anything of either address beyond the provider's host: one of the marked values, a query, a parameter name or the path. + internal static bool Leaks(string? text) + => text is not null && new[] { State, Nonce, Challenge, Hint, "?", "client_id", "id_token_hint", "redirect_uri", "/authorize", "/end-session" }.Any(part => text.Contains(part, StringComparison.OrdinalIgnoreCase)); + + + + /// Every public property of a view model as the text a view would show for it, which is what a binding can reach. + internal static List Bound(object viewModel) + => [.. viewModel.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(property => Convert.ToString(property.GetValue(viewModel), CultureInfo.InvariantCulture))]; +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index 858055f..7e8a913 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -253,8 +253,8 @@ public sealed class CompanionSignInBrowserTests [InlineData("begin", 0, "The server's sign-in configuration is not usable.", "QqqSessionException: The server's sign-in configuration is not usable.")] [InlineData("no state", 0, "The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.", "InvalidOperationException: The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.")] [InlineData("no inbox", 0, "synthetic open failure", "IOException: synthetic open failure")] - [InlineData("browser", 0, "The default browser could not be opened (Windows error 2).", "IOException: The default browser could not be opened (Windows error 2).")] - [InlineData("launcher", 0, "The default browser could not be opened (InvalidOperationException).", "IOException: The default browser could not be opened (InvalidOperationException).")] + [InlineData("browser", 0, BrowserStartFailure.WindowsReport, "IOException: " + BrowserStartFailure.WindowsReport)] + [InlineData("launcher", 0, BrowserStartFailure.OtherReport, "IOException: " + BrowserStartFailure.OtherReport)] [InlineData("inbox", 1, "Invalid QQQ browser callback.", "InvalidDataException: Invalid QQQ browser callback.")] [InlineData("complete", 1, "The server's answer was not usable.", "QqqSessionException: The server's answer was not usable.")] [InlineData("export", 1, "Sign in before exporting the session.", "QqqSessionException: Sign in before exporting the session.")] @@ -309,6 +309,40 @@ public sealed class CompanionSignInBrowserTests + /// + /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole sign-in + /// address, with the attempt's state, nonce and code challenge. None of that is logged or kept. The reason the + /// wizard is given says that the default browser could not be opened and what to check, the log says the same + /// with the kind of failure, and no log line and no property a view binds to holds one of those values or any + /// query at all. The same holds for a launcher that fails in another way and names the address in its text. + /// + [Theory] + [InlineData(true, BrowserStartFailure.WindowsReport)] + [InlineData(false, BrowserStartFailure.OtherReport)] + public async Task Browser_ThatCannotBeStarted_IsReportedWithoutAnythingOfTheSignInAddress(bool asWindows, string report) + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + world.Sessions[0].AuthorizationOverride = BrowserStartFailure.SignInAddress; + world.BrowserFailure = asWindows ? BrowserStartFailure.AsWindows(BrowserStartFailure.SignInAddress) : BrowserStartFailure.AsAnotherKind(BrowserStartFailure.SignInAddress); + Assert.True(BrowserStartFailure.Leaks(world.BrowserFailure.Message)); + + Assert.Null(await SignInWorld.EndsAsync(signIn.SignInWithBrowserAsync())); + + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.Equal(report, signIn.Failure); + Assert.Contains("ERROR Browser sign-in not completed: IOException: " + report, world.Log.Entries, StringComparer.Ordinal); + Assert.Contains(world.Log.Entries, entry => entry.StartsWith("DEBUG Browser sign-in not completed detail: System.IO.IOException: " + report, StringComparison.Ordinal)); + Assert.DoesNotContain(world.Log.Entries, BrowserStartFailure.Leaks); + Assert.DoesNotContain(BrowserStartFailure.Bound(signIn), BrowserStartFailure.Leaks); + Assert.Empty(world.Opened); + Assert.True(Assert.Single(world.Inboxes).Disposed); + Assert.True(signIn.HasSession); + Assert.False(signIn.IsBusy); + } + + + /// /// When a browser sign-in is not completed, what the protocol handler recorded is copied into the log, so a /// hand-off that stopped outside the companion can be seen in one place; when it recorded nothing in the last ten diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs index 6be93b8..c606abe 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -107,7 +107,7 @@ public sealed class ProviderSignOutTests [Theory] [InlineData("limit", "TaskCanceledException: A task was canceled.")] [InlineData("token", "TaskCanceledException: A task was canceled.")] - [InlineData("browser", "IOException: The default browser could not be opened (Windows error 2).")] + [InlineData("browser", "IOException: " + BrowserStartFailure.WindowsReport)] [InlineData("no inbox", "UnauthorizedAccessException: synthetic open failure")] [InlineData("inbox", "IOException: synthetic pipe failure")] public async Task ProviderThatDoesNotReturn_IsNotConfirmed(string ending, string cause) @@ -142,6 +142,34 @@ public sealed class ProviderSignOutTests + /// + /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole + /// end-session address, with the provider's ID token hint and this sign-out's state. The sign-out is reported as + /// not confirmed, the log says that the default browser could not be opened, with the kind of failure and what to + /// check, and no log line holds one of those values or any query at all. The same holds for a launcher that fails + /// in another way and names the address in its text. + /// + [Theory] + [InlineData(true, BrowserStartFailure.WindowsReport)] + [InlineData(false, BrowserStartFailure.OtherReport)] + public async Task BrowserThatCannotBeStarted_IsReportedWithoutAnythingOfTheSignOutAddress(bool asWindows, string report) + { + QqqProviderLogout logout = new(BrowserStartFailure.SignOutAddress, new Uri(SignInWorld.Callback), BrowserStartFailure.State); + SignInWorld world = new() { BrowserFailure = asWindows ? BrowserStartFailure.AsWindows(BrowserStartFailure.SignOutAddress) : BrowserStartFailure.AsAnotherKind(BrowserStartFailure.SignOutAddress) }; + Assert.True(BrowserStartFailure.Leaks(world.BrowserFailure.Message)); + + Assert.False(await SignInWorld.EndsAsync(Over(world).CompleteAsync(logout))); + + Assert.Equal(["INFO Browser callback inbox open.", + "INFO Opening the identity provider's sign-out page in the default browser (id.example.com).", + "WARN Identity provider sign-out was not confirmed: IOException: " + report], world.Log.Entries); + Assert.DoesNotContain(world.Log.Entries, BrowserStartFailure.Leaks); + Assert.Empty(world.Opened); + Assert.True(Assert.Single(world.Inboxes).Disposed); + } + + + /// A provider sign-out cannot work without a browser, the dispatcher and a log, and says which is missing; and it needs a sign-out to complete. [Fact] public async Task MissingCollaborator_IsRefused() diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs index 7a54879..2fb3b92 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs @@ -309,7 +309,8 @@ public sealed class SignInFlowBrowserTests /// /// A failure anywhere in the exchange (the inbox cannot be opened, the server refuses to begin, the browser cannot be started, /// the inbox breaks, a malformed or oversize callback is written to the inbox, the server rejects the callback) is reported as - /// not completed with its reason and never escapes the flow; the session stays for an explicit retry. + /// not completed with its reason and never escapes the flow; the session stays for an explicit retry. The reason is the + /// failure's own text, except for a browser that cannot be started, whose text is replaced by the kind of failure. /// [Theory] [InlineData("inbox")] @@ -346,8 +347,10 @@ public sealed class SignInFlowBrowserTests } await running; - Assert.Equal(new FeedbackMessage("Browser sign-in not completed", "No validated account session was received. Reason: " + failure.Message + " Check the server's advertised native sign-in grant and installed callback configuration, then try again explicitly. The activity log has the full detail.", FeedbackSeverity.Warning), fixture.Shown[^1]); - Assert.Contains("ERROR Browser sign-in not completed: " + failure.GetType().Name + ": " + failure.Message, fixture.Log.Entries, StringComparer.Ordinal); + string reason = step is "browser" ? BrowserStartFailure.WindowsReport : failure.Message; + string logged = step is "browser" ? "IOException: " + reason : failure.GetType().Name + ": " + reason; + Assert.Equal(new FeedbackMessage("Browser sign-in not completed", "No validated account session was received. Reason: " + reason + " Check the server's advertised native sign-in grant and installed callback configuration, then try again explicitly. The activity log has the full detail.", FeedbackSeverity.Warning), fixture.Shown[^1]); + Assert.Contains("ERROR Browser sign-in not completed: " + logged, fixture.Log.Entries, StringComparer.Ordinal); Assert.Empty(fixture.Requests); Assert.True(fixture.Flow.HasSession); Assert.True(fixture.Flow.BrowserOffered); @@ -359,6 +362,41 @@ public sealed class SignInFlowBrowserTests + /// + /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole sign-in + /// address, with the attempt's state, nonce and code challenge. None of that is logged or shown. The operator is + /// told that the default browser could not be opened and what to check, the log says the same with the kind of + /// failure, and no log line, message or property a view binds to holds one of those values or any query at all. + /// The same holds for a launcher that fails in another way and names the address in its text. + /// + [Theory] + [InlineData(true, BrowserStartFailure.WindowsReport)] + [InlineData(false, BrowserStartFailure.OtherReport)] + public async Task BrowserThatCannotBeStarted_IsReportedWithoutAnythingOfTheSignInAddress(bool asWindows, string report) + { + SignInFixture fixture = await DiscoveredAsync(); + fixture.Sessions[0].AuthorizationOverride = BrowserStartFailure.SignInAddress; + fixture.BrowserFailure = asWindows ? BrowserStartFailure.AsWindows(BrowserStartFailure.SignInAddress) : BrowserStartFailure.AsAnotherKind(BrowserStartFailure.SignInAddress); + Assert.True(BrowserStartFailure.Leaks(fixture.BrowserFailure.Message)); + + await fixture.Flow.SignInWithBrowserAsync(PairingChoice.KeepCurrent); + + Assert.Equal(new FeedbackMessage("Browser sign-in not completed", "No validated account session was received. Reason: " + report + " Check the server's advertised native sign-in grant and installed callback configuration, then try again explicitly. The activity log has the full detail.", FeedbackSeverity.Warning), fixture.Shown[^1]); + Assert.Contains("ERROR Browser sign-in not completed: IOException: " + report, fixture.Log.Entries, StringComparer.Ordinal); + Assert.Contains(fixture.Log.Entries, entry => entry.StartsWith("DEBUG Browser sign-in not completed detail: System.IO.IOException: " + report, StringComparison.Ordinal)); + Assert.DoesNotContain(fixture.Log.Entries, BrowserStartFailure.Leaks); + Assert.DoesNotContain(fixture.Shown, message => BrowserStartFailure.Leaks(message.Title) || BrowserStartFailure.Leaks(message.Message)); + Assert.DoesNotContain(BrowserStartFailure.Bound(fixture.Flow), BrowserStartFailure.Leaks); + Assert.Empty(fixture.Opened); + Assert.Empty(fixture.Requests); + Assert.Equal(SignInStage.Ready, fixture.Flow.Stage); + Assert.True(fixture.Flow.HasSession); + Assert.False(fixture.Flow.IsBusy); + Assert.All(fixture.Inboxes, inbox => Assert.True(inbox.Disposed)); + } + + + /// After a failed attempt the session can be used for a second one, which begins a new login of its own; a callback left over from the first attempt is refused by the server, and the callback of the second attempt signs in. [Fact] public async Task SecondAttemptOnTheSameSession_RefusesTheFirstAttemptsCallback() diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs index b6187fe..e817004 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs @@ -309,13 +309,50 @@ public sealed class SignInFlowSignOutTests + /// + /// When Windows cannot start the browser for the provider's sign-out, the failure it gives names what it could not + /// start: the whole end-session address, with the provider's ID token hint and this sign-out's state. None of that + /// is logged or shown. The log says that the default browser could not be opened, with the kind of failure and what + /// to check, the sign-out still completes on this computer with the warning the dialog already gave for a provider + /// that did not confirm, and no log line, message or property a view binds to holds one of those values or any + /// query at all. The same holds for a launcher that fails in another way and names the address in its text. + /// + [Theory] + [InlineData(true, BrowserStartFailure.WindowsReport)] + [InlineData(false, BrowserStartFailure.OtherReport)] + public async Task ProviderSignOutPageThatCannotBeStarted_IsReportedWithoutAnythingOfTheSignOutAddress(bool asWindows, string report) + { + QqqProviderLogout logout = new(BrowserStartFailure.SignOutAddress, new Uri(SignInFixture.Callback), BrowserStartFailure.State); + SignInFixture fixture = new() + { + Service = _ => Task.FromResult(JsonSerializer.Serialize(new PipeSignOutResult("Signed out of QQQ.", logout), PrintApiClient.JsonOptions)), + BrowserFailure = asWindows ? BrowserStartFailure.AsWindows(BrowserStartFailure.SignOutAddress) : BrowserStartFailure.AsAnotherKind(BrowserStartFailure.SignOutAddress), + }; + Assert.True(BrowserStartFailure.Leaks(fixture.BrowserFailure.Message)); + + Assert.True(await fixture.Flow.SignOutAsync()); + + Assert.Equal("WARN Identity provider sign-out was not confirmed: IOException: " + report, fixture.Log.Entries[^1]); + Assert.Equal([new FeedbackMessage("Account sign-out", "Signed out of QQQ. Finish signing out of the identity provider on the page that opened in your browser.", FeedbackSeverity.Informational), + new FeedbackMessage("Account sign-out", "Signed out of QQQ. The identity provider sign-out was opened in your browser but did not confirm; close that page and sign out there if it is still open.", FeedbackSeverity.Warning)], fixture.Shown); + Assert.DoesNotContain(fixture.Log.Entries, BrowserStartFailure.Leaks); + Assert.DoesNotContain(fixture.Shown, message => BrowserStartFailure.Leaks(message.Title) || BrowserStartFailure.Leaks(message.Message)); + Assert.DoesNotContain(BrowserStartFailure.Bound(fixture.Flow), BrowserStartFailure.Leaks); + Assert.Empty(fixture.Opened); + Assert.True(Assert.Single(fixture.Inboxes).Disposed); + Assert.Equal(SignInStage.Idle, fixture.Flow.Stage); + Assert.False(fixture.Flow.IsBusy); + } + + + /// /// When the provider does not come back within two minutes, the browser cannot be opened, or the caller cancels, the /// wait ends, the sign-out still completes locally, and the operator is warned that the provider did not confirm. /// [Theory] [InlineData("limit", "TaskCanceledException")] - [InlineData("browser", "Win32Exception: The system cannot find the file specified.")] + [InlineData("browser", "IOException: " + BrowserStartFailure.WindowsReport)] [InlineData("token", "TaskCanceledException")] public async Task ProviderThatDoesNotReturn_IsReportedAsUnconfirmed(string ending, string cause) { -- 2.54.0 From a6b78ca4d78a4edf853660ae7a04913340494f25 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:40:32 -0600 Subject: [PATCH 04/27] fix(presentation): a browser sign-in whose wait has ended no longer asks the session to complete Between receiving the callback and completing the sign-in, CompanionSignIn did not look at the cancellation token, which the dialog's flow does. Waiting for a callback that has already arrived returns it whatever the token says, so when the browser came back at once and Cancel was pressed (or the three minutes ran out) in the same moment, the session was asked to complete a sign-in for an attempt that was then reported as cancelled. The real session client refuses before it consumes anything, but ISignInSession does not promise that, and the comment that said a session refuses was wrong. The token is now looked at after the wait on the ticket, and the comment says why the check is made here. Tests: the callback reaches its ticket and the wait is ended, by Cancel and by the limit, before the sign-in starts waiting; the session must never be asked to complete, and keeps what it holds. The inbox answers inline for this, so the order of events is certain and no thread is waited for. A second test pins that the completion is given the exchange's own token: the token the session was handed is live while it completes and ends when Cancel is pressed. The test support for both is a launch hook and an inline inbox in the fakes, and NoContext moves out of the dispatcher tests to be shared. Review of afe7e08, B1. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.Browser.cs | 10 ++- .../Fakes/FakeInbox.cs | 7 +- .../Fakes/FakeSession.cs | 6 ++ .../Fakes/NoContext.cs | 27 +++++++ .../Fakes/SignInWorld.cs | 15 +++- .../SignIn/BrowserCallbackDispatcherTests.cs | 18 ----- .../SignIn/CompanionSignInBrowserTests.cs | 78 +++++++++++++++++++ 7 files changed, 136 insertions(+), 25 deletions(-) create mode 100644 tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs index 32f0bc1..87e4375 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -96,9 +96,12 @@ public sealed partial class CompanionSignIn /// returned, register that state with the dispatcher (which has an inbox open before the browser is, so a fast /// redirect is not lost), open the provider's page in the default browser, wait for the callback with that state, /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Only the - /// provider's host is logged, never the address, its state or the callback. The token is looked at again once the - /// sign-in was begun, so a browser is not opened for a wait that has already ended; completing takes the same - /// token, and a session refuses to complete for a wait that has ended. + /// provider's host is logged, never the address, its state or the callback. The token is looked at again after + /// each wait: once the sign-in was begun, so a browser is not opened for a wait that has already ended, and once + /// the callback is there, so the session is not asked to complete for one. That second look is needed because a + /// callback that has already arrived is handed over whatever the token says, and a session is not bound to + /// refuse: the check is made here and not left to it. Completing takes the same token, so a wait that ends while + /// the session completes ends the completion too. /// private async Task ExchangeWithBrowserAsync(ISignInSession session, CancellationToken cancellationToken) { @@ -115,6 +118,7 @@ public sealed partial class CompanionSignIn _log.Info("Opening the identity provider's sign-in page in the default browser ({Provider}).", QqqOrigin.ShownAuthority(authorization)); BrowserLaunch.Open(_browser, authorization); Uri callback = await ticket.Callback.WaitAsync(cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); _log.Info("Browser callback received; completing the sign-in."); await session.CompleteBrowserSignInAsync(callback, cancellationToken); } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs index 4ace4aa..2c9740b 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs @@ -11,10 +11,13 @@ namespace Qqq.PrintAgent.Presentation.Tests.Fakes; /// A callback inbox a test delivers to by hand. Waiting ends when a callback is delivered, when a failure is injected, or /// when the flow's token is cancelled, exactly like the real pipe inbox. Like the real one it finishes on whatever thread /// delivered the callback, not on the caller's, so a flow that forgot to return to its own thread is caught by a test. +/// An inbox that answers inline is the exception a test asks for when it has to know that a delivery was dealt with +/// before it does the next thing: whoever waits on it, with no synchronization context on the delivering thread, +/// continues inside the call that delivers. /// -internal sealed class FakeInbox : IBrowserCallbackInbox +internal sealed class FakeInbox(bool answersInline = false) : IBrowserCallbackInbox { - private readonly TaskCompletionSource _callback = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _callback = new(answersInline ? TaskCreationOptions.None : TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _listening = new(TaskCreationOptions.RunContinuationsAsynchronously); private Task? _wait; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs index 9c425ce..527eee2 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeSession.cs @@ -111,6 +111,11 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer + /// The token the flow gave the completion of a browser sign-in, which is how a test sees that ending the flow's wait ends the completion too. + internal CancellationToken? CompleteToken { get; private set; } + + + /// True once the flow discarded this session. internal bool Disposed { get; private set; } @@ -232,6 +237,7 @@ internal sealed class FakeSession(Uri origin, QqqCertificateExceptionOrigins cer { ObjectDisposedException.ThrowIf(Disposed, this); Callback = callback; + CompleteToken = cancellationToken; _completeEntered.TrySetResult(); try { diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs new file mode 100644 index 0000000..ed58897 --- /dev/null +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Presentation.Tests.Fakes; + +/// +/// Removes the test runner's synchronization context from the calling thread until it is disposed. With a context +/// present, .NET never continues an awaiting method inside the call that completes what it awaits; without one it +/// does, which is what happens on the thread-pool threads the callback dispatcher works on. A test uses this to make +/// that order of events certain: when the call that delivers something returns, whoever awaited it has dealt with it. +/// +internal sealed class NoContext : IDisposable +{ + private readonly SynchronizationContext? _before = SynchronizationContext.Current; + + + + /// Removes the context. + internal NoContext() => SynchronizationContext.SetSynchronizationContext(null); + + + + /// Puts the context back. + public void Dispose() => SynchronizationContext.SetSynchronizationContext(_before); +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs index 682eae1..55717c3 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs @@ -87,6 +87,11 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr + /// When set, it runs once the browser has been asked to open an address, on the thread that asked and before that call returns. A test uses it to make something happen between the provider's page opening and the sign-in starting to wait for its callback. + internal Action? Launched { get; set; } + + + /// Every inbox that was opened, oldest first. internal List Inboxes { get; } = []; @@ -97,6 +102,11 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr + /// When set, the inboxes opened from then on answer inline (see ). + internal bool InboxesAnswerInline { get; set; } + + + /// The protocol handler trace; empty means the browser never launched the handler. internal List Trace { get; } = []; @@ -226,7 +236,7 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr - /// Records the address instead of opening a browser, or fails. + /// Records the address instead of opening a browser, then runs what the test asked for at that moment; or fails. public void Open(Uri address) { if(BrowserFailure is not null) @@ -235,6 +245,7 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr } ListeningAtLaunch.Add(Inboxes.Count(inbox => inbox.Waiting && !inbox.Disposed)); Opened.Add(address); + Launched?.Invoke(address); } @@ -246,7 +257,7 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr { throw InboxFailure; } - FakeInbox inbox = new(); + FakeInbox inbox = new(InboxesAnswerInline); Inboxes.Add(inbox); _awaitedInbox?.TrySetResult(inbox); return inbox; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 2b65284..fdfe00e 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -389,24 +389,6 @@ public sealed class BrowserCallbackDispatcherTests - /// Removes the test runner's synchronization context from the calling thread until it is disposed. With a context present, .NET never continues an awaiting method inside the call that completes what it awaits; without one it does, which is what happens on the thread-pool threads the dispatcher works on. - private sealed class NoContext : IDisposable - { - private readonly SynchronizationContext? _before = SynchronizationContext.Current; - - - - /// Removes the context. - internal NoContext() => SynchronizationContext.SetSynchronizationContext(null); - - - - /// Puts the context back. - public void Dispose() => SynchronizationContext.SetSynchronizationContext(_before); - } - - - /// A callback source whose inboxes do not notice being closed and answer when the test says so, on the test's own thread. private sealed class LateInboxes : IBrowserCallbackSource { diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index 7e8a913..440ab24 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -428,6 +428,84 @@ public sealed class CompanionSignInBrowserTests + /// + /// The callback is already there, and the wait has already ended, when the sign-in starts waiting for the + /// callback: the browser came back at once and, in the same moment, the operator pressed Cancel or the three + /// minutes ran out. Waiting for something that has already arrived does not look at the token, so the sign-in + /// looks itself. The session is never asked to complete and nothing says a callback was received; the attempt + /// ends as cancelled or timed out, and the session, which was handed nothing, stays for another attempt. The + /// inbox answers inline here, so the callback has reached its ticket before the wait is ended, which the test + /// checks: it was not dropped, and its inbox was closed, inside the call that delivered it. + /// + [Theory] + [InlineData(false, CompanionSignInState.BrowserCanceled)] + [InlineData(true, CompanionSignInState.BrowserTimedOut)] + public async Task Browser_WaitEndedAsTheCallbackArrived_NeverAsksTheSessionToComplete(bool byLimit, CompanionSignInState ending) + { + SignInWorld world = new() { InboxesAnswerInline = true }; + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + bool routed = false; + world.Launched = _ => + { + using NoContext none = new(); + world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); + routed = world.Inboxes[0].Disposed; + if(byLimit) + { + world.Time.Advance(CompanionSignIn.BrowserSignInLimit); + } + else + { + signIn.CancelBrowserSignIn(); + } + }; + + QqqSessionCredential? credential = await SignInWorld.EndsAsync(signIn.SignInWithBrowserAsync()); + + Assert.True(routed); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("was dropped", StringComparison.Ordinal)); + Assert.Null(credential); + Assert.Null(session.Callback); + Assert.Null(session.CompleteToken); + Assert.DoesNotContain("INFO Browser callback received; completing the sign-in.", world.Log.Entries, StringComparer.Ordinal); + Assert.Equal(ending, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(session.Disposed); + Assert.False(signIn.IsBusy); + Assert.Single(world.Opened); + Assert.DoesNotContain(world.Log.Entries, Secret); + } + + + + /// + /// The session is asked to complete with the exchange's own token, not with one that never ends: while the session + /// is completing, the token it was given is still live, and Cancel ends it, so the completion stops with the + /// attempt instead of running on behind an attempt that was reported as cancelled. + /// + [Fact] + public async Task Browser_CancelledWhileTheSessionCompletes_EndsTheCompletionToo() + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + session.PendingComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Task running = signIn.SignInWithBrowserAsync(); + world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); + await session.CompleteEntered.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(session.CompleteToken is { CanBeCanceled: true, IsCancellationRequested: false }); + + signIn.CancelBrowserSignIn(); + + Assert.True(session.CompleteToken is { IsCancellationRequested: true }); + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.BrowserCanceled, signIn.State); + Assert.False(signIn.IsBusy); + } + + + /// Nothing is attempted without a session, or on a session that does not offer the browser: no credential, no inbox, no browser, nothing announced or logged. [Fact] public async Task Browser_WithoutASessionThatOffersIt_NothingIsAttempted() -- 2.54.0 From f9a31ca41fc1fda28a6d71ec8f59c5a1ab1e2856 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:42:35 -0600 Subject: [PATCH 05/27] fix(presentation): a discard from a subscriber while an operation is released is carried out at once Discard() decided "an operation is running" by the busy flag. An operation that is being released clears its wait, announces how it ended, and only then stops being busy. A subscriber that called Discard() from that announcement set the discarding flag and cancelled nothing, and no operation was left to act on it: the session stayed, and the flag stayed set, so the next read returned an offer and then lost its session as it ended. Discard() now decides by the operation's own wait, which exists exactly while the operation can still discard the session on its way out. When it is gone, no call is using the session, and the session is discarded on the spot. A read could also return an offer whose session was already gone: a subscriber that discards while the read announces "ready" is honoured when the read ends. PrepareAsync now returns an offer only while it is the one that is held, and null otherwise, which is what Offer and HasSession say at that moment; a debug entry records why. Tests: the reviewer's probe P5 as a test (a caller-cancelled password sign-in whose "ready" announcement discards; the session goes at once and the next read and sign-in work), and a read whose "ready" announcement discards (null is returned, nothing is held, the next read works). Review of afe7e08, S1. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.cs | 24 ++++-- .../SignIn/CompanionSignInTests.cs | 86 +++++++++++++++++++ 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs index 90193cb..318d588 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -108,7 +108,10 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable /// offered are those the service's check and this read both found; a difference is logged. When the description /// names another sign-in provider than the check reported, or this account refuses the server's certificate, or the /// description cannot be read, the state says which and no session is kept. It returns the offer, or null when - /// nothing can be signed in with, when the caller stopped waiting, or when another operation is running. + /// nothing can be signed in with, when the caller stopped waiting, or when another operation is running. An offer + /// is returned only while the session it was made on is the one that is held: when a subscriber discarded the + /// session while the result was being announced, the read returns null, as then is, so a + /// caller is never handed an offer it cannot sign in with. /// public async Task PrepareAsync(Uri server, ServerCheckResult check, QqqCertificateExceptionOrigins certificateException, CancellationToken cancellationToken = default) { @@ -119,7 +122,13 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable { return null; } - return await RunAsync("Reading the sign-in description", CompanionSignInState.Preparing, token => ReadDescriptionAsync(server, check, certificateException, token), cancellationToken); + SignInOffer? offer = await RunAsync("Reading the sign-in description", CompanionSignInState.Preparing, token => ReadDescriptionAsync(server, check, certificateException, token), cancellationToken); + if(offer is not null && !ReferenceEquals(offer, _offer)) + { + _log.Debug("The sign-in description was read, and its session was discarded before the read returned, so the read offers nothing."); + return null; + } + return offer; } @@ -261,7 +270,12 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable /// Discards the session, if any, so a later sign-in starts with a new preparation. While an operation is running /// the session is in use, so this cancels the operation instead, and the operation discards the session as it /// ends: discarding a session under a call that is still using it makes that call fail in ways that look like - /// errors. Either way no session is held once the running operation, if any, has ended. + /// errors. Either way no session is held once the running operation, if any, has ended. "Running" is decided by + /// the operation's own wait, which exists exactly while the operation can still discard the session for us, and + /// not by , which stays true a little longer: an operation that is being released announces + /// how it ended before it lets go, and a subscriber that calls this from that announcement finds no call using + /// the session any more, so the session is discarded at once. Leaving it to the operation then would leave it + /// to nobody. /// public void Discard() { @@ -269,10 +283,10 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable { return; } - if(_operating) + if(_operation is { } running) { _discarding = true; - _operation?.Cancel(); + running.Cancel(); return; } DropSession(); diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs index fa653b8..e403e7d 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -524,6 +524,92 @@ public sealed class CompanionSignInTests + /// + /// An operation that is being released says how it ended before it lets go of the sign-in, so for the length of + /// that announcement the sign-in is still busy while no call uses the session any more. A subscriber that + /// discards from that announcement gets the session discarded at once: left to the operation, as a discard + /// during a running call is, it would have been left to nobody, and every later read would have lost its + /// session as it ended. Here a password sign-in whose caller stopped waiting ends ready, a subscriber discards + /// at that moment, and afterwards the next read keeps its session and a sign-in on it works. + /// + [Fact] + public async Task Discard_FromASubscriberWhileAnOperationIsBeingReleased_DiscardsAtOnce() + { + using CancellationTokenSource caller = new(); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + bool? busyWhenDiscarded = null; + signIn.PropertyChanged += (_, change) => + { + if(busyWhenDiscarded is null && string.Equals(change.PropertyName, nameof(CompanionSignIn.State), StringComparison.Ordinal) && signIn.State == CompanionSignInState.Ready) + { + busyWhenDiscarded = signIn.IsBusy; + signIn.Discard(); + } + }; + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password", caller.Token); + await caller.CancelAsync(); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.True(busyWhenDiscarded); + Assert.True(world.Sessions[0].Disposed); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.False(signIn.IsBusy); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + + Assert.Equal(new SignInOffer(true, false), offer); + Assert.Same(offer, signIn.Offer); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[1].Disposed); + Assert.NotNull(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); + Assert.Equal(CompanionSignInState.SignedIn, signIn.State); + } + + + + /// + /// A read never returns an offer whose session is gone. A subscriber that discards while the read announces that + /// it is ready ends the read's session with it: the read returns nothing, exactly as the sign-in then offers + /// nothing and holds no session, and a debug entry says why. The sign-in is free and can read again. + /// + [Fact] + public async Task Prepare_SessionDiscardedWhileItsResultIsAnnounced_ReturnsNoOffer() + { + SignInWorld world = new(); + using CompanionSignIn signIn = world.NewSignIn(); + bool discard = true; + signIn.PropertyChanged += (_, change) => + { + if(discard && string.Equals(change.PropertyName, nameof(CompanionSignIn.State), StringComparison.Ordinal) && signIn.State == CompanionSignInState.Ready) + { + signIn.Discard(); + } + }; + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + + Assert.Null(offer); + Assert.Null(signIn.Offer); + Assert.False(signIn.HasSession); + Assert.True(Assert.Single(world.Sessions).Disposed); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); + Assert.False(signIn.IsBusy); + Assert.Equal("DEBUG The sign-in description was read, and its session was discarded before the read returned, so the read offers nothing.", world.Log.Entries[^1]); + Assert.DoesNotContain(world.Log.Entries, entry => entry.StartsWith("ERROR", StringComparison.Ordinal)); + + discard = false; + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[1].Disposed); + } + + + /// /// Disposing while the server checks a password only cancels. The session is not discarded under the running /// call, which would make the call end with "disposed": it ends with the cancellation, quietly, the session is -- 2.54.0 From c3cf0731b1f572d6b164bbeee97b38c252bf4703 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:46:12 -0600 Subject: [PATCH 06/27] fix(presentation): an inbox failure of an unexpected kind ends each waiting exchange as a reported failure The dispatcher fails every waiting ticket with whatever the inbox failed with, and each exchange catches a fixed list of failures. A failure outside that list therefore left SignInWithBrowserAsync, from every sign-in that was waiting, and ProviderSignOut.CompleteAsync as an exception nobody handles. The real inbox can do that: it throws ArgumentException when the process that sent a callback has already exited (Process.GetProcessById), which any process in the user's session can cause. BrowserCallbackFailure holds the list every exchange reports (IO, invalid data, unauthorized access, Windows error, invalid operation, cancelled). The dispatcher hands tickets the inbox's failure when it is on the list, and otherwise an IOException with fixed text and the failure's type name, never its message. The same is done for a failure to open the inbox, which is thrown to whoever registers. The dialog's SignInFlow has the same hole for its one sign-in. The dispatcher change does not close it, because that flow opens its own inbox, so its wait for the callback now turns an unlisted failure into the same reported one. Its sign-out has the hole too and is left as it is: this round changes that file only for the message of a browser that did not start. Tests, each with ArgumentException, OverflowException and TimeoutException carrying a marked text: two waiting tickets; two waiting sign-ins (the reviewer's probe P4); a waiting sign-out; the dialog's sign-in (P4b); and an inbox that cannot be opened. Each ends as a reported failure, nothing escapes, and the marked text is in no log line, reason, message or bound property. Review of afe7e08, S2. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 11 +++- .../SignIn/BrowserCallbackDispatcher.cs | 29 +++++++--- .../SignIn/BrowserCallbackFailure.cs | 30 ++++++++++ .../SignIn/SignInFlow.Browser.cs | 24 +++++++- .../Fakes/SignInWorld.cs | 22 ++++++++ .../SignIn/BrowserCallbackDispatcherTests.cs | 55 +++++++++++++++++++ .../SignIn/CompanionSignInBrowserTests.cs | 38 +++++++++++++ .../SignIn/ProviderSignOutTests.cs | 25 +++++++++ .../SignIn/SignInFlowBrowserTests.cs | 33 +++++++++++ 9 files changed, 257 insertions(+), 10 deletions(-) create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackFailure.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c4cbb4..f096a90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,10 +12,15 @@ to check: that a default browser is set in Windows Settings under Apps, Default otherwise unchanged. Every release up to 1.2.1 has the sign-in case; the sign-out case was never in a release ([audit](docs/AUDIT-2026-11-10.md), U22). +An unexpected failure of the browser callback inbox no longer leaves the connection dialog's browser sign-in as an +unhandled error (2.0). The inbox gives an argument error when the process that sent a callback has already exited, +which the dialog's flow did not expect. It is now reported as "Browser sign-in not completed", with the kind of +failure as the reason. + Sign-in in the companion, rebuilt for several servers (2.0; not used by the window yet). Three types were added to the presentation assembly for the connection wizard and the per-server Connection page of [ADR-0005](docs/adr/0005-connection-wizard-and-server-tree.md). Nothing the operator sees changes through them in -this build: the connection dialog still runs on the existing flow, whose one change is the entry above. +this build: the connection dialog still runs on the existing flow, whose only changes are the entries above. - `CompanionSignIn` is the part of signing in that needs a session and runs as the signed-in Windows user. It reads the server's sign-in description, signs in by password or through the browser, and returns the session credential @@ -29,7 +34,9 @@ this build: the connection dialog still runs on the existing flow, whose one cha OAuth state it sent and waits for the callback that carries it, so two servers can be signing in at once. A callback that carries no state, more than one, or a state nobody waits for is dropped, and the log says only that one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that waits fails - once and the next registration opens a new inbox. + once and the next registration opens a new inbox. Whatever the inbox fails with, each sign-in or sign-out that + waits ends as a failure it reports: a failure of a kind they do not expect (the inbox gives an argument error when + the process that sent a callback has already exited) reaches them as one that names only its kind. - `ProviderSignOut` is the identity provider's half of a sign-out: it opens the provider's sign-out page and waits up to two minutes for the browser to return with that sign-out's own state. - When Windows cannot start the browser, its failure text names what it could not start, which is the whole sign-in diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index 34ecb8f..af1d18c 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -14,9 +14,12 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// when tickets still wait, a new one is opened. A callback that carries no state, more than one, or a state nobody /// waits for is dropped, and the log says only that one was dropped: nothing of a callback, its state or its code is /// ever logged, and a registered state is held only while its ticket waits. When the inbox itself fails, which -/// includes an inbox that refuses what it received as no callback at all, every waiting ticket fails with that -/// failure and the next registration opens a new inbox. Tickets are registered from the window's thread and -/// callbacks arrive on others, so the waiting set is guarded, and this never continues on a caller's thread. +/// includes an inbox that refuses what it received as no callback at all, every waiting ticket fails and the next +/// registration opens a new inbox. The tickets are given the inbox's failure when it is of a kind every exchange +/// reports, and otherwise one that names only its kind (see ), so whatever an +/// inbox fails with ends each exchange as a failure it reports and never as an exception nobody handles. Tickets +/// are registered from the window's thread and callbacks arrive on others, so the waiting set is guarded, and this +/// never continues on a caller's thread. /// public sealed class BrowserCallbackDispatcher { @@ -42,8 +45,9 @@ public sealed class BrowserCallbackDispatcher /// Registers the state a browser exchange sent and returns the ticket to await. The inbox is open when this /// returns, so the caller opens the browser afterwards and a fast redirect is not lost. A state that is already /// waiting is refused, because two exchanges could not be told apart. When the inbox cannot be opened the failure is - /// thrown to the caller and nothing is registered. The caller disposes the ticket when its exchange ends, however - /// it ends. + /// thrown to the caller and nothing is registered; a failure of a kind the exchanges do not report is thrown as + /// one that names only its kind, as it is for a ticket. The caller disposes the ticket when its exchange ends, + /// however it ends. /// public BrowserCallbackTicket Register(string state) { @@ -61,6 +65,11 @@ public sealed class BrowserCallbackDispatcher { Listen(); } + catch(Exception exception) when(!BrowserCallbackFailure.Listed(exception)) + { + _waiting.Remove(state); + throw BrowserCallbackFailure.Reported(exception); + } catch(Exception) { _waiting.Remove(state); @@ -259,13 +268,19 @@ public sealed class BrowserCallbackDispatcher - /// Fails the tickets a broken inbox left waiting, each once, and logs the kind of failure and how many it ended. The failure's own text is left to each exchange to report, so nothing an inbox put in a message is logged from here. + /// + /// Fails the tickets a broken inbox left waiting, each once, and logs the kind of failure and how many it ended. + /// The tickets get the failure itself when it is of a kind every exchange reports, whose text is then left to + /// each exchange to report, and otherwise one that names only its kind. Nothing an inbox put in a message is + /// logged from here. + /// private void End(BrowserCallbackTicket[] stranded, Exception failure) { _log.Error("The browser callback inbox failed ({Failure}); {Waiting} waiting browser exchange(s) were ended and have to be started again.", failure.GetType().Name, stranded.Length); + Exception reported = BrowserCallbackFailure.Reported(failure); foreach(BrowserCallbackTicket ticket in stranded) { - ticket.Fail(failure); + ticket.Fail(reported); } } } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackFailure.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackFailure.cs new file mode 100644 index 0000000..50022f8 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackFailure.cs @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// What an exchange that waits for a browser callback is told when the callback inbox fails. Each exchange reports a +/// fixed list of failures as "not completed" and lets anything else through, as it would a programming error. The +/// inbox is fed by other processes, so it can fail outside that list: the real one fails with an argument error when +/// the process that sent a callback has already exited, which any process in the user's session can bring about. Such +/// a failure has to end a sign-in as a failure the operator is told about, in every exchange that waits, and not as +/// an exception nobody handles. So a failure outside the list is replaced by one inside it that names only the kind +/// of failure. Its own text is not passed on: nothing is known about what an unexpected failure says. +/// +internal static class BrowserCallbackFailure +{ + /// True for the kinds of inbox failure every exchange reports itself, with the failure's own text: a pipe that broke or was refused, a callback the inbox refused, and a wait that was ended. + internal static bool Listed(Exception failure) + => failure is IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception or InvalidOperationException or OperationCanceledException; + + + + /// The failure to hand to an exchange: the inbox's own when it is of a listed kind, and otherwise one with fixed text and the kind of failure. + internal static Exception Reported(Exception failure) + => Listed(failure) ? failure : new IOException("The browser callback inbox failed (" + failure.GetType().Name + "), so no callback could be received. Try again."); +} diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs index 4207a0f..daf855c 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.Browser.cs @@ -141,6 +141,7 @@ public sealed partial class SignInFlow /// cannot be started is reported by the kind of failure only, because Windows' own text for it names the whole address /// with its state (see ). A callback that is /// malformed or too large is refused by the inbox as invalid data, which the caller reports like any other failed exchange. + /// An inbox failure of a kind the caller does not report is turned into one it does (see ). /// The token is looked at again after each wait, so a browser is not opened and a login is not completed for a wait /// that has already ended. /// @@ -152,7 +153,7 @@ public sealed partial class SignInFlow cancellationToken.ThrowIfCancellationRequested(); _log.Info("Opening the identity provider's sign-in page in the default browser (" + QqqOrigin.ShownAuthority(authorization) + ")."); BrowserLaunch.Open(_browser, authorization); - Uri callback = await inbox.ReceiveAsync(cancellationToken); + Uri callback = await ReceiveCallbackAsync(inbox, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _callbackArrived = true; _log.Info("Browser callback received; completing the sign-in."); @@ -161,6 +162,27 @@ public sealed partial class SignInFlow + /// + /// Waits for the callback. The inbox is fed by other processes and can fail in ways the exchange does not list as + /// failures to report: the real one fails with an argument error when the process that sent a callback has already + /// exited. Such a failure is replaced by one the exchange reports, with fixed text and the kind of failure (see + /// ), so it ends the sign-in as "not completed" instead of leaving the flow as an + /// exception nobody handles. + /// + private static async Task ReceiveCallbackAsync(IBrowserCallbackInbox inbox, CancellationToken cancellationToken) + { + try + { + return await inbox.ReceiveAsync(cancellationToken); + } + catch(Exception exception) when(!BrowserCallbackFailure.Listed(exception)) + { + throw BrowserCallbackFailure.Reported(exception); + } + } + + + /// /// Handles a hand-over that never left this computer; every other outcome was already reported by the hand-over. When /// the service did not accept a connection in time, nothing was handed over, so the attempt ends like a cancelled diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs index 55717c3..0a70ac1 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs @@ -30,6 +30,9 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr /// The callback the fake installation has registered. internal const string Callback = "io.qrun.qqq-print-agent:/oauth/callback"; + /// The marked text of an inbox failure of a kind no exchange lists, so a test can show that nothing of it is logged or shown. + internal const string UnlistedFailureText = "synthetic-inbox-failure-text"; + private volatile TaskCompletionSource? _awaitedInbox; @@ -152,6 +155,25 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr + /// + /// An inbox failure of a kind no exchange lists as one to report, by the name of its type: the argument error the + /// real inbox gives when the process that sent a callback has already exited, an arithmetic overflow, or a + /// time-out. Its text is the marked one. + /// + internal static Exception UnlistedInboxFailure(string kind) => kind switch + { + nameof(ArgumentException) => new ArgumentException(UnlistedFailureText, nameof(kind)), + nameof(OverflowException) => new OverflowException(UnlistedFailureText), + _ => new TimeoutException(UnlistedFailureText), + }; + + + + /// What an exchange is told, and reports, when the inbox failed in such a way: fixed text and the kind of failure. + internal static string InboxFailedReport(string kind) => "The browser callback inbox failed (" + kind + "), so no callback could be received. Try again."; + + + /// A new sign-in over this world. internal CompanionSignIn NewSignIn() => new(this, this, this, Dispatcher, Log, Time); diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index fdfe00e..3108bd2 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -238,6 +238,61 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// The inbox is fed by other processes and can fail in a way no exchange lists as a failure to report: the real + /// one gives an argument error when the process that sent a callback has already exited. Left as it is, such a + /// failure would leave every waiting exchange as an exception nobody handles. Both waiting tickets get one + /// failure of a kind every exchange reports instead: its text is fixed and names the kind of failure, the + /// original is not attached to it, and nothing of the original's own text reaches the log. + /// + [Theory] + [InlineData(nameof(ArgumentException))] + [InlineData(nameof(OverflowException))] + [InlineData(nameof(TimeoutException))] + public async Task Dispatcher_InboxFailsInAWayNoExchangeLists_EveryWaiterGetsAFailureItReports(string kind) + { + SignInWorld world = new(); + using BrowserCallbackTicket first = world.Dispatcher.Register("synthetic-state-a"); + using BrowserCallbackTicket second = world.Dispatcher.Register("synthetic-state-b"); + + world.Inboxes[0].Fail(SignInWorld.UnlistedInboxFailure(kind)); + + IOException reported = await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(first.Callback)); + Assert.Same(reported, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(second.Callback))); + Assert.Equal(SignInWorld.InboxFailedReport(kind), reported.Message); + Assert.Null(reported.InnerException); + Assert.DoesNotContain(SignInWorld.UnlistedFailureText, reported.ToString(), StringComparison.Ordinal); + Assert.True(world.Inboxes[0].Disposed); + Assert.Equal([InboxOpen, $"ERROR The browser callback inbox failed ({kind}); 2 waiting browser exchange(s) were ended and have to be started again."], world.Log.Entries); + } + + + + /// + /// The same holds when the inbox cannot be opened: a failure of a kind no exchange lists is thrown to whoever + /// registered as one that names only its kind, nothing of its text is kept, and nothing is left registered. + /// + [Fact] + public async Task InboxThatCannotBeOpenedInAWayNoExchangeLists_FailsTheRegistrationWithAFailureItReports() + { + SignInWorld world = new() { InboxFailure = SignInWorld.UnlistedInboxFailure(nameof(ArgumentException)) }; + + IOException reported = Assert.Throws(() => world.Dispatcher.Register("synthetic-state-a")); + + Assert.Equal(SignInWorld.InboxFailedReport(nameof(ArgumentException)), reported.Message); + Assert.Null(reported.InnerException); + Assert.DoesNotContain(SignInWorld.UnlistedFailureText, reported.ToString(), StringComparison.Ordinal); + Assert.Empty(world.Inboxes); + Assert.Empty(world.Log.Entries); + + world.InboxFailure = null; + using BrowserCallbackTicket ticket = world.Dispatcher.Register("synthetic-state-a"); + Assert.Single(world.Inboxes).Deliver(CallbackFor("synthetic-state-a")); + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(ticket.Callback)); + } + + + /// When the inbox cannot be opened for the first ticket, the failure goes to whoever registered and nothing is left registered: the same state can be registered again once the inbox can be opened. [Fact] public async Task InboxThatCannotBeOpened_FailsTheRegistration_AndLeavesNothingBehind() diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index 440ab24..dfd9b04 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -309,6 +309,44 @@ public sealed class CompanionSignInBrowserTests + /// + /// Two servers are signing in through the browser when the inbox fails in a way no sign-in lists as a failure to + /// report: the argument error the real inbox gives when the process that sent a callback has already exited, an + /// overflow, a time-out. Nothing escapes either sign-in. Each ends as "not completed" with a reason that names + /// the kind of failure in fixed text, keeps its session and is free again, and nothing of the failure's own text + /// reaches the log or a property a view binds to. + /// + [Theory] + [InlineData(nameof(ArgumentException))] + [InlineData(nameof(OverflowException))] + [InlineData(nameof(TimeoutException))] + public async Task Browser_InboxFailsInAWayNoSignInLists_EveryWaitingSignInReportsItAndNothingEscapes(string kind) + { + SignInWorld world = new(); + using CompanionSignIn first = await world.BrowserReadyAsync(); + using CompanionSignIn second = await world.BrowserReadyAsync(SignInWorld.OtherServer); + Task firstRunning = first.SignInWithBrowserAsync(); + Task secondRunning = second.SignInWithBrowserAsync(); + + Assert.Single(world.Inboxes).Fail(SignInWorld.UnlistedInboxFailure(kind)); + + Assert.Null(await SignInWorld.EndsAsync(firstRunning)); + Assert.Null(await SignInWorld.EndsAsync(secondRunning)); + Assert.All([first, second], signIn => + { + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.Equal(SignInWorld.InboxFailedReport(kind), signIn.Failure); + Assert.True(signIn.HasSession); + Assert.False(signIn.IsBusy); + Assert.DoesNotContain(BrowserStartFailure.Bound(signIn), text => text is not null && text.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal)); + }); + Assert.Equal(2, world.Log.Entries.Count(entry => string.Equals(entry, "ERROR Browser sign-in not completed: IOException: " + SignInWorld.InboxFailedReport(kind), StringComparison.Ordinal))); + Assert.Contains($"ERROR The browser callback inbox failed ({kind}); 2 waiting browser exchange(s) were ended and have to be started again.", world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal) || Secret(entry)); + } + + + /// /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole sign-in /// address, with the attempt's state, nonce and code challenge. None of that is logged or kept. The reason the diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs index c606abe..8f1bc87 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -142,6 +142,31 @@ public sealed class ProviderSignOutTests + /// + /// The inbox fails, while the sign-out waits, in a way the sign-out does not list as a failure to report: the + /// argument error the real inbox gives when the process that sent a callback has already exited, an overflow, a + /// time-out. Nothing escapes: the sign-out is not confirmed, and the log names the kind of failure in fixed text + /// and holds nothing of the failure's own text. + /// + [Theory] + [InlineData(nameof(ArgumentException))] + [InlineData(nameof(OverflowException))] + [InlineData(nameof(TimeoutException))] + public async Task InboxFailsInAWayTheSignOutDoesNotList_IsNotConfirmedAndNothingEscapes(string kind) + { + SignInWorld world = new(); + + Task running = Over(world).CompleteAsync(Logout()); + Assert.Single(world.Inboxes).Fail(SignInWorld.UnlistedInboxFailure(kind)); + + Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal("WARN Identity provider sign-out was not confirmed: IOException: " + SignInWorld.InboxFailedReport(kind), world.Log.Entries[^1]); + Assert.True(world.Inboxes[0].Disposed); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal) || entry.Contains(Hint, StringComparison.Ordinal) || entry.Contains(State, StringComparison.Ordinal)); + } + + + /// /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole /// end-session address, with the provider's ID token hint and this sign-out's state. The sign-out is reported as diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs index 2fb3b92..5c8779c 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowBrowserTests.cs @@ -362,6 +362,39 @@ public sealed class SignInFlowBrowserTests + /// + /// The inbox fails, while the dialog's sign-in waits, in a way the flow does not list as a failure to report: the + /// argument error the real inbox gives when the process that sent a callback has already exited, an overflow, a + /// time-out. It does not escape the flow: the sign-in is reported as not completed with a reason that names the + /// kind of failure in fixed text, the session stays for an explicit retry, and nothing of the failure's own text + /// is logged or shown. + /// + [Theory] + [InlineData(nameof(ArgumentException))] + [InlineData(nameof(OverflowException))] + [InlineData(nameof(TimeoutException))] + public async Task InboxFailsInAWayTheFlowDoesNotList_IsReportedByItsKindAndDoesNotEscape(string kind) + { + SignInFixture fixture = await DiscoveredAsync(); + string report = SignInWorld.InboxFailedReport(kind); + + Task running = fixture.Flow.SignInWithBrowserAsync(PairingChoice.KeepCurrent); + fixture.Inboxes[0].Fail(SignInWorld.UnlistedInboxFailure(kind)); + + Assert.True(await SignInFixture.EndsAsync(running)); + Assert.Equal(new FeedbackMessage("Browser sign-in not completed", "No validated account session was received. Reason: " + report + " Check the server's advertised native sign-in grant and installed callback configuration, then try again explicitly. The activity log has the full detail.", FeedbackSeverity.Warning), fixture.Shown[^1]); + Assert.Contains("ERROR Browser sign-in not completed: IOException: " + report, fixture.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(fixture.Log.Entries, entry => entry.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal)); + Assert.DoesNotContain(fixture.Shown, message => message.Message.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal)); + Assert.Empty(fixture.Requests); + Assert.Equal(SignInStage.Ready, fixture.Flow.Stage); + Assert.True(fixture.Flow.HasSession); + Assert.False(fixture.Flow.IsBusy); + Assert.True(fixture.Inboxes[0].Disposed); + } + + + /// /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole sign-in /// address, with the attempt's state, nonce and code challenge. None of that is logged or shown. The operator is -- 2.54.0 From 4729364e84152cd96d6116f727ed115c37abb182 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:47:15 -0600 Subject: [PATCH 07/27] test(presentation): pin that a callback's state is matched exactly Nothing in the suite failed when the dispatcher's waiting set was keyed without regard to case, or when a ticket was completed for a callback whose state is the beginning of its own. The head matches exactly; the tests did not say so. The dropped-callback theory gains four rows against a ticket waiting for "synthetic-state-x": the same letters in upper case, the state without its last character, the state with one more, and the state followed by a space. Each must be dropped and leave the ticket waiting. Review of afe7e08, S3. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcherTests.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 3108bd2..956f8b4 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -123,9 +123,11 @@ public sealed class BrowserCallbackDispatcherTests /// /// A callback that cannot be given to anyone is dropped: one with no state, with the state twice, with an empty - /// state, with a parameter whose name only looks like "state", or with a state nobody waits for. The ticket that - /// waits is untouched, a new inbox is opened for it, and the log holds the fixed sentence and nothing of the - /// callback. The ticket's own callback, sent to the new inbox, still reaches it. + /// state, with a parameter whose name only looks like "state", or with a state nobody waits for. A state is + /// somebody's only when it is exactly the one that was registered: the same letters in another case, the + /// beginning of it, more than it, or it with a space after it are all nobody's. The ticket that waits is + /// untouched, a new inbox is opened for it, and the log holds the fixed sentence and nothing of the callback. + /// The ticket's own callback, sent to the new inbox, still reaches it. /// [Theory] [InlineData("?code=synthetic-code")] @@ -134,6 +136,10 @@ public sealed class BrowserCallbackDispatcherTests [InlineData("?STATE=synthetic-state-x")] [InlineData("?state")] [InlineData("?state=synthetic-state-unknown&code=synthetic-code")] + [InlineData("?code=synthetic-code&state=SYNTHETIC-STATE-X")] + [InlineData("?code=synthetic-code&state=synthetic-state-")] + [InlineData("?code=synthetic-code&state=synthetic-state-xy")] + [InlineData("?code=synthetic-code&state=synthetic-state-x%20")] public async Task Dispatcher_CallbackWithNoStateOrTwo_IsDropped_AndNotLogged(string query) { SignInWorld world = new(); -- 2.54.0 From 7c4e851ee58b6110a6c5f6f328a4503452b9bfa8 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:48:50 -0600 Subject: [PATCH 08/27] docs(audit): U22 and the changelog say which tags have the sign-out case U22 said the sign-out case "is in no tag", and the changelog that it "was never in a release". The tag snapshot-2.0.0-rc.1 (commit 6f0237d), which docs/SESSION-STATE.md records as a Gitea prerelease published on 2026-11-10 as a development snapshot and not installed anywhere, has both cases unguarded (SignInFlow.Browser.cs:152, SignInFlow.SignOut.cs:114). "Every tag from v0.2.0-rc.1 to v1.2.1" also left that snapshot out, and the changelog's "every release up to 1.2.1" included 0.1.x, which has no browser sign-in. Checked with git tag --contains 2c1c5f1 and 5d4b7f4 and by reading the browser start at every tag: - sign-in case: the eleven version tags v0.2.0-rc.1 to v1.2.1, and snapshot-2.0.0-rc.1; not in the four 0.1.x tags. - sign-out case: snapshot-2.0.0-rc.1 only; in no version tag. - release/1.2.2, unreleased and in no tag: both. - closed for 2.0 builds after the snapshot; the snapshot stays as published. Both documents now say exactly that. Review of afe7e08, S4. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 +++- docs/AUDIT-2026-11-10.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f096a90..3426564 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,9 @@ whole sign-in address, with that attempt's state, nonce and code challenge. When for the identity provider's sign-out, the log entry named the provider's sign-out address the same way, with its ID token hint. Both now say only that the default browser could not be opened, with the Windows error number, and what to check: that a default browser is set in Windows Settings under Apps, Default apps. Sign-in and sign-out are -otherwise unchanged. Every release up to 1.2.1 has the sign-in case; the sign-out case was never in a release +otherwise unchanged. Every release from 0.2.0-rc.1 to 1.2.1 has the sign-in case (0.1.x has no browser sign-in). The +sign-out case is in no release. Both cases are in the development snapshot `snapshot-2.0.0-rc.1`, which was not +installed anywhere, and on the unreleased `release/1.2.2` branch; 2.0 builds after that snapshot have neither ([audit](docs/AUDIT-2026-11-10.md), U22). An unexpected failure of the browser callback inbox no longer leaves the connection dialog's browser sign-in as an diff --git a/docs/AUDIT-2026-11-10.md b/docs/AUDIT-2026-11-10.md index d241fe3..594b5ce 100644 --- a/docs/AUDIT-2026-11-10.md +++ b/docs/AUDIT-2026-11-10.md @@ -273,7 +273,7 @@ Found while building the companion's sign-in for the connection wizard (2026-11- | ID | Severity | Finding | Status | | --- | --- | --- | --- | -| U22 | Not rated | A browser that cannot be started puts the address it was asked to open into the companion's log and, at sign-in, into the dialog. The companion starts the browser through the Windows shell, and when that fails .NET's failure text names what could not be started: "An error occurred trying to start process '' ..." (seen on .NET 10.0.14 with a shell start of a file that does not exist; no browser was involved). At a browser sign-in the address is the provider's authorization address, with that attempt's `state`, `nonce` and `code_challenge`; the text was logged at error level and shown as the reason of "Browser sign-in not completed", and the whole failure was logged again as debug detail (`SignInFlow.Browser.cs:98-103`, started at `:152`, read at `ebea861`). At a provider sign-out the address is the provider's end-session address, with the `id_token_hint` (the provider's ID token) and the sign-out's `state`; the text was logged as a warning and not shown (`SignInFlow.SignOut.cs:121-125`, started at `:114`). The log file's own redaction removes the value of `state` from such a line in 2.0 and nothing else of it; `id_token_hint=` passes unchanged, which is the gap W40 records, and W40's note that no log line can carry it did not hold for this one. The dialog's message is not redacted at all. It takes a failed browser start to happen: no default browser, or a broken handler for web addresses. Releases: the sign-in case is in every tag from `v0.2.0-rc.1` to `v1.2.1` (introduced by `2c1c5f1`, 2026-10-31; in `v1.2.1` the start is `src/Qqq.PrintAgent/MainWindow.Authentication.cs:339` and the catch that logs and shows the text is at `:294-298`), and 1.2.1's log has no rule for `state`, so installed 1.2.x systems write and show the address whole. The sign-out case came with `5d4b7f4` (2026-11-09), is in no tag, and is on the unreleased `release/1.2.2` branch (`MainWindow.Authentication.cs:303`, `:311`) together with the sign-in case (`:395`, `:354`). Read from the code in each case, not run | Closed for 2.0 by the change that adds this row: every browser start in the presentation assembly goes through `BrowserLaunch`, which replaces the failure with fixed text (that the default browser could not be opened, the kind of failure or the Windows error number, and what to check), in the dialog's flow and in the new `CompanionSignIn` and `ProviderSignOut`. Open for 1.2.x: `release/1.2.2` still has both cases, and 1.2.1 as installed has the sign-in case | +| U22 | Not rated | A browser that cannot be started puts the address it was asked to open into the companion's log and, at sign-in, into the dialog. The companion starts the browser through the Windows shell, and when that fails .NET's failure text names what could not be started: "An error occurred trying to start process '' ..." (seen on .NET 10.0.14 with a shell start of a file that does not exist; no browser was involved). At a browser sign-in the address is the provider's authorization address, with that attempt's `state`, `nonce` and `code_challenge`; the text was logged at error level and shown as the reason of "Browser sign-in not completed", and the whole failure was logged again as debug detail (`SignInFlow.Browser.cs:98-103`, started at `:152`, read at `ebea861`). At a provider sign-out the address is the provider's end-session address, with the `id_token_hint` (the provider's ID token) and the sign-out's `state`; the text was logged as a warning and not shown (`SignInFlow.SignOut.cs:121-125`, started at `:114`). The log file's own redaction removes the value of `state` from such a line in 2.0 and nothing else of it; `id_token_hint=` passes unchanged, which is the gap W40 records, and W40's note that no log line can carry it did not hold for this one. The dialog's message is not redacted at all. It takes a failed browser start to happen: no default browser, or a broken handler for web addresses. Tags (from `git tag --contains` and the code at each tag): the sign-in case is in the eleven version tags from `v0.2.0-rc.1` to `v1.2.1` and in `snapshot-2.0.0-rc.1`; the four 0.1.x tags have no browser sign-in. It was introduced by `2c1c5f1` (2026-10-31); in `v1.2.1` the start is `src/Qqq.PrintAgent/MainWindow.Authentication.cs:339` and the catch that logs and shows the text is at `:294-298`, and 1.2.1's log has no rule for `state`, so installed 1.2.x systems write and show the address whole. The sign-out case came with `5d4b7f4` (2026-11-09) and is in one tag, `snapshot-2.0.0-rc.1`, and in no version tag. That snapshot (commit `6f0237d`) has both cases unguarded (`SignInFlow.Browser.cs:152`, `SignInFlow.SignOut.cs:114`); `docs/SESSION-STATE.md` records it as a Gitea prerelease published on 2026-11-10 as a development snapshot and not installed anywhere. The unreleased `release/1.2.2` branch, which is in no tag, has both cases too (`MainWindow.Authentication.cs:303`, `:311` for the sign-out; `:395`, `:354` for the sign-in). Read from the code in each case, not run | Closed for 2.0 builds after `snapshot-2.0.0-rc.1` by the change that adds this row: every browser start in the presentation assembly goes through `BrowserLaunch`, which replaces the failure with fixed text (that the default browser could not be opened, the kind of failure or the Windows error number, and what to check), in the dialog's flow and in the new `CompanionSignIn` and `ProviderSignOut`. The snapshot itself has both cases and stays as published. Open for 1.2.x: `release/1.2.2` still has both cases, and 1.2.1 as installed has the sign-in case | ### Repository -- 2.54.0 From df45fde261dc8f9591418ccb425730401e91e093 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:51:52 -0600 Subject: [PATCH 09/27] fix(presentation): a browser sign-in whose wait ends after the callback was handed over discards the session When Cancel or the three minute limit landed as the session finished completing, the step ended as cancelled or timed out, no credential was taken, and the session was kept, signed in on the server. Nothing could export from it, but a sign-in reported as cancelled should not leave a signed-in session behind. CompanionSignIn now notes the moment it hands the callback to the session. An attempt whose wait ends after that (the operator cancelled, the limit ran out, or the caller stopped waiting, which had the same residue under the state "ready") discards the session, withdraws its offer before the ending is announced, and logs why. An attempt whose wait ends before the hand-over gave the session nothing and keeps it, as before, and so does an attempt that failed, whenever it failed. The note is forgotten when the attempt ends, so it cannot reach a later operation. The type's summary, SignInWithBrowserAsync, the two states and the changelog now say exactly when a cancelled or timed-out attempt keeps its session and when it does not. Tests: the wait ends at the moment the session completes, by Cancel, by the limit and by the caller (the reviewer's probe P9 as a theory): no credential, the session discarded, the offer withdrawn first, a new read works. Cancel while the session completes discards too. A wait that ends before the hand-over keeps the session (asserted in the test added for B1). A failed completion keeps the session, and a later read that is stopped is not taken for one whose session has to go. Review of afe7e08, nit 1. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 6 +- .../SignIn/CompanionSignIn.Browser.cs | 45 ++++++++- .../SignIn/CompanionSignIn.cs | 9 +- .../SignIn/CompanionSignInState.cs | 4 +- .../SignIn/CompanionSignInBrowserTests.cs | 92 +++++++++++++++++-- 5 files changed, 137 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3426564..dc22e9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,8 +30,10 @@ this build: the connection dialog still runs on the existing flow, whose only ch read under is given with each read. It offers only the methods that the service's check and its own read both found, and logs a difference. It stops when the description names another sign-in provider than the check reported. When this Windows account refuses a certificate the service accepted, or the sign-in provider's - certificate, it says which of the two it was and keeps the refused certificate for the wizard to show. A cancelled - or timed-out browser sign-in keeps its session, so the next attempt needs no new read. + certificate, it says which of the two it was and keeps the refused certificate for the wizard to show. A browser + sign-in that is cancelled or times out before its callback has been handed to the session keeps the session, so + the next attempt needs no new read. Once the callback has been handed over the server may complete the sign-in, + so an attempt that is cancelled, times out or is stopped after that discards the session. - `BrowserCallbackDispatcher` owns the one browser callback inbox. A sign-in or a provider sign-out registers the OAuth state it sent and waits for the callback that carries it, so two servers can be signing in at once. A callback that carries no state, more than one, or a state nobody waits for is dropped, and the log says only that diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs index 87e4375..b2a136b 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -13,6 +13,17 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// cancellation, and what is recorded when the browser never comes back. The callback is awaited through the one /// , by the state this attempt sent, so another server's sign-in can be waiting /// at the same time and a callback that is not this attempt's never reaches it. +/// +/// When an attempt keeps its session. An attempt that failed keeps it, whatever the failure and whenever it +/// happened. An attempt whose wait ended (the operator cancelled, the three minutes ran out, or the caller stopped +/// waiting) keeps it only when that happened before the callback was handed to the session: the session was given +/// nothing then, and the next attempt can use it without a new read. From the moment the callback is handed over, +/// the server may complete the sign-in on that session whatever happens here. An attempt that then ends without a +/// result discards the session, so that nothing here holds a signed-in session behind an attempt that was reported +/// as cancelled, and the next attempt needs a new read: is false and +/// is null, while the state still says how the attempt ended (cancelled, timed out, or not prepared for a caller +/// that stopped waiting). +/// /// public sealed partial class CompanionSignIn { @@ -21,6 +32,7 @@ public sealed partial class CompanionSignIn private static readonly TimeSpan s_traceWindow = TimeSpan.FromMinutes(10); private CancellationTokenSource? _browserCancel; + private bool _handedOver; @@ -28,9 +40,11 @@ public sealed partial class CompanionSignIn /// Signs in through the browser, with a three minute limit, and returns the session credential. Nothing happens /// without a session that offers the browser. The redirect address is the one this application's installer /// registered, and it is used only when the server also lists it, so a server cannot steer the callback elsewhere. - /// A cancelled, timed-out or failed attempt is reported by state and keeps the session, so the operator can try + /// A cancelled, timed-out or failed attempt is reported by state. A failed attempt keeps the session, and so does + /// one that was cancelled or timed out before its callback was handed to the session, so the operator can try /// again: a late callback of the abandoned attempt carries a state nobody waits for and is dropped by the - /// dispatcher. It returns null when no credential was obtained. + /// dispatcher. One that was cancelled or timed out after the callback was handed over discards the session (the + /// type's summary says when a session is kept). It returns null when no credential was obtained. /// public async Task SignInWithBrowserAsync(CancellationToken cancellationToken = default) { @@ -52,8 +66,9 @@ public sealed partial class CompanionSignIn /// The exchange under its limit, and what its ending means. The Cancel button reaches the exchange through a /// field, which is cleared before the exchange's cancellation sources are released, so a Cancel that arrives while /// a failed exchange is still being reported finds nothing to cancel. An exchange that the operator cancelled or - /// that ran out of time is said to be exactly that. A wait that the caller or disposal ended is left to the - /// runner. Announcing the result is outside the protected part, as it is for a password sign-in. + /// that ran out of time is said to be exactly that, and loses its session when the callback had already been + /// handed to it. A wait that the caller or disposal ended is left to the runner, which does the same as it + /// releases the sign-in. Announcing the result is outside the protected part, as it is for a password sign-in. /// private async Task TryBrowserSignInAsync(ISignInSession session, CancellationToken token) { @@ -62,6 +77,7 @@ public sealed partial class CompanionSignIn using CancellationTokenSource cancel = new(); using var exchange = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancel.Token, token); QqqSessionCredential credential; + _handedOver = false; _browserCancel = cancel; try { @@ -73,6 +89,7 @@ public sealed partial class CompanionSignIn { _log.Info(cancel.IsCancellationRequested ? "Browser sign-in to {Server} was cancelled by the operator." : "Browser sign-in to {Server} was given up after the three minute limit.", QqqOrigin.ShownAuthority(session.Origin)); ReportCallbackTrace(); + DropHandedOverSession(); Settle(cancel.IsCancellationRequested ? CompanionSignInState.BrowserCanceled : CompanionSignInState.BrowserTimedOut); return null; } @@ -120,11 +137,31 @@ public sealed partial class CompanionSignIn Uri callback = await ticket.Callback.WaitAsync(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _log.Info("Browser callback received; completing the sign-in."); + _handedOver = true; await session.CompleteBrowserSignInAsync(callback, cancellationToken); } + /// + /// Discards the session when the browser attempt that is ending had handed its callback to it. The server may + /// have completed that sign-in, so a session kept here could be signed in behind an attempt that was reported as + /// cancelled, timed out or stopped. An attempt that ended before the hand-over gave the session nothing, and + /// keeps it. + /// + private void DropHandedOverSession() + { + if(!_handedOver) + { + return; + } + _handedOver = false; + _log.Info("The browser sign-in ended without a result after its callback had been handed to the session, so the session is discarded: the server may have signed it in, and nothing here waits for that. The next attempt reads the sign-in description again."); + DropSession(); + } + + + /// /// Copies the protocol handler's recent trace into the activity log, or states that the browser never launched the /// handler at all, so a hand-off that stops outside the companion is still visible in one place. The handler diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs index 318d588..373ebf2 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -396,9 +396,10 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable /// Releases the sign-in after an operation. A sign-in that was disposed, or whose session was asked to be /// discarded, while the operation ran discards the session here, now that no call is using it. An operation that /// ended without an outcome of its own (its caller stopped waiting, or it threw something unexpected) leaves the - /// state that matches what is held. The state is settled first and the sign-in released after it, so a subscriber - /// that starts the next operation when the sign-in becomes free does not have its state overwritten, and the - /// release happens even when a subscriber throws. + /// state that matches what is held; when it was a browser sign-in that had already handed its callback to the + /// session, the session is discarded first, as it is for one the operator cancelled. The state is settled first + /// and the sign-in released after it, so a subscriber that starts the next operation when the sign-in becomes + /// free does not have its state overwritten, and the release happens even when a subscriber throws. /// private void End(CancellationTokenSource? wait) { @@ -413,11 +414,13 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable } else if(_state is CompanionSignInState.Preparing or CompanionSignInState.SigningIn or CompanionSignInState.WaitingForBrowser) { + DropHandedOverSession(); Settle(_session is null ? CompanionSignInState.NotPrepared : CompanionSignInState.Ready); } } finally { + _handedOver = false; wait?.Dispose(); _operating = false; OnPropertyChanged(nameof(IsBusy)); diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs index 67cace9..645628e 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignInState.cs @@ -45,10 +45,10 @@ public enum CompanionSignInState /// The password sign-in was not completed; gives the reason, which never says which part was wrong. The session is kept for another attempt. PasswordFailed, - /// The operator cancelled the browser sign-in. The session is kept for another attempt. + /// The operator cancelled the browser sign-in. The session is kept for another attempt when the callback had not yet been handed to it, and discarded otherwise. BrowserCanceled, - /// The browser sign-in was given up after its time limit. The session is kept for another attempt. + /// The browser sign-in was given up after its time limit. The session is kept for another attempt when the callback had not yet been handed to it, and discarded otherwise. BrowserTimedOut, /// The browser sign-in was not completed; gives the reason. The session is kept for another attempt. diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index dfd9b04..6aef1be 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -14,6 +14,7 @@ namespace Qqq.PrintAgent.Presentation.Tests.SignIn; public sealed class CompanionSignInBrowserTests { private const string Requested = "INFO Browser sign-in requested for print.example.com; this application's callback is io.qrun.qqq-print-agent:/oauth/callback."; + private const string Discarded = "INFO The browser sign-in ended without a result after its callback had been handed to the session, so the session is discarded: the server may have signed it in, and nothing here waits for that. The next attempt reads the sign-in description again."; private const string NeverLaunched = "WARN The browser never launched the sign-in protocol handler in the last 10 minutes (no entries in trace/auth-callback.log). Either the identity provider did not redirect to io.qrun.qqq-print-agent:/oauth/callback (check the provider's allowed redirect URIs and any error page it showed), or the browser blocked opening the QQQ Print Agent sign-in link."; @@ -441,27 +442,63 @@ public sealed class CompanionSignInBrowserTests - /// When the operator cancels at the very moment the session completes the sign-in, the wait has ended: no credential is taken, and the attempt ends as cancelled. - [Fact] - public async Task Browser_CompletedAtTheMomentItIsCancelled_TakesNoCredential() + /// + /// The wait ends at the very moment the session completes the sign-in: the operator cancels, the three minutes + /// run out, or the caller stops waiting. No credential is taken, and the attempt ends as what ended it. The + /// session, though, was handed the callback and is signed in on the server by now, so it is not kept behind an + /// attempt that was reported as cancelled: it is discarded, what it offered is withdrawn before the ending is + /// announced, the log says why, and a sign-in then needs a new read, which works. + /// + [Theory] + [InlineData("cancel", CompanionSignInState.BrowserCanceled)] + [InlineData("limit", CompanionSignInState.BrowserTimedOut)] + [InlineData("caller", CompanionSignInState.NotPrepared)] + public async Task Browser_WaitEndsAfterTheCallbackWasHandedOver_TakesNoCredentialAndDiscardsTheSession(string by, CompanionSignInState ending) { + using CancellationTokenSource caller = new(); SignInWorld world = new(); using CompanionSignIn signIn = await world.BrowserReadyAsync(); FakeSession session = world.Sessions[0]; session.BeforeAnswer = () => { - if(session.Callback is not null) + if(session.Callback is null) { - signIn.CancelBrowserSignIn(); + return; + } + switch(by) + { + case "cancel": + signIn.CancelBrowserSignIn(); + break; + case "limit": + world.Time.Advance(CompanionSignIn.BrowserSignInLimit); + break; + default: + caller.Cancel(); + break; } }; + List changes = SignInWorld.Watch(signIn); - Task running = signIn.SignInWithBrowserAsync(); + Task running = signIn.SignInWithBrowserAsync(caller.Token); world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); Assert.Null(await SignInWorld.EndsAsync(running)); - Assert.Equal(CompanionSignInState.BrowserCanceled, signIn.State); + Assert.Equal(ending, signIn.State); Assert.NotNull(session.Callback); + Assert.NotNull(session.ExportCredential()); + Assert.True(session.Disposed); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.False(signIn.IsBusy); + Assert.Equal(["IsBusy=True", "State=WaitingForBrowser", "Offer=null", "HasSession=False", "State=" + ending, "IsBusy=False"], changes); + Assert.Single(world.Log.Entries, entry => string.Equals(entry, Discarded, StringComparison.Ordinal)); + Assert.DoesNotContain(world.Log.Entries, entry => entry.StartsWith("ERROR", StringComparison.Ordinal) || Secret(entry)); + Assert.Null(await signIn.SignInWithBrowserAsync()); + + Assert.NotNull(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.BrowserCheck, QqqCertificateExceptionOrigins.None)); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[1].Disposed); } @@ -509,18 +546,54 @@ public sealed class CompanionSignInBrowserTests Assert.DoesNotContain("INFO Browser callback received; completing the sign-in.", world.Log.Entries, StringComparer.Ordinal); Assert.Equal(ending, signIn.State); Assert.True(signIn.HasSession); + Assert.Equal(new SignInOffer(false, true), signIn.Offer); Assert.False(session.Disposed); Assert.False(signIn.IsBusy); Assert.Single(world.Opened); + Assert.DoesNotContain(Discarded, world.Log.Entries, StringComparer.Ordinal); Assert.DoesNotContain(world.Log.Entries, Secret); } + /// + /// An attempt that failed keeps its session even when the callback had been handed over: here the server refuses + /// the completion. That the callback was handed over is forgotten when the attempt ends, so a later operation + /// that is stopped is not taken for a browser sign-in whose session has to go: a read whose caller had already + /// stopped waiting leaves the session where it was and logs nothing about discarding it. + /// + [Fact] + public async Task Browser_FailedAfterTheCallbackWasHandedOver_KeepsTheSession_AlsoThroughALaterStoppedRead() + { + using CancellationTokenSource caller = new(); + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + FakeSession session = world.Sessions[0]; + session.CompleteFailure = new QqqSessionException(QqqSessionException.FailureKind.InvalidResponse, "The server's answer was not usable."); + Task running = signIn.SignInWithBrowserAsync(); + world.Inboxes[0].Deliver(session.CallbackForLatestAttempt); + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(CompanionSignInState.BrowserFailed, signIn.State); + Assert.NotNull(session.Callback); + Assert.True(signIn.HasSession); + + await caller.CancelAsync(); + Assert.Null(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.BrowserCheck, QqqCertificateExceptionOrigins.None, caller.Token)); + + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.False(session.Disposed); + Assert.Single(world.Sessions); + Assert.DoesNotContain(Discarded, world.Log.Entries, StringComparer.Ordinal); + } + + + /// /// The session is asked to complete with the exchange's own token, not with one that never ends: while the session /// is completing, the token it was given is still live, and Cancel ends it, so the completion stops with the - /// attempt instead of running on behind an attempt that was reported as cancelled. + /// attempt instead of running on behind an attempt that was reported as cancelled. The session had been handed + /// the callback by then, so it is discarded with the attempt. /// [Fact] public async Task Browser_CancelledWhileTheSessionCompletes_EndsTheCompletionToo() @@ -540,6 +613,9 @@ public sealed class CompanionSignInBrowserTests Assert.Null(await SignInWorld.EndsAsync(running)); Assert.Equal(CompanionSignInState.BrowserCanceled, signIn.State); Assert.False(signIn.IsBusy); + Assert.False(signIn.HasSession); + Assert.True(session.Disposed); + Assert.Contains(Discarded, world.Log.Entries, StringComparer.Ordinal); } -- 2.54.0 From 8669430dc2fc40c2dab93501c3a8eac648c0a73c Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:57:16 -0600 Subject: [PATCH 10/27] test(presentation): the two sign-ins that lose their inbox continue on one thread The test added for S2 (faa8865) ends two browser sign-ins with one inbox failure. Both then continued at the same moment on different threads and wrote to the recording log, a plain list, at the same time: one entry could be lost, and the count of "not completed" entries came out as 1 instead of 2. It failed 5 times in 25 runs of that test alone, and once during an unrelated single-change run, which is how it was noticed. The test now runs on the single-threaded context the announcement test uses, as a window would: each sign-in continues on that one thread, one after the other. 40 runs of the test alone passed. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignInBrowserTests.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index 6aef1be..f02a63c 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -315,13 +315,25 @@ public sealed class CompanionSignInBrowserTests /// report: the argument error the real inbox gives when the process that sent a callback has already exited, an /// overflow, a time-out. Nothing escapes either sign-in. Each ends as "not completed" with a reason that names /// the kind of failure in fixed text, keeps its session and is free again, and nothing of the failure's own text - /// reaches the log or a property a view binds to. + /// reaches the log or a property a view binds to. One failure ends both sign-ins in the same moment, so the test + /// runs them on a single-threaded context, as a window does: each continues on that one thread, one after the + /// other, and the two never write to the log at the same time. /// [Theory] [InlineData(nameof(ArgumentException))] [InlineData(nameof(OverflowException))] [InlineData(nameof(TimeoutException))] - public async Task Browser_InboxFailsInAWayNoSignInLists_EveryWaitingSignInReportsItAndNothingEscapes(string kind) + public void Browser_InboxFailsInAWayNoSignInLists_EveryWaitingSignInReportsItAndNothingEscapes(string kind) + { + using PumpContext pump = new(); + + pump.Run(() => TwoSignInsLoseTheirInboxAsync(kind)); + } + + + + /// Two browser sign-ins wait on the one inbox, the inbox fails with a failure of the named kind, and both must end as reported failures. + private static async Task TwoSignInsLoseTheirInboxAsync(string kind) { SignInWorld world = new(); using CompanionSignIn first = await world.BrowserReadyAsync(); -- 2.54.0 From 2366f6765bab59669983cf307d1a5d75c25e8d2a Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:59:19 -0600 Subject: [PATCH 11/27] fix(presentation): a disposed sign-in no longer announces that a property is about to change CompanionSignIn promises that nothing is announced after disposal, and kept that for PropertyChanged only. PropertyChanging was still raised, for Offer and State, as an operation that was running at disposal ended. OnPropertyChanging is now held back after disposal as OnPropertyChanged is. Tests: the two disposal tests also record PropertyChanging, during a running operation and when nothing runs, and require that nothing arrives after Dispose while the offer is withdrawn and the state settles. Review of afe7e08, nit 2. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.cs | 14 +++++++++++++- .../Fakes/SignInWorld.cs | 10 ++++++++++ .../SignIn/CompanionSignInTests.cs | 11 ++++++++++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs index 373ebf2..329a00a 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -18,7 +18,8 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// caller's business. A password is passed straight to the session and never kept, and the credential is only ever a /// return value, never a property. One operation runs at a time; a second one is refused and logged. Everything it /// announces is raised on the thread that called it. Disposing it only cancels: the running operation ends itself, -/// discards the session on its way out, and from then on nothing is announced. +/// discards the session on its way out, and from then on nothing is announced, neither that a property changed nor +/// that one is about to. /// public sealed partial class CompanionSignIn : ObservableObject, IDisposable { @@ -328,6 +329,17 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable + /// Announces that a property is about to change, unless the sign-in was disposed, for the same reason: "nothing is announced after disposal" holds for both of the events a view can subscribe to. + protected override void OnPropertyChanging(PropertyChangingEventArgs e) + { + if(!_disposed) + { + base.OnPropertyChanging(e); + } + } + + + /// Records that the server accepted the user and returns the credential to hand to the caller. private QqqSessionCredential SignedIn(ISignInSession session, QqqSessionCredential credential) { diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs index 0a70ac1..7eecc36 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs @@ -220,6 +220,16 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr + /// Records the name of every property a sign-in says is about to change from now on, in order: the other event a view can subscribe to. + internal static List WatchChanging(CompanionSignIn signIn) + { + List changing = []; + signIn.PropertyChanging += (_, change) => changing.Add(change.PropertyName!); + return changing; + } + + + /// /// Awaits something that has to end by itself and fails the test, instead of hanging the run, when it does not. The /// limit is real time, but it only ever runs out when the code under test is broken; a passing test never waits for it. diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs index e403e7d..7b46247 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -614,7 +614,8 @@ public sealed class CompanionSignInTests /// Disposing while the server checks a password only cancels. The session is not discarded under the running /// call, which would make the call end with "disposed": it ends with the cancellation, quietly, the session is /// discarded then, and from the moment of disposal nothing more is announced: a view that has closed is not - /// called back. Only a debug entry records the end. + /// called back, neither with a change nor with the notice that one is coming, although the session's offer is + /// withdrawn and the state settles as the operation ends. Only a debug entry records the end. /// [Fact] public async Task Dispose_OnlyCancels_NothingIsAnnouncedAfterwards() @@ -623,14 +624,19 @@ public sealed class CompanionSignInTests CompanionSignIn signIn = await world.PasswordReadyAsync(); world.Sessions[0].PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); List changes = SignInWorld.Watch(signIn); + List changing = SignInWorld.WatchChanging(signIn); Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password"); Assert.Equal(["IsBusy=True", "State=SigningIn"], changes); + Assert.Equal([nameof(CompanionSignIn.State)], changing); signIn.Dispose(); Assert.Null(await SignInWorld.EndsAsync(running)); Assert.True(world.Sessions[0].Disposed); Assert.Equal(["IsBusy=True", "State=SigningIn"], changes); + Assert.Equal([nameof(CompanionSignIn.State)], changing); + Assert.Null(signIn.Offer); + Assert.Equal(CompanionSignInState.NotPrepared, signIn.State); Assert.False(signIn.HasSession); Assert.False(signIn.IsBusy); Assert.Equal(["INFO Password sign-in submitted to print.example.com.", "DEBUG Password sign-in ended early because the sign-in was closed (TaskCanceledException)."], world.Log.Entries); @@ -648,6 +654,7 @@ public sealed class CompanionSignInTests SignInWorld world = new(); CompanionSignIn signIn = await world.PasswordReadyAsync(); List changes = SignInWorld.Watch(signIn); + List changing = SignInWorld.WatchChanging(signIn); signIn.Dispose(); signIn.Dispose(); @@ -655,6 +662,8 @@ public sealed class CompanionSignInTests signIn.CancelBrowserSignIn(); Assert.True(world.Sessions[0].Disposed); + Assert.Null(signIn.Offer); + Assert.Empty(changing); Assert.Null(await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None)); Assert.Null(await signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password")); Assert.Null(await signIn.SignInWithBrowserAsync()); -- 2.54.0 From e445f42620048713667d3613d92557bfec6d5a45 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 23:59:33 -0600 Subject: [PATCH 12/27] fix(presentation): a log that throws cannot break the callback dispatcher The dispatcher wrote "inbox open" after it had made an inbox the open one and before it started waiting on it. A log that threw there left an inbox nobody read: the registration failed, and the next ticket shared that inbox and waited on it until it was disposed. The other two entries had the same exposure: a log that threw on "dropped" ended the wait for callbacks while tickets still waited, and one that threw on "inbox failed" left the tickets of a broken inbox waiting for their own time limits. Every entry the dispatcher writes now goes through one method that leaves a failure of the log with the log: the entry is lost, and the dispatcher goes on. That covers all three places, where starting the wait before the first entry would have covered one. Test: a log that fails on every entry. A registration returns its ticket with the inbox open and being read, a callback for nobody is dropped and the next inbox is opened, the ticket's own callback reaches it, and the tickets of a broken inbox are failed. The test checks that each kind of entry was attempted. Review of afe7e08, nit 3. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcher.cs | 29 ++++++- .../SignIn/BrowserCallbackDispatcherTests.cs | 79 +++++++++++++++++++ 2 files changed, 104 insertions(+), 4 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index af1d18c..3f04f99 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -19,7 +19,7 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// reports, and otherwise one that names only its kind (see ), so whatever an /// inbox fails with ends each exchange as a failure it reports and never as an exception nobody handles. Tickets /// are registered from the window's thread and callbacks arrive on others, so the waiting set is guarded, and this -/// never continues on a caller's thread. +/// never continues on a caller's thread. A log that fails does not stop any of it. /// public sealed class BrowserCallbackDispatcher { @@ -133,12 +133,33 @@ public sealed class BrowserCallbackDispatcher CancellationTokenSource listening = new(); _inbox = inbox; _listening = listening; - _log.Info("Browser callback inbox open."); + Record(static log => log.Info("Browser callback inbox open.")); _ = ReceiveAsync(inbox, listening.Token); } + /// + /// Writes a log entry in a way that cannot break the dispatcher. Its entries are written between steps that + /// belong together: after an inbox was opened and before anyone waits on it, after an inbox was closed and before + /// the next one is opened, before the tickets of a broken inbox are failed. A log that threw there would leave + /// an inbox nobody reads, or tickets waiting for nothing until their own time limits ran out. So a failure of + /// the log stays with the log: the entry is lost, and the dispatcher goes on. + /// + private void Record(Action entry) + { + try + { + entry(_log); + } + catch(Exception) + { + // A log that cannot be written to must not cost an operator the sign-in that is waiting. + } + } + + + /// /// Closes the open inbox. The caller holds the gate. The fields are cleared before the wait is cancelled, because /// cancelling can run the end of that wait at once, on this thread, and it must then find that its inbox is no @@ -205,7 +226,7 @@ public sealed class BrowserCallbackDispatcher } if(ticket is null) { - _log.Warning("A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged."); + Record(static log => log.Warning("A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged.")); } failure = Reopen(out stranded); } @@ -276,7 +297,7 @@ public sealed class BrowserCallbackDispatcher /// private void End(BrowserCallbackTicket[] stranded, Exception failure) { - _log.Error("The browser callback inbox failed ({Failure}); {Waiting} waiting browser exchange(s) were ended and have to be started again.", failure.GetType().Name, stranded.Length); + Record(log => log.Error("The browser callback inbox failed ({Failure}); {Waiting} waiting browser exchange(s) were ended and have to be started again.", failure.GetType().Name, stranded.Length)); Exception reported = BrowserCallbackFailure.Reported(failure); foreach(BrowserCallbackTicket ticket in stranded) { diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 956f8b4..21e80c1 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -394,6 +394,44 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// A log that cannot be written to does not stop the dispatcher. Every entry it writes fails here, and all the + /// same: a registration returns its ticket with the inbox open and being read; a callback for nobody is dropped + /// and the next inbox is opened and read; the ticket's own callback reaches it; and when an inbox breaks, the + /// tickets that wait are failed and not left waiting. Each of the three entries was attempted, so the test is + /// about entries that failed and not about entries that were never written. + /// + [Fact] + public async Task LogThatThrows_DoesNotBreakTheDispatcher() + { + SignInWorld world = new(); + ThrowingLog log = new(); + BrowserCallbackDispatcher dispatcher = new(world, log); + + using BrowserCallbackTicket ticket = dispatcher.Register("synthetic-state-a"); + FakeInbox inbox = Assert.Single(world.Inboxes); + Assert.True(inbox.Waiting); + Task reopened = world.NextInboxAsync(); + inbox.Deliver(CallbackFor("synthetic-state-of-nobody")); + FakeInbox next = await reopened; + Assert.True(inbox.Disposed); + Assert.False(ticket.Callback.IsCompleted); + next.Deliver(CallbackFor("synthetic-state-a")); + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(ticket.Callback)); + + using BrowserCallbackTicket first = dispatcher.Register("synthetic-state-b"); + using BrowserCallbackTicket second = dispatcher.Register("synthetic-state-c"); + IOException failure = new("synthetic pipe failure"); + world.Inboxes[2].Fail(failure); + + Assert.Same(failure, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(first.Callback))); + Assert.Same(failure, await Assert.ThrowsAsync(() => SignInWorld.EndsAsync(second.Callback))); + Assert.All(world.Inboxes, opened => Assert.True(opened.Disposed)); + Assert.Equal(["INFO", "WARN", "INFO", "INFO", "ERROR"], log.Attempts); + } + + + /// /// Two exchanges cannot wait under one state, because a callback could not be told to belong to one of them. The /// second registration is refused without naming the state, and the first is left as it was. A state of nothing is @@ -450,6 +488,47 @@ public sealed class BrowserCallbackDispatcherTests + /// A log that fails on every entry, as a log whose file cannot be written would, and notes the level of each entry that was attempted. + private sealed class ThrowingLog : IPresentationLog + { + /// The level of every entry that was attempted, oldest first. + internal List Attempts { get; } = []; + + + + /// Fails. + public void Info(string message) => Fail("INFO"); + + + + /// Fails. + public void Warning(string message) => Fail("WARN"); + + + + /// Fails. + public void Error(string message) => Fail("ERROR"); + + + + /// Fails. + public void Debug(string message) => Fail("DEBUG"); + + + + /// Notes the attempt and fails. + private void Fail(string level) + { + lock(Attempts) + { + Attempts.Add(level); + } + throw new IOException("synthetic log failure"); + } + } + + + /// A callback source whose inboxes do not notice being closed and answer when the test says so, on the test's own thread. private sealed class LateInboxes : IBrowserCallbackSource { -- 2.54.0 From 59a8057bd6bb7d68b357a8bc92384b4942a8bc21 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:00:49 -0600 Subject: [PATCH 13/27] refactor(presentation): the callback dispatcher works through inboxes in a loop Opening an inbox started a wait on it, and the end of that wait opened the next inbox, which started the next wait. When a wait was already complete as it started, all of that happened inside the call that opened the first inbox, one level deeper for every callback: 200 inboxes that answered at once gave a stack 1,560 frames deep. The real inbox never completes synchronously, so this did not happen in use, but nothing in the type said it could not. The wait is now one loop for a whole run of inboxes. Opening an inbox no longer starts a wait: a registration starts one, and a wait that has routed a callback goes on with the inbox that was opened for the tickets still waiting. What happens to a callback, to a closed inbox and to an inbox that cannot be opened is unchanged. Test: 200 inboxes in a row answer at once with a callback for nobody. All are dropped, the stack is no deeper when the last inbox is opened than when the second was, and the ticket's own callback then reaches it. Review of afe7e08, nit 4. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcher.cs | 97 ++++++++++--------- .../SignIn/BrowserCallbackDispatcherTests.cs | 84 ++++++++++++++++ 2 files changed, 136 insertions(+), 45 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index 3f04f99..0087193 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -63,7 +63,8 @@ public sealed class BrowserCallbackDispatcher { try { - Listen(); + (IBrowserCallbackInbox inbox, CancellationToken closed) = Open(); + _ = ReceiveAsync(inbox, closed); } catch(Exception exception) when(!BrowserCallbackFailure.Listed(exception)) { @@ -126,15 +127,20 @@ public sealed class BrowserCallbackDispatcher - /// Opens an inbox and starts waiting for its one callback. The caller holds the gate. A failure to open is thrown, and no inbox is then open. - private void Listen() + /// + /// Opens an inbox, makes it the open one, and returns it with the token that ends the wait on it when it is + /// closed. The caller holds the gate, and waits on the inbox next: a registration starts the wait before it lets + /// go of the gate, and the wait that has just routed a callback goes on with the inbox it is given. A failure to + /// open is thrown, and no inbox is then open. + /// + private (IBrowserCallbackInbox Inbox, CancellationToken Closed) Open() { IBrowserCallbackInbox inbox = _callbacks.Open(); CancellationTokenSource listening = new(); _inbox = inbox; _listening = listening; Record(static log => log.Info("Browser callback inbox open.")); - _ = ReceiveAsync(inbox, listening.Token); + return (inbox, listening.Token); } @@ -179,24 +185,31 @@ public sealed class BrowserCallbackDispatcher /// - /// Waits for the one callback of an inbox and routes it. Any failure of the wait, whatever its kind, is the inbox + /// Waits for the one callback of an inbox, routes it, and goes on with the inbox that was opened for the tickets + /// that still wait, until none is. It is one loop for a whole run of inboxes, not a call per inbox: an inbox + /// whose callback is already there when the wait starts is dealt with at once, and a call per inbox would then + /// go one level deeper for every such callback. Any failure of the wait, whatever its kind, is the inbox /// failing, and has to reach the tickets that wait: a failure left here would leave every one of them waiting for /// its own time limit. The wait that ends because the inbox was closed is told apart inside /// , by the inbox no longer being the open one. /// - private async Task ReceiveAsync(IBrowserCallbackInbox inbox, CancellationToken listening) + private async Task ReceiveAsync(IBrowserCallbackInbox inbox, CancellationToken closed) { - Uri callback; - try + IBrowserCallbackInbox? open = inbox; + while(open is not null) { - callback = await inbox.ReceiveAsync(listening).ConfigureAwait(false); + Uri callback; + try + { + callback = await open.ReceiveAsync(closed).ConfigureAwait(false); + } + catch(Exception exception) + { + Fail(open, exception); + return; + } + open = Route(open, callback, out closed); } - catch(Exception exception) - { - Fail(inbox, exception); - return; - } - Route(inbox, callback); } @@ -204,16 +217,20 @@ public sealed class BrowserCallbackDispatcher /// /// Hands a received callback to the ticket whose state it carries, or drops it. The inbox that delivered it is /// closed and, when tickets still wait, the next one is opened in the same step, so an inbox is open exactly while - /// a ticket waits and the gap between two inboxes is as short as it can be. A callback from an inbox that was - /// closed meanwhile (its last ticket ended as the callback arrived) is dropped. The log line for a drop is fixed - /// text, written before the next inbox opens so the log reads in the order things happened. The ticket is - /// completed last, outside the gate. + /// a ticket waits and the gap between two inboxes is as short as it can be. That next inbox is returned, with the + /// token that ends the wait on it, for the caller to wait on; null means nothing is left to wait for, or another + /// wait already has the open inbox. When the next inbox cannot be opened, the tickets that wait cannot receive + /// anything and are failed. A callback from an inbox that was closed meanwhile (its last ticket ended as the + /// callback arrived) is dropped. The log line for a drop is fixed text, written before the next inbox opens so + /// the log reads in the order things happened. The ticket is completed last, outside the gate. /// - private void Route(IBrowserCallbackInbox inbox, Uri callback) + private IBrowserCallbackInbox? Route(IBrowserCallbackInbox inbox, Uri callback, out CancellationToken closed) { BrowserCallbackTicket? ticket = null; - BrowserCallbackTicket[] stranded; - Exception? failure; + BrowserCallbackTicket[] stranded = []; + Exception? failure = null; + IBrowserCallbackInbox? next = null; + closed = CancellationToken.None; lock(_gate) { if(ReferenceEquals(_inbox, inbox)) @@ -228,35 +245,25 @@ public sealed class BrowserCallbackDispatcher { Record(static log => log.Warning("A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged.")); } - failure = Reopen(out stranded); + if(_inbox is null && _waiting.Count != 0) + { + try + { + (next, closed) = Open(); + } + catch(Exception exception) + { + stranded = TakeWaiting(); + failure = exception; + } + } } if(failure is not null) { End(stranded, failure); } ticket?.Complete(callback); - } - - - - /// Opens the next inbox when tickets wait and none is open. The caller holds the gate. When it cannot be opened, the tickets that wait cannot receive anything: they are taken out for the caller to fail, and the failure is returned. - private Exception? Reopen(out BrowserCallbackTicket[] stranded) - { - stranded = []; - if(_inbox is not null || _waiting.Count == 0) - { - return null; - } - try - { - Listen(); - return null; - } - catch(Exception exception) - { - stranded = TakeWaiting(); - return exception; - } + return next; } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 21e80c1..3fc6aad 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -432,6 +432,36 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// An inbox can have its callback ready the moment it is opened, and the next one too. Two hundred inboxes in a + /// row answer at once here, each with a callback for nobody. The dispatcher drops each and opens the next in one + /// loop: the stack is no deeper when the last inbox is opened than when the second was, where a call per inbox + /// would have gone deeper with every callback. The ticket is still waiting afterwards, on the first inbox that + /// did not answer at once, and its own callback reaches it there. + /// + [Fact] + public async Task InboxesThatAnswerAtOnce_AreWorkedThroughInALoop() + { + EagerInboxes source = new(200); + RecordingLog log = new(); + BrowserCallbackDispatcher dispatcher = new(source, log); + + using BrowserCallbackTicket ticket = dispatcher.Register("synthetic-state-a"); + + Assert.Equal(201, source.Depths.Count); + Assert.Equal(200, log.Entries.Count(entry => string.Equals(entry, Dropped, StringComparison.Ordinal))); + Assert.Equal(201, log.Entries.Count(entry => string.Equals(entry, InboxOpen, StringComparison.Ordinal))); + Assert.InRange(source.Depths.Skip(1).Max() - source.Depths[1], 0, 8); + Assert.False(ticket.Callback.IsCompleted); + + source.Waiting.SetResult(CallbackFor("synthetic-state-a")); + + Assert.Equal(CallbackFor("synthetic-state-a"), await SignInWorld.EndsAsync(ticket.Callback)); + Assert.Equal(201, source.Depths.Count); + } + + + /// /// Two exchanges cannot wait under one state, because a callback could not be told to belong to one of them. The /// second registration is refused without naming the state, and the first is left as it was. A state of nothing is @@ -529,6 +559,60 @@ public sealed class BrowserCallbackDispatcherTests + /// A callback source whose first inboxes answer the moment they are waited on, each with a callback for nobody, and whose next inbox waits for the test. It notes how deep the stack is each time an inbox is opened. + private sealed class EagerInboxes(int eager) : IBrowserCallbackSource + { + /// The depth of the stack at each opening of an inbox, oldest first. + internal List Depths { get; } = []; + + + + /// What the first inbox that does not answer at once waits for. + internal TaskCompletionSource Waiting { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + + + /// The registered callback. + public string RedirectUri => SignInWorld.Callback; + + + + /// Not read by the dispatcher. + public string TracePath => "trace/auth-callback.log"; + + + + /// Notes the depth of the stack and opens the next inbox. + public IBrowserCallbackInbox Open() + { + Depths.Add(new System.Diagnostics.StackTrace().FrameCount); + return new EagerInbox(Depths.Count <= eager ? Task.FromResult(CallbackFor("synthetic-state-of-nobody")) : Waiting.Task); + } + + + + /// Not read by the dispatcher. + public IReadOnlyList RecentTrace(TimeSpan window) => []; + } + + + + /// An inbox whose wait is the task it was given: one that is already complete, or one the test completes. + private sealed class EagerInbox(Task answer) : IBrowserCallbackInbox + { + /// Returns the answer, which may already be there. + public Task ReceiveAsync(CancellationToken cancellationToken) => answer; + + + + /// Nothing to close. + public void Dispose() + { + } + } + + + /// A callback source whose inboxes do not notice being closed and answer when the test says so, on the test's own thread. private sealed class LateInboxes : IBrowserCallbackSource { -- 2.54.0 From 8890357ccd29e740625a5c5e7be70beacfa460e5 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:03:06 -0600 Subject: [PATCH 14/27] refactor(presentation): the callback ticket and its registration are internal BrowserCallbackDispatcher.Register, BrowserCallbackTicket and the ticket's Callback were public. Callback is a Task that carries a browser callback with its one-time code and state. Only the presentation assembly's own sign-in and sign-out register and wait, so all three are now internal; the dispatcher's public surface is its constructor, which the companion needs to create the one instance. Test: the ticket is not a visible type and has no public property, and the dispatcher declares no public method or property and one public constructor. Review of afe7e08, nit 5. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcher.cs | 5 +++-- .../SignIn/BrowserCallbackTicket.cs | 7 ++++--- .../SignIn/BrowserCallbackDispatcherTests.cs | 21 +++++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index 0087193..19cfa66 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -47,9 +47,10 @@ public sealed class BrowserCallbackDispatcher /// waiting is refused, because two exchanges could not be told apart. When the inbox cannot be opened the failure is /// thrown to the caller and nothing is registered; a failure of a kind the exchanges do not report is thrown as /// one that names only its kind, as it is for a ticket. The caller disposes the ticket when its exchange ends, - /// however it ends. + /// however it ends. Only the presentation assembly's own exchanges register: a ticket's task carries a callback + /// with its one-time code and state, so neither this nor the ticket is offered to code outside the assembly. /// - public BrowserCallbackTicket Register(string state) + internal BrowserCallbackTicket Register(string state) { ArgumentException.ThrowIfNullOrEmpty(state); BrowserCallbackTicket ticket = new(this, state); diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs index c5f0335..ef45353 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs @@ -9,9 +9,10 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// One browser exchange's claim on the callback inbox: the sign-in or provider sign-out that registered an OAuth state /// with the waits on this for the callback carrying that state. Disposing it /// ends the claim, after which a callback with that state is dropped. The state is held only while the ticket waits -/// and is never shown: the ticket has no public member that returns it. +/// and is never shown. The ticket's task carries the callback, with its one-time code and state, so the ticket is +/// internal to the presentation assembly, whose sign-in and sign-out are the only ones to wait on it. /// -public sealed class BrowserCallbackTicket : IDisposable +internal sealed class BrowserCallbackTicket : IDisposable { private readonly TaskCompletionSource _callback = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly BrowserCallbackDispatcher _dispatcher; @@ -37,7 +38,7 @@ public sealed class BrowserCallbackTicket : IDisposable /// it, fails with the inbox's failure when the inbox failed while this ticket waited, and is cancelled when the /// ticket is disposed first. Whoever awaits it continues on its own thread, never inside the dispatcher. /// - public Task Callback => _callback.Task; + internal Task Callback => _callback.Task; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 3fc6aad..b2032c5 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -3,6 +3,7 @@ * SPDX-License-Identifier: MIT */ +using System.Reflection; using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Presentation.SignIn; using Qqq.PrintAgent.Presentation.Tests.Fakes; @@ -506,6 +507,26 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// A ticket's task carries a callback with its one-time code and state, so code outside the presentation assembly + /// can neither see a ticket nor register for one: the ticket is not a public type and offers no public property, + /// and the dispatcher's public surface is its constructor alone. + /// + [Fact] + public void TicketAndRegistration_AreNotOfferedOutsideTheAssembly() + { + const BindingFlags declaredPublic = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly; + + Assert.False(typeof(BrowserCallbackTicket).IsVisible); + Assert.Empty(typeof(BrowserCallbackTicket).GetProperties(declaredPublic)); + Assert.True(typeof(BrowserCallbackDispatcher).IsVisible); + Assert.Empty(typeof(BrowserCallbackDispatcher).GetMethods(declaredPublic)); + Assert.Empty(typeof(BrowserCallbackDispatcher).GetProperties(declaredPublic)); + Assert.Single(typeof(BrowserCallbackDispatcher).GetConstructors(declaredPublic)); + } + + + /// The dispatcher cannot work without a place callbacks arrive and a log, and says which is missing. [Fact] public void MissingCollaborator_IsRefused() -- 2.54.0 From 9a95ed6b08d37d7d5fdd248ecca9b26d56cab3f3 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:05:45 -0600 Subject: [PATCH 15/27] fix(presentation): a ticket that was failed and never awaited raises no unobserved task exception When the inbox failed after an exchange's own wait had ended and before the exchange disposed its ticket, the ticket's task was failed and nobody ever looked at it. The runtime reports such a task through TaskScheduler.UnobservedTaskException when it is collected. The ticket now marks the failure as seen when it is failed. Whoever does await the ticket still gets the failure. Test: a ticket is failed, disposed without being looked at and let go, and everything is collected. An ordinary failed task, let go the same way, is the control: it is reported, which shows the collection did what it had to, and the ticket is not. The two are told apart, and from any other test's failures, by their own texts. Nothing is waited for: the collections and finalizers run to completion before the counts are read. Review of afe7e08, nit 10. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackTicket.cs | 15 +++- .../SignIn/BrowserCallbackDispatcherTests.cs | 70 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs index ef45353..80c6ced 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs @@ -47,8 +47,19 @@ internal sealed class BrowserCallbackTicket : IDisposable - /// Ends the wait with the inbox's failure. - internal void Fail(Exception failure) => _callback.TrySetException(failure); + /// + /// Ends the wait with the inbox's failure, and marks the failure as seen. An exchange whose own wait had already + /// ended (its token was cancelled) disposes the ticket without ever looking at the task, and the runtime reports + /// a failed task nobody looked at as an unobserved error once it is collected. Whoever does await the ticket is + /// given the failure all the same. + /// + internal void Fail(Exception failure) + { + if(_callback.TrySetException(failure)) + { + _ = _callback.Task.Exception; + } + } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index b2032c5..8808436 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -4,6 +4,7 @@ */ using System.Reflection; +using System.Runtime.CompilerServices; using Qqq.PrintAgent.Core.Authentication; using Qqq.PrintAgent.Presentation.SignIn; using Qqq.PrintAgent.Presentation.Tests.Fakes; @@ -507,6 +508,75 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// An inbox can fail after an exchange has stopped waiting and before it has disposed its ticket. The ticket is + /// then failed and never looked at. The runtime reports a failed task nobody looked at as an unobserved error + /// when the task is collected, and a ticket must not be the cause of one. The test fails a ticket, lets it go + /// without looking at it, and has everything collected; beside it, as the control, an ordinary task is failed + /// and let go the same way. The control is reported, which shows that the collection did what it had to, and + /// the ticket is not. Each failure is told from any other test's by its own text, and nothing here waits: the + /// collections run to completion before the counts are read. + /// + [Fact] + public void TicketFailedAndNeverLookedAt_LeavesNoUnobservedFailure() + { + const string ticketText = "synthetic failure of a ticket nobody looked at"; + const string controlText = "synthetic failure of a task nobody looked at"; + int tickets = 0; + int controls = 0; + void Count(object? sender, UnobservedTaskExceptionEventArgs unobserved) + { + tickets += unobserved.Exception.InnerExceptions.Count(inner => string.Equals(inner.Message, ticketText, StringComparison.Ordinal)); + controls += unobserved.Exception.InnerExceptions.Count(inner => string.Equals(inner.Message, controlText, StringComparison.Ordinal)); + } + TaskScheduler.UnobservedTaskException += Count; + try + { + FailATicketAndLetItGo(ticketText); + FailATaskAndLetItGo(controlText); + for(int round = 0; round < 3; round++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + } + finally + { + TaskScheduler.UnobservedTaskException -= Count; + } + + Assert.Equal(1, controls); + Assert.Equal(0, tickets); + } + + + + /// Registers a ticket, breaks its inbox so the ticket is failed inside that call, disposes the ticket without looking at its task, and returns with nothing left that refers to it. It is not inlined, so the caller's frame holds nothing of it either. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void FailATicketAndLetItGo(string text) + { + using NoContext none = new(); + LateInboxes source = new(); + BrowserCallbackDispatcher dispatcher = new(source, new RecordingLog()); + BrowserCallbackTicket ticket = dispatcher.Register("synthetic-state-a"); + source.Inboxes[0].Answer.SetException(new IOException(text)); + Assert.True(ticket.Callback.IsFaulted); + ticket.Dispose(); + } + + + + /// The control: fails an ordinary task and returns with nothing left that refers to it. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void FailATaskAndLetItGo(string text) + { + TaskCompletionSource source = new(); + source.SetException(new IOException(text)); + Assert.True(source.Task.IsFaulted); + } + + + /// /// A ticket's task carries a callback with its one-time code and state, so code outside the presentation assembly /// can neither see a ticket nor register for one: the ticket is not a public type and offers no public property, -- 2.54.0 From f04d882ee96c62b0e0e768baa56b864de858b0b8 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:06:42 -0600 Subject: [PATCH 16/27] fix(presentation): a callback the session would refuse to read is dropped, not handed to a sign-in The dispatcher read the state of a callback more leniently than the session reads a callback: "??state=x" read as "x", and entries without "=" were ignored. Such a callback was handed to the exchange whose state it seemed to carry, the session then refused it, and that ended the sign-in. Sending one needs the state. ReadState now applies the rules of Core's callback parser: an absolute address without fragment or user information, a query of 2 to 16,384 characters, every entry a name and a value, no name repeated, no control character in a name or a value. An address that breaks one of them has no state, so the callback is dropped as nobody's and the exchange goes on waiting for the real one. The same reading is used for the authorization address a session prepares, which Core builds from distinct names. One consequence for a provider sign-out: its callback is matched by QqqProviderLogout, which is laxer about names other than "state". A sign-out callback that repeats another name or holds a control character is now dropped and the sign-out waits out its limit, where it would have been confirmed. Tests: the reviewer's cases and the remaining rules as rows of the ReadState theory (a second question mark, an entry without a value, a repeated name, a control character in a value and in a name, a fragment, user information, an empty query) and the length limit at its edge; five of them again through the dispatcher with the right state in them, where each must be dropped and leave the ticket waiting. Review of afe7e08, nit 11. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 5 ++- .../SignIn/BrowserCallbackDispatcher.cs | 42 ++++++++++++------- .../SignIn/BrowserCallbackDispatcherTests.cs | 41 ++++++++++++++++-- 3 files changed, 68 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc22e9d..feece6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,8 +36,9 @@ this build: the connection dialog still runs on the existing flow, whose only ch so an attempt that is cancelled, times out or is stopped after that discards the session. - `BrowserCallbackDispatcher` owns the one browser callback inbox. A sign-in or a provider sign-out registers the OAuth state it sent and waits for the callback that carries it, so two servers can be signing in at once. A - callback that carries no state, more than one, or a state nobody waits for is dropped, and the log says only that - one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that waits fails + callback that carries no state, more than one, or a state nobody waits for is dropped, and so is one the session + would refuse to read (an entry without a value, a repeated name, a control character, a fragment); the log says + only that one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that waits fails once and the next registration opens a new inbox. Whatever the inbox fails with, each sign-in or sign-out that waits ends as a failure it reports: a failure of a kind they do not expect (the inbox gives an argument error when the process that sent a callback has already exited) reaches them as one that names only its kind. diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index 19cfa66..51cfce3 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -11,9 +11,10 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// ticket to await, and this hands each callback to the ticket whose state it carries. Two servers can then be signing /// in at once, and a late callback for an exchange that has ended is dropped instead of failing another. An inbox is /// open exactly while at least one ticket waits. Each inbox takes one callback, so after every callback it is closed and, -/// when tickets still wait, a new one is opened. A callback that carries no state, more than one, or a state nobody -/// waits for is dropped, and the log says only that one was dropped: nothing of a callback, its state or its code is -/// ever logged, and a registered state is held only while its ticket waits. When the inbox itself fails, which +/// when tickets still wait, a new one is opened. A callback that carries no state, more than one, a state nobody +/// waits for, or a query the session would refuse to read is dropped, and the log says only that one was dropped: +/// nothing of a callback, its state or its code is ever logged, and a registered state is held only while its +/// ticket waits. When the inbox itself fails, which /// includes an inbox that refuses what it received as no callback at all, every waiting ticket fails and the next /// registration opens a new inbox. The tickets are given the inbox's failure when it is of a kind every exchange /// reports, and otherwise one that names only its kind (see ), so whatever an @@ -23,6 +24,9 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// public sealed class BrowserCallbackDispatcher { + /// The longest query a callback may have, in characters; the session refuses a longer one. + internal const int LongestQuery = 16_384; + private readonly IBrowserCallbackSource _callbacks; private readonly IPresentationLog _log; private readonly Lock _gate = new(); @@ -86,29 +90,37 @@ public sealed class BrowserCallbackDispatcher /// /// Reads the one state parameter of an address's query: the state a sign-in sent, from the authorization - /// address, or the state a callback returns. It is null when the address has none, an empty one or more than one, - /// because a repeated parameter could make two readers disagree about which exchange a callback belongs to. + /// address, or the state a callback returns. The query is read by the rules the session applies to a callback + /// before it accepts it (QqqSessionClient, in Core): the address is absolute and has no fragment and no + /// user information, the query is there and no longer than a callback's may be, every entry is a name and a + /// value, no name is repeated, and neither a name nor a value holds a control character. An address that breaks + /// one of them has no state here. A callback like that is therefore dropped as nobody's, where a more lenient + /// reading would hand it to the exchange whose state it seems to carry, only for the session to refuse it and + /// end that sign-in. There is no state either when the parameter is missing or empty. A repeated name is refused + /// because two readers could disagree about which exchange a callback belongs to. /// internal static string? ReadState(Uri address) { - string? state = null; - if(!address.IsAbsoluteUri) + if(!address.IsAbsoluteUri || address.Fragment.Length != 0 || address.UserInfo.Length != 0 || address.Query.Length is < 2 or > LongestQuery) { return null; } - foreach(string entry in address.Query.TrimStart('?').Split('&')) + Dictionary values = new(StringComparer.Ordinal); + foreach(string entry in address.Query[1..].Split('&')) { string[] pair = entry.Split('=', 2); - if(pair.Length == 2 && string.Equals(Uri.UnescapeDataString(pair[0].Replace('+', ' ')), "state", StringComparison.Ordinal)) + if(pair.Length != 2) { - if(state is not null) - { - return null; - } - state = Uri.UnescapeDataString(pair[1].Replace('+', ' ')); + return null; + } + string name = Uri.UnescapeDataString(pair[0].Replace('+', ' ')); + string value = Uri.UnescapeDataString(pair[1].Replace('+', ' ')); + if(name.Any(char.IsControl) || value.Any(char.IsControl) || !values.TryAdd(name, value)) + { + return null; } } - return string.IsNullOrEmpty(state) ? null : state; + return values.TryGetValue("state", out string? state) && state.Length != 0 ? state : null; } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 8808436..d630167 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -129,7 +129,10 @@ public sealed class BrowserCallbackDispatcherTests /// somebody's only when it is exactly the one that was registered: the same letters in another case, the /// beginning of it, more than it, or it with a space after it are all nobody's. The ticket that waits is /// untouched, a new inbox is opened for it, and the log holds the fixed sentence and nothing of the callback. - /// The ticket's own callback, sent to the new inbox, still reaches it. + /// The ticket's own callback, sent to the new inbox, still reaches it. A callback the session would refuse to + /// read is nobody's too, even with the right state in it: a query that starts with a second question mark, an + /// entry without a value, a repeated name, a control character, or a fragment. Handed to the exchange, each of + /// these would have ended its sign-in; dropped, it leaves the exchange waiting for the real one. /// [Theory] [InlineData("?code=synthetic-code")] @@ -142,6 +145,11 @@ public sealed class BrowserCallbackDispatcherTests [InlineData("?code=synthetic-code&state=synthetic-state-")] [InlineData("?code=synthetic-code&state=synthetic-state-xy")] [InlineData("?code=synthetic-code&state=synthetic-state-x%20")] + [InlineData("??state=synthetic-state-x")] + [InlineData("?state=synthetic-state-x&synthetic-entry-without-a-value")] + [InlineData("?code=synthetic-code&code=synthetic-code&state=synthetic-state-x")] + [InlineData("?state=synthetic-state-x&code=synthetic%00code")] + [InlineData("?state=synthetic-state-x#synthetic-fragment")] public async Task Dispatcher_CallbackWithNoStateOrTwo_IsDropped_AndNotLogged(string query) { SignInWorld world = new(); @@ -488,10 +496,23 @@ public sealed class BrowserCallbackDispatcherTests /// /// The state of an address is its one "state" parameter, decoded: found wherever it stands in the query, with a - /// plus sign and a percent escape read as the provider wrote them. There is none when the parameter is missing, - /// empty, repeated or named differently, when the address has no query, and when it is not an absolute address. + /// plus sign and a percent escape read as the provider wrote them, in the name as well as in the value. There is + /// none when the parameter is missing, empty, repeated or named differently, when the address has no query, and + /// when it is not an absolute address. There is none either when the session would refuse the query: it starts + /// with a second question mark, an entry has no value, any name is repeated, a name or a value holds a control + /// character, or the address has a fragment or user information. /// [Theory] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?%73tate=synthetic-state-a", "synthetic-state-a")] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic-state-a&State=synthetic-state-b", "synthetic-state-a")] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback??state=synthetic-state-a", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic-state-a&synthetic", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?code=a&code=b&state=synthetic-state-a", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic-state-a%00", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?synthetic%0Aname=a&state=synthetic-state-a", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic-state-a#state=synthetic-state-b", null)] + [InlineData("https://synthetic-user@id.example.com/authorize?state=synthetic-state-a", null)] + [InlineData("io.qrun.qqq-print-agent:/oauth/callback?", null)] [InlineData("https://id.example.com/authorize?client_id=synthetic&state=synthetic-state-a&nonce=synthetic", "synthetic-state-a")] [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic%2Dstate+a", "synthetic-state a")] [InlineData("io.qrun.qqq-print-agent:/oauth/callback?state=synthetic=state", "synthetic=state")] @@ -597,6 +618,20 @@ public sealed class BrowserCallbackDispatcherTests + /// A query is read up to the length the session accepts for a callback and not beyond: one character more, and the address has no state. + [Fact] + public void ReadState_QueryLongerThanACallbacksMayBe_HasNoState() + { + const string prefix = "?state=synthetic-state-a&synthetic="; + string longest = prefix + new string('a', BrowserCallbackDispatcher.LongestQuery - prefix.Length); + + Assert.Equal(16_384, BrowserCallbackDispatcher.LongestQuery); + Assert.Equal("synthetic-state-a", BrowserCallbackDispatcher.ReadState(new Uri(SignInWorld.Callback + longest))); + Assert.Null(BrowserCallbackDispatcher.ReadState(new Uri(SignInWorld.Callback + longest + "a"))); + } + + + /// The dispatcher cannot work without a place callbacks arrive and a log, and says which is missing. [Fact] public void MissingCollaborator_IsRefused() -- 2.54.0 From 295906ac416f5e149d12eaf1de2312d7a6b0c658 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:10:27 -0600 Subject: [PATCH 17/27] test(presentation): pin that a table-based server names no provider and that a ticket's waiter continues elsewhere Two claims in the new types survived a single change each with every test passing. "A table-based server names no provider" (CompanionSignIn.Judge): a table-based description that also carries a native grant with an issuer is now read against a check that reported no provider. The issuer must not be taken for a provider that changed, and the password is offered. "Whoever awaits a ticket continues on its own thread, never inside the dispatcher" (the ticket's RunContinuationsAsynchronously): a waiter that asks to be continued inside the call that ends the ticket must not be running on that thread while that call runs, for a callback and for a failure. The test compares threads and a flag the ending call holds, and waits for nothing but the waiter itself. Review of afe7e08, nit 6. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcherTests.cs | 36 +++++++++++++++++++ .../SignIn/CompanionSignInTests.cs | 28 +++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index d630167..11066bc 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -529,6 +529,42 @@ public sealed class BrowserCallbackDispatcherTests + /// + /// Whoever waits on a ticket continues on a thread of its own, never inside the dispatcher, which completes + /// tickets from the thread a callback arrived on. The waiter here asks to be continued inside the very call that + /// ends the ticket, which is what an awaiting method without a synchronization context does, and it is not: when + /// it runs, the call that gave the ticket its callback, or its failure, is not running on that thread. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task TicketsWaiter_IsNotContinuedInsideTheCallThatEndsTheTicket(bool callback) + { + SignInWorld world = new(); + using BrowserCallbackTicket ticket = world.Dispatcher.Register("synthetic-state-a"); + int ending = Environment.CurrentManagedThreadId; + bool inside = false; + bool? continuedInside = null; + Task waiter = ticket.Callback.ContinueWith(_ => continuedInside = inside && Environment.CurrentManagedThreadId == ending, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + + inside = true; + if(callback) + { + ticket.Complete(CallbackFor("synthetic-state-a")); + } + else + { + ticket.Fail(new IOException("synthetic pipe failure")); + } + inside = false; + + await waiter.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.False(continuedInside); + Assert.Equal(callback, ticket.Callback.IsCompletedSuccessfully); + } + + + /// /// An inbox can fail after an exchange has stopped waiting and before it has disposed its ticket. The ticket is /// then failed and never looked at. The runtime reports a failed task nobody looked at as an unobserved error diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs index 7b46247..ae02e6e 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -144,6 +144,34 @@ public sealed class CompanionSignInTests + /// + /// A table-based server names no sign-in provider, by the rule the service's check applies: it takes a user name + /// and password and nothing else. Its description can still carry a native session grant with an issuer, which + /// is not a provider anybody is sent to. The check reported none for it, and the read agrees: the grant's issuer + /// is not taken for a provider that changed, and the password is offered. + /// + [Fact] + public async Task Prepare_TableBasedServerWithANativeGrant_NamesNoProvider() + { + QqqAuthenticationMetadata description = new() + { + Type = "TABLE_BASED", + Values = new QqqAuthenticationMetadata.ProviderValues { NativeSessionLogin = new QqqAuthenticationMetadata.NativeGrant { Issuer = SignInWorld.Provider, RedirectUris = [SignInWorld.Callback] } }, + }; + SignInWorld world = new() { ConfigureSession = session => session.Metadata = description }; + using CompanionSignIn signIn = world.NewSignIn(); + Assert.Equal(new Uri(SignInWorld.Provider), description.ProviderOrigin); + + SignInOffer? offer = await signIn.PrepareAsync(new Uri(SignInWorld.Server), SignInWorld.PasswordCheck, QqqCertificateExceptionOrigins.None); + + Assert.Equal(new SignInOffer(true, false), offer); + Assert.Equal(CompanionSignInState.Ready, signIn.State); + Assert.True(signIn.HasSession); + Assert.Equal([Reading, "INFO Sign-in methods for print.example.com: password."], world.Log.Entries); + } + + + /// /// The provider is compared as an origin. The check's address and the description's issuer are the same provider /// when their scheme, host and port are: whatever the letter case, an explicit default port or a path on either -- 2.54.0 From b37dad505ca82bbc04ce4610e1f9fc7c4cf465b2 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:11:16 -0600 Subject: [PATCH 18/27] fix(presentation): a provider sign-out its caller stopped is logged as information, in fixed words ProviderSignOut logged every way of not being confirmed as a warning with the failure's type and text, the caller's own cancellation included: "WARN Identity provider sign-out was not confirmed: TaskCanceledException: A task was canceled." A caller that ends the wait has stopped it on purpose. That case is now logged at information level as "Identity provider sign-out was stopped by its caller before the provider confirmed.", with nothing of the cancellation in it. Failures are logged as before. Test: the row for the caller's token expects that entry and no warning; every other row still expects its warning. Review of afe7e08, nit 9. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/ProviderSignOut.cs | 8 ++++++- .../SignIn/ProviderSignOutTests.cs | 22 ++++++++++--------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs index 2ea1d6d..6970867 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs @@ -46,7 +46,8 @@ public sealed class ProviderSignOut /// first, which opens the inbox, so a fast redirect is not lost. It returns whether the provider confirmed: false /// when it did not come back in time, when the callback with this state is not on the registered address, when /// the browser or the inbox failed, and when the caller's token ended the wait. Only the provider's host is - /// logged. + /// logged. A failure is logged as a warning with its kind and text; the caller's own cancellation is a + /// deliberate stop, and is logged as information in fixed words. /// public async Task CompleteAsync(QqqProviderLogout logout, CancellationToken cancellationToken = default) { @@ -63,6 +64,11 @@ public sealed class ProviderSignOut _log.Info(matched ? "Identity provider sign-out callback matched." : "Identity provider sign-out callback did not match this sign-out."); return matched; } + catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested) + { + _log.Info("Identity provider sign-out was stopped by its caller before the provider confirmed."); + return false; + } catch(Exception exception) when(exception is OperationCanceledException or IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception or InvalidOperationException or ArgumentException) { _log.Warning("Identity provider sign-out was not confirmed: {Failure}", QqqSessionDiagnostics.Describe(exception)); diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs index 8f1bc87..bbd0084 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -100,17 +100,18 @@ public sealed class ProviderSignOutTests /// /// When the provider does not come back within two minutes, the browser cannot be opened, the inbox cannot be - /// opened or breaks, or the caller stops waiting, the sign-out is not confirmed, and the log says so with the kind - /// of failure. Windows names what it could not start in its failure, which is the whole sign-out address with the - /// token hint; none of that reaches the log. + /// opened or breaks, or the caller stops waiting, the sign-out is not confirmed. A failure is logged as a warning + /// with its kind. The caller's own cancellation is not a failure: it is logged as information, in fixed words, + /// without the text of the cancellation. Windows names what it could not start in its failure, which is the + /// whole sign-out address with the token hint; none of that reaches the log. /// [Theory] - [InlineData("limit", "TaskCanceledException: A task was canceled.")] - [InlineData("token", "TaskCanceledException: A task was canceled.")] - [InlineData("browser", "IOException: " + BrowserStartFailure.WindowsReport)] - [InlineData("no inbox", "UnauthorizedAccessException: synthetic open failure")] - [InlineData("inbox", "IOException: synthetic pipe failure")] - public async Task ProviderThatDoesNotReturn_IsNotConfirmed(string ending, string cause) + [InlineData("limit", "WARN Identity provider sign-out was not confirmed: TaskCanceledException: A task was canceled.")] + [InlineData("token", "INFO Identity provider sign-out was stopped by its caller before the provider confirmed.")] + [InlineData("browser", "WARN Identity provider sign-out was not confirmed: IOException: " + BrowserStartFailure.WindowsReport)] + [InlineData("no inbox", "WARN Identity provider sign-out was not confirmed: UnauthorizedAccessException: synthetic open failure")] + [InlineData("inbox", "WARN Identity provider sign-out was not confirmed: IOException: synthetic pipe failure")] + public async Task ProviderThatDoesNotReturn_IsNotConfirmed(string ending, string entry) { SignInWorld world = new() { @@ -134,7 +135,8 @@ public sealed class ProviderSignOutTests } Assert.False(await SignInWorld.EndsAsync(running)); - Assert.Equal("WARN Identity provider sign-out was not confirmed: " + cause, world.Log.Entries[^1]); + Assert.Equal(entry, world.Log.Entries[^1]); + Assert.Equal(string.Equals(ending, "token", StringComparison.Ordinal), !world.Log.Entries.Exists(line => line.StartsWith("WARN", StringComparison.Ordinal))); Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); Assert.Equal(string.Equals(ending, "browser", StringComparison.Ordinal) || string.Equals(ending, "no inbox", StringComparison.Ordinal) ? 0 : 1, world.Opened.Count); Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(Hint, StringComparison.Ordinal) || entry.Contains(State, StringComparison.Ordinal)); -- 2.54.0 From e46d6127885b0b0f40f181ed9eb4157cdece1342 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:12:42 -0600 Subject: [PATCH 19/27] feat(presentation): the provider sign-out says how it ended, not only whether it was confirmed ProviderSignOut.CompleteAsync returned a bool, so the page that will show its result could not tell "the browser was never opened" from "the provider did not confirm", and the operator is told something different for each. It now returns ProviderSignOutResult: - Confirmed: the browser came back, on the registered address, with this sign-out's state. - NotOpened: the default browser could not be started, or the callback inbox could not be opened and so no browser was started. The operator saw no page. - NotConfirmed: the page was opened and the provider did not come back within two minutes, came back with the state on another address, or the inbox failed meanwhile. - Cancelled: the caller's token ended it. A sign-out whose caller had already stopped waiting when it was started now opens nothing, neither an inbox nor a page, and ends as Cancelled. Running out of time is logged in fixed words instead of the text of a cancellation, and a page that was not opened is logged as that. Tests: every way of not being confirmed with its result, whether a page was opened, and its log entry, including an inbox whose own wait was ended by something else and the two minute limit to the second; a caller that had already stopped; the existing tests moved from bool to the result. From the first author's notes on afe7e08. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 4 +- .../SignIn/ProviderSignOut.cs | 38 ++++--- .../SignIn/ProviderSignOutResult.cs | 27 +++++ .../SignIn/ProviderSignOutTests.cs | 104 +++++++++++------- 4 files changed, 121 insertions(+), 52 deletions(-) create mode 100644 src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOutResult.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index feece6d..8bfc7c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,9 @@ this build: the connection dialog still runs on the existing flow, whose only ch waits ends as a failure it reports: a failure of a kind they do not expect (the inbox gives an argument error when the process that sent a callback has already exited) reaches them as one that names only its kind. - `ProviderSignOut` is the identity provider's half of a sign-out: it opens the provider's sign-out page and waits - up to two minutes for the browser to return with that sign-out's own state. + up to two minutes for the browser to return with that sign-out's own state. Its result says how it ended: + confirmed, not opened (the browser or the callback inbox could not be opened, so the operator saw no page), not + confirmed (the page was opened and the provider did not confirm), or cancelled by its caller. - When Windows cannot start the browser, its failure text names what it could not start, which is the whole sign-in or sign-out address. The new types report only the kind of failure, so no state and no token hint can reach the log or the screen that way. diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs index 6970867..7e20402 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs @@ -15,7 +15,8 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// with this sign-out's own state, through the one , so it can run while a /// sign-in to another server waits for its callback. Ending the session in the service is the caller's part. The /// sign-out request carries the provider's ID token hint: it goes to the browser and nowhere else, and neither it -/// nor its state is logged or kept. +/// nor its state is logged or kept. The result says how it ended (), so the page +/// that shows it can tell a page that was never opened from a provider that did not confirm. /// public sealed class ProviderSignOut { @@ -43,36 +44,47 @@ public sealed class ProviderSignOut /// /// Opens the provider's end-session page in the default browser and waits up to two minutes for the browser to /// return to this application's registered callback with this sign-out's own state. The state is registered - /// first, which opens the inbox, so a fast redirect is not lost. It returns whether the provider confirmed: false - /// when it did not come back in time, when the callback with this state is not on the registered address, when - /// the browser or the inbox failed, and when the caller's token ended the wait. Only the provider's host is - /// logged. A failure is logged as a warning with its kind and text; the caller's own cancellation is a - /// deliberate stop, and is logged as information in fixed words. + /// first, which opens the inbox, so a fast redirect is not lost, and no page is opened for a caller whose token + /// has already ended. It says how the sign-out ended. Confirmed: the browser came back, on the registered + /// address, with this state. Not opened: the inbox or the browser could not be opened, so the operator saw no + /// page. Not confirmed: the page was opened, and the provider did not come back in time, came back with this + /// state on another address, or the inbox failed meanwhile. Cancelled: the caller's token ended the sign-out. + /// Only the provider's host is logged. A failure is logged as a warning with its kind and text; running out of + /// time is logged as a warning in fixed words; the caller's own cancellation is a deliberate stop, and is logged + /// as information in fixed words. /// - public async Task CompleteAsync(QqqProviderLogout logout, CancellationToken cancellationToken = default) + public async Task CompleteAsync(QqqProviderLogout logout, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(logout); + bool opened = false; + using CancellationTokenSource limit = new(Limit, _time); + using var wait = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancellationToken); try { + cancellationToken.ThrowIfCancellationRequested(); using BrowserCallbackTicket ticket = _dispatcher.Register(logout.State); - using CancellationTokenSource limit = new(Limit, _time); - using var wait = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancellationToken); _log.Info("Opening the identity provider's sign-out page in the default browser ({Provider}).", QqqOrigin.ShownAuthority(logout.EndSessionUri)); BrowserLaunch.Open(_browser, logout.EndSessionUri); + opened = true; Uri callback = await ticket.Callback.WaitAsync(wait.Token); bool matched = logout.Matches(callback); _log.Info(matched ? "Identity provider sign-out callback matched." : "Identity provider sign-out callback did not match this sign-out."); - return matched; + return matched ? ProviderSignOutResult.Confirmed : ProviderSignOutResult.NotConfirmed; } catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested) { _log.Info("Identity provider sign-out was stopped by its caller before the provider confirmed."); - return false; + return ProviderSignOutResult.Cancelled; + } + catch(OperationCanceledException) when(limit.IsCancellationRequested) + { + _log.Warning("Identity provider sign-out was not confirmed: the provider did not return within the two minute limit."); + return ProviderSignOutResult.NotConfirmed; } catch(Exception exception) when(exception is OperationCanceledException or IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception or InvalidOperationException or ArgumentException) { - _log.Warning("Identity provider sign-out was not confirmed: {Failure}", QqqSessionDiagnostics.Describe(exception)); - return false; + _log.Warning(opened ? "Identity provider sign-out was not confirmed: {Failure}" : "The identity provider's sign-out page was not opened: {Failure}", QqqSessionDiagnostics.Describe(exception)); + return opened ? ProviderSignOutResult.NotConfirmed : ProviderSignOutResult.NotOpened; } } } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOutResult.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOutResult.cs new file mode 100644 index 0000000..f3109c5 --- /dev/null +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOutResult.cs @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Presentation.SignIn; + +/// +/// How the identity provider's half of a sign-out ended (see ). A page that shows the +/// result has to tell these apart, because what the operator is told to do differs: nothing, look at the browser +/// setting, look at the page that is still open, or nothing because it was stopped on purpose. The log has the +/// kind of failure behind the middle two. +/// +public enum ProviderSignOutResult +{ + /// The provider's page was opened and the browser came back to this application's registered callback with this sign-out's own state: the provider's session has ended. + Confirmed, + + /// The provider's page was not opened, so the operator saw nothing and the provider's session is as it was: the default browser could not be started, or the callback inbox could not be opened, in which case no browser was started either. + NotOpened, + + /// The provider's page was opened and the provider did not confirm: the browser did not come back within the limit, it came back with this sign-out's state on another address, or the callback inbox failed while the sign-out waited. The page may still be open, and the provider's session may or may not have ended. + NotConfirmed, + + /// The caller's token ended the sign-out before the provider confirmed. When the token had already ended as the sign-out was started, nothing was opened; otherwise the provider's page was opened and may still be open. + Cancelled, +} diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs index bbd0084..4221c0f 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -10,7 +10,7 @@ using Qqq.PrintAgent.Presentation.Tests.Fakes; namespace Qqq.PrintAgent.Presentation.Tests.SignIn; -/// The identity provider's half of a sign-out: its page is opened, its return is recognized by this sign-out's own state within two minutes, and nothing of the request reaches the log. +/// The identity provider's half of a sign-out: its page is opened, its return is recognized by this sign-out's own state within two minutes, the result says how it ended, and nothing of the request reaches the log. public sealed class ProviderSignOutTests { private const string Hint = "synthetic-id-token-hint"; @@ -40,7 +40,7 @@ public sealed class ProviderSignOutTests SignInWorld world = new(); QqqProviderLogout logout = Logout(); - Task running = Over(world).CompleteAsync(logout); + Task running = Over(world).CompleteAsync(logout); FakeInbox inbox = Assert.Single(world.Inboxes); Assert.Equal([1], world.ListeningAtLaunch); Assert.Equal(logout.EndSessionUri, Assert.Single(world.Opened)); @@ -52,7 +52,7 @@ public sealed class ProviderSignOutTests Assert.False(running.IsCompleted); next.Deliver(new Uri(SignInWorld.Callback + "?state=" + State)); - Assert.True(await SignInWorld.EndsAsync(running)); + Assert.Equal(ProviderSignOutResult.Confirmed, await SignInWorld.EndsAsync(running)); Assert.True(next.Disposed); Assert.Equal(["INFO Browser callback inbox open.", "INFO Opening the identity provider's sign-out page in the default browser (id.example.com).", @@ -71,10 +71,10 @@ public sealed class ProviderSignOutTests SignInWorld world = new(); QqqProviderLogout logout = Logout("l\u043Egin.example.com:8443"); - Task running = Over(world).CompleteAsync(logout); + Task running = Over(world).CompleteAsync(logout); world.Inboxes[0].Deliver(new Uri(SignInWorld.Callback + "?state=" + State)); - Assert.True(await SignInWorld.EndsAsync(running)); + Assert.Equal(ProviderSignOutResult.Confirmed, await SignInWorld.EndsAsync(running)); Assert.Same(logout.EndSessionUri, Assert.Single(world.Opened)); Assert.Contains("INFO Opening the identity provider's sign-out page in the default browser (xn--lgin-55d.example.com:8443).", world.Log.Entries, StringComparer.Ordinal); Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains('\u043E', StringComparison.Ordinal) || entry.Contains("synthetic", StringComparison.Ordinal)); @@ -82,16 +82,16 @@ public sealed class ProviderSignOutTests - /// A callback that carries this sign-out's state but is not on the registered address is handed to the sign-out, which does not take it as the provider finishing. + /// A callback that carries this sign-out's state but is not on the registered address is handed to the sign-out, which does not take it as the provider finishing: the page was opened, and the provider did not confirm. [Fact] public async Task CallbackWithItsStateOnAnotherAddress_DoesNotConfirm() { SignInWorld world = new(); - Task running = Over(world).CompleteAsync(Logout()); + Task running = Over(world).CompleteAsync(Logout()); world.Inboxes[0].Deliver(new Uri("io.qrun.qqq-print-agent:/oauth/other?state=" + State)); - Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal(ProviderSignOutResult.NotConfirmed, await SignInWorld.EndsAsync(running)); Assert.Equal("INFO Identity provider sign-out callback did not match this sign-out.", world.Log.Entries[^1]); Assert.True(world.Inboxes[0].Disposed); } @@ -99,19 +99,23 @@ public sealed class ProviderSignOutTests /// - /// When the provider does not come back within two minutes, the browser cannot be opened, the inbox cannot be - /// opened or breaks, or the caller stops waiting, the sign-out is not confirmed. A failure is logged as a warning - /// with its kind. The caller's own cancellation is not a failure: it is logged as information, in fixed words, - /// without the text of the cancellation. Windows names what it could not start in its failure, which is the - /// whole sign-out address with the token hint; none of that reaches the log. + /// A sign-out that is not confirmed says which way it went, because the operator is told something different for + /// each. The page was never opened when the browser or the inbox could not be opened. The page was opened and the + /// provider did not confirm when two minutes passed, when the inbox broke meanwhile, or when the inbox's own wait + /// was ended by something other than this sign-out. The caller stopped it when its token ended the wait. A + /// failure is logged as a warning with its kind, running out of time as a warning in fixed words, and the + /// caller's own cancellation as information in fixed words, without the text of the cancellation. Windows names + /// what it could not start in its failure, which is the whole sign-out address with the token hint; none of that + /// reaches the log. /// [Theory] - [InlineData("limit", "WARN Identity provider sign-out was not confirmed: TaskCanceledException: A task was canceled.")] - [InlineData("token", "INFO Identity provider sign-out was stopped by its caller before the provider confirmed.")] - [InlineData("browser", "WARN Identity provider sign-out was not confirmed: IOException: " + BrowserStartFailure.WindowsReport)] - [InlineData("no inbox", "WARN Identity provider sign-out was not confirmed: UnauthorizedAccessException: synthetic open failure")] - [InlineData("inbox", "WARN Identity provider sign-out was not confirmed: IOException: synthetic pipe failure")] - public async Task ProviderThatDoesNotReturn_IsNotConfirmed(string ending, string entry) + [InlineData("limit", ProviderSignOutResult.NotConfirmed, 1, "WARN Identity provider sign-out was not confirmed: the provider did not return within the two minute limit.")] + [InlineData("token", ProviderSignOutResult.Cancelled, 1, "INFO Identity provider sign-out was stopped by its caller before the provider confirmed.")] + [InlineData("browser", ProviderSignOutResult.NotOpened, 0, "WARN The identity provider's sign-out page was not opened: IOException: " + BrowserStartFailure.WindowsReport)] + [InlineData("no inbox", ProviderSignOutResult.NotOpened, 0, "WARN The identity provider's sign-out page was not opened: UnauthorizedAccessException: synthetic open failure")] + [InlineData("inbox", ProviderSignOutResult.NotConfirmed, 1, "WARN Identity provider sign-out was not confirmed: IOException: synthetic pipe failure")] + [InlineData("inbox wait ended", ProviderSignOutResult.NotConfirmed, 1, "WARN Identity provider sign-out was not confirmed: OperationCanceledException: synthetic end of the inbox's wait")] + public async Task ProviderThatDoesNotConfirm_SaysWhetherItsPageWasOpened(string ending, ProviderSignOutResult result, int opened, string entry) { SignInWorld world = new() { @@ -120,26 +124,50 @@ public sealed class ProviderSignOutTests }; using CancellationTokenSource cancellation = new(); - Task running = Over(world).CompleteAsync(Logout(), cancellation.Token); - if(string.Equals(ending, "limit", StringComparison.Ordinal)) + Task running = Over(world).CompleteAsync(Logout(), cancellation.Token); + switch(ending) { - world.Time.Advance(TimeSpan.FromMinutes(2)); - } - else if(string.Equals(ending, "token", StringComparison.Ordinal)) - { - await cancellation.CancelAsync(); - } - else if(string.Equals(ending, "inbox", StringComparison.Ordinal)) - { - world.Inboxes[0].Fail(new IOException("synthetic pipe failure")); + case "limit": + world.Time.Advance(ProviderSignOut.Limit - TimeSpan.FromSeconds(1)); + Assert.False(running.IsCompleted); + world.Time.Advance(TimeSpan.FromSeconds(1)); + break; + case "token": + await cancellation.CancelAsync(); + break; + case "inbox": + world.Inboxes[0].Fail(new IOException("synthetic pipe failure")); + break; + case "inbox wait ended": + world.Inboxes[0].Fail(new OperationCanceledException("synthetic end of the inbox's wait")); + break; + default: + break; } - Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal(result, await SignInWorld.EndsAsync(running)); Assert.Equal(entry, world.Log.Entries[^1]); Assert.Equal(string.Equals(ending, "token", StringComparison.Ordinal), !world.Log.Entries.Exists(line => line.StartsWith("WARN", StringComparison.Ordinal))); Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); - Assert.Equal(string.Equals(ending, "browser", StringComparison.Ordinal) || string.Equals(ending, "no inbox", StringComparison.Ordinal) ? 0 : 1, world.Opened.Count); - Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(Hint, StringComparison.Ordinal) || entry.Contains(State, StringComparison.Ordinal)); + Assert.Equal(opened, world.Opened.Count); + Assert.DoesNotContain(world.Log.Entries, line => line.Contains(Hint, StringComparison.Ordinal) || line.Contains(State, StringComparison.Ordinal)); + } + + + + /// A sign-out whose caller had already stopped waiting when it was started opens nothing: no inbox and no browser page. It ends as cancelled, and says so as information. + [Fact] + public async Task CallerThatHadAlreadyStopped_OpensNothing() + { + SignInWorld world = new(); + using CancellationTokenSource cancellation = new(); + await cancellation.CancelAsync(); + + Assert.Equal(ProviderSignOutResult.Cancelled, await SignInWorld.EndsAsync(Over(world).CompleteAsync(Logout(), cancellation.Token))); + + Assert.Empty(world.Inboxes); + Assert.Empty(world.Opened); + Assert.Equal(["INFO Identity provider sign-out was stopped by its caller before the provider confirmed."], world.Log.Entries); } @@ -158,10 +186,10 @@ public sealed class ProviderSignOutTests { SignInWorld world = new(); - Task running = Over(world).CompleteAsync(Logout()); + Task running = Over(world).CompleteAsync(Logout()); Assert.Single(world.Inboxes).Fail(SignInWorld.UnlistedInboxFailure(kind)); - Assert.False(await SignInWorld.EndsAsync(running)); + Assert.Equal(ProviderSignOutResult.NotConfirmed, await SignInWorld.EndsAsync(running)); Assert.Equal("WARN Identity provider sign-out was not confirmed: IOException: " + SignInWorld.InboxFailedReport(kind), world.Log.Entries[^1]); Assert.True(world.Inboxes[0].Disposed); Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(SignInWorld.UnlistedFailureText, StringComparison.Ordinal) || entry.Contains(Hint, StringComparison.Ordinal) || entry.Contains(State, StringComparison.Ordinal)); @@ -172,7 +200,7 @@ public sealed class ProviderSignOutTests /// /// When Windows cannot start the browser, the failure it gives names what it could not start: the whole /// end-session address, with the provider's ID token hint and this sign-out's state. The sign-out is reported as - /// not confirmed, the log says that the default browser could not be opened, with the kind of failure and what to + /// not opened, the log says that the default browser could not be opened, with the kind of failure and what to /// check, and no log line holds one of those values or any query at all. The same holds for a launcher that fails /// in another way and names the address in its text. /// @@ -185,11 +213,11 @@ public sealed class ProviderSignOutTests SignInWorld world = new() { BrowserFailure = asWindows ? BrowserStartFailure.AsWindows(BrowserStartFailure.SignOutAddress) : BrowserStartFailure.AsAnotherKind(BrowserStartFailure.SignOutAddress) }; Assert.True(BrowserStartFailure.Leaks(world.BrowserFailure.Message)); - Assert.False(await SignInWorld.EndsAsync(Over(world).CompleteAsync(logout))); + Assert.Equal(ProviderSignOutResult.NotOpened, await SignInWorld.EndsAsync(Over(world).CompleteAsync(logout))); Assert.Equal(["INFO Browser callback inbox open.", "INFO Opening the identity provider's sign-out page in the default browser (id.example.com).", - "WARN Identity provider sign-out was not confirmed: IOException: " + report], world.Log.Entries); + "WARN The identity provider's sign-out page was not opened: IOException: " + report], world.Log.Entries); Assert.DoesNotContain(world.Log.Entries, BrowserStartFailure.Leaks); Assert.Empty(world.Opened); Assert.True(Assert.Single(world.Inboxes).Disposed); -- 2.54.0 From 144681b981075caca0cea21c0afc1867697f82ab Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:15:08 -0600 Subject: [PATCH 20/27] fix(companion): a sign-out whose provider page could not be opened no longer says the page was opened When the default browser could not be started for the identity provider's sign-out, the connection dialog still told the operator that the provider's sign-out "was opened in your browser but did not confirm; close that page and sign out there if it is still open". No page had been opened. The dialog now says that the provider's sign-out page could not be opened, that the operator may therefore still be signed in to the provider and the next sign-in may not ask for credentials, and what to check, in the fixed words every report of a browser that could not be opened ends with (BrowserLaunch.Remedy). Nothing of the failure's own text is shown, as before, and the log entry is unchanged. The change to SignInFlow.SignOut.cs is exactly this: the flow's private wait returns ProviderSignOutResult instead of a bool, with NotOpened for a browser that did not start, and SignInMessages.ProviderSignedOut takes that result. A callback inbox that cannot be opened is still reported with the old sentence, although no page is opened then either; that is left as it was. Tests: the two tests of a browser that cannot be started expect the new message, and that no message says a page "was opened in your browser"; the other unconfirmed endings keep their sentence. From the first author's notes on afe7e08. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 6 +++-- .../SignIn/BrowserLaunch.cs | 2 +- .../SignIn/SignInFlow.SignOut.cs | 20 ++++++++++---- .../SignIn/SignInMessages.cs | 16 ++++++++--- .../SignIn/SignInFlowSignOutTests.cs | 27 +++++++++++-------- 5 files changed, 48 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bfc7c8..b31a761 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,10 @@ sign-in not completed" message repeated Windows' own error text, and that text n whole sign-in address, with that attempt's state, nonce and code challenge. When the browser could not be started for the identity provider's sign-out, the log entry named the provider's sign-out address the same way, with its ID token hint. Both now say only that the default browser could not be opened, with the Windows error number, and what -to check: that a default browser is set in Windows Settings under Apps, Default apps. Sign-in and sign-out are -otherwise unchanged. Every release from 0.2.0-rc.1 to 1.2.1 has the sign-in case (0.1.x has no browser sign-in). The +to check: that a default browser is set in Windows Settings under Apps, Default apps. After a sign-out whose +provider page could not be opened, the dialog used to say that the provider's sign-out "was opened in your browser +but did not confirm"; it now says that the page could not be opened, that the provider's session may therefore +still be there, and what to check. Sign-in and sign-out are otherwise unchanged. Every release from 0.2.0-rc.1 to 1.2.1 has the sign-in case (0.1.x has no browser sign-in). The sign-out case is in no release. Both cases are in the development snapshot `snapshot-2.0.0-rc.1`, which was not installed anywhere, and on the unreleased `release/1.2.2` branch; 2.0 builds after that snapshot have neither ([audit](docs/AUDIT-2026-11-10.md), U22). diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs index 1e8d8d3..1efe4a6 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserLaunch.cs @@ -16,7 +16,7 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// internal static class BrowserLaunch { - /// What an operator can do about a browser that could not be opened; it follows the kind of failure in the failure's text, which is shown as the reason a sign-in was not completed. + /// What an operator can do about a browser that could not be opened; it follows the kind of failure in the failure's text, which is shown as the reason a sign-in was not completed, and it ends what the dialog says about a provider sign-out whose page could not be opened. internal const string Remedy = "Check that a default browser is set in Windows Settings under Apps, Default apps, then try again."; diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs index 3824f32..02afd4d 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInFlow.SignOut.cs @@ -101,11 +101,13 @@ public sealed partial class SignInFlow /// to this application's registered callback with this sign-out's own state. The inbox is opened first so a fast redirect is not lost. /// The request carries a sensitive token hint, so only its host is logged, and a browser that cannot be started is logged by /// the kind of failure only, because Windows' own text for it names the whole request (see ). - /// Returns whether the provider confirmed; the wait + /// Returns whether the provider confirmed, did not confirm, or was never asked because the browser could not be + /// started, which the operator is told as what it is (an inbox that could not be opened is still returned as not + /// confirmed, as it was before); the wait /// also ends when the caller's token does. When the flow is disposed the wait ends without a result, and that is left /// to the runner as a quiet end instead of being reported as an unconfirmed sign-out. /// - private async Task CompleteProviderSignOutAsync(QqqProviderLogout logout, CancellationToken cancellationToken) + private async Task CompleteProviderSignOutAsync(QqqProviderLogout logout, CancellationToken cancellationToken) { try { @@ -113,17 +115,25 @@ public sealed partial class SignInFlow using CancellationTokenSource limit = new(ProviderSignOutLimit, _time); using var wait = CancellationTokenSource.CreateLinkedTokenSource(limit.Token, cancellationToken); _log.Info("Opening the identity provider's sign-out page in the default browser (" + QqqOrigin.ShownAuthority(logout.EndSessionUri) + ")."); - BrowserLaunch.Open(_browser, logout.EndSessionUri); + try + { + BrowserLaunch.Open(_browser, logout.EndSessionUri); + } + catch(IOException exception) when(!_disposed) + { + _log.Warning("Identity provider sign-out was not confirmed: " + QqqSessionDiagnostics.Describe(exception)); + return ProviderSignOutResult.NotOpened; + } Uri callback = await inbox.ReceiveAsync(wait.Token); ThrowIfDisposed(); bool matched = logout.Matches(callback); _log.Info("Identity provider sign-out callback " + (matched ? "matched." : "did not match this sign-out.")); - return matched; + return matched ? ProviderSignOutResult.Confirmed : ProviderSignOutResult.NotConfirmed; } catch(Exception exception) when(!_disposed && exception is OperationCanceledException or IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception) { _log.Warning("Identity provider sign-out was not confirmed: " + QqqSessionDiagnostics.Describe(exception)); - return false; + return ProviderSignOutResult.NotConfirmed; } } } diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/SignInMessages.cs b/src/Qqq.PrintAgent.Presentation/SignIn/SignInMessages.cs index bc3fa44..489c1af 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/SignInMessages.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/SignInMessages.cs @@ -148,10 +148,18 @@ public static class SignInMessages - /// Whether the identity provider confirmed its sign-out, and what to do when it did not. - public static FeedbackMessage ProviderSignedOut(string message, bool confirmed) => confirmed - ? new("Account sign-out", message + " The identity provider session ended too, so the next sign-in asks for credentials.", FeedbackSeverity.Success) - : new("Account sign-out", message + " The identity provider sign-out was opened in your browser but did not confirm; close that page and sign out there if it is still open.", FeedbackSeverity.Warning); + /// + /// How the identity provider's sign-out ended, and what to do when it was not confirmed. A page that was never + /// opened, because the default browser could not be started, is said to be exactly that, with what to check: the + /// operator has no page to close, and the provider's session, if there is one, is still there. Every other + /// unconfirmed ending is told as before. + /// + public static FeedbackMessage ProviderSignedOut(string message, ProviderSignOutResult result) => result switch + { + ProviderSignOutResult.Confirmed => new("Account sign-out", message + " The identity provider session ended too, so the next sign-in asks for credentials.", FeedbackSeverity.Success), + ProviderSignOutResult.NotOpened => new("Account sign-out", message + " The identity provider's sign-out page could not be opened in your browser, so you may still be signed in to the identity provider and the next sign-in may not ask for credentials. " + BrowserLaunch.Remedy, FeedbackSeverity.Warning), + _ => new("Account sign-out", message + " The identity provider sign-out was opened in your browser but did not confirm; close that page and sign out there if it is still open.", FeedbackSeverity.Warning), + }; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs index e817004..955f1ed 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/SignInFlowSignOutTests.cs @@ -313,9 +313,11 @@ public sealed class SignInFlowSignOutTests /// When Windows cannot start the browser for the provider's sign-out, the failure it gives names what it could not /// start: the whole end-session address, with the provider's ID token hint and this sign-out's state. None of that /// is logged or shown. The log says that the default browser could not be opened, with the kind of failure and what - /// to check, the sign-out still completes on this computer with the warning the dialog already gave for a provider - /// that did not confirm, and no log line, message or property a view binds to holds one of those values or any - /// query at all. The same holds for a launcher that fails in another way and names the address in its text. + /// to check. The sign-out still completes on this computer, and the operator is told what is true: the provider's + /// page could not be opened, so the provider's session may still be there, and what to check. It is not told that a + /// page "was opened in your browser", because none was. No log line, message or property a view binds to holds one + /// of those values or any query at all. The same holds for a launcher that fails in another way and names the + /// address in its text. /// [Theory] [InlineData(true, BrowserStartFailure.WindowsReport)] @@ -334,7 +336,8 @@ public sealed class SignInFlowSignOutTests Assert.Equal("WARN Identity provider sign-out was not confirmed: IOException: " + report, fixture.Log.Entries[^1]); Assert.Equal([new FeedbackMessage("Account sign-out", "Signed out of QQQ. Finish signing out of the identity provider on the page that opened in your browser.", FeedbackSeverity.Informational), - new FeedbackMessage("Account sign-out", "Signed out of QQQ. The identity provider sign-out was opened in your browser but did not confirm; close that page and sign out there if it is still open.", FeedbackSeverity.Warning)], fixture.Shown); + new FeedbackMessage("Account sign-out", "Signed out of QQQ. The identity provider's sign-out page could not be opened in your browser, so you may still be signed in to the identity provider and the next sign-in may not ask for credentials. " + BrowserStartFailure.Remedy, FeedbackSeverity.Warning)], fixture.Shown); + Assert.DoesNotContain(fixture.Shown, message => message.Message.Contains("was opened in your browser", StringComparison.Ordinal)); Assert.DoesNotContain(fixture.Log.Entries, BrowserStartFailure.Leaks); Assert.DoesNotContain(fixture.Shown, message => BrowserStartFailure.Leaks(message.Title) || BrowserStartFailure.Leaks(message.Message)); Assert.DoesNotContain(BrowserStartFailure.Bound(fixture.Flow), BrowserStartFailure.Leaks); @@ -347,14 +350,16 @@ public sealed class SignInFlowSignOutTests /// - /// When the provider does not come back within two minutes, the browser cannot be opened, or the caller cancels, the - /// wait ends, the sign-out still completes locally, and the operator is warned that the provider did not confirm. + /// When the provider does not come back within two minutes, the browser cannot be opened, or the caller cancels, + /// the wait ends, the sign-out still completes locally, and the operator is warned. The warning says that the + /// provider did not confirm, except for a browser that could not be opened, where it says that instead: no page + /// was opened that could be closed. /// [Theory] - [InlineData("limit", "TaskCanceledException")] - [InlineData("browser", "IOException: " + BrowserStartFailure.WindowsReport)] - [InlineData("token", "TaskCanceledException")] - public async Task ProviderThatDoesNotReturn_IsReportedAsUnconfirmed(string ending, string cause) + [InlineData("limit", "TaskCanceledException", "did not confirm; close that page and sign out there if it is still open.")] + [InlineData("browser", "IOException: " + BrowserStartFailure.WindowsReport, "could not be opened in your browser, so you may still be signed in to the identity provider and the next sign-in may not ask for credentials. " + BrowserStartFailure.Remedy)] + [InlineData("token", "TaskCanceledException", "did not confirm; close that page and sign out there if it is still open.")] + public async Task ProviderThatDoesNotReturn_IsReportedAsUnconfirmed(string ending, string cause, string told) { SignInFixture fixture = WithProviderSignOut(); fixture.BrowserFailure = string.Equals(ending, "browser", StringComparison.Ordinal) ? new Win32Exception(2, "The system cannot find the file specified.") : null; @@ -372,7 +377,7 @@ public sealed class SignInFlowSignOutTests Assert.True(await SignInFixture.EndsAsync(running)); Assert.Equal(FeedbackSeverity.Warning, fixture.Shown[^1].Severity); - Assert.EndsWith("did not confirm; close that page and sign out there if it is still open.", fixture.Shown[^1].Message, StringComparison.Ordinal); + Assert.EndsWith(told, fixture.Shown[^1].Message, StringComparison.Ordinal); Assert.Contains(fixture.Log.Entries, entry => entry.StartsWith("WARN Identity provider sign-out was not confirmed: " + cause, StringComparison.Ordinal)); Assert.True(fixture.Inboxes[0].Disposed); Assert.False(fixture.Flow.IsBusy); -- 2.54.0 From 9d679a20f9dc63b15bbd40bc6b7882ad6e953aef Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:16:44 -0600 Subject: [PATCH 21/27] fix(presentation): a browser sign-in that ended before a page was opened no longer blames the browser When a browser sign-in ended without a result, CompanionSignIn copied the protocol handler's trace or, when there was none, logged that "the browser never launched the sign-in protocol handler" and that "either the identity provider did not redirect ... or the browser blocked opening the QQQ Print Agent sign-in link". It said so for attempts that ended before any browser was started: the server did not list this application's callback, the callback inbox could not be opened, or the default browser could not be started. Nothing had been opened that could have redirected or been blocked. The exchange now notes what it is at until the provider's page is open. An attempt that ends before that logs, as information, that it ended before a browser page was opened and what it had not got past: the server does not list this application's callback; the session had not prepared a usable sign-in address; the attempt was not yet waiting for its callback; the default browser was not started. It does not read the handler's trace, which could only be another attempt's. Attempts that end after the page was opened are reported as before. This is kept to CompanionSignIn. The dialog's flow has the same wording and keeps it: its text is its own, not shared. Tests: the failure theory expects the entry that is true for each row and that the trace is read only after a page was opened; the unlisted callback and the browser that cannot be started expect their own reason; Cancel and the limit while the session is still beginning say that no page was opened. Review of afe7e08, nit 8. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.Browser.cs | 27 ++++++- .../SignIn/CompanionSignInBrowserTests.cs | 78 +++++++++++++++---- 2 files changed, 88 insertions(+), 17 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs index b2a136b..38fc0b8 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -33,6 +33,7 @@ public sealed partial class CompanionSignIn private static readonly TimeSpan s_traceWindow = TimeSpan.FromMinutes(10); private CancellationTokenSource? _browserCancel; private bool _handedOver; + private string? _unopened; @@ -112,7 +113,9 @@ public sealed partial class CompanionSignIn /// The browser exchange itself: begin the sign-in on the session, read the state it sent from the address it /// returned, register that state with the dispatcher (which has an inbox open before the browser is, so a fast /// redirect is not lost), open the provider's page in the default browser, wait for the callback with that state, - /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Only the + /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Until + /// the page is open, the exchange notes what it is at, so an attempt that ends before any browser was involved can + /// say that, and why (see ). Only the /// provider's host is logged, never the address, its state or the callback. The token is looked at again after /// each wait: once the sign-in was begun, so a browser is not opened for a wait that has already ended, and once /// the callback is there, so the session is not asked to complete for one. That second look is needed because a @@ -123,17 +126,22 @@ public sealed partial class CompanionSignIn private async Task ExchangeWithBrowserAsync(ISignInSession session, CancellationToken cancellationToken) { _log.Info("Browser sign-in requested for {Server}; this application's callback is {Callback}.", QqqOrigin.ShownAuthority(session.Origin), _callbacks.RedirectUri); + _unopened = "the server does not list this application's callback"; if(!_redirects.Contains(_callbacks.RedirectUri, StringComparer.Ordinal)) { _log.Warning("The server's native grant does not list this application's callback {Callback}; it lists {Count} other address(es). Add the callback to the QQQ native session grant.", _callbacks.RedirectUri, _redirects.Count); throw new InvalidOperationException("No approved native browser callback is configured."); } + _unopened = "the session had not prepared a usable sign-in address"; Uri authorization = await session.BeginBrowserSignInAsync(new Uri(_callbacks.RedirectUri), cancellationToken); cancellationToken.ThrowIfCancellationRequested(); string state = BrowserCallbackDispatcher.ReadState(authorization) ?? throw new InvalidOperationException("The sign-in address the session prepared carries no state of its own, so its callback could not be told from another."); + _unopened = "the attempt was not yet waiting for its callback"; using BrowserCallbackTicket ticket = _dispatcher.Register(state); _log.Info("Opening the identity provider's sign-in page in the default browser ({Provider}).", QqqOrigin.ShownAuthority(authorization)); + _unopened = "the default browser was not started"; BrowserLaunch.Open(_browser, authorization); + _unopened = null; Uri callback = await ticket.Callback.WaitAsync(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); _log.Info("Browser callback received; completing the sign-in."); @@ -163,12 +171,23 @@ public sealed partial class CompanionSignIn /// - /// Copies the protocol handler's recent trace into the activity log, or states that the browser never launched the - /// handler at all, so a hand-off that stops outside the companion is still visible in one place. The handler - /// writes that trace without the query of any callback. + /// Says what is known about the hand-off from the browser when an attempt ends without a result. When the + /// provider's page was opened, it copies the protocol handler's recent trace into the activity log, or states + /// that the browser never launched the handler at all, so a hand-off that stops outside the companion is still + /// visible in one place. The handler writes that trace without the query of any callback. When the attempt ended + /// before a page was opened, none of that applies: no browser was started, so nothing could have redirected or + /// been blocked, and a trace from the last ten minutes would be some other attempt's. The entry then says that + /// no page was opened and what the attempt had not got past: the server not listing this application's callback, + /// the session not having prepared an address, the wait for the callback not having started, or the browser not + /// having started. /// private void ReportCallbackTrace() { + if(_unopened is { } reason) + { + _log.Info("This attempt ended before a browser page was opened ({Reason}), so the sign-in protocol handler was not involved and its trace is not copied here.", reason); + return; + } IReadOnlyList lines = _callbacks.RecentTrace(s_traceWindow); if(lines.Count == 0) { diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index f02a63c..3afda3c 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -19,6 +19,11 @@ public sealed class CompanionSignInBrowserTests + /// What the log says, in place of anything about the protocol handler, when an attempt ended before a browser page was opened, with what the attempt had not got past. + private static string NotOpened(string reason) => "INFO This attempt ended before a browser page was opened (" + reason + "), so the sign-in protocol handler was not involved and its trace is not copied here."; + + + /// True when an entry holds something that must never be logged: a sign-in state, a one-time code or a session token. private static bool Secret(string entry) => entry.Contains("synthetic-state", StringComparison.Ordinal) || entry.Contains("one-time-code", StringComparison.Ordinal) || entry.Contains("synthetic-session-token", StringComparison.Ordinal); @@ -200,6 +205,9 @@ public sealed class CompanionSignInBrowserTests Assert.True(signIn.HasSession); Assert.False(signIn.IsBusy); Assert.Equal("WARN The server's native grant does not list this application's callback io.qrun.qqq-print-agent:/oauth/callback; it lists 2 other address(es). Add the callback to the QQQ native session grant.", world.Log.Entries[1]); + Assert.Equal(NotOpened("the server does not list this application's callback"), world.Log.Entries[2]); + Assert.DoesNotContain(NeverLaunched, world.Log.Entries, StringComparer.Ordinal); + Assert.Empty(world.TraceWindows); Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains("synthetic-other-callback", StringComparison.Ordinal) || entry.Contains("/oauth/Callback", StringComparison.Ordinal)); } @@ -248,19 +256,22 @@ public sealed class CompanionSignInBrowserTests /// state, the inbox cannot be opened, the browser cannot be opened, the inbox breaks while waiting, the session /// refuses the callback, no credential can be taken, or the server's own time limit ends the completion. When /// the browser cannot be opened the failure Windows gives names the whole sign-in address; the reason shown and - /// logged names only the kind of failure. No state reaches the log or the reason in any of them. + /// logged names only the kind of failure. No state reaches the log or the reason in any of them. What the log + /// adds about the hand-off from the browser is true for where the attempt stopped: before a page was opened it + /// says that, with what the attempt had not got past, and reads no handler trace; after, it says that the + /// browser never launched the protocol handler. /// [Theory] - [InlineData("begin", 0, "The server's sign-in configuration is not usable.", "QqqSessionException: The server's sign-in configuration is not usable.")] - [InlineData("no state", 0, "The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.", "InvalidOperationException: The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.")] - [InlineData("no inbox", 0, "synthetic open failure", "IOException: synthetic open failure")] - [InlineData("browser", 0, BrowserStartFailure.WindowsReport, "IOException: " + BrowserStartFailure.WindowsReport)] - [InlineData("launcher", 0, BrowserStartFailure.OtherReport, "IOException: " + BrowserStartFailure.OtherReport)] - [InlineData("inbox", 1, "Invalid QQQ browser callback.", "InvalidDataException: Invalid QQQ browser callback.")] - [InlineData("complete", 1, "The server's answer was not usable.", "QqqSessionException: The server's answer was not usable.")] - [InlineData("export", 1, "Sign in before exporting the session.", "QqqSessionException: Sign in before exporting the session.")] - [InlineData("time limit", 1, "The server did not answer in time.", "TaskCanceledException: The server did not answer in time.")] - public async Task Browser_FailureDuringTheExchange_IsReportedWithItsReason(string step, int opened, string reason, string logged) + [InlineData("begin", "the session had not prepared a usable sign-in address", "The server's sign-in configuration is not usable.", "QqqSessionException: The server's sign-in configuration is not usable.")] + [InlineData("no state", "the session had not prepared a usable sign-in address", "The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.", "InvalidOperationException: The sign-in address the session prepared carries no state of its own, so its callback could not be told from another.")] + [InlineData("no inbox", "the attempt was not yet waiting for its callback", "synthetic open failure", "IOException: synthetic open failure")] + [InlineData("browser", "the default browser was not started", BrowserStartFailure.WindowsReport, "IOException: " + BrowserStartFailure.WindowsReport)] + [InlineData("launcher", "the default browser was not started", BrowserStartFailure.OtherReport, "IOException: " + BrowserStartFailure.OtherReport)] + [InlineData("inbox", null, "Invalid QQQ browser callback.", "InvalidDataException: Invalid QQQ browser callback.")] + [InlineData("complete", null, "The server's answer was not usable.", "QqqSessionException: The server's answer was not usable.")] + [InlineData("export", null, "Sign in before exporting the session.", "QqqSessionException: Sign in before exporting the session.")] + [InlineData("time limit", null, "The server did not answer in time.", "TaskCanceledException: The server did not answer in time.")] + public async Task Browser_FailureDuringTheExchange_IsReportedWithItsReason(string step, string? unopened, string reason, string logged) { const string address = "https://id.example.com/authorize?state=synthetic-state-a-1"; SignInWorld world = new(); @@ -300,9 +311,11 @@ public sealed class CompanionSignInBrowserTests Assert.True(signIn.HasSession); Assert.False(session.Disposed); Assert.False(signIn.IsBusy); - Assert.Equal(opened, world.Opened.Count); + Assert.Equal(unopened is null ? 1 : 0, world.Opened.Count); Assert.All(world.Inboxes, inbox => Assert.True(inbox.Disposed)); - Assert.Contains(NeverLaunched, world.Log.Entries, StringComparer.Ordinal); + Assert.Single(world.Log.Entries, entry => string.Equals(entry, unopened is null ? NeverLaunched : NotOpened(unopened), StringComparison.Ordinal)); + Assert.Equal(unopened is null ? 1 : 0, world.TraceWindows.Count); + Assert.DoesNotContain(world.Log.Entries, entry => entry.Contains(unopened is null ? "before a browser page was opened" : "never launched", StringComparison.Ordinal)); Assert.Contains("ERROR Browser sign-in not completed: " + logged, world.Log.Entries, StringComparer.Ordinal); Assert.DoesNotContain(world.Log.Entries, Secret); Assert.False(Secret(signIn.Failure!)); @@ -386,6 +399,8 @@ public sealed class CompanionSignInBrowserTests Assert.Contains(world.Log.Entries, entry => entry.StartsWith("DEBUG Browser sign-in not completed detail: System.IO.IOException: " + report, StringComparison.Ordinal)); Assert.DoesNotContain(world.Log.Entries, BrowserStartFailure.Leaks); Assert.DoesNotContain(BrowserStartFailure.Bound(signIn), BrowserStartFailure.Leaks); + Assert.Contains(NotOpened("the default browser was not started"), world.Log.Entries, StringComparer.Ordinal); + Assert.DoesNotContain(NeverLaunched, world.Log.Entries, StringComparer.Ordinal); Assert.Empty(world.Opened); Assert.True(Assert.Single(world.Inboxes).Disposed); Assert.True(signIn.HasSession); @@ -394,6 +409,43 @@ public sealed class CompanionSignInBrowserTests + /// + /// The operator cancels, or the three minutes run out, while the session is still beginning the sign-in. No + /// browser page was opened, so the log does not say that the browser never launched the protocol handler or that + /// the provider did not redirect: it says the attempt ended before a page was opened and what it had not got + /// past. The session stays. + /// + [Theory] + [InlineData(false, CompanionSignInState.BrowserCanceled, "INFO Browser sign-in to print.example.com was cancelled by the operator.")] + [InlineData(true, CompanionSignInState.BrowserTimedOut, "INFO Browser sign-in to print.example.com was given up after the three minute limit.")] + public async Task Browser_WaitEndsWhileTheSessionBegins_SaysNoPageWasOpened(bool byLimit, CompanionSignInState ending, string entry) + { + SignInWorld world = new(); + using CompanionSignIn signIn = await world.BrowserReadyAsync(); + world.Sessions[0].PendingBegin = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + Task running = signIn.SignInWithBrowserAsync(); + if(byLimit) + { + world.Time.Advance(CompanionSignIn.BrowserSignInLimit); + } + else + { + signIn.CancelBrowserSignIn(); + } + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.Equal(ending, signIn.State); + Assert.Equal([Requested, entry, NotOpened("the session had not prepared a usable sign-in address")], world.Log.Entries); + Assert.Empty(world.Opened); + Assert.Empty(world.Inboxes); + Assert.Empty(world.TraceWindows); + Assert.True(signIn.HasSession); + Assert.False(world.Sessions[0].Disposed); + } + + + /// /// When a browser sign-in is not completed, what the protocol handler recorded is copied into the log, so a /// hand-off that stopped outside the companion can be seen in one place; when it recorded nothing in the last ten -- 2.54.0 From ddefb134c0504996a4b5659f35a676055327c493 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:17:42 -0600 Subject: [PATCH 22/27] docs(presentation): every private field of the new sign-in types says what it holds The repository's rule is a /// on every member. The private fields of BrowserCallbackDispatcher, BrowserCallbackTicket, CompanionSignIn (both parts) and ProviderSignOut had none. Each now says what it holds and, where it matters, when: which fields are guarded by the gate, which wait exists while an operation can still be cancelled, which flags outlive an attempt and which do not. SignInFlow is left as it is. No behaviour changes. Review of afe7e08, nit 7. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/BrowserCallbackDispatcher.cs | 11 +++++++ .../SignIn/BrowserCallbackTicket.cs | 3 ++ .../SignIn/CompanionSignIn.Browser.cs | 11 +++++-- .../SignIn/CompanionSignIn.cs | 33 +++++++++++++++++++ .../SignIn/ProviderSignOut.cs | 7 ++++ 5 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs index 51cfce3..45d6e9e 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackDispatcher.cs @@ -27,11 +27,22 @@ public sealed class BrowserCallbackDispatcher /// The longest query a callback may have, in characters; the session refuses a longer one. internal const int LongestQuery = 16_384; + /// Where an inbox is opened. private readonly IBrowserCallbackSource _callbacks; + + /// The log; written to only through , so that it cannot break the dispatcher. private readonly IPresentationLog _log; + + /// Guards the waiting set and the open inbox, which the window's thread and the threads callbacks arrive on both change. private readonly Lock _gate = new(); + + /// The tickets that wait, by the state each registered. A state is compared exactly: it is somebody's only when it is the very one that was sent. private readonly Dictionary _waiting = new(StringComparer.Ordinal); + + /// The inbox that is open; null while no ticket waits. A wait that ends on an inbox that is no longer this one has nothing to do. private IBrowserCallbackInbox? _inbox; + + /// Ends the wait on the open inbox when the inbox is closed; null while none is open. private CancellationTokenSource? _listening; diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs index 80c6ced..a095362 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/BrowserCallbackTicket.cs @@ -14,7 +14,10 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// internal sealed class BrowserCallbackTicket : IDisposable { + /// What the exchange waits on. Its continuations run asynchronously, so whoever awaits the ticket never continues inside the dispatcher, on the thread a callback arrived on. private readonly TaskCompletionSource _callback = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// The dispatcher the ticket is registered with, which is told when the claim ends. private readonly BrowserCallbackDispatcher _dispatcher; diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs index 38fc0b8..f9f6a72 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -30,9 +30,16 @@ public sealed partial class CompanionSignIn /// How long a browser sign-in waits before it is given up. public static readonly TimeSpan BrowserSignInLimit = TimeSpan.FromMinutes(3); + /// How far back the protocol handler's trace is read when a browser sign-in ends without a result. private static readonly TimeSpan s_traceWindow = TimeSpan.FromMinutes(10); + + /// What the Cancel button cancels: set while a browser exchange runs, and cleared before the exchange's cancellation sources are released. private CancellationTokenSource? _browserCancel; + + /// True from the moment the running browser attempt hands its callback to the session until the attempt has ended. An attempt that ends without a result while this is set discards the session. private bool _handedOver; + + /// What the running browser attempt has not got past on its way to opening the provider's page, in words for the log; null once the page is open. An attempt that ends while this is set never involved a browser. private string? _unopened; @@ -115,8 +122,8 @@ public sealed partial class CompanionSignIn /// redirect is not lost), open the provider's page in the default browser, wait for the callback with that state, /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Until /// the page is open, the exchange notes what it is at, so an attempt that ends before any browser was involved can - /// say that, and why (see ). Only the - /// provider's host is logged, never the address, its state or the callback. The token is looked at again after + /// say that, and why (see ). Only the provider's host is logged, never the + /// address, its state or the callback. The token is looked at again after /// each wait: once the sign-in was begun, so a browser is not opened for a wait that has already ended, and once /// the callback is there, so the session is not asked to complete for one. That second look is needed because a /// callback that has already arrived is handed over whatever the token says, and a session is not bound to diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs index 329a00a..1e8cebf 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -23,22 +23,55 @@ namespace Qqq.PrintAgent.Presentation.SignIn; /// public sealed partial class CompanionSignIn : ObservableObject, IDisposable { + /// Creates the session a read of the sign-in description runs on. private readonly ISignInSessionFactory _sessions; + + /// Opens the provider's page; used only through . private readonly IBrowserLauncher _browser; + + /// Names this application's registered callback and reads the protocol handler's trace. The inbox itself belongs to the dispatcher. private readonly IBrowserCallbackSource _callbacks; + + /// The one dispatcher a browser sign-in waits for its callback through. private readonly BrowserCallbackDispatcher _dispatcher; + + /// The log. No password, credential, code, state or address with a query is ever passed to it. private readonly IPresentationLog _log; + + /// The clock the browser sign-in's time limit runs on. private readonly TimeProvider _time; + + /// Cancelled when the sign-in is disposed, which ends the operation that is running. private readonly CancellationTokenSource _lifetime = new(); + + /// The session that is held, on which a sign-in can be made; null when none is. private ISignInSession? _session; + + /// The callbacks the held session's description lists for a browser sign-in. They are compared with this application's own and never logged. private IReadOnlyList _redirects = []; + + /// The wait of the operation that is running, from its start until it begins to be released; null otherwise. While it is set, the operation can still be cancelled and will discard the session on its way out. private CancellationTokenSource? _operation; + + /// Backs . private CompanionSignInState _state; + + /// Backs . private SignInOffer? _offer; + + /// Backs . private QqqCertificateRejection? _rejection; + + /// Backs . private string? _failure; + + /// True from the moment an operation claims the sign-in until it has been released, announcements included; it backs . private bool _operating; + + /// True when a discard was asked for while an operation ran: the operation discards the session as it ends. private bool _discarding; + + /// True once the sign-in was disposed; nothing is started or announced after that. private bool _disposed; diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs index 7e20402..9f7e50f 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/ProviderSignOut.cs @@ -23,9 +23,16 @@ public sealed class ProviderSignOut /// How long the provider is given to confirm its sign-out. public static readonly TimeSpan Limit = TimeSpan.FromMinutes(2); + /// Opens the provider's page; used only through . private readonly IBrowserLauncher _browser; + + /// The one dispatcher the sign-out waits for its callback through. private readonly BrowserCallbackDispatcher _dispatcher; + + /// The log. Neither the token hint nor the state nor the address is ever passed to it. private readonly IPresentationLog _log; + + /// The clock the two minute limit runs on. private readonly TimeProvider _time; -- 2.54.0 From 56969892bd5ba74ffe71ad27876933ccf1756646 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:18:33 -0600 Subject: [PATCH 23/27] docs(tests): the private fields and constants of the sign-in tests say what they hold The same rule as for the source types, for the test types this branch added or touched: the fakes' private fields (FakeInbox, NoContext, SignInWorld) and the expected log entries the four test classes keep as constants each get their ///. No test changes. Review of afe7e08, nit 7. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs | 5 +++++ tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs | 1 + tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs | 1 + .../SignIn/BrowserCallbackDispatcherTests.cs | 3 +++ .../SignIn/CompanionSignInBrowserTests.cs | 5 +++++ .../SignIn/CompanionSignInTests.cs | 1 + .../SignIn/ProviderSignOutTests.cs | 3 +++ 7 files changed, 19 insertions(+) diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs index 2c9740b..cc064fe 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/FakeInbox.cs @@ -17,8 +17,13 @@ namespace Qqq.PrintAgent.Presentation.Tests.Fakes; /// internal sealed class FakeInbox(bool answersInline = false) : IBrowserCallbackInbox { + /// What the wait ends with: the callback a test delivers, or the failure it injects. private readonly TaskCompletionSource _callback = new(answersInline ? TaskCreationOptions.None : TaskCreationOptions.RunContinuationsAsynchronously); + + /// Completed when the flow starts waiting. private readonly TaskCompletionSource _listening = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// The flow's wait, once it has started. private Task? _wait; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs index ed58897..b5eda5c 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/NoContext.cs @@ -13,6 +13,7 @@ namespace Qqq.PrintAgent.Presentation.Tests.Fakes; /// internal sealed class NoContext : IDisposable { + /// The context the thread had, to put back. private readonly SynchronizationContext? _before = SynchronizationContext.Current; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs index 7eecc36..c382be6 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/Fakes/SignInWorld.cs @@ -33,6 +33,7 @@ internal sealed class SignInWorld : ISignInSessionFactory, IBrowserLauncher, IBr /// The marked text of an inbox failure of a kind no exchange lists, so a test can show that nothing of it is logged or shown. internal const string UnlistedFailureText = "synthetic-inbox-failure-text"; + /// Completed with the next inbox that is opened, for a test that waits for it (see ). private volatile TaskCompletionSource? _awaitedInbox; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs index 11066bc..ef9e172 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/BrowserCallbackDispatcherTests.cs @@ -19,7 +19,10 @@ namespace Qqq.PrintAgent.Presentation.Tests.SignIn; /// public sealed class BrowserCallbackDispatcherTests { + /// The whole of what the log says about a callback that was dropped. private const string Dropped = "WARN A browser callback that belongs to no waiting sign-in or sign-out was dropped. Nothing of it is logged."; + + /// What the log says each time an inbox is opened. private const string InboxOpen = "INFO Browser callback inbox open."; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs index 3afda3c..ad47b32 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInBrowserTests.cs @@ -13,8 +13,13 @@ namespace Qqq.PrintAgent.Presentation.Tests.SignIn; /// The companion's browser sign-in: the exchange through the default browser and the one callback dispatcher, its time limit and cancellation, what is reported when it does not complete, and the thread everything is announced on. public sealed class CompanionSignInBrowserTests { + /// The first entry of every browser sign-in to the first server. private const string Requested = "INFO Browser sign-in requested for print.example.com; this application's callback is io.qrun.qqq-print-agent:/oauth/callback."; + + /// What the log says when an attempt that ended without a result had already handed its callback to the session, which is then discarded. private const string Discarded = "INFO The browser sign-in ended without a result after its callback had been handed to the session, so the session is discarded: the server may have signed it in, and nothing here waits for that. The next attempt reads the sign-in description again."; + + /// What the log says when a page was opened and the protocol handler recorded nothing. private const string NeverLaunched = "WARN The browser never launched the sign-in protocol handler in the last 10 minutes (no entries in trace/auth-callback.log). Either the identity provider did not redirect to io.qrun.qqq-print-agent:/oauth/callback (check the provider's allowed redirect URIs and any error page it showed), or the browser blocked opening the QQQ Print Agent sign-in link."; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs index ae02e6e..5b71eb3 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -15,6 +15,7 @@ namespace Qqq.PrintAgent.Presentation.Tests.SignIn; /// The companion's own sign-in: reading a server's sign-in description as the signed-in user, signing in by password, and what it holds, announces and logs. Browser sign-in has its own file. public sealed class CompanionSignInTests { + /// The first entry of every read of the first server's description under no certificate exception. private const string Reading = "INFO Reading the sign-in description of print.example.com as this Windows account; an untrusted certificate is accepted from none."; diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs index 4221c0f..97c2800 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/ProviderSignOutTests.cs @@ -13,7 +13,10 @@ namespace Qqq.PrintAgent.Presentation.Tests.SignIn; /// The identity provider's half of a sign-out: its page is opened, its return is recognized by this sign-out's own state within two minutes, the result says how it ended, and nothing of the request reaches the log. public sealed class ProviderSignOutTests { + /// The marked ID token hint of the synthetic sign-out address, which must reach no log line. private const string Hint = "synthetic-id-token-hint"; + + /// The state of the synthetic sign-out, which must reach no log line. private const string State = "synthetic-sign-out-state"; -- 2.54.0 From 5bb2dc382a70d44c559e4fe62e74feefed6c7005 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:20:53 -0600 Subject: [PATCH 24/27] docs(presentation): reflow the comment on the browser exchange The comment on ExchangeWithBrowserAsync was left with a short line when the sentence about what the exchange notes before a page is open was added for nit 8. Words unchanged. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.Browser.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs index f9f6a72..9257742 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.Browser.cs @@ -123,12 +123,12 @@ public sealed partial class CompanionSignIn /// and complete the sign-in on the session that started it. The registration ends when the exchange does. Until /// the page is open, the exchange notes what it is at, so an attempt that ends before any browser was involved can /// say that, and why (see ). Only the provider's host is logged, never the - /// address, its state or the callback. The token is looked at again after - /// each wait: once the sign-in was begun, so a browser is not opened for a wait that has already ended, and once - /// the callback is there, so the session is not asked to complete for one. That second look is needed because a - /// callback that has already arrived is handed over whatever the token says, and a session is not bound to - /// refuse: the check is made here and not left to it. Completing takes the same token, so a wait that ends while - /// the session completes ends the completion too. + /// address, its state or the callback. The token is looked at again after each wait: once the sign-in was begun, + /// so a browser is not opened for a wait that has already ended, and once the callback is there, so the session + /// is not asked to complete for one. That second look is needed because a callback that has already arrived is + /// handed over whatever the token says, and a session is not bound to refuse: the check is made here and not left + /// to it. Completing takes the same token, so a wait that ends while the session completes ends the completion + /// too. /// private async Task ExchangeWithBrowserAsync(ISignInSession session, CancellationToken cancellationToken) { -- 2.54.0 From 45d0c5198212ab696d843e81eb5b6bb952419d96 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:20:54 -0600 Subject: [PATCH 25/27] fix(presentation): disposing from a subscriber while an operation is released discards the session Dispose() had the hole Discard() had (S1), seen while reading the fixes through: it decided "an operation is running" by the busy flag and left the session to that operation. An operation that has ended and is being released announces how it ended while still busy. A view that disposed the sign-in from that announcement left the session to an operation that was past the point of discarding it, so the session was never disposed. Dispose() now decides as Discard() does, by the operation's own wait. Test: a caller-cancelled password sign-in whose "ready" announcement disposes the sign-in; the session is discarded and nothing more is announced. Review of afe7e08, S1 (the same defect in Dispose). Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- .../SignIn/CompanionSignIn.cs | 8 +++-- .../SignIn/CompanionSignInTests.cs | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs index 1e8cebf..1dd5cc3 100644 --- a/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs +++ b/src/Qqq.PrintAgent.Presentation/SignIn/CompanionSignIn.cs @@ -331,8 +331,10 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable /// /// Ends the sign-in. It only cancels: an operation that is still running sees the cancellation, ends quietly and - /// discards the session itself. When nothing is running the session is discarded here. After this nothing is - /// announced. + /// discards the session itself. When nothing is running the session is discarded here, and "running" is decided + /// as it is in , by the operation's own wait: a subscriber that disposes the sign-in while + /// an operation that has ended is being released finds no call using the session, and nothing left that would + /// discard it later. After this nothing is announced. /// public void Dispose() { @@ -342,7 +344,7 @@ public sealed partial class CompanionSignIn : ObservableObject, IDisposable } _disposed = true; _lifetime.Cancel(); - if(!_operating) + if(_operation is null) { DropSession(); } diff --git a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs index 5b71eb3..6d5b853 100644 --- a/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs +++ b/tests/Qqq.PrintAgent.Presentation.Tests/SignIn/CompanionSignInTests.cs @@ -601,6 +601,39 @@ public sealed class CompanionSignInTests + /// + /// The same moment, with the sign-in disposed instead of discarded: a view that closes when it hears how an + /// operation ended. The operation has ended and is only being released, so nothing is left that would discard + /// the session later. Disposing discards it there and then, and nothing more is announced. + /// + [Fact] + public async Task Dispose_FromASubscriberWhileAnOperationIsBeingReleased_DiscardsTheSession() + { + using CancellationTokenSource caller = new(); + SignInWorld world = new(); + CompanionSignIn signIn = await world.PasswordReadyAsync(); + world.Sessions[0].PendingPassword = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + List changes = SignInWorld.Watch(signIn); + signIn.PropertyChanged += (_, change) => + { + if(string.Equals(change.PropertyName, nameof(CompanionSignIn.State), StringComparison.Ordinal) && signIn.State == CompanionSignInState.Ready) + { + signIn.Dispose(); + } + }; + Task running = signIn.SignInWithPasswordAsync("synthetic-operator", "synthetic-password", caller.Token); + await caller.CancelAsync(); + + Assert.Null(await SignInWorld.EndsAsync(running)); + Assert.True(world.Sessions[0].Disposed); + Assert.False(signIn.HasSession); + Assert.Null(signIn.Offer); + Assert.False(signIn.IsBusy); + Assert.Equal(["IsBusy=True", "State=SigningIn", "State=Ready"], changes); + } + + + /// /// A read never returns an offer whose session is gone. A subscriber that discards while the read announces that /// it is ready ends the read's session with it: the read returns nothing, exactly as the sign-in then offers -- 2.54.0 From df8ba707b9464a48c69d58c0169df4191f58f874 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:21:42 -0600 Subject: [PATCH 26/27] docs(changelog): reflow the sign-in entries and name the dispatcher's log rule Two paragraphs of the unreleased sign-in entries had lines left long by this round's additions; they are wrapped again, words unchanged. The dispatcher's entry gains the one sentence it lacked for nit 3: a log that cannot be written to does not stop the dispatcher. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b31a761..923b4aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,10 +11,10 @@ token hint. Both now say only that the default browser could not be opened, with to check: that a default browser is set in Windows Settings under Apps, Default apps. After a sign-out whose provider page could not be opened, the dialog used to say that the provider's sign-out "was opened in your browser but did not confirm"; it now says that the page could not be opened, that the provider's session may therefore -still be there, and what to check. Sign-in and sign-out are otherwise unchanged. Every release from 0.2.0-rc.1 to 1.2.1 has the sign-in case (0.1.x has no browser sign-in). The -sign-out case is in no release. Both cases are in the development snapshot `snapshot-2.0.0-rc.1`, which was not -installed anywhere, and on the unreleased `release/1.2.2` branch; 2.0 builds after that snapshot have neither -([audit](docs/AUDIT-2026-11-10.md), U22). +still be there, and what to check. Sign-in and sign-out are otherwise unchanged. Every release from 0.2.0-rc.1 to +1.2.1 has the sign-in case (0.1.x has no browser sign-in). The sign-out case is in no release. Both cases are in the +development snapshot `snapshot-2.0.0-rc.1`, which was not installed anywhere, and on the unreleased `release/1.2.2` +branch; 2.0 builds after that snapshot have neither ([audit](docs/AUDIT-2026-11-10.md), U22). An unexpected failure of the browser callback inbox no longer leaves the connection dialog's browser sign-in as an unhandled error (2.0). The inbox gives an argument error when the process that sent a callback has already exited, @@ -40,10 +40,11 @@ this build: the connection dialog still runs on the existing flow, whose only ch OAuth state it sent and waits for the callback that carries it, so two servers can be signing in at once. A callback that carries no state, more than one, or a state nobody waits for is dropped, and so is one the session would refuse to read (an entry without a value, a repeated name, a control character, a fragment); the log says - only that one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that waits fails - once and the next registration opens a new inbox. Whatever the inbox fails with, each sign-in or sign-out that - waits ends as a failure it reports: a failure of a kind they do not expect (the inbox gives an argument error when - the process that sent a callback has already exited) reaches them as one that names only its kind. + only that one was dropped. An inbox is open exactly while something waits. When the inbox fails, everything that + waits fails once and the next registration opens a new inbox. Whatever the inbox fails with, each sign-in or + sign-out that waits ends as a failure it reports: a failure of a kind they do not expect (the inbox gives an + argument error when the process that sent a callback has already exited) reaches them as one that names only its + kind. A log that cannot be written to does not stop the dispatcher. - `ProviderSignOut` is the identity provider's half of a sign-out: it opens the provider's sign-out page and waits up to two minutes for the browser to return with that sign-out's own state. Its result says how it ended: confirmed, not opened (the browser or the callback inbox could not be opened, so the operator saw no page), not -- 2.54.0 From 0b9102e87b5f490cadd0fc4f771097da3c6533a4 Mon Sep 17 00:00:00 2001 From: James Maes Date: Wed, 11 Nov 2026 00:28:42 -0600 Subject: [PATCH 27/27] docs(audit): U22 says what the log's redaction removes on the new base The branch was replayed onto release/2.0 at 4e01519, which has the redaction fixes that closed W40. U22 said that the log's redaction removes only the value of state from the text of a failed browser start and that id_token_hint passes unchanged. That was true where it was found, at ebea861, and is not true any more. Run against the replayed head, in a scratch copy, with the text Windows gives for a failed start: the sign-out address loses its id_token_hint and its state; the sign-in address loses its state and keeps its nonce and code_challenge. The row now says what held when it was found and what holds now. Nothing else in it changes: BrowserLaunch keeps the address out of the line whatever the redaction does. Signed-off-by: James Maes Co-Authored-By: Claude Fable 5.2 --- docs/AUDIT-2026-11-10.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/AUDIT-2026-11-10.md b/docs/AUDIT-2026-11-10.md index 594b5ce..a467549 100644 --- a/docs/AUDIT-2026-11-10.md +++ b/docs/AUDIT-2026-11-10.md @@ -273,7 +273,7 @@ Found while building the companion's sign-in for the connection wizard (2026-11- | ID | Severity | Finding | Status | | --- | --- | --- | --- | -| U22 | Not rated | A browser that cannot be started puts the address it was asked to open into the companion's log and, at sign-in, into the dialog. The companion starts the browser through the Windows shell, and when that fails .NET's failure text names what could not be started: "An error occurred trying to start process '' ..." (seen on .NET 10.0.14 with a shell start of a file that does not exist; no browser was involved). At a browser sign-in the address is the provider's authorization address, with that attempt's `state`, `nonce` and `code_challenge`; the text was logged at error level and shown as the reason of "Browser sign-in not completed", and the whole failure was logged again as debug detail (`SignInFlow.Browser.cs:98-103`, started at `:152`, read at `ebea861`). At a provider sign-out the address is the provider's end-session address, with the `id_token_hint` (the provider's ID token) and the sign-out's `state`; the text was logged as a warning and not shown (`SignInFlow.SignOut.cs:121-125`, started at `:114`). The log file's own redaction removes the value of `state` from such a line in 2.0 and nothing else of it; `id_token_hint=` passes unchanged, which is the gap W40 records, and W40's note that no log line can carry it did not hold for this one. The dialog's message is not redacted at all. It takes a failed browser start to happen: no default browser, or a broken handler for web addresses. Tags (from `git tag --contains` and the code at each tag): the sign-in case is in the eleven version tags from `v0.2.0-rc.1` to `v1.2.1` and in `snapshot-2.0.0-rc.1`; the four 0.1.x tags have no browser sign-in. It was introduced by `2c1c5f1` (2026-10-31); in `v1.2.1` the start is `src/Qqq.PrintAgent/MainWindow.Authentication.cs:339` and the catch that logs and shows the text is at `:294-298`, and 1.2.1's log has no rule for `state`, so installed 1.2.x systems write and show the address whole. The sign-out case came with `5d4b7f4` (2026-11-09) and is in one tag, `snapshot-2.0.0-rc.1`, and in no version tag. That snapshot (commit `6f0237d`) has both cases unguarded (`SignInFlow.Browser.cs:152`, `SignInFlow.SignOut.cs:114`); `docs/SESSION-STATE.md` records it as a Gitea prerelease published on 2026-11-10 as a development snapshot and not installed anywhere. The unreleased `release/1.2.2` branch, which is in no tag, has both cases too (`MainWindow.Authentication.cs:303`, `:311` for the sign-out; `:395`, `:354` for the sign-in). Read from the code in each case, not run | Closed for 2.0 builds after `snapshot-2.0.0-rc.1` by the change that adds this row: every browser start in the presentation assembly goes through `BrowserLaunch`, which replaces the failure with fixed text (that the default browser could not be opened, the kind of failure or the Windows error number, and what to check), in the dialog's flow and in the new `CompanionSignIn` and `ProviderSignOut`. The snapshot itself has both cases and stays as published. Open for 1.2.x: `release/1.2.2` still has both cases, and 1.2.1 as installed has the sign-in case | +| U22 | Not rated | A browser that cannot be started puts the address it was asked to open into the companion's log and, at sign-in, into the dialog. The companion starts the browser through the Windows shell, and when that fails .NET's failure text names what could not be started: "An error occurred trying to start process '' ..." (seen on .NET 10.0.14 with a shell start of a file that does not exist; no browser was involved). At a browser sign-in the address is the provider's authorization address, with that attempt's `state`, `nonce` and `code_challenge`; the text was logged at error level and shown as the reason of "Browser sign-in not completed", and the whole failure was logged again as debug detail (`SignInFlow.Browser.cs:98-103`, started at `:152`, read at `ebea861`). At a provider sign-out the address is the provider's end-session address, with the `id_token_hint` (the provider's ID token) and the sign-out's `state`; the text was logged as a warning and not shown (`SignInFlow.SignOut.cs:121-125`, started at `:114`). When this was found (at `ebea861`) the log file's own redaction removed the value of `state` from such a line in 2.0 and nothing else of it: `id_token_hint=` passed unchanged, which was the gap W40 recorded, and W40's note that no log line can carry it did not hold for this one. The redaction fixes that closed W40 now remove the ID token hint as well; a sign-in address still keeps its `nonce` and `code_challenge` (run against 2.0 at `4e01519`, with the text Windows gives for a failed start). The dialog's message is not redacted at all. It takes a failed browser start to happen: no default browser, or a broken handler for web addresses. Tags (from `git tag --contains` and the code at each tag): the sign-in case is in the eleven version tags from `v0.2.0-rc.1` to `v1.2.1` and in `snapshot-2.0.0-rc.1`; the four 0.1.x tags have no browser sign-in. It was introduced by `2c1c5f1` (2026-10-31); in `v1.2.1` the start is `src/Qqq.PrintAgent/MainWindow.Authentication.cs:339` and the catch that logs and shows the text is at `:294-298`, and 1.2.1's log has no rule for `state`, so installed 1.2.x systems write and show the address whole. The sign-out case came with `5d4b7f4` (2026-11-09) and is in one tag, `snapshot-2.0.0-rc.1`, and in no version tag. That snapshot (commit `6f0237d`) has both cases unguarded (`SignInFlow.Browser.cs:152`, `SignInFlow.SignOut.cs:114`); `docs/SESSION-STATE.md` records it as a Gitea prerelease published on 2026-11-10 as a development snapshot and not installed anywhere. The unreleased `release/1.2.2` branch, which is in no tag, has both cases too (`MainWindow.Authentication.cs:303`, `:311` for the sign-out; `:395`, `:354` for the sign-in). Read from the code in each case, not run | Closed for 2.0 builds after `snapshot-2.0.0-rc.1` by the change that adds this row: every browser start in the presentation assembly goes through `BrowserLaunch`, which replaces the failure with fixed text (that the default browser could not be opened, the kind of failure or the Windows error number, and what to check), in the dialog's flow and in the new `CompanionSignIn` and `ProviderSignOut`. The snapshot itself has both cases and stays as published. Open for 1.2.x: `release/1.2.2` still has both cases, and 1.2.1 as installed has the sign-in case | ### Repository -- 2.54.0