From f8a56ec4f026307fbfd15bc947a50159834be86e Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:07:42 -0600 Subject: [PATCH 01/13] refactor(cli)!: remove the --legacy-compat mode The owner decided this for 2.0. The mode talked to servers older than the realtime printing API, which the service cannot use, and it was the last code that sent a device token outside a QQQ session. The command line now only sends requests to the installed service over its pipe. Gone with the mode: the separate per-user data directory (--data-dir), the command line's worker lock, the run-once claim pass (run --once), the isolated enroll and expose paths, and --service, whose branches inside those paths could never run because the mode refused the flag. The duplicated enrollment-code read and the hard-coded agent version "0.1.0" were in the isolated enroll path and go with it. --legacy-compat, --data-dir, --once and --service are refused by name before any service call, so a script written for the mode fails instead of acting on the service. The next change replaces this check with strict argument parsing. The executable's three internal roles are untouched: --printer-worker, --apply-update and --auth-callback. After this change nothing in the product starts qqq-print-agent.exe as a printer worker (the service starts its own executable for that; only the removed mode started this one), but the role still works as before. Deleted tests, both of the removed mode: ProgramTests ForegroundData_UsesCurrentUserAndCannotOverwriteServiceCredentials (data directory selection) and ForegroundMutation_CannotAcquireActiveWorkerDirectory (worker lock). NativeCliRoutingTests ForegroundOptionsRequireExplicitCompatibilityBeforeAnyServiceCall is replaced by RemovedLegacyOptionsAreRefusedBeforeAnyServiceCall. Code in Core and Windows that only this mode reached in production is left in place for the branches now editing those projects. BREAKING CHANGE: --legacy-compat, --data-dir, --once and --service are no longer accepted. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/Program.cs | 178 ++---------------- .../NativeCliRoutingTests.cs | 21 ++- .../Qqq.PrintAgent.Cli.Tests/ProgramTests.cs | 28 +-- 3 files changed, 26 insertions(+), 201 deletions(-) diff --git a/src/Qqq.PrintAgent.Cli/Program.cs b/src/Qqq.PrintAgent.Cli/Program.cs index 50572fd..d1d6456 100644 --- a/src/Qqq.PrintAgent.Cli/Program.cs +++ b/src/Qqq.PrintAgent.Cli/Program.cs @@ -3,19 +3,16 @@ * SPDX-License-Identifier: MIT */ -using System.Text.Json; -using Qqq.PrintAgent.Core.Printing; using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli; -/// Scriptable setup, printer selection and foreground diagnostics. +/// Scriptable management of the installed service: setup, printer selection and status. public static class Program { /// - /// Entry point. Three argument shapes are internal and fixed: the isolated printer worker (a child process the service - /// starts for each native printer call), the MSI update helper, and the browser sign-in callback forwarder. Everything - /// else is an operator command. + /// Entry point. Three argument shapes are internal and fixed: the isolated printer worker, the MSI update helper, and the + /// browser sign-in callback forwarder. Everything else is an operator command. /// public static Task Main(string[] args) => args switch { @@ -52,70 +49,39 @@ public static class Program /// - /// Routes an operator command. Without the explicit legacy flag, printing commands go to the installed service over its - /// authenticated pipe, because the service owns the signed-in session; only with the flag do they use a separate - /// per-user data directory and the old device-token transport, and that is announced on every run. + /// Routes an operator command to the installed service over its authenticated pipe, because the service owns the + /// signed-in session, the pairing and all printing. The command line has no state or server transport of its own. The + /// options of the removed legacy mode are refused by name, so a script written for it fails loudly instead of running + /// against the service by accident. /// internal static async Task DispatchAsync(string[] args, Func>? serviceCommand = null) { string command = args.FirstOrDefault() ?? "help"; - bool legacy = UseLegacyCompatibility(args); - if(legacy) + if(args.Any(argument => argument is "--legacy-compat" or "--data-dir" or "--once" or "--service")) { - Console.Error.WriteLine("Explicit legacy compatibility diagnostics: private device bearer transport, separate local state. This is not QQQ user sign-in."); + throw new ArgumentException("The --legacy-compat mode and its options (--data-dir, --once, --service) were removed in 2.0. The command line only manages the installed service.", nameof(args)); } - if(!legacy && command is "printers" or "enroll" or "expose" or "run" or "sign-out") + if(command is "printers" or "enroll" or "expose" or "run" or "sign-out") { return await DispatchServiceAsync(args, serviceCommand ?? AgentPipeClient.SendAsync); } - string directory = ResolveDataDirectory(args); switch(command) { - case "printers": - Console.WriteLine(JsonSerializer.Serialize(CreatePrinterBackend().Discover(), PrintApiClient.JsonOptions)); - return 0; case "service-status": case "snapshot": Console.WriteLine(await AgentPipeClient.SendAsync(new PipeRequest(command is "snapshot" ? "snapshot" : "status"))); return 0; - case "enroll": - return await EnrollAsync(args, directory); - case "expose": - return await SetExposureAsync(args, directory); - case "run": - return await RunAsync(args, directory); default: - Console.WriteLine("printers | enroll --server URL | expose --printer ID --exposed true|false | run | sign-out | service-status | snapshot\nNormal commands use the authenticated installed service. Sign in through the companion first. run requests a connection refresh; the Windows service owns unattended printing.\nExplicit isolated legacy diagnostics only: add --legacy-compat and a separate --data-dir; legacy run accepts --once. Enrollment code is read from QQQ_PRINT_ENROLLMENT_CODE or an interactive prompt."); + Console.WriteLine("printers | enroll --server URL | expose --printer ID --exposed true|false | run | sign-out | service-status | snapshot\nCommands use the authenticated installed service. Sign in through the companion first. run requests a connection refresh; the Windows service owns unattended printing.\nEnrollment code is read from QQQ_PRINT_ENROLLMENT_CODE or an interactive prompt."); return command is "help" ? 0 : 1; } } - /// Reports whether the legacy flag was given, and refuses it combined with --service, because legacy mode must never touch the installed service's state. - internal static bool UseLegacyCompatibility(string[] args) - { - bool legacy = args.Contains("--legacy-compat", StringComparer.Ordinal); - if(legacy && args.Contains("--service", StringComparer.Ordinal)) - { - throw new ArgumentException("Legacy compatibility cannot access the installed service's state.", nameof(args)); - } - return legacy; - } - - - - /// - /// Sends a normal command to the installed service and prints its reply, exiting 1 when the reply is an error. Options - /// that only make sense for the isolated legacy mode (a data directory, run once) are refused here with an explanation, - /// so a script cannot silently run against the wrong state. - /// + /// Sends a command to the installed service and prints its reply, exiting 1 when the reply is an error. private static async Task DispatchServiceAsync(string[] args, Func> send) { - if(args.Contains("--data-dir", StringComparer.Ordinal) || args.Contains("--once", StringComparer.Ordinal)) - { - throw new ArgumentException("Foreground diagnostic options require explicit --legacy-compat. Normal printing is owned by the signed-in Windows service.", nameof(args)); - } PipeRequest request = args[0] switch { "run" => new("reconnect"), @@ -155,124 +121,4 @@ public static class Program int index = Array.IndexOf(args, key); return index >= 0 && index + 1 < args.Length ? args[index + 1] : null; } - - - - /// - /// Chooses the data directory. --service selects the installed machine directory; otherwise a per-user directory is used, - /// and the machine directory is refused there, so a foreground command can never overwrite the service's credentials by accident. - /// - internal static string ResolveDataDirectory(string[] args) - { - if(args.Contains("--service", StringComparer.Ordinal)) - { - return AgentStore.DefaultDirectory; - } - string directory = Path.GetFullPath(Option(args, "--data-dir") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QqqPrintAgent")); - if(string.Equals(Path.TrimEndingDirectorySeparator(directory), Path.TrimEndingDirectorySeparator(AgentStore.DefaultDirectory), StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidOperationException("Use --service to manage the installed service. Foreground commands require a separate per-user data directory."); - } - return directory; - } - - - - /// Takes the exclusive lock on a data directory so two foreground commands (or one beside the service) cannot write the same journal at once. - internal static FileStream AcquireWorkerLock(string directory) - { - Directory.CreateDirectory(directory); - return new FileStream(Path.Combine(directory, "worker.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); - } - - - - /// Creates the isolated printer backend that runs each native call in a child copy of this executable, bounding any blocking driver call. - private static IsolatedPrinterBackend CreatePrinterBackend() => new(Environment.ProcessPath ?? throw new InvalidOperationException("Cannot locate the printer helper executable.")); - - - - /// - /// Runs one legacy diagnostic claim pass. Continuous legacy polling is gone, so only --once is accepted. Ctrl+C ends the - /// pass cleanly (exit 0); any other cancellation is a failure. It uses a separate data directory and the device token. - /// - private static async Task RunAsync(string[] args, string directory) - { - if(!args.Contains("--once", StringComparer.Ordinal)) - { - throw new InvalidOperationException("Continuous legacy polling is no longer supported. Sign in to the installed native-session service for realtime printing. --once is a legacy diagnostic only."); - } - using FileStream instance = AcquireWorkerLock(directory); - using AgentStore journal = new(directory); - AgentConfiguration config = journal.LoadConfiguration() ?? throw new InvalidOperationException("Enroll this account first."); - using PrintApiClient client = new(config.ServerUrl, config.DeviceToken); - ExposedPrinterBackend printers = new(CreatePrinterBackend(), journal.GetExposedPrinterIds); - PrintWorker worker = new(client, printers, journal, Console.WriteLine); - using CancellationTokenSource stopping = new(); - ConsoleCancelEventHandler cancelHandler = (_, e) => { e.Cancel = true; stopping.Cancel(); }; - Console.CancelKeyPress += cancelHandler; - try - { await worker.RunOnceAsync(stopping.Token); } - catch(OperationCanceledException) when(stopping.IsCancellationRequested) { return 0; } - finally { Console.CancelKeyPress -= cancelHandler; } - return 0; - } - - - - /// Shares or hides one printer, through the service when --service is given and otherwise in the separate legacy directory after validating against current discovery. - private static async Task SetExposureAsync(string[] args, string directory) - { - string id = Option(args, "--printer") ?? throw new ArgumentException("--printer is required.", nameof(args)); - if(!bool.TryParse(Option(args, "--exposed"), out bool exposed)) - { - throw new ArgumentException("--exposed must be true or false.", nameof(args)); - } - if(args.Contains("--service", StringComparer.Ordinal)) - { - string response = await AgentPipeClient.SendAsync(new PipeRequest("set-exposure", PrinterId: id, Exposed: exposed)); - Console.WriteLine(response); - return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0; - } - using FileStream instance = AcquireWorkerLock(directory); - using AgentStore store = new(directory); - store.SetExposure(id, exposed, CreatePrinterBackend().Discover()); - Console.WriteLine(exposed ? "Printer exposed to QQQ." : "Printer hidden from QQQ."); - return 0; - } - - - - /// - /// Enrolls this computer with a one-time code read from the environment or a prompt, never from the command line. With - /// --service the installed service does it; otherwise the legacy path enrolls into a separate directory and saves the - /// device connection protected for the current user. - /// - private static async Task EnrollAsync(string[] args, string directory) - { - string server = Option(args, "--server") ?? throw new ArgumentException("--server is required.", nameof(args)); - string? code = Environment.GetEnvironmentVariable("QQQ_PRINT_ENROLLMENT_CODE"); - if(string.IsNullOrWhiteSpace(code)) - { - Console.Write("Enrollment code: "); - code = Console.ReadLine(); - } - if(string.IsNullOrWhiteSpace(code)) - { - throw new InvalidOperationException("Enrollment code is required."); - } - if(args.Contains("--service", StringComparer.Ordinal)) - { - string response = await AgentPipeClient.SendAsync(new PipeRequest("enroll", server, code)); - Console.WriteLine(response); - return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0; - } - using FileStream instance = AcquireWorkerLock(directory); - using AgentStore store = new(directory, recoverUnreadableConfiguration: true); - using PrintApiClient api = new(server); - EnrollmentResponse result = await api.EnrollAsync(new EnrollmentRequest(code, Environment.MachineName, "0.1.0")); - store.SaveConfiguration(new AgentConfiguration(server, result.DeviceId, result.DeviceToken, result.PollIntervalSeconds)); - Console.WriteLine($"Enrolled device {result.DeviceId}."); - return 0; - } } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs index 84f573e..f60f460 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs @@ -7,7 +7,7 @@ using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; -/// With the signed-in service installed, the command-line tool sends its commands to the service over the management pipe instead of using a private device token, and refuses foreground options unless legacy mode is explicitly requested. +/// The command-line tool sends its commands to the installed service over the management pipe, and refuses the options of the removed legacy mode instead of running a script written for it against the service. public sealed class NativeCliRoutingTests { /// The printers, run and sign-out commands are each translated into the matching service request (printers, reconnect, sign-out) and succeed with exit code 0, so normal use goes through the service that owns the signed-in session. @@ -29,13 +29,18 @@ public sealed class NativeCliRoutingTests - /// Foreground-only options such as running once are refused before any service call unless legacy compatibility is named, and legacy mode cannot be combined with the service flag. The compatibility check itself is true only when the legacy flag is present. - [Fact] - public async Task ForegroundOptionsRequireExplicitCompatibilityBeforeAnyServiceCall() + /// The legacy flag and each option that existed only for it (a separate data directory, run once, the service selector) are refused before any service call, with whatever command they accompany. + [Theory] + [InlineData("run", "--legacy-compat")] + [InlineData("run", "--once")] + [InlineData("run", "--legacy-compat", "--once", "--data-dir", "C:\\synthetic")] + [InlineData("printers", "--data-dir", "C:\\synthetic")] + [InlineData("enroll", "--service", "--server", "https://qqq.example.test")] + [InlineData("service-status", "--service")] + [InlineData("--legacy-compat")] + public async Task RemovedLegacyOptionsAreRefusedBeforeAnyServiceCall(params string[] args) { - await Assert.ThrowsAsync(() => Program.DispatchAsync(["run", "--once"], _ => throw new InvalidOperationException("Must not contact service."))); - Assert.Throws(() => Program.UseLegacyCompatibility(["run", "--legacy-compat", "--service"])); - Assert.True(Program.UseLegacyCompatibility(["run", "--legacy-compat"])); - Assert.False(Program.UseLegacyCompatibility(["run"])); + ArgumentException refusal = await Assert.ThrowsAsync(() => Program.DispatchAsync(args, _ => throw new InvalidOperationException("Must not contact service."))); + Assert.Contains("removed in 2.0", refusal.Message, StringComparison.Ordinal); } } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs index 9199818..eebd6a9 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs @@ -5,35 +5,9 @@ namespace Qqq.PrintAgent.Cli.Tests; -/// Command-line entry point behavior: which data folder foreground runs may use, single-worker locking, and exit codes for help and failures. +/// Command-line entry point behavior: exit codes for help and failures. public sealed class ProgramTests { - /// A foreground run defaults to the current user's own data folder and may not be pointed at the service's protected machine folder, where it could overwrite the service's credentials; only the explicit service mode resolves to that folder. - [Fact] - public void ForegroundData_UsesCurrentUserAndCannotOverwriteServiceCredentials() - { - Assert.Equal(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "QqqPrintAgent"), Program.ResolveDataDirectory([])); - Assert.Throws(() => Program.ResolveDataDirectory(["--data-dir", Qqq.PrintAgent.Windows.AgentStore.DefaultDirectory])); - Assert.Equal(Qqq.PrintAgent.Windows.AgentStore.DefaultDirectory, Program.ResolveDataDirectory(["--service"])); - } - - - - /// The worker lock is exclusive per data folder: while one worker holds it, a second attempt fails, so a foreground command cannot modify state under an active worker. - [Fact] - public void ForegroundMutation_CannotAcquireActiveWorkerDirectory() - { - string directory = Path.Combine(Path.GetTempPath(), "qqq-cli-lock-" + Guid.NewGuid().ToString("N")); - try - { - using FileStream worker = Program.AcquireWorkerLock(directory); - Assert.Throws(() => Program.AcquireWorkerLock(directory)); - } - finally { Directory.Delete(directory, recursive: true); } - } - - - /// Asking for help prints usage and exits with code 0. [Fact] public async Task Help_ExitsSuccessfully() -- 2.54.0 From d4a77e32d5a43a53e993179f9c960e70be482dea Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:09:39 -0600 Subject: [PATCH 02/13] refactor(cli)!: inject the console, enrollment code and pipe; parse arguments strictly The command line's decisions move from Program into CommandLine, which reaches the outside world only through CommandLineHost: the two output streams, the environment variable and prompt that supply the enrollment code, the pipe request sender, and the three helper entry points. Program is left as one expression that binds the real ones by method reference, so nothing in the assembly needs the installed service, the real pipe or the real console to be tested, and nothing is excluded from coverage. Audit findings fixed here: - --help and -h exited 1; they now print the usage on standard output and exit 0, as help and no arguments already did. - An unknown command printed the usage on standard output; it now goes to standard error with "Unknown command.", still exit 1. - service-status and snapshot used the real pipe client directly, so no test could reach them, and exited 0 even when the service replied "Error:". They take the injected sender and exit 1 on an error reply like every other command. - The reply was tested for "Error:" twice; it is examined once. Arguments are now strict. A command accepts exactly its own options, each once and each with a non-blank value, in any order; extra words, repeated, missing or misspelled options are refused before the enrollment code is read and before the service is contacted. The reason and the usage go to standard error with exit 1. This replaces the by-name refusal of the removed legacy options: --legacy-compat, --data-dir, --once and --service are now simply arguments no command accepts. Until now unknown extra arguments were ignored. A refusal never repeats what was typed, because a mistyped command line can carry an enrollment code or a sign-in callback address and standard error is often captured. Unchanged: the request each command sends, the reply printed as the service wrote it, the sign-out note, the prompt text, exit code 1 for every failure, and the three internal roles (the printer worker still runs outside the shared failure handling, because its standard output is a protocol its parent parses). ProgramTests and NativeCliRoutingTests are replaced by CliUsageTests, CliServiceCommandTests and CliArgumentRefusalTests over a hand-written CliFixture; every behavior the old tests held is held by a new one. BREAKING CHANGE: a command line with unexpected arguments is refused instead of having them ignored; service-status and snapshot exit 1 on an error reply; the argument-error messages changed. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/CommandLine.cs | 221 ++++++++++++++++++ src/Qqq.PrintAgent.Cli/CommandLineHost.cs | 30 +++ src/Qqq.PrintAgent.Cli/Program.cs | 119 +--------- .../CliArgumentRefusalTests.cs | 116 +++++++++ tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs | 164 +++++++++++++ .../CliServiceCommandTests.cs | 164 +++++++++++++ .../Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs | 129 ++++++++++ .../NativeCliRoutingTests.cs | 46 ---- .../Qqq.PrintAgent.Cli.Tests/ProgramTests.cs | 35 --- 9 files changed, 833 insertions(+), 191 deletions(-) create mode 100644 src/Qqq.PrintAgent.Cli/CommandLine.cs create mode 100644 src/Qqq.PrintAgent.Cli/CommandLineHost.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs delete mode 100644 tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs delete mode 100644 tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs new file mode 100644 index 0000000..6090dda --- /dev/null +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli; + +/// +/// Everything qqq-print-agent.exe decides: which role an argument list selects, which request an operator command becomes, +/// what is printed where, and the exit code a script sees. The command line holds no state of its own and never talks to a +/// QQQ server: an operator command is one request to the installed service over its administrator pipe, because the service +/// owns the sign-in, the pairing and all printing. The outside world is reached only through the host, so tests run this +/// class against fakes. +/// +internal sealed class CommandLine(CommandLineHost host) +{ + /// The environment variable that supplies the one-time enrollment code to a script. + internal const string EnrollmentCodeVariable = "QQQ_PRINT_ENROLLMENT_CODE"; + + + + /// The help text: printed on standard output when asked for, and on standard error after a refused command line. + internal const string Usage = """ + Usage: qqq-print-agent + + Commands: + printers List the printers the service can see, as JSON. + enroll --server URL Pair this computer with a QQQ server using a one-time enrollment code. + expose --printer ID --exposed true|false Share a printer with QQQ, or stop sharing it. + run Ask the service to refresh its connection to QQQ. + sign-out End the service's QQQ session. + service-status Show the service's connection status. + snapshot Show the service's state as JSON: connection, printers, recent jobs and logs. + help Show this text (also --help, -h). + + Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. + Run from an administrator prompt, and sign in through the companion app first. + The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or typed at a prompt; + it is never accepted on the command line. + Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. + """; + + + + /// Each operator command, with the pipe operation it becomes and the options it requires. Every listed option is mandatory, and nothing else is accepted. + private static readonly Dictionary s_commands = new(StringComparer.Ordinal) + { + ["printers"] = ("printers", []), + ["enroll"] = ("enroll", ["--server"]), + ["expose"] = ("set-exposure", ["--printer", "--exposed"]), + ["run"] = ("reconnect", []), + ["sign-out"] = ("sign-out", []), + ["service-status"] = ("status", []), + ["snapshot"] = ("snapshot", []), + }; + + + + /// The names of the operator commands, exposed so a test can hold the help text to the commands that really exist. + internal static IReadOnlyCollection CommandNames => s_commands.Keys; + + + + /// + /// Runs one invocation and returns the process exit code. Three argument shapes are internal and fixed: the isolated + /// printer worker, the MSI update helper and the browser sign-in callback forwarder, each started by another part of the + /// product with exactly these arguments. Everything else is an operator command. A failure becomes one line on standard + /// error and exit code 1; a timeout or cancellation does too, so a script never mistakes an operation that did not finish + /// for one that succeeded. + /// + internal async Task RunAsync(string[] args) + { + ///////////////////////////////////////////////////////////////////////////// + // the printer worker answers its parent with one JSON line on standard // + // output and reports its own failures there, so nothing here may catch or // + // print for it: it runs outside the handling that the other roles share // + ///////////////////////////////////////////////////////////////////////////// + if(args is ["--printer-worker"]) + { + return await host.RunPrinterWorkerAsync(); + } + try + { + return args switch + { + ["--apply-update", string request] => await host.ApplyUpdateAsync(request), + ["--auth-callback", string callback] => await ForwardSignInCallbackAsync(callback), + _ => await ManageServiceAsync(args), + }; + } + catch(OperationCanceledException) + { + host.Error.WriteLine("The operation timed out or was canceled before completion."); + return 1; + } + catch(Exception exception) + { + host.Error.WriteLine(exception.Message); + return 1; + } + } + + + + /// Hands the browser's callback address to the companion that is waiting for it. Success is exit code 0; a refusal is thrown and reported by the caller. + private async Task ForwardSignInCallbackAsync(string callback) + { + await host.ForwardSignInCallbackAsync(callback, CancellationToken.None); + return 0; + } + + + + /// + /// Carries out an operator command: help is printed here, and any other command is checked against the table, turned into + /// one pipe request and sent to the service. The reply is printed as the service wrote it. A reply that starts with + /// "Error:" is the service refusing or failing the request, so it exits 1 for every command. + /// + private async Task ManageServiceAsync(string[] args) + { + /////////////////////////////////////////////////////////////////////////// + // help is decided by the first word alone: "help enroll" is a person // + // asking how to enroll, and answering costs nothing and sends nothing // + /////////////////////////////////////////////////////////////////////////// + if(args is [] or ["help" or "--help" or "-h", ..]) + { + host.Output.WriteLine(Usage); + return 0; + } + if(!s_commands.TryGetValue(args[0], out (string Operation, string[] Options) command)) + { + return RefuseArguments("Unknown command."); + } + Dictionary? options = ReadOptions(args, command.Options); + if(options is null) + { + return RefuseArguments($"Invalid arguments for '{args[0]}'."); + } + bool? exposed = null; + if(options.TryGetValue("--exposed", out string? text)) + { + if(!bool.TryParse(text, out bool parsed)) + { + return RefuseArguments("--exposed must be true or false."); + } + exposed = parsed; + } + + //////////////////////////////////////////////////////////////////////////// + // the enrollment code is asked for last, once the command line is known // + // to be valid, so a mistyped command never prompts for a single-use code // + //////////////////////////////////////////////////////////////////////////// + PipeRequest request = new(command.Operation, options.GetValueOrDefault("--server"), args[0] is "enroll" ? ReadEnrollmentCode() : null, + options.GetValueOrDefault("--printer"), exposed); + string response = await host.SendAsync(request); + host.Output.WriteLine(response); + bool failed = response.StartsWith("Error:", StringComparison.Ordinal); + if(args[0] is "sign-out" && !failed) + { + host.Output.WriteLine("The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too."); + } + return failed ? 1 : 0; + } + + + + /// + /// Refuses a command line: the reason and the help text go to standard error and the exit code is 1. The reason never + /// repeats what was typed. A refused command line can hold a secret in the wrong place (an enrollment code given as an + /// argument, a sign-in callback address), and standard error is routinely captured into logs. + /// + private int RefuseArguments(string reason) + { + host.Error.WriteLine(reason); + host.Error.WriteLine(Usage); + return 1; + } + + + + /// + /// Reads the "--name value" pairs that follow a command, in any order. Every option of a command is required exactly + /// once, so the argument count must match, each name must be one of the command's own, no name may repeat and no value + /// may be blank. Anything else returns null, and the caller refuses the whole command line rather than guess. + /// + private static Dictionary? ReadOptions(string[] args, string[] names) + { + if(args.Length != 1 + (2 * names.Length)) + { + return null; + } + Dictionary values = new(StringComparer.Ordinal); + for(int index = 1; index < args.Length; index += 2) + { + if(!names.Contains(args[index], StringComparer.Ordinal) || string.IsNullOrWhiteSpace(args[index + 1]) || !values.TryAdd(args[index], args[index + 1])) + { + return null; + } + } + return values; + } + + + + /// + /// Reads the one-time enrollment code from the environment, or prompts for it, so the code never appears in the command + /// line or shell history. It is passed to the service and nowhere else: this class never prints it. + /// + private string ReadEnrollmentCode() + { + string? code = host.ReadEnvironmentVariable(EnrollmentCodeVariable); + if(string.IsNullOrWhiteSpace(code)) + { + host.Output.Write("Enrollment code: "); + code = host.ReadLine(); + } + return !string.IsNullOrWhiteSpace(code) ? code : throw new InvalidOperationException("Enrollment code is required."); + } +} diff --git a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs new file mode 100644 index 0000000..9686365 --- /dev/null +++ b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli; + +/// +/// Everything outside the process that the command line touches, each as a replaceable function, so +/// runs in a test without the real console, the installed service or its pipe. supplies the real ones. +/// +/// Standard output: service replies, usage that was asked for, and the enrollment prompt. +/// Standard error: failures and usage shown because the arguments were wrong. +/// Reads one environment variable; the enrollment code arrives this way so it stays out of the command line and shell history. +/// Reads one line of standard input, for the enrollment code when the variable is not set; null at end of input. +/// Sends one request to the installed service over its administrator pipe and returns the reply text. +/// Runs this process as an isolated printer worker and returns its exit code. +/// Applies the prepared MSI update named by a request file and returns the exit code. +/// Forwards a browser sign-in callback address to the running companion. +internal sealed record CommandLineHost( + TextWriter Output, + TextWriter Error, + Func ReadEnvironmentVariable, + Func ReadLine, + Func> SendAsync, + Func> RunPrinterWorkerAsync, + Func> ApplyUpdateAsync, + Func ForwardSignInCallbackAsync); diff --git a/src/Qqq.PrintAgent.Cli/Program.cs b/src/Qqq.PrintAgent.Cli/Program.cs index d1d6456..54d7d22 100644 --- a/src/Qqq.PrintAgent.Cli/Program.cs +++ b/src/Qqq.PrintAgent.Cli/Program.cs @@ -7,118 +7,17 @@ using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli; -/// Scriptable management of the installed service: setup, printer selection and status. +/// +/// Process entry point of qqq-print-agent.exe. It decides nothing: it hands the real console, environment, service pipe and +/// helper entry points to , which holds every decision and is tested against fakes. +/// public static class Program { /// - /// Entry point. Three argument shapes are internal and fixed: the isolated printer worker, the MSI update helper, and the - /// browser sign-in callback forwarder. Everything else is an operator command. + /// Binds the outside world and runs the arguments. Each boundary is passed as a method reference, not a wrapper, so there + /// is no code here that a test cannot reach: asking for help exercises this whole composition without touching the service. /// - public static Task Main(string[] args) => args switch - { - ["--printer-worker"] => PrinterWorkerHost.RunAsync(), - ["--apply-update", string request] => ExecuteAsync(() => MsiUpdateInstaller.ApplyAsync(request)), - ["--auth-callback", string callback] => ExecuteAsync(async () => - { - await QqqBrowserCallback.ForwardFromHandlerAsync(callback); - return 0; - }), - _ => ExecuteAsync(() => DispatchAsync(args)), - }; - - - - /// - /// Runs a command and turns failures into a one-line message on standard error and exit code 1. A timeout or cancellation - /// also exits 1, so a script never mistakes an operation that did not finish for one that succeeded. - /// - internal static async Task ExecuteAsync(Func> command) - { - try - { - return await command(); - } - catch(OperationCanceledException) - { - Console.Error.WriteLine("The operation timed out or was canceled before completion."); - return 1; - } - catch(Exception exception) { Console.Error.WriteLine(exception.Message); return 1; } - } - - - - /// - /// Routes an operator command to the installed service over its authenticated pipe, because the service owns the - /// signed-in session, the pairing and all printing. The command line has no state or server transport of its own. The - /// options of the removed legacy mode are refused by name, so a script written for it fails loudly instead of running - /// against the service by accident. - /// - internal static async Task DispatchAsync(string[] args, Func>? serviceCommand = null) - { - string command = args.FirstOrDefault() ?? "help"; - if(args.Any(argument => argument is "--legacy-compat" or "--data-dir" or "--once" or "--service")) - { - throw new ArgumentException("The --legacy-compat mode and its options (--data-dir, --once, --service) were removed in 2.0. The command line only manages the installed service.", nameof(args)); - } - if(command is "printers" or "enroll" or "expose" or "run" or "sign-out") - { - return await DispatchServiceAsync(args, serviceCommand ?? AgentPipeClient.SendAsync); - } - switch(command) - { - case "service-status": - case "snapshot": - Console.WriteLine(await AgentPipeClient.SendAsync(new PipeRequest(command is "snapshot" ? "snapshot" : "status"))); - return 0; - default: - Console.WriteLine("printers | enroll --server URL | expose --printer ID --exposed true|false | run | sign-out | service-status | snapshot\nCommands use the authenticated installed service. Sign in through the companion first. run requests a connection refresh; the Windows service owns unattended printing.\nEnrollment code is read from QQQ_PRINT_ENROLLMENT_CODE or an interactive prompt."); - return command is "help" ? 0 : 1; - } - } - - - - /// Sends a command to the installed service and prints its reply, exiting 1 when the reply is an error. - private static async Task DispatchServiceAsync(string[] args, Func> send) - { - PipeRequest request = args[0] switch - { - "run" => new("reconnect"), - "enroll" => new("enroll", Option(args, "--server") ?? throw new ArgumentException("--server is required.", nameof(args)), ReadEnrollmentCode()), - "expose" => new("set-exposure", PrinterId: Option(args, "--printer") ?? throw new ArgumentException("--printer is required.", nameof(args)), - Exposed: bool.TryParse(Option(args, "--exposed"), out bool exposed) ? exposed : throw new ArgumentException("--exposed must be true or false.", nameof(args))), - _ => new(args[0]), - }; - string response = await send(request); - Console.WriteLine(response); - if(args[0] is "sign-out" && !response.StartsWith("Error:", StringComparison.Ordinal)) - { - Console.WriteLine("The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too."); - } - return response.StartsWith("Error:", StringComparison.Ordinal) ? 1 : 0; - } - - - - /// Reads the one-time enrollment code from the environment, or prompts for it, so the code never appears in the command line or shell history. - private static string ReadEnrollmentCode() - { - string? code = Environment.GetEnvironmentVariable("QQQ_PRINT_ENROLLMENT_CODE"); - if(string.IsNullOrWhiteSpace(code)) - { - Console.Write("Enrollment code: "); - code = Console.ReadLine(); - } - return !string.IsNullOrWhiteSpace(code) ? code : throw new InvalidOperationException("Enrollment code is required."); - } - - - - /// Returns the value following a named option, or null when the option is absent or has no value. - private static string? Option(string[] args, string key) - { - int index = Array.IndexOf(args, key); - return index >= 0 && index + 1 < args.Length ? args[index + 1] : null; - } + public static Task Main(string[] args) + => new CommandLine(new CommandLineHost(Console.Out, Console.Error, Environment.GetEnvironmentVariable, Console.ReadLine, + AgentPipeClient.SendAsync, PrinterWorkerHost.RunAsync, MsiUpdateInstaller.ApplyAsync, QqqBrowserCallback.ForwardFromHandlerAsync)).RunAsync(args); } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs new file mode 100644 index 0000000..3ed6d85 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Malformed command lines. A command accepts exactly its own options, each once and each with a value, and nothing else. +/// Anything different is refused before the service is contacted and before the enrollment code is asked for: the reason and +/// the usage go to standard error, standard output stays empty and the exit code is 1. The tool never guesses what was meant. +/// +public sealed class CliArgumentRefusalTests +{ + /// A command that takes no options refuses any extra word, including help flags after the command and every option of the removed legacy mode (--legacy-compat, --data-dir, --once, --service). + [Theory] + [InlineData("printers", "extra")] + [InlineData("printers", "--help")] + [InlineData("printers", "--legacy-compat")] + [InlineData("printers", "--legacy-compat", "--data-dir", "C:\\synthetic")] + [InlineData("run", "--once")] + [InlineData("run", "--once", "--legacy-compat")] + [InlineData("run", "--data-dir", "C:\\synthetic")] + [InlineData("run", "--service")] + [InlineData("sign-out", "--service")] + [InlineData("sign-out", "now")] + [InlineData("service-status", "--service")] + [InlineData("service-status", "-h")] + [InlineData("snapshot", "--data-dir", "C:\\synthetic")] + [InlineData("snapshot", "")] + public async Task CommandWithoutOptions_RefusesAnythingExtra(params string[] args) + { + await AssertRefusedAsync($"Invalid arguments for '{args[0]}'.", args); + } + + + + /// Enrolling requires exactly --server with a value: a missing, blank, repeated, misspelled or positional server, any other option, and any trailing word are all refused. + [Theory] + [InlineData("enroll")] + [InlineData("enroll", "--server")] + [InlineData("enroll", "--server", "")] + [InlineData("enroll", "--server", " ")] + [InlineData("enroll", "https://qqq.example.test")] + [InlineData("enroll", "https://qqq.example.test", "--server")] + [InlineData("enroll", "--Server", "https://qqq.example.test")] + [InlineData("enroll", "--printer", "synthetic-queue-1")] + [InlineData("enroll", "--server", "https://qqq.example.test", "--server", "https://other.example.test")] + [InlineData("enroll", "--server", "https://qqq.example.test", "extra")] + [InlineData("enroll", "--server", "https://qqq.example.test", "--service")] + [InlineData("enroll", "--server", "https://qqq.example.test", "--legacy-compat")] + [InlineData("enroll", "--server", "https://qqq.example.test", "--data-dir", "C:\\synthetic")] + [InlineData("enroll", "--legacy-compat", "--server", "https://qqq.example.test")] + public async Task Enroll_RefusesAnythingButOneServer(params string[] args) + { + await AssertRefusedAsync("Invalid arguments for 'enroll'.", args); + } + + + + /// Sharing a printer requires exactly --printer and --exposed, each once with a value: either one missing, blank or repeated, any other option, and any trailing word are all refused. + [Theory] + [InlineData("expose")] + [InlineData("expose", "--printer", "synthetic-queue-1")] + [InlineData("expose", "--exposed", "true")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed")] + [InlineData("expose", "--printer", "--exposed", "true")] + [InlineData("expose", "--printer", "", "--exposed", "true")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", " ")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--printer", "synthetic-queue-2")] + [InlineData("expose", "--exposed", "true", "--exposed", "false")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--server", "https://qqq.example.test")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "extra")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "--service")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "--legacy-compat")] + [InlineData("expose", "synthetic-queue-1", "true")] + public async Task Expose_RefusesAnythingButOnePrinterAndOneChoice(params string[] args) + { + await AssertRefusedAsync("Invalid arguments for 'expose'.", args); + } + + + + /// The choice must be the word true or false; a number, yes or no, or any other word is refused with a message that says so. + [Theory] + [InlineData("yes")] + [InlineData("no")] + [InlineData("1")] + [InlineData("0")] + [InlineData("on")] + [InlineData("truee")] + public async Task Expose_RefusesAChoiceThatIsNotTrueOrFalse(string choice) + { + await AssertRefusedAsync("--exposed must be true or false.", "expose", "--printer", "synthetic-queue-1", "--exposed", choice); + await AssertRefusedAsync("--exposed must be true or false.", "expose", "--exposed", choice, "--printer", "synthetic-queue-1"); + } + + + + /// Runs the arguments against a command line whose enrollment code is available, and requires a complete refusal: exit code 1, the reason and the usage on standard error, nothing on standard output, nothing sent, and neither the environment nor standard input consulted. + private static async Task AssertRefusedAsync(string reason, params string[] args) + { + using CliFixture cli = new(); + cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471"; + cli.TypedLines.Enqueue("synthetic-code-4471"); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal(reason + "\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n")); + Assert.Empty(cli.Sent); + Assert.Empty(cli.VariablesRead); + Assert.Equal(0, cli.LinesRead); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs new file mode 100644 index 0000000..4d0d960 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Shared harness for the command-line tests: the real wired to hand-written fakes for the console, +/// the environment, the service pipe and the three helper entry points. A test scripts what the outside world answers, runs +/// an argument list, then reads exactly what was written, sent and started. Nothing here touches the real console, the +/// installed service or a printer. Captured output uses "\n" line endings so expected text reads the same on every machine. +/// +internal sealed class CliFixture : IDisposable +{ + private readonly StringWriter _output = new() { NewLine = "\n" }; + private readonly StringWriter _error = new() { NewLine = "\n" }; + + + + /// Everything written to standard output so far. + internal string Output => _output.ToString(); + + + + /// Everything written to standard error so far. + internal string Error => _error.ToString(); + + + + /// The environment the command line sees; a name that is absent reads as not set. + internal Dictionary Variables { get; } = new(StringComparer.Ordinal); + + + + /// The names of the environment variables that were read, in order. + internal List VariablesRead { get; } = []; + + + + /// The lines an operator would type, in order; when they run out, standard input is at its end. + internal Queue TypedLines { get; } = new(); + + + + /// How many times a line was asked for from standard input. + internal int LinesRead { get; private set; } + + + + /// The reply the fake service gives to every request. + internal string Reply { get; set; } = "Synthetic service reply."; + + + + /// When set, the fake pipe fails with this instead of replying, after recording the request. + internal Exception? SendFailure { get; set; } + + + + /// Every request sent to the fake service, in order. + internal List Sent { get; } = []; + + + + /// The exit code the fake printer worker and update helper report. + internal int HelperExitCode { get; set; } + + + + /// When set, whichever helper entry point is started fails with this. + internal Exception? HelperFailure { get; set; } + + + + /// How many times this process was started as a printer worker. + internal int WorkerRuns { get; private set; } + + + + /// The request-file paths handed to the update helper, in order. + internal List UpdateRequests { get; } = []; + + + + /// The sign-in callback addresses handed to the forwarder, each with the cancellation token it was given. + internal List<(string Callback, CancellationToken Token)> Callbacks { get; } = []; + + + + /// Everything the command line wrote, to either stream; a secret must never appear in it. + internal string Everything => Output + Error; + + + + /// Runs one invocation of the command line against the fakes and returns its exit code. + internal Task RunAsync(params string[] args) + => new CommandLine(new CommandLineHost(_output, _error, ReadVariable, ReadLine, SendAsync, RunWorkerAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args); + + + + /// Records which variable was asked for and answers from the scripted variables. + private string? ReadVariable(string name) + { + VariablesRead.Add(name); + return Variables.GetValueOrDefault(name); + } + + + + /// Hands out the next typed line, or null once the operator has nothing more to type. + private string? ReadLine() + { + LinesRead++; + return TypedLines.Count > 0 ? TypedLines.Dequeue() : null; + } + + + + /// Records the request, then replies or fails as scripted. + private Task SendAsync(PipeRequest request) + { + Sent.Add(request); + return SendFailure is null ? Task.FromResult(Reply) : Task.FromException(SendFailure); + } + + + + /// Counts a printer-worker start and reports the scripted exit code or failure. + private Task RunWorkerAsync() + { + WorkerRuns++; + return HelperFailure is null ? Task.FromResult(HelperExitCode) : Task.FromException(HelperFailure); + } + + + + /// Records the update request path and reports the scripted exit code or failure. + private Task ApplyUpdateAsync(string requestPath) + { + UpdateRequests.Add(requestPath); + return HelperFailure is null ? Task.FromResult(HelperExitCode) : Task.FromException(HelperFailure); + } + + + + /// Records the callback address and token, then succeeds or fails as scripted. + private Task ForwardCallbackAsync(string callback, CancellationToken token) + { + Callbacks.Add((callback, token)); + return HelperFailure is null ? Task.CompletedTask : Task.FromException(HelperFailure); + } + + + + /// Releases the two capture writers. + public void Dispose() + { + _output.Dispose(); + _error.Dispose(); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs new file mode 100644 index 0000000..6c038d1 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Operator commands. Each one becomes exactly one request to the installed service over its pipe; the reply is printed as +/// the service wrote it; and the exit code tells a script whether the service did what was asked. The pipe is a fake here, +/// so these tests need no installed service. +/// +public sealed class CliServiceCommandTests +{ + private const string SignOutNote = "The identity provider's browser session is not ended from the command line; use Sign out in the QQQ Print Agent app to end it too."; + + + + /// A command without options sends one request that carries only its operation name (run asks for a reconnect, service-status for the status), prints the reply on standard output and exits 0. + [Theory] + [InlineData("printers", "printers")] + [InlineData("run", "reconnect")] + [InlineData("service-status", "status")] + [InlineData("snapshot", "snapshot")] + public async Task CommandWithoutOptions_SendsItsOperationAndPrintsTheReply(string command, string operation) + { + using CliFixture cli = new() { Reply = "Synthetic service accepted the request." }; + + int exitCode = await cli.RunAsync(command); + + Assert.Equal(0, exitCode); + Assert.Equal(new PipeRequest(operation), Assert.Single(cli.Sent)); + Assert.Equal("Synthetic service accepted the request.\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// Signing out sends the sign-out operation and, when the service accepts it, adds one line saying the identity provider's browser session is still open, because only the companion can end that. + [Fact] + public async Task SignOut_SendsTheOperationAndSaysTheProviderSessionRemains() + { + using CliFixture cli = new() { Reply = "Signed out." }; + + int exitCode = await cli.RunAsync("sign-out"); + + Assert.Equal(0, exitCode); + Assert.Equal(new PipeRequest("sign-out"), Assert.Single(cli.Sent)); + Assert.Equal("Signed out.\n" + SignOutNote + "\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// Sharing or hiding a printer sends the printer and the choice, and nothing else. The two options may come in either order, and true or false is accepted in any letter case. + [Theory] + [InlineData(true, "expose", "--printer", "synthetic-queue-1", "--exposed", "true")] + [InlineData(false, "expose", "--printer", "synthetic-queue-1", "--exposed", "false")] + [InlineData(true, "expose", "--exposed", "TRUE", "--printer", "synthetic-queue-1")] + [InlineData(false, "expose", "--exposed", "False", "--printer", "synthetic-queue-1")] + public async Task Expose_SendsThePrinterAndTheChoice(bool exposed, params string[] args) + { + using CliFixture cli = new() { Reply = "{\"status\":\"Connected\"}" }; + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(0, exitCode); + Assert.Equal(new PipeRequest("set-exposure", PrinterId: "synthetic-queue-1", Exposed: exposed), Assert.Single(cli.Sent)); + Assert.Equal("{\"status\":\"Connected\"}\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// Enrolling sends the server address and the enrollment code together in one request, and nothing else. + [Fact] + public async Task Enroll_SendsTheServerAndTheCode() + { + using CliFixture cli = new() { Reply = "Enrolled." }; + cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471"; + + int exitCode = await cli.RunAsync("enroll", "--server", "https://qqq.example.test"); + + Assert.Equal(0, exitCode); + Assert.Equal(new PipeRequest("enroll", "https://qqq.example.test", "synthetic-code-4471"), Assert.Single(cli.Sent)); + Assert.Equal("Enrolled.\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// A reply that begins with "Error:" means the service refused or failed the request. It is still printed on standard output as the service wrote it, and every command then exits 1, so a script cannot take a refusal for success. Signing out adds no note when it did not happen. + [Theory] + [InlineData("printers")] + [InlineData("run")] + [InlineData("sign-out")] + [InlineData("service-status")] + [InlineData("snapshot")] + [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true")] + [InlineData("enroll", "--server", "https://qqq.example.test")] + public async Task ErrorReply_IsPrintedAndFailsTheCommand(params string[] args) + { + using CliFixture cli = new() { Reply = "Error: The synthetic service refused." }; + cli.Variables[CommandLine.EnrollmentCodeVariable] = "synthetic-code-4471"; + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(1, exitCode); + Assert.Single(cli.Sent); + Assert.Equal("Error: The synthetic service refused.\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// Only a reply that starts with "Error:" in exactly that form is a failure; the word appearing later in a reply, or in another letter case, is ordinary text. + [Theory] + [InlineData("Last error: none.")] + [InlineData("error: lower case is not the service's refusal form")] + [InlineData("")] + public async Task ReplyThatOnlyMentionsAnError_IsNotAFailure(string reply) + { + using CliFixture cli = new() { Reply = reply }; + + int exitCode = await cli.RunAsync("service-status"); + + Assert.Equal(0, exitCode); + Assert.Equal(reply + "\n", cli.Output); + } + + + + /// When the service cannot be reached or is not the installed service, the reason is one line on standard error, standard output stays empty and the exit code is 1. + [Fact] + public async Task PipeFailure_IsOneLineOnStandardErrorAndFails() + { + using CliFixture cli = new() { SendFailure = new UnauthorizedAccessException("The local endpoint is not the installed Windows print service. No request was sent.") }; + + int exitCode = await cli.RunAsync("snapshot"); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal("The local endpoint is not the installed Windows print service. No request was sent.\n", cli.Error); + } + + + + /// A request that times out or is canceled exits 1 with a fixed sentence, never 0 and never an unhandled exception, so an operation that did not finish is not mistaken for one that succeeded. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task TimeoutOrCancellation_FailsWithAFixedMessage(bool taskCanceled) + { + using CliFixture cli = new() { SendFailure = taskCanceled ? new TaskCanceledException("Synthetic request timeout.") : new OperationCanceledException("Synthetic cancellation.") }; + + int exitCode = await cli.RunAsync("run"); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal("The operation timed out or was canceled before completion.\n", cli.Error); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs new file mode 100644 index 0000000..7605619 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Help and unknown commands. Asking for help is a success and prints the usage on standard output; a command the tool does +/// not know is a failure and prints the usage on standard error, so a script that captures output never mistakes help text +/// for a result. Neither contacts the service. +/// +public sealed class CliUsageTests +{ + /// The exact help text an operator sees. It is repeated here on purpose: changing what the tool tells operators should be a deliberate edit in two places, not a side effect. + private const string ExpectedUsage = """ + Usage: qqq-print-agent + + Commands: + printers List the printers the service can see, as JSON. + enroll --server URL Pair this computer with a QQQ server using a one-time enrollment code. + expose --printer ID --exposed true|false Share a printer with QQQ, or stop sharing it. + run Ask the service to refresh its connection to QQQ. + sign-out End the service's QQQ session. + service-status Show the service's connection status. + snapshot Show the service's state as JSON: connection, printers, recent jobs and logs. + help Show this text (also --help, -h). + + Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. + Run from an administrator prompt, and sign in through the companion app first. + The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or typed at a prompt; + it is never accepted on the command line. + Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. + """; + + + + /// No arguments, help, --help and -h all print exactly the usage on standard output, write nothing to standard error, send nothing to the service and exit 0. Words after the help word do not change that. + [Theory] + [InlineData] + [InlineData("help")] + [InlineData("--help")] + [InlineData("-h")] + [InlineData("help", "enroll")] + [InlineData("--help", "--anything")] + public async Task AskingForHelp_PrintsUsageOnStandardOutputAndSucceeds(params string[] args) + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(0, exitCode); + Assert.Equal(ExpectedUsage.ReplaceLineEndings("\n") + "\n", cli.Output.ReplaceLineEndings("\n")); + Assert.Equal("", cli.Error); + Assert.Empty(cli.Sent); + } + + + + /// A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, and the option that selected the removed legacy mode is no longer a word the tool knows. + [Theory] + [InlineData("status")] + [InlineData("Printers")] + [InlineData("--legacy-compat")] + [InlineData("--legacy-compat", "run", "--once")] + [InlineData("--service")] + [InlineData("--version")] + [InlineData("")] + public async Task UnknownCommand_PrintsUsageOnStandardErrorAndFails(params string[] args) + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal("Unknown command.\n" + ExpectedUsage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n")); + Assert.Empty(cli.Sent); + } + + + + /// The refusal never repeats what was typed. A mistyped command line can carry a secret (an enrollment code, a sign-in callback address) and standard error is often captured into logs. + [Fact] + public async Task UnknownCommand_IsNotEchoed() + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync("frobnicate-7Q2", "synthetic-secret-91"); + + Assert.Equal(1, exitCode); + Assert.DoesNotContain("frobnicate-7Q2", cli.Everything, StringComparison.Ordinal); + Assert.DoesNotContain("synthetic-secret-91", cli.Everything, StringComparison.Ordinal); + } + + + + /// The usage lists every command the tool accepts, each at the start of its own line, so help cannot fall behind the commands that exist. + [Fact] + public void Usage_ListsEveryCommand() + { + string[] lines = CommandLine.Usage.ReplaceLineEndings("\n").Split('\n'); + + Assert.Equal(7, CommandLine.CommandNames.Count); + Assert.All(CommandLine.CommandNames, name => Assert.Contains(lines, line => line.StartsWith(" " + name + " ", StringComparison.Ordinal))); + } + + + + /// The usage no longer describes the removed legacy mode or any option that existed only for it. + [Theory] + [InlineData("legacy")] + [InlineData("--data-dir")] + [InlineData("--once")] + [InlineData("--service")] + public void Usage_DoesNotMentionTheRemovedLegacyMode(string removed) + { + Assert.DoesNotContain(removed, CommandLine.Usage, StringComparison.OrdinalIgnoreCase); + } + + + + /// The real entry point, with the real console and pipe client bound, answers help with exit code 0 and never needs the service for it. This is the only test that runs the production composition in this process. + [Fact] + public async Task RealEntryPoint_AnswersHelpWithoutTheService() + { + Assert.Equal(0, await Program.Main(["--help"])); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs deleted file mode 100644 index f60f460..0000000 --- a/tests/Qqq.PrintAgent.Cli.Tests/NativeCliRoutingTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2026 James Maes - * SPDX-License-Identifier: MIT - */ - -using Qqq.PrintAgent.Windows; - -namespace Qqq.PrintAgent.Cli.Tests; - -/// The command-line tool sends its commands to the installed service over the management pipe, and refuses the options of the removed legacy mode instead of running a script written for it against the service. -public sealed class NativeCliRoutingTests -{ - /// The printers, run and sign-out commands are each translated into the matching service request (printers, reconnect, sign-out) and succeed with exit code 0, so normal use goes through the service that owns the signed-in session. - [Theory] - [InlineData("printers", "printers")] - [InlineData("run", "reconnect")] - [InlineData("sign-out", "sign-out")] - public async Task NormalCommandsUseServiceRatherThanPrivateBearerTransport(string command, string expected) - { - PipeRequest? sent = null; - int result = await Program.DispatchAsync([command], request => - { - sent = request; - return Task.FromResult("Synthetic service accepted request."); - }); - Assert.Equal(0, result); - Assert.Equal(expected, sent!.Operation); - } - - - - /// The legacy flag and each option that existed only for it (a separate data directory, run once, the service selector) are refused before any service call, with whatever command they accompany. - [Theory] - [InlineData("run", "--legacy-compat")] - [InlineData("run", "--once")] - [InlineData("run", "--legacy-compat", "--once", "--data-dir", "C:\\synthetic")] - [InlineData("printers", "--data-dir", "C:\\synthetic")] - [InlineData("enroll", "--service", "--server", "https://qqq.example.test")] - [InlineData("service-status", "--service")] - [InlineData("--legacy-compat")] - public async Task RemovedLegacyOptionsAreRefusedBeforeAnyServiceCall(params string[] args) - { - ArgumentException refusal = await Assert.ThrowsAsync(() => Program.DispatchAsync(args, _ => throw new InvalidOperationException("Must not contact service."))); - Assert.Contains("removed in 2.0", refusal.Message, StringComparison.Ordinal); - } -} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs deleted file mode 100644 index eebd6a9..0000000 --- a/tests/Qqq.PrintAgent.Cli.Tests/ProgramTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2026 James Maes - * SPDX-License-Identifier: MIT - */ - -namespace Qqq.PrintAgent.Cli.Tests; - -/// Command-line entry point behavior: exit codes for help and failures. -public sealed class ProgramTests -{ - /// Asking for help prints usage and exits with code 0. - [Fact] - public async Task Help_ExitsSuccessfully() - { - Assert.Equal(0, await Program.Main(["help"])); - } - - - - /// Enrolling without the required server address fails with exit code 1 instead of prompting or guessing. - [Fact] - public async Task Enroll_MissingServerFails() - { - Assert.Equal(1, await Program.Main(["enroll"])); - } - - - - /// A request that times out ends the command with exit code 1 rather than an unhandled exception. - [Fact] - public async Task RequestTimeout_ExitsWithFailure() - { - Assert.Equal(1, await Program.ExecuteAsync(() => Task.FromException(new TaskCanceledException("Request timeout.")))); - } -} -- 2.54.0 From 6a49e4d724b21955671e66bc33cfce0a432a5d78 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:11:30 -0600 Subject: [PATCH 03/13] test(cli): hold the enrollment code secret and pin the three helper roles CliEnrollmentCodeTests: the code is taken from QQQ_PRINT_ENROLLMENT_CODE without prompting or reading standard input; a missing or blank variable prompts on standard output and uses the typed line as typed; no code at all fails with one line on standard error and sends nothing; the code never appears in standard output or standard error whether enrollment is accepted, refused by the service, timed out or failed to send; and a code put on the command line is refused, not used and not repeated. CliHelperRoleTests: exactly --printer-worker runs the worker, returns its exit code unchanged, prints nothing and does not catch its failures; --apply-update passes the request path through and returns the helper's exit code; --auth-callback forwards the address unchanged with no deadline of its own and never prints it, including on failure; and one argument too many or too few starts no helper. With these the command-line assembly measures 100% line coverage (78 of 78) from tests that run against fakes only. The minimum is raised in the next change, once the figure has held over repeated full runs. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- .../CliEnrollmentCodeTests.cs | 144 ++++++++++++++++ .../CliHelperRoleTests.cs | 160 ++++++++++++++++++ 2 files changed, 304 insertions(+) create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs new file mode 100644 index 0000000..f37475a --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The one-time enrollment code is a secret. It comes from an environment variable or a prompt, never from the command line; +/// it goes to the service in the enrollment request and nowhere else; and nothing the tool prints ever contains it, whether +/// the enrollment works, is refused or cannot be sent. +/// +public sealed class CliEnrollmentCodeTests +{ + private const string Code = "synthetic-code-4471"; + private const string Server = "https://qqq.example.test"; + + + + /// With the variable set, the code is taken from QQQ_PRINT_ENROLLMENT_CODE and no prompt is shown and nothing is read from standard input, so an unattended script never blocks. + [Fact] + public async Task CodeInTheEnvironment_IsUsedWithoutPrompting() + { + using CliFixture cli = new() { Reply = "Enrolled." }; + cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = Code; + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal("QQQ_PRINT_ENROLLMENT_CODE", Assert.Single(cli.VariablesRead)); + Assert.Equal(0, cli.LinesRead); + Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode); + Assert.Equal("Enrolled.\n", cli.Output); + } + + + + /// With the variable missing or blank, the tool prompts on standard output and uses the line the operator types, exactly as typed. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task NoCodeInTheEnvironment_PromptsAndUsesTheTypedLine(string? variable) + { + using CliFixture cli = new() { Reply = "Enrolled." }; + cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = variable; + cli.TypedLines.Enqueue(Code); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(1, cli.LinesRead); + Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent)); + Assert.Equal("Enrollment code: Enrolled.\n", cli.Output); + Assert.Equal("", cli.Error); + } + + + + /// When no code is available (standard input is closed, or the operator enters a blank line), enrollment fails with one line on standard error and exit code 1, and no request reaches the service. + [Theory] + [InlineData(false, null)] + [InlineData(true, "")] + [InlineData(true, " ")] + public async Task NoCodeAtAll_FailsWithoutContactingTheService(bool typed, string? line) + { + using CliFixture cli = new(); + if(typed) + { + cli.TypedLines.Enqueue(line); + } + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(1, exitCode); + Assert.Empty(cli.Sent); + Assert.Equal("Enrollment code: ", cli.Output); + Assert.Equal("Enrollment code is required.\n", cli.Error); + } + + + + /// The code is never printed, whichever way it arrived and however the enrollment ends: accepted, refused by the service, timed out, or failed to send. + [Theory] + [InlineData(true, "accepted")] + [InlineData(false, "accepted")] + [InlineData(true, "refused")] + [InlineData(false, "refused")] + [InlineData(true, "timeout")] + [InlineData(false, "timeout")] + [InlineData(true, "failure")] + [InlineData(false, "failure")] + public async Task Code_NeverAppearsInOutput(bool fromEnvironment, string outcome) + { + using CliFixture cli = new() + { + Reply = outcome is "refused" ? "Error: The synthetic service refused the enrollment." : "Enrolled.", + SendFailure = outcome switch + { + "timeout" => new TaskCanceledException("Synthetic request timeout."), + "failure" => new IOException("Service connection closed before a complete response was received."), + _ => null, + }, + }; + if(fromEnvironment) + { + cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = Code; + } + else + { + cli.TypedLines.Enqueue(Code); + } + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(outcome is "accepted" ? 0 : 1, exitCode); + Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode); + Assert.DoesNotContain(Code, cli.Everything, StringComparison.Ordinal); + } + + + + /// A code put on the command line is refused, not used: nothing is sent, and the refusal does not repeat the code, so a mistake does not also copy the secret into captured error output. + [Theory] + [InlineData("enroll", "--server", Server, Code)] + [InlineData("enroll", "--server", Server, "--code", Code)] + [InlineData("enroll", "--code", Code)] + [InlineData("enroll", Code)] + [InlineData("enrol", "--server", Server, "--code", Code)] + public async Task CodeOnTheCommandLine_IsRefusedAndNotEchoed(params string[] args) + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(1, exitCode); + Assert.Empty(cli.Sent); + Assert.Equal("", cli.Output); + Assert.DoesNotContain(Code, cli.Error, StringComparison.Ordinal); + Assert.Equal(0, cli.LinesRead); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs new file mode 100644 index 0000000..5db0b11 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The three roles other parts of the product start this executable in, each with fixed arguments: the isolated printer +/// worker, the MSI update helper and the browser sign-in callback forwarder. These tests pin which arguments select each +/// role, what is passed on, and how a failure is reported, with fakes standing in for the worker, the installer and the +/// companion. CliProcessTests starts the real executable to prove the same routing in the shipped entry point. +/// +public sealed class CliHelperRoleTests +{ + private const string Callback = "io.qrun.qqq-print-agent:/oauth/callback?code=synthetic-code-91&state=synthetic-state-17"; + + + + /// Exactly --printer-worker runs the printer worker once and returns its exit code unchanged. The command line itself writes nothing, because the worker's standard output is a one-line protocol its parent parses. + [Theory] + [InlineData(0)] + [InlineData(1)] + public async Task PrinterWorker_RunsTheWorkerAndReturnsItsExitCode(int workerExitCode) + { + using CliFixture cli = new() { HelperExitCode = workerExitCode }; + + int exitCode = await cli.RunAsync("--printer-worker"); + + Assert.Equal(workerExitCode, exitCode); + Assert.Equal(1, cli.WorkerRuns); + Assert.Equal("", cli.Everything); + Assert.Empty(cli.Sent); + } + + + + /// A failure inside the printer worker is not caught or printed by the command line: the worker reports its own failures to its parent, and anything else must surface as a crash, not as a line the parent would try to parse. + [Fact] + public async Task PrinterWorker_FailureIsNotCaughtOrPrinted() + { + using CliFixture cli = new() { HelperFailure = new InvalidOperationException("Synthetic worker failure.") }; + + InvalidOperationException failure = await Assert.ThrowsAsync(() => cli.RunAsync("--printer-worker")); + + Assert.Equal("Synthetic worker failure.", failure.Message); + Assert.Equal("", cli.Everything); + } + + + + /// The update helper receives exactly the request path it was started with and its exit code is returned unchanged; the command line prints nothing of its own. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(1603)] + public async Task ApplyUpdate_PassesTheRequestPathAndReturnsTheExitCode(int helperExitCode) + { + using CliFixture cli = new() { HelperExitCode = helperExitCode }; + + int exitCode = await cli.RunAsync("--apply-update", "C:\\synthetic\\updates\\request.json"); + + Assert.Equal(helperExitCode, exitCode); + Assert.Equal("C:\\synthetic\\updates\\request.json", Assert.Single(cli.UpdateRequests)); + Assert.Equal("", cli.Everything); + Assert.Equal(0, cli.WorkerRuns); + Assert.Empty(cli.Sent); + } + + + + /// An update helper that throws is reported as one line on standard error and exit code 1. + [Fact] + public async Task ApplyUpdate_FailureIsOneLineOnStandardErrorAndFails() + { + using CliFixture cli = new() { HelperFailure = new UnauthorizedAccessException("Synthetic update refusal.") }; + + int exitCode = await cli.RunAsync("--apply-update", "C:\\synthetic\\updates\\request.json"); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal("Synthetic update refusal.\n", cli.Error); + } + + + + /// The sign-in callback address is forwarded exactly as the browser supplied it, without a cancellation deadline of the command line's own, and a delivered callback exits 0 with nothing printed. + [Fact] + public async Task AuthCallback_ForwardsTheAddressUnchangedAndSucceeds() + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync("--auth-callback", Callback); + + Assert.Equal(0, exitCode); + (string forwarded, CancellationToken token) = Assert.Single(cli.Callbacks); + Assert.Equal(Callback, forwarded); + Assert.False(token.CanBeCanceled); + Assert.Equal("", cli.Everything); + Assert.Empty(cli.Sent); + } + + + + /// A callback that cannot be delivered exits 1 with the forwarder's reason on standard error, and the address, which carries a one-time authorization code, is not printed. + [Fact] + public async Task AuthCallback_FailureIsReportedWithoutTheAddress() + { + using CliFixture cli = new() { HelperFailure = new UnauthorizedAccessException("Browser callbacks require the installed CLI location.") }; + + int exitCode = await cli.RunAsync("--auth-callback", Callback); + + Assert.Equal(1, exitCode); + Assert.Equal("", cli.Output); + Assert.Equal("Browser callbacks require the installed CLI location.\n", cli.Error); + Assert.DoesNotContain("synthetic-code-91", cli.Everything, StringComparison.Ordinal); + } + + + + /// A callback hand-off that is canceled or times out exits 1 with the fixed timeout sentence. + [Fact] + public async Task AuthCallback_TimeoutFailsWithTheFixedMessage() + { + using CliFixture cli = new() { HelperFailure = new OperationCanceledException("Synthetic hand-off timeout.") }; + + int exitCode = await cli.RunAsync("--auth-callback", Callback); + + Assert.Equal(1, exitCode); + Assert.Equal("The operation timed out or was canceled before completion.\n", cli.Error); + } + + + + /// The role arguments are exact. One argument too many or too few does not start a helper: the command line is refused as an unknown command, and what was typed, which may be a callback address, is not repeated. + [Theory] + [InlineData("--printer-worker", "extra")] + [InlineData("--printer-worker", "--printer-worker")] + [InlineData("--Printer-Worker")] + [InlineData("--apply-update")] + [InlineData("--apply-update", "C:\\synthetic\\updates\\request.json", "extra")] + [InlineData("--auth-callback")] + [InlineData("--auth-callback", Callback, "extra")] + [InlineData("run", "--printer-worker")] + public async Task InexactRoleArguments_StartNoHelperAndAreRefused(params string[] args) + { + using CliFixture cli = new(); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(1, exitCode); + Assert.Equal(0, cli.WorkerRuns); + Assert.Empty(cli.UpdateRequests); + Assert.Empty(cli.Callbacks); + Assert.Empty(cli.Sent); + Assert.Equal("", cli.Output); + Assert.EndsWith(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Error.ReplaceLineEndings("\n"), StringComparison.Ordinal); + Assert.DoesNotContain("synthetic-code-91", cli.Error, StringComparison.Ordinal); + } +} -- 2.54.0 From eb39586fcedbd9ca1f41b658757b888c6faaf980 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:16:26 -0600 Subject: [PATCH 04/13] test(cli): start the built executable; raise the qqq-print-agent minimum to 100 CliProcessTests starts the qqq-print-agent.exe built beside the test assembly and checks what a script would see: --help, -h, help and no arguments exit 0 with the usage on standard output and nothing on standard error; an unknown command (the removed --legacy-compat) exits 1 with the reason and usage on standard error and nothing on standard output. It also keeps the printer-worker role tested in the shipped entry point. Started with --printer-worker and no parent, the executable refuses in the worker's own one-line JSON protocol; started with a live parent, it reads one request from standard input and answers it. Both requests are ones the worker must refuse, so no printer is reached. A process that does not end within a minute is killed and fails the test. build/minimum-coverage.json: qqq-print-agent 37 -> 100. The assembly measured exactly 100% (78 of 78 lines) on three consecutive full gate runs with the minimum already at 100, and on a fourth run in which an unrelated timing-dependent runtime test failed (AgentControlConcurrencyTests.RemoteDisconnectAndReconnectDoNotInterruptBlockedPrintOrControlPolling). Every line is reached by tests that run in-process against fakes, so the figure does not depend on timing or on the child processes. Nothing in the assembly is excluded from coverage. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- build/minimum-coverage.json | 2 +- .../CliProcessTests.cs | 148 ++++++++++++++++++ 2 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs diff --git a/build/minimum-coverage.json b/build/minimum-coverage.json index 8789ab8..bf87664 100644 --- a/build/minimum-coverage.json +++ b/build/minimum-coverage.json @@ -1,5 +1,5 @@ { "Qqq.PrintAgent.Core": 86, "Qqq.PrintAgent.Windows": 69, - "qqq-print-agent": 37 + "qqq-print-agent": 100 } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs new file mode 100644 index 0000000..768888a --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The built qqq-print-agent.exe, started as a real process. The other command-line tests drive the logic against fakes; +/// these prove the shipped entry point is wired to it: real exit codes, real standard output and standard error, and the +/// printer-worker role still answering its parent. None of them needs the installed service, and none reaches a printer: +/// the worker is only ever given a request it must refuse. +/// +public sealed class CliProcessTests +{ + private const string ParentVariable = "QQQ_PRINT_WORKER_PARENT"; + + + + /// The executable built beside this test assembly. + private static string Executable => Path.ChangeExtension(typeof(Program).Assembly.Location, ".exe"); + + + + /// Asking the real executable for help exits 0 with the usage on standard output and nothing on standard error. + [Theory] + [InlineData("--help")] + [InlineData("-h")] + [InlineData("help")] + public async Task Help_ExitsZeroWithUsageOnStandardOutput(string argument) + { + (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null, argument); + + Assert.Equal(0, exitCode); + Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); + Assert.Equal("", error); + } + + + + /// With no arguments at all the real executable also prints the usage and exits 0. + [Fact] + public async Task NoArguments_ExitsZeroWithUsageOnStandardOutput() + { + (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null); + + Assert.Equal(0, exitCode); + Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); + Assert.Equal("", error); + } + + + + /// An unknown command, here the removed legacy flag, makes the real executable exit 1 with the reason and the usage on standard error and nothing on standard output. + [Fact] + public async Task UnknownCommand_ExitsOneWithUsageOnStandardError() + { + (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null, "--legacy-compat", "run", "--once"); + + Assert.Equal(1, exitCode); + Assert.Equal("", output); + Assert.Equal("Unknown command.\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", error); + } + + + + /// Started as a printer worker without a parent to watch, the real executable refuses in the worker's own protocol: one JSON line on standard output reporting failure, exit code 1, and nothing on standard error. That refusal comes from the worker host, which shows the role is still reached through this executable. + [Fact] + public async Task PrinterWorker_WithoutAParent_RefusesInTheWorkerProtocol() + { + (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: "{\"operation\":\"discover\"}", "--printer-worker"); + + Assert.Equal(1, exitCode); + using var answer = JsonDocument.Parse(output); + Assert.False(answer.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("launched by the print connector", answer.RootElement.GetProperty("error").GetString(), StringComparison.Ordinal); + Assert.Equal("", error); + } + + + + /// Started as a printer worker by a live parent, the real executable reads one request from standard input and answers it on standard output. The request names an operation that does not exist, so the worker refuses it without touching any printer. + [Fact] + public async Task PrinterWorker_WithAParent_ReadsARequestAndAnswersIt() + { + (int exitCode, string output, string error) = await RunAsync(Environment.ProcessId, "{\"operation\":\"synthetic-operation\"}", "--printer-worker"); + + Assert.Equal(1, exitCode); + using var answer = JsonDocument.Parse(output); + Assert.False(answer.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("Unknown printer worker operation.", answer.RootElement.GetProperty("error").GetString()); + Assert.Equal("", error); + } + + + + /// + /// Starts the executable with the given arguments and waits for it to end, returning its exit code and what it wrote, with + /// line endings normalized. The worker's parent variable is set only when a parent is given, standard input carries the + /// given line and is then closed, and a process that has not finished within a minute is killed so a hang fails the test + /// instead of blocking the run. + /// + private static async Task<(int ExitCode, string Output, string Error)> RunAsync(int? parentProcessId, string? input, params string[] args) + { + ProcessStartInfo start = new(Executable) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach(string argument in args) + { + start.ArgumentList.Add(argument); + } + start.Environment.Remove(ParentVariable); + if(parentProcessId is int parent) + { + start.Environment[ParentVariable] = parent.ToString(CultureInfo.InvariantCulture); + } + using Process process = Process.Start(start) ?? throw new InvalidOperationException("The command-line executable did not start."); + using CancellationTokenSource limit = new(TimeSpan.FromMinutes(1)); + try + { + Task output = process.StandardOutput.ReadToEndAsync(limit.Token); + Task error = process.StandardError.ReadToEndAsync(limit.Token); + if(input is not null) + { + await process.StandardInput.WriteLineAsync(input.AsMemory(), limit.Token); + } + process.StandardInput.Close(); + await process.WaitForExitAsync(limit.Token); + return (process.ExitCode, (await output).ReplaceLineEndings("\n"), (await error).ReplaceLineEndings("\n")); + } + finally + { + if(!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + } + } +} -- 2.54.0 From 5fb365cb6c403c4edd4537cba5a863529b093542 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:18:04 -0600 Subject: [PATCH 05/13] docs: describe the 2.0 command line; drop the removed legacy mode Nothing in the documentation describes --legacy-compat, --data-dir, --once or --service as usable any more. - docs/ADMINISTRATION.md gains a Command line section: the commands, where the enrollment code comes from, the exit codes and output streams, strict arguments, and what to do with per-user state the removed mode left in %LOCALAPPDATA%\QqqPrintAgent. - docs/INSTALLATION.md, docs/QQQ-SIGN-IN.md, docs/DEVELOPMENT.md and docs/TROUBLESHOOTING.md lose the legacy diagnostics sentences. Printer worker children are started by the service only; the worker.lock rows now describe the service, which still holds that lock. - docs/security/threat-model.md: the command line has no server transport and keeps no credentials or journal; a refused command line is never echoed. - CHANGELOG.md records the breaking command-line changes under Unreleased. - CLAUDE.md: the CLI project row and where the command-line tests live. Left as dated history: installer/VALIDATION.md, docs/FUNCTIONAL-AUDIT.md, the completed items in docs/TODO.md and the older CHANGELOG entries. docs/SESSION-STATE.md is not touched here; its line giving the coverage minimums as 86 / 68 / 37 is out of date now that the command line is at 100. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- CHANGELOG.md | 12 ++++++++++++ CLAUDE.md | 4 ++-- docs/ADMINISTRATION.md | 23 ++++++++++++++++++++++- docs/DEVELOPMENT.md | 6 +++--- docs/INSTALLATION.md | 6 +++--- docs/QQQ-SIGN-IN.md | 2 +- docs/TROUBLESHOOTING.md | 4 ++-- docs/security/threat-model.md | 4 ++-- 8 files changed, 47 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4516459..c01677c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,18 @@ capability gets the ordinary logout, and the log says the provider session was n `sign-out` cannot open the companion's callback inbox, so it still ends only the QQQ session and says so. No change to pairing, history or the printing protocol. +Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the installed service over its pipe. The +`--legacy-compat` mode is removed with everything that existed for it: the separate per-user data directory +(`--data-dir`), the command line's worker lock, the run-once claim pass (`run --once`), the isolated enroll and +expose paths, and the `--service` flag. It was the last code that sent a device token outside a QQQ session. +`--help`, `-h`, `help` and no arguments print the usage on standard output and exit 0 (`--help` and `-h` used to +exit 1); an unknown command prints it on standard error and exits 1. Arguments are checked strictly: a command +accepts exactly its own options, each once, and anything else is refused without contacting the service and +without repeating what was typed. `service-status` and `snapshot` now exit 1 when the service replies with an +error, as the other commands already did. State left in `%LOCALAPPDATA%\QqqPrintAgent` by the removed mode is no +longer read; see [Administrator operations](docs/ADMINISTRATION.md#command-line). The executable's internal roles +(printer worker, MSI update helper, browser sign-in callback) are unchanged. + ## 1.2.1 Release-pipeline fix only; same source as 1.2.0 otherwise. The stable release workflow's per-edition diff --git a/CLAUDE.md b/CLAUDE.md index 87b711f..ad8e4b0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,7 +71,7 @@ Five projects, strict layering (Core → Windows → Service/UI/CLI). Business l | `Qqq.PrintAgent.Windows` | Spooler/PDF/ZPL backends, SQLite + DPAPI store, named-pipe IPC, the long-running runtime | `AgentRuntime.*.cs` (partial class split by concern), `AgentPipe*`, `AgentStore` | | `Qqq.PrintAgent.Service` | Windows Service host only | `PrintService.cs` | | `Qqq.PrintAgent` | WinUI/AppKit companion: tray, Printers/Jobs/Logs/Settings views, MSI update UX | `MainWindow.*.cs` (partial class split by concern) | -| `Qqq.PrintAgent.Cli` | Authenticated service management over the pipe; isolated legacy diagnostics | `Program.cs` | +| `Qqq.PrintAgent.Cli` | Service management over the pipe, nothing else; the same executable is also the MSI update helper and the browser sign-in callback forwarder | `CommandLine.cs` (`Program.cs` only binds the real console, pipe and helpers) | Large classes are deliberately split into partial files by concern (`AgentRuntime.Realtime.cs`, `AgentRuntime.Jobs.cs`, `MainWindow.Updates.cs`, ...). Add new behavior to the matching partial rather than growing `AgentRuntime.cs` / `MainWindow.xaml.cs`. @@ -86,7 +86,7 @@ Large classes are deliberately split into partial files by concern (`AgentRuntim ## Test layout - `tests/Qqq.PrintAgent.Core.Tests`: protocol fixtures (`ProtocolFixtureTests`), loopback WebSocket peer, worker state machine, media contracts. New Core tests are written here (see the host note under Commands for where it builds). -- `tests/Qqq.PrintAgent.Cli.Tests`: despite the name, this is the Windows runtime suite (`AgentRuntime*`, `AgentRealtime*`, `AgentPipe*`, `AgentStore*`). Put Windows-layer tests here. +- `tests/Qqq.PrintAgent.Cli.Tests`: despite the name, this is mostly the Windows runtime suite (`AgentRuntime*`, `AgentRealtime*`, `AgentPipe*`, `AgentStore*`). Put Windows-layer tests here. The command-line tests are its `Cli*Tests.cs` files: they drive `CommandLine` through `CliFixture` (fakes for console, environment, pipe and helpers), and `CliProcessTests` starts the built executable. - `tests/Qqq.PrintAgent.WorkerFixture`: child-process fixture used by runtime tests. ## Conventions worth knowing diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index 9f5ef45..c93120b 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -24,10 +24,31 @@ Get-Service QqqPrintAgent, Spooler & 'C:\Program Files\QQQ Print Agent\Cli\qqq-print-agent.exe' service-status ``` -Use the actual install path if it differs. Normal CLI commands and the companion use the authenticated installed service. Its printer list reflects the service identity; explicit isolated legacy diagnostics may see different queues under their invoking account. +Use the actual install path if it differs. CLI commands and the companion use the authenticated installed service, so the printer list reflects the service identity, not the account that runs the command. Use the built-in AppKit activity log for shared service and companion events, with source labels and severity filtering. Windows Event Viewer can also help diagnose service-host startup failures. Record relevant timestamps, job IDs and error text without customer document contents. +## Command line + +`qqq-print-agent.exe` manages the installed service and nothing else. Each command is one request over the administrator-only pipe, so run it from an elevated prompt with the service running. Sign in through the companion first: enrollment and the connection commands act on the service's QQQ session. + +| Command | What the service does | +| --- | --- | +| `printers` | Lists the printers it can see, as JSON | +| `enroll --server URL` | Pairs this computer with a QQQ server using a one-time enrollment code | +| `expose --printer ID --exposed true\|false` | Shares a printer with QQQ, or stops sharing it | +| `run` | Refreshes its connection to QQQ | +| `sign-out` | Ends its QQQ session (the identity provider's browser session is ended only by Sign out in the companion) | +| `service-status` | Reports its connection status | +| `snapshot` | Reports its state as JSON: connection, printers, recent jobs and logs | +| `help`, `--help`, `-h`, or no arguments | Nothing; the usage is printed | + +The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable, or typed at a prompt when the variable is not set. It is never accepted as an argument and never printed. + +The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Replies and requested usage go to standard output; failures, and the usage shown for a refused command line, go to standard error. A command accepts exactly the options shown, each once; anything else is refused before the service is contacted, and the refusal does not repeat what was typed. + +Version 2.0 removed `--legacy-compat` and the options that existed for it (`--data-dir`, `--once`, `--service`). If that mode was ever used on a machine, its separate per-user state is still in `%LOCALAPPDATA%\QqqPrintAgent` (`connection.dpapi`, `journal.db`, `worker.lock`). Nothing reads it any more; delete it once the device it enrolled has been revoked in QQQ. Leave `auth-callback.log` in that folder: the browser sign-in helper still writes it. + ## Credentials and network Sign in through standard QQQ authentication, then associate an existing unbound pairing or enroll a new device explicitly. Every normal printing request requires the current QQQ user session and secondary device proof; server user, tenant and record permissions still apply. Session renewal does not change the journal's device identity. Revoke the device in QQQ when decommissioning a machine. Revocation cannot recall a job already accepted by the Windows spooler. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 037eecf..a75f99d 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -12,7 +12,7 @@ and reconnect rules. The service never falls back from WSS to job/control pollin | Qqq.PrintAgent.Windows | Native spooler/PDF adapter, SQLite/DPAPI store and local management runtime | | Qqq.PrintAgent.Service | .NET Windows Service host | | Qqq.PrintAgent | AppKit/WinUI setup, details and tray companion | -| Qqq.PrintAgent.Cli | Authenticated service management and explicit isolated legacy diagnostics | +| Qqq.PrintAgent.Cli | Management of the installed service over its pipe; also the MSI update helper and browser sign-in callback forwarder | The service owns the credential, journal and print operations. The UI is optional at runtime and sees only credential-free snapshots. Service IPC uses the `QqqPrintAgent` named pipe and accepts administrator clients. `snapshot` returns connection health, all locally discovered printers with exposure state, the latest 50 jobs and the latest 100 in-memory log entries. `set-exposure` persists a selected queue and returns a fresh snapshot. Legacy `status`, `printers` and `enroll` operations remain available. @@ -51,9 +51,9 @@ $agent = '.\src\Qqq.PrintAgent.Cli\bin\x64\Debug\net10.0-windows10.0.19041.0\qqq & $agent run ``` -`run` requests a connection refresh through the authenticated service; it does not start a second foreground worker. Device setup and explicit printer exposure use that same service. Submit a physical test only when authorized, after approving the selected exposed queue in QQQ. +`run` requests a connection refresh through the authenticated service; the command line never claims or prints a job itself. Device setup and explicit printer exposure use that same service. Submit a physical test only when authorized, after approving the selected exposed queue in QQQ. -Direct bearer diagnostics require explicit `--legacy-compat` and a separate private `--data-dir`; they cannot use `--service` and are never an automatic fallback. The exclusive `worker.lock` prevents simultaneous workers on one journal. Do not point a development worker at installed state. +The command line has no state and no server transport of its own: every command is one request to the service. The `--legacy-compat` bearer diagnostics and their `--data-dir`, `--once` and `--service` options were removed in 2.0. The service holds an exclusive `worker.lock` in its data directory, so a second service host cannot run against the same journal; do not point a development service at installed state. `CommandLine` takes the console, the environment, the pipe and the helper entry points as injected functions, so its tests need none of them. ## Virtual file printer (macOS/Linux) diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 60b1fcd..27b28a0 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -18,7 +18,7 @@ Run the MSI as an administrator. Windows Installer deploys one coherent applicat - The `QqqPrintAgent` automatic Windows service, running as LocalSystem and depending on the Windows Spooler. - The native **QQQ Print Agent** setup/status app and Start-menu entry. -- The `qqq-print-agent.exe` diagnostic CLI. +- The `qqq-print-agent.exe` command-line tool, which manages the service. - A restricted `%ProgramData%\QqqPrintAgent` directory for enrollment and the job journal. There is no inbound firewall rule or local HTTP server. The client requires outbound WSS upgrades and HTTPS to the QQQ server; update checks/downloads use HTTPS to GitHub release services. Use the matching qbit-printing 1.0.0 server with native printing API 2.3. There is no job/control polling fallback. The UI requests administrator elevation because its management pipe permits only SYSTEM and local administrators. @@ -49,7 +49,7 @@ Full uninstall removes only tasks whose name, current-user SID, interactive prin ## Isolated native printer operations -Discovery, submission and cancellation run in a short-lived child of the service or explicit diagnostic CLI. Control requests use anonymous standard-input/output pipes. Realtime documents stream to protected owned staging files; their content is not placed in command arguments or logs. Discovery and cancellation have bounded helper deadlines. Realtime printing uses the server's `nativeSubmissionTimeoutMillis`, default 120 seconds, rather than a fixed submission deadline. A timed-out child is terminated, with bounded cleanup, and also watches its parent. The child still runs with service privileges; isolation limits a blocked driver, not its authority. +Discovery, submission and cancellation run in a short-lived child of the service. Control requests use anonymous standard-input/output pipes. Realtime documents stream to protected owned staging files; their content is not placed in command arguments or logs. Discovery and cancellation have bounded helper deadlines. Realtime printing uses the server's `nativeSubmissionTimeoutMillis`, default 120 seconds, rather than a fixed submission deadline. A timed-out child is terminated, with bounded cleanup, and also watches its parent. The child still runs with service privileges; isolation limits a blocked driver, not its authority. This bounds a blocked printer driver without stopping cloud connectivity permanently. It cannot retract bytes already accepted by a printer: timeout, crash or cancellation after submission begins is an uncertain outcome and requires inspection before reprinting. Existing spooler receipt cancellation verifies the exact QQQ document identity before requesting cancellation; it does not prove that no paper or label has already emerged. Synthetic subprocess tests use a fake backend and never access a printer. @@ -65,7 +65,7 @@ Use qbit-printing 1.0.0 on QQQ 4.1.0-RC.21 or a compatible newer server; the rel For an existing unbound installation, choose **Associate the existing pairing with my account**; preserve its device record and history. For a new installation, complete sign-in and enter a single-use enrollment code created in QQQ. Enrollment runs in the service, protecting its device proof and QQQ session under the service identity. The desktop does not retain the password or device token. **Set up a new pairing** is an explicit replacement flow, not routine upgrade migration. -Normal CLI setup, printer exposure and connection commands use the authenticated installed service. Sign in through the companion first; `run` requests a connection refresh. Explicit `--legacy-compat` diagnostics require a separate `--data-dir` and cannot use `--service`. Do not copy a user-protected DPAPI credential into ProgramData: credentials are bound to the account that created them. The service owns unattended discovery and printing. +CLI setup, printer exposure and connection commands are requests to the authenticated installed service; see [Administrator operations](ADMINISTRATION.md#command-line). Sign in through the companion first; `run` requests a connection refresh. The command line keeps no credentials or data of its own. Do not copy a user-protected DPAPI credential into ProgramData: credentials are bound to the account that created them. The service owns unattended discovery and printing. ## Updates diff --git a/docs/QQQ-SIGN-IN.md b/docs/QQQ-SIGN-IN.md index 6727dc4..1c3dc76 100644 --- a/docs/QQQ-SIGN-IN.md +++ b/docs/QQQ-SIGN-IN.md @@ -12,7 +12,7 @@ The installed browser callback is exactly `io.qrun.qqq-print-agent:/oauth/callba **Shared server with the Android scanner.** One QQQ host and one OAuth2 provider/`clientId` can serve both clients. The native grant's `redirectUris` must contain both exact callbacks, `io.qrun.qqq-print-agent:/oauth/callback` (print agent) and `io.qrun.mobile.scanner.oauth://callback/oauth2redirect` (scanner), and the provider must allow both exactly (no wildcards). The host must also advertise the `api` and `android` client channels and both the `printing` and `mobile-scanners` extensions. Nonce handling is negotiated per server: when the grant descriptor has `nonceValidation: REQUIRED` (which the scanner demands) or `OPTIONAL`, or when discovery advertises the `nativeSessionNonceValidation` capability, the agent sends that attempt's own authorization nonce as `expectedNonce` in the `manageSession` exchange. When neither is present (older servers) the exchange body is unchanged. Any other non-empty policy value is refused as a server configuration problem before a browser opens. The nonce is never taken from the callback, regenerated or logged. Human permissions (`printing_admin` versus the scanner's `mobile.*`) and device credentials stay separate. Validation against a real shared Authentik host is pending; this is not released. -Normal CLI `printers`, `enroll`, `expose`, `run` and `sign-out` commands use the installed authenticated service. `run` requests a connection refresh; the service owns unattended printing. Direct bearer-based foreground diagnostics require explicit `--legacy-compat` and a separate user data directory; they cannot use `--service`. They are a compatibility diagnostic, not the app's sign-in or fallback path. +The CLI `printers`, `enroll`, `expose`, `run` and `sign-out` commands use the installed authenticated service. `run` requests a connection refresh; the service owns unattended printing. The command line has no sign-in or transport of its own: the bearer-based `--legacy-compat` diagnostics were removed in 2.0. The server and its identity provider govern session lifetime, renewal and current permissions. Unattended service operation does not promise an indefinite authorization lifetime: expiration, revocation or a policy change can require a new sign-in. Configure the advertised native session grant and approved callback for each deployment. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index c67124a..74f81b3 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -2,7 +2,7 @@ | Symptom | Check | | --- | --- | -| Companion cannot connect to service | Confirm the MSI is installed, `QqqPrintAgent` is running, and the companion is elevated. A development CLI worker does not host the installed service pipe. | +| Companion cannot connect to service | Confirm the MSI is installed, `QqqPrintAgent` is running, and the companion is elevated. The command-line tool is only a client of that pipe; it does not host it. | | Sign-in or discovery fails | Open **View logs**: every step (discovery, authentication metadata, native grant validation, provider discovery, browser callback, session verification by the service, device binding, identity check) is logged with the reason it stopped, and the dialog shows the same reason. Turn on **Debug logging** in Log settings for request routes, status codes, timings and realtime frames. | | Sign-in works in the companion but "Service authorization not completed" | The service verifies the session itself as LocalSystem. A self-signed or private-authority certificate (for example a local Caddy root) that your user account trusts is not in the machine store, so the service's TLS check fails; the log shows `TLS certificate for host rejected: RemoteCertificateChainErrors`. Install the issuing root in **Local Machine → Trusted Root Certification Authorities**, or enter the server address and enable **Allow untrusted server certificate for this server** in Connection settings for a development server (the exception is bound to that one server). | | Enrollment fails | Complete standard QQQ sign-in, then check the server URL, fresh/unconsumed code, device/facility configuration and server logs. Remote endpoints require HTTPS. The log records each enrollment step and the server's answer. | @@ -17,7 +17,7 @@ | PDF clipped or wrong size | Select actual size versus fit deliberately. Match the machine default, advertised media profile or explicit per-job PDF dimensions to the loaded stock; see [Printer media](PRINTER-MEDIA.md). | | Zebra prints text or blank labels | Confirm ZPL-capable hardware/driver, DPI, stock dimensions and actual printer mode. Inspect the specific document; previously confirmed output does not qualify every format/driver combination. | | Protected configuration cannot be opened | It belongs to another Windows identity, or the service account changed. Re-enroll through the service after resolving old jobs; do not copy a user-enrolled DPAPI file. | -| Another worker owns the directory | Stop the duplicate CLI worker. Only one worker may own a given journal/data directory. | +| Another worker owns the directory | A second copy of the service host (for example a development build started by hand) holds `worker.lock`. Stop it. Only one service may own a given journal/data directory. | | MSI publisher warning | Stable 1.0.1 is signed. Verify the exact official release checksum and Authenticode signature as described in [Installation](INSTALLATION.md). Earlier prereleases may be unsigned. | ## ZPL prints but PDF does not diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index d79a32b..73868dc 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -8,9 +8,9 @@ The signed 1.0.1 release uses the realtime and native-authentication boundaries The remote-control adapter accepts only inventory refresh and cancellation of one locally journaled spooler job. Desired pause/disconnect state is revisioned and persists by canonical server URL and device identity; older or conflicting revisions cannot resume a device. An independently processed authenticated WSS channel carries controls and receipts while documents stream over separate same-origin HTTPS requests. There is no job/control polling fallback. A paused device claims no new work. A disconnected device retains control traffic and in-flight receipts; already-submitted printing is not recalled. Reconnect is a transport refresh, never an OS or service restart. See [the realtime contract and operational limits](../REALTIME.md). -The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. Explicit isolated CLI diagnostics may use the compatibility bearer adapter with `--legacy-compat`; it is not a fallback from native authentication. +The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. The command line has no server transport: the `--legacy-compat` bearer diagnostics were removed in 2.0, so no shipped code path sends the device token outside a native session, and the command line keeps no credentials or journal of its own. -The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. Normal CLI operations use the existing authenticated service pipe. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. +The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or a prompt; a command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. Sign-out also ends the identity provider's browser session. The companion sends only the fixed registered callback with `sign-out`; the service refuses any other value, asks QQQ to log out with `nativeLogout.postLogoutRedirectUri`, and returns the provider end-session request to the companion over the administrator-only pipe. That request carries the provider's ID token hint (sensitive, bounded to 32 KiB, no whitespace or control characters), so it is never logged, the record prints redacted, and only the provider host is logged. Core refuses the data unless the issuer equals the one QQQ advertises, the end-session endpoint is HTTPS on the issuer's origin and identical to the provider's own discovery, and the callback is the one requested. The browser return is accepted only on the exact callback with the state this sign-out generated. Browser sign-in also sends `max_age=0` beside `prompt=login`. -- 2.54.0 From a8ac2b1e06dcc0cb5a745a2d0746822d343c7e73 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:46:03 -0600 Subject: [PATCH 06/13] refactor(cli)!: remove the printer-worker role and the direct Core reference Review of 45b448f confirmed that nothing starts qqq-print-agent.exe as a printer worker. The only worker start is IsolatedPrinterBackend.InvokeAsync, constructed only by the service with its own executable path, and the same holds at tags v1.0.1 and v1.2.1; the removed legacy mode was the only code that ever passed this executable's path. --printer-worker is therefore no longer a role: the special case in CommandLine.RunAsync, the host's RunPrinterWorkerAsync and its binding in Program are gone, and the argument is refused as an unknown command like any other word. The update helper and the sign-in callback forwarder are unchanged. The command line uses no Core type, so the project drops its direct Core reference and the global using; Core still arrives through the Windows layer, and the lock file is unchanged. The project file's header comment described the template, not this project, and is rewritten. Tests: the worker cases leave CliHelperRoleTests and CliProcessTests; --printer-worker joins the unknown-command theory, and a process test shows the real executable writes nothing to standard output when given the worker's argument and a worker request. BREAKING CHANGE: qqq-print-agent.exe --printer-worker exits 1 with usage. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- CHANGELOG.md | 6 +- src/Qqq.PrintAgent.Cli/CommandLine.cs | 19 ++---- src/Qqq.PrintAgent.Cli/CommandLineHost.cs | 2 - src/Qqq.PrintAgent.Cli/Program.cs | 2 +- .../Qqq.PrintAgent.Cli.csproj | 21 +++---- tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs | 20 +------ .../CliHelperRoleTests.cs | 48 ++------------- .../CliProcessTests.cs | 60 +++++-------------- .../Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs | 4 +- 9 files changed, 45 insertions(+), 137 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c01677c..df72a20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,8 +22,10 @@ exit 1); an unknown command prints it on standard error and exits 1. Arguments a accepts exactly its own options, each once, and anything else is refused without contacting the service and without repeating what was typed. `service-status` and `snapshot` now exit 1 when the service replies with an error, as the other commands already did. State left in `%LOCALAPPDATA%\QqqPrintAgent` by the removed mode is no -longer read; see [Administrator operations](docs/ADMINISTRATION.md#command-line). The executable's internal roles -(printer worker, MSI update helper, browser sign-in callback) are unchanged. +longer read; see [Administrator operations](docs/ADMINISTRATION.md#command-line). The executable is +no longer a printer worker: `--printer-worker` is an unknown command. Only the removed mode ever started it that +way; the service starts its own executable as the worker, in 1.x as now. Its two remaining internal roles (MSI +update helper, browser sign-in callback) are unchanged. ## 1.2.1 diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index 6090dda..c971023 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -64,23 +64,14 @@ internal sealed class CommandLine(CommandLineHost host) /// - /// Runs one invocation and returns the process exit code. Three argument shapes are internal and fixed: the isolated - /// printer worker, the MSI update helper and the browser sign-in callback forwarder, each started by another part of the - /// product with exactly these arguments. Everything else is an operator command. A failure becomes one line on standard - /// error and exit code 1; a timeout or cancellation does too, so a script never mistakes an operation that did not finish - /// for one that succeeded. + /// Runs one invocation and returns the process exit code. Two argument shapes are internal and fixed: the MSI update + /// helper and the browser sign-in callback forwarder, each started by another part of the product with exactly these + /// arguments. Everything else is an operator command. This executable is not a printer worker: the service starts its + /// own executable for that. A failure becomes one line on standard error and exit code 1; a timeout or cancellation + /// does too, so a script never mistakes an operation that did not finish for one that succeeded. /// internal async Task RunAsync(string[] args) { - ///////////////////////////////////////////////////////////////////////////// - // the printer worker answers its parent with one JSON line on standard // - // output and reports its own failures there, so nothing here may catch or // - // print for it: it runs outside the handling that the other roles share // - ///////////////////////////////////////////////////////////////////////////// - if(args is ["--printer-worker"]) - { - return await host.RunPrinterWorkerAsync(); - } try { return args switch diff --git a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs index 9686365..0b0960c 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs @@ -16,7 +16,6 @@ namespace Qqq.PrintAgent.Cli; /// Reads one environment variable; the enrollment code arrives this way so it stays out of the command line and shell history. /// Reads one line of standard input, for the enrollment code when the variable is not set; null at end of input. /// Sends one request to the installed service over its administrator pipe and returns the reply text. -/// Runs this process as an isolated printer worker and returns its exit code. /// Applies the prepared MSI update named by a request file and returns the exit code. /// Forwards a browser sign-in callback address to the running companion. internal sealed record CommandLineHost( @@ -25,6 +24,5 @@ internal sealed record CommandLineHost( Func ReadEnvironmentVariable, Func ReadLine, Func> SendAsync, - Func> RunPrinterWorkerAsync, Func> ApplyUpdateAsync, Func ForwardSignInCallbackAsync); diff --git a/src/Qqq.PrintAgent.Cli/Program.cs b/src/Qqq.PrintAgent.Cli/Program.cs index 54d7d22..f448bd0 100644 --- a/src/Qqq.PrintAgent.Cli/Program.cs +++ b/src/Qqq.PrintAgent.Cli/Program.cs @@ -19,5 +19,5 @@ public static class Program /// public static Task Main(string[] args) => new CommandLine(new CommandLineHost(Console.Out, Console.Error, Environment.GetEnvironmentVariable, Console.ReadLine, - AgentPipeClient.SendAsync, PrinterWorkerHost.RunAsync, MsiUpdateInstaller.ApplyAsync, QqqBrowserCallback.ForwardFromHandlerAsync)).RunAsync(args); + AgentPipeClient.SendAsync, MsiUpdateInstaller.ApplyAsync, QqqBrowserCallback.ForwardFromHandlerAsync)).RunAsync(args); } diff --git a/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj b/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj index e141157..b1264ac 100644 --- a/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj +++ b/src/Qqq.PrintAgent.Cli/Qqq.PrintAgent.Cli.csproj @@ -5,9 +5,11 @@ - + Exe net10.0-windows10.0.19041.0 @@ -18,20 +20,11 @@ - + - - - - - - - - - + diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs index 4d0d960..a67203d 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs @@ -9,7 +9,7 @@ namespace Qqq.PrintAgent.Cli.Tests; /// /// Shared harness for the command-line tests: the real wired to hand-written fakes for the console, -/// the environment, the service pipe and the three helper entry points. A test scripts what the outside world answers, runs +/// the environment, the service pipe and the two helper entry points. A test scripts what the outside world answers, runs /// an argument list, then reads exactly what was written, sent and started. Nothing here touches the real console, the /// installed service or a printer. Captured output uses "\n" line endings so expected text reads the same on every machine. /// @@ -65,7 +65,7 @@ internal sealed class CliFixture : IDisposable - /// The exit code the fake printer worker and update helper report. + /// The exit code the fake update helper reports. internal int HelperExitCode { get; set; } @@ -75,11 +75,6 @@ internal sealed class CliFixture : IDisposable - /// How many times this process was started as a printer worker. - internal int WorkerRuns { get; private set; } - - - /// The request-file paths handed to the update helper, in order. internal List UpdateRequests { get; } = []; @@ -97,7 +92,7 @@ internal sealed class CliFixture : IDisposable /// Runs one invocation of the command line against the fakes and returns its exit code. internal Task RunAsync(params string[] args) - => new CommandLine(new CommandLineHost(_output, _error, ReadVariable, ReadLine, SendAsync, RunWorkerAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args); + => new CommandLine(new CommandLineHost(_output, _error, ReadVariable, ReadLine, SendAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args); @@ -128,15 +123,6 @@ internal sealed class CliFixture : IDisposable - /// Counts a printer-worker start and reports the scripted exit code or failure. - private Task RunWorkerAsync() - { - WorkerRuns++; - return HelperFailure is null ? Task.FromResult(HelperExitCode) : Task.FromException(HelperFailure); - } - - - /// Records the update request path and reports the scripted exit code or failure. private Task ApplyUpdateAsync(string requestPath) { diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs index 5db0b11..1c9e073 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliHelperRoleTests.cs @@ -6,10 +6,10 @@ namespace Qqq.PrintAgent.Cli.Tests; /// -/// The three roles other parts of the product start this executable in, each with fixed arguments: the isolated printer -/// worker, the MSI update helper and the browser sign-in callback forwarder. These tests pin which arguments select each -/// role, what is passed on, and how a failure is reported, with fakes standing in for the worker, the installer and the -/// companion. CliProcessTests starts the real executable to prove the same routing in the shipped entry point. +/// The two roles other parts of the product start this executable in, each with fixed arguments: the MSI update helper +/// and the browser sign-in callback forwarder. These tests pin which arguments select each role, what is passed on, and +/// how a failure is reported, with fakes standing in for the installer and the companion. The executable is not a printer +/// worker; the service starts its own executable for that, and CliUsageTests holds --printer-worker to an unknown command. /// public sealed class CliHelperRoleTests { @@ -17,38 +17,6 @@ public sealed class CliHelperRoleTests - /// Exactly --printer-worker runs the printer worker once and returns its exit code unchanged. The command line itself writes nothing, because the worker's standard output is a one-line protocol its parent parses. - [Theory] - [InlineData(0)] - [InlineData(1)] - public async Task PrinterWorker_RunsTheWorkerAndReturnsItsExitCode(int workerExitCode) - { - using CliFixture cli = new() { HelperExitCode = workerExitCode }; - - int exitCode = await cli.RunAsync("--printer-worker"); - - Assert.Equal(workerExitCode, exitCode); - Assert.Equal(1, cli.WorkerRuns); - Assert.Equal("", cli.Everything); - Assert.Empty(cli.Sent); - } - - - - /// A failure inside the printer worker is not caught or printed by the command line: the worker reports its own failures to its parent, and anything else must surface as a crash, not as a line the parent would try to parse. - [Fact] - public async Task PrinterWorker_FailureIsNotCaughtOrPrinted() - { - using CliFixture cli = new() { HelperFailure = new InvalidOperationException("Synthetic worker failure.") }; - - InvalidOperationException failure = await Assert.ThrowsAsync(() => cli.RunAsync("--printer-worker")); - - Assert.Equal("Synthetic worker failure.", failure.Message); - Assert.Equal("", cli.Everything); - } - - - /// The update helper receives exactly the request path it was started with and its exit code is returned unchanged; the command line prints nothing of its own. [Theory] [InlineData(0)] @@ -63,7 +31,6 @@ public sealed class CliHelperRoleTests Assert.Equal(helperExitCode, exitCode); Assert.Equal("C:\\synthetic\\updates\\request.json", Assert.Single(cli.UpdateRequests)); Assert.Equal("", cli.Everything); - Assert.Equal(0, cli.WorkerRuns); Assert.Empty(cli.Sent); } @@ -134,14 +101,12 @@ public sealed class CliHelperRoleTests /// The role arguments are exact. One argument too many or too few does not start a helper: the command line is refused as an unknown command, and what was typed, which may be a callback address, is not repeated. [Theory] - [InlineData("--printer-worker", "extra")] - [InlineData("--printer-worker", "--printer-worker")] - [InlineData("--Printer-Worker")] [InlineData("--apply-update")] [InlineData("--apply-update", "C:\\synthetic\\updates\\request.json", "extra")] + [InlineData("--Apply-Update", "C:\\synthetic\\updates\\request.json")] [InlineData("--auth-callback")] [InlineData("--auth-callback", Callback, "extra")] - [InlineData("run", "--printer-worker")] + [InlineData("run", "--apply-update", "C:\\synthetic\\updates\\request.json")] public async Task InexactRoleArguments_StartNoHelperAndAreRefused(params string[] args) { using CliFixture cli = new(); @@ -149,7 +114,6 @@ public sealed class CliHelperRoleTests int exitCode = await cli.RunAsync(args); Assert.Equal(1, exitCode); - Assert.Equal(0, cli.WorkerRuns); Assert.Empty(cli.UpdateRequests); Assert.Empty(cli.Callbacks); Assert.Empty(cli.Sent); diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs index 768888a..4d277e5 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs @@ -4,23 +4,16 @@ */ using System.Diagnostics; -using System.Globalization; -using System.Text.Json; namespace Qqq.PrintAgent.Cli.Tests; /// /// The built qqq-print-agent.exe, started as a real process. The other command-line tests drive the logic against fakes; -/// these prove the shipped entry point is wired to it: real exit codes, real standard output and standard error, and the -/// printer-worker role still answering its parent. None of them needs the installed service, and none reaches a printer: -/// the worker is only ever given a request it must refuse. +/// these prove the shipped entry point is wired to it: real exit codes, real standard output and standard error. None of +/// them needs the installed service: every command line here is answered or refused before the service would be contacted. /// public sealed class CliProcessTests { - private const string ParentVariable = "QQQ_PRINT_WORKER_PARENT"; - - - /// The executable built beside this test assembly. private static string Executable => Path.ChangeExtension(typeof(Program).Assembly.Location, ".exe"); @@ -33,7 +26,7 @@ public sealed class CliProcessTests [InlineData("help")] public async Task Help_ExitsZeroWithUsageOnStandardOutput(string argument) { - (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null, argument); + (int exitCode, string output, string error) = await RunAsync(input: null, argument); Assert.Equal(0, exitCode); Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); @@ -46,7 +39,7 @@ public sealed class CliProcessTests [Fact] public async Task NoArguments_ExitsZeroWithUsageOnStandardOutput() { - (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null); + (int exitCode, string output, string error) = await RunAsync(input: null); Assert.Equal(0, exitCode); Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); @@ -55,11 +48,11 @@ public sealed class CliProcessTests - /// An unknown command, here the removed legacy flag, makes the real executable exit 1 with the reason and the usage on standard error and nothing on standard output. + /// An unknown command makes the real executable exit 1 with the reason and the usage on standard error and nothing on standard output. [Fact] public async Task UnknownCommand_ExitsOneWithUsageOnStandardError() { - (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: null, "--legacy-compat", "run", "--once"); + (int exitCode, string output, string error) = await RunAsync(input: null, "status"); Assert.Equal(1, exitCode); Assert.Equal("", output); @@ -68,43 +61,26 @@ public sealed class CliProcessTests - /// Started as a printer worker without a parent to watch, the real executable refuses in the worker's own protocol: one JSON line on standard output reporting failure, exit code 1, and nothing on standard error. That refusal comes from the worker host, which shows the role is still reached through this executable. + /// The real executable is not a printer worker. Given the worker's argument and a worker request on standard input, it answers nothing on standard output, where a parent would expect the worker's reply, and refuses the argument as an unknown command. [Fact] - public async Task PrinterWorker_WithoutAParent_RefusesInTheWorkerProtocol() + public async Task PrinterWorkerArgument_IsAnUnknownCommand() { - (int exitCode, string output, string error) = await RunAsync(parentProcessId: null, input: "{\"operation\":\"discover\"}", "--printer-worker"); + (int exitCode, string output, string error) = await RunAsync("{\"operation\":\"discover\"}", "--printer-worker"); Assert.Equal(1, exitCode); - using var answer = JsonDocument.Parse(output); - Assert.False(answer.RootElement.GetProperty("success").GetBoolean()); - Assert.Contains("launched by the print connector", answer.RootElement.GetProperty("error").GetString(), StringComparison.Ordinal); - Assert.Equal("", error); - } - - - - /// Started as a printer worker by a live parent, the real executable reads one request from standard input and answers it on standard output. The request names an operation that does not exist, so the worker refuses it without touching any printer. - [Fact] - public async Task PrinterWorker_WithAParent_ReadsARequestAndAnswersIt() - { - (int exitCode, string output, string error) = await RunAsync(Environment.ProcessId, "{\"operation\":\"synthetic-operation\"}", "--printer-worker"); - - Assert.Equal(1, exitCode); - using var answer = JsonDocument.Parse(output); - Assert.False(answer.RootElement.GetProperty("success").GetBoolean()); - Assert.Equal("Unknown printer worker operation.", answer.RootElement.GetProperty("error").GetString()); - Assert.Equal("", error); + Assert.Equal("", output); + Assert.Equal("Unknown command.\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", error); } /// /// Starts the executable with the given arguments and waits for it to end, returning its exit code and what it wrote, with - /// line endings normalized. The worker's parent variable is set only when a parent is given, standard input carries the - /// given line and is then closed, and a process that has not finished within a minute is killed so a hang fails the test - /// instead of blocking the run. + /// line endings normalized. Standard input carries the given line, if any, and is then closed. The enrollment code + /// variable is removed from the child's environment, so the result does not depend on the machine running the test. A + /// process that has not finished within a minute is killed, so a hang fails the test instead of blocking the run. /// - private static async Task<(int ExitCode, string Output, string Error)> RunAsync(int? parentProcessId, string? input, params string[] args) + private static async Task<(int ExitCode, string Output, string Error)> RunAsync(string? input, params string[] args) { ProcessStartInfo start = new(Executable) { @@ -118,11 +94,7 @@ public sealed class CliProcessTests { start.ArgumentList.Add(argument); } - start.Environment.Remove(ParentVariable); - if(parentProcessId is int parent) - { - start.Environment[ParentVariable] = parent.ToString(CultureInfo.InvariantCulture); - } + start.Environment.Remove(CommandLine.EnrollmentCodeVariable); using Process process = Process.Start(start) ?? throw new InvalidOperationException("The command-line executable did not start."); using CancellationTokenSource limit = new(TimeSpan.FromMinutes(1)); try diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs index 7605619..b05a072 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs @@ -57,10 +57,12 @@ public sealed class CliUsageTests - /// A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, and the option that selected the removed legacy mode is no longer a word the tool knows. + /// A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, the option that selected the removed legacy mode is no longer a word the tool knows, and --printer-worker is not a role of this executable: the service starts its own executable as the printer worker. [Theory] [InlineData("status")] [InlineData("Printers")] + [InlineData("--printer-worker")] + [InlineData("--printer-worker", "extra")] [InlineData("--legacy-compat")] [InlineData("--legacy-compat", "run", "--once")] [InlineData("--service")] -- 2.54.0 From 4522898d9b73b911ecc95fb9710fb35f8ec87963 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:48:43 -0600 Subject: [PATCH 07/13] fix(cli)!: prompt for the enrollment code on standard error, read it without echo, trim it The prompt was written to standard output with no line end, so a script that piped the code in captured "Enrollment code: Enrolled." as one line, and a code typed at a console stayed on the screen. - The prompt goes to standard error and its line is ended there after the read, before the reply or an error message. Standard output now holds the service's reply and nothing else. - When standard input is a console the code is read key by key without being shown: Enter ends it, Backspace removes the last character, keys that produce no printable character are ignored. When standard input is redirected a line is read, as before. - White space around the code is dropped, from the variable and from standard input. A code never has any, and cmd's "echo CODE | ..." pipes a trailing space. Until now the code was sent as given. The host gains IsInputRedirected and ReadKey. The key loop lives in CommandLine, so Backspace and Enter handling is tested with fake keys; Program binds Console.ReadKey by method reference and a one-line IsInputRedirected, which an in-process test calls. Nothing is excluded from coverage. The usage text says how the code is read. Tests: prompt stream and line end for a piped and a typed code; no key is ever read with echo; Backspace, an empty-line Backspace and non-character keys; trimming from all three sources with inner white space kept; no code at all from a closed, blank or Enter-only input; and a process test that runs the real executable with the variable removed and standard input closed, which exercises the real redirected-input binding and stops before the service would be contacted. The no-echo read was not run against a real console: that needs an interactive one. BREAKING CHANGE: the enrollment prompt moved from standard output to standard error; a typed code is no longer shown; the code is trimmed. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/CommandLine.cs | 48 ++++- src/Qqq.PrintAgent.Cli/CommandLineHost.cs | 10 +- src/Qqq.PrintAgent.Cli/Program.cs | 7 +- .../CliEnrollmentCodeTests.cs | 170 ++++++++++++++---- tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs | 51 +++++- .../CliProcessTests.cs | 22 +++ .../Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs | 4 +- 7 files changed, 261 insertions(+), 51 deletions(-) diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index c971023..5667ac4 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -3,6 +3,7 @@ * SPDX-License-Identifier: MIT */ +using System.Text; using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli; @@ -37,8 +38,8 @@ internal sealed class CommandLine(CommandLineHost host) Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. - The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or typed at a prompt; - it is never accepted on the command line. + The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input: + typed at a prompt, where it is not shown, or piped in. It is never accepted on the command line. Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. """; @@ -196,17 +197,50 @@ internal sealed class CommandLine(CommandLineHost host) /// - /// Reads the one-time enrollment code from the environment, or prompts for it, so the code never appears in the command - /// line or shell history. It is passed to the service and nowhere else: this class never prints it. + /// Reads the one-time enrollment code from the environment, or else from standard input, so the code never appears in + /// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. + /// Surrounding white space is dropped, because a code never has any and a shell can add it (cmd's "echo CODE | ..." + /// sends a trailing space). /// private string ReadEnrollmentCode() { string? code = host.ReadEnvironmentVariable(EnrollmentCodeVariable); if(string.IsNullOrWhiteSpace(code)) { - host.Output.Write("Enrollment code: "); - code = host.ReadLine(); + /////////////////////////////////////////////////////////////////////////// + // the prompt goes to standard error, so a script that pipes the code in // + // and captures standard output gets the service's reply and nothing // + // else. neither way of reading echoes the line end, so the prompt line // + // is ended here, before the reply or an error message is written // + /////////////////////////////////////////////////////////////////////////// + host.Error.Write("Enrollment code: "); + code = host.IsInputRedirected() ? host.ReadLine() : ReadWithoutEcho(); + host.Error.WriteLine(); } - return !string.IsNullOrWhiteSpace(code) ? code : throw new InvalidOperationException("Enrollment code is required."); + return !string.IsNullOrWhiteSpace(code) ? code.Trim() : throw new InvalidOperationException("Enrollment code is required."); + } + + + + /// + /// Reads one line from the console key by key without showing it, so a code typed at the prompt is not left on the + /// screen or in a terminal recording. Enter ends the line, Backspace removes the last character typed, and keys that + /// produce no character (arrows, function keys) are ignored. + /// + private string ReadWithoutEcho() + { + StringBuilder typed = new(); + for(ConsoleKeyInfo key = host.ReadKey(true); key.Key != ConsoleKey.Enter; key = host.ReadKey(true)) + { + if(key.Key == ConsoleKey.Backspace) + { + typed.Length = Math.Max(0, typed.Length - 1); + } + else if(!char.IsControl(key.KeyChar)) + { + typed.Append(key.KeyChar); + } + } + return typed.ToString(); } } diff --git a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs index 0b0960c..af678d7 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs @@ -11,10 +11,12 @@ namespace Qqq.PrintAgent.Cli; /// Everything outside the process that the command line touches, each as a replaceable function, so /// runs in a test without the real console, the installed service or its pipe. supplies the real ones. /// -/// Standard output: service replies, usage that was asked for, and the enrollment prompt. -/// Standard error: failures and usage shown because the arguments were wrong. +/// Standard output: service replies, and usage that was asked for. +/// Standard error: failures, usage shown because the arguments were wrong, and the enrollment prompt. /// Reads one environment variable; the enrollment code arrives this way so it stays out of the command line and shell history. -/// Reads one line of standard input, for the enrollment code when the variable is not set; null at end of input. +/// Says whether standard input is a file or a pipe instead of a console, which decides how the enrollment code is read. +/// Reads one line of redirected standard input, for an enrollment code that is piped in; null at end of input. +/// Reads one key from the console, for an enrollment code that is typed; the argument says whether to keep the key off the screen. /// Sends one request to the installed service over its administrator pipe and returns the reply text. /// Applies the prepared MSI update named by a request file and returns the exit code. /// Forwards a browser sign-in callback address to the running companion. @@ -22,7 +24,9 @@ internal sealed record CommandLineHost( TextWriter Output, TextWriter Error, Func ReadEnvironmentVariable, + Func IsInputRedirected, Func ReadLine, + Func ReadKey, Func> SendAsync, Func> ApplyUpdateAsync, Func ForwardSignInCallbackAsync); diff --git a/src/Qqq.PrintAgent.Cli/Program.cs b/src/Qqq.PrintAgent.Cli/Program.cs index f448bd0..1f20e25 100644 --- a/src/Qqq.PrintAgent.Cli/Program.cs +++ b/src/Qqq.PrintAgent.Cli/Program.cs @@ -18,6 +18,11 @@ public static class Program /// is no code here that a test cannot reach: asking for help exercises this whole composition without touching the service. /// public static Task Main(string[] args) - => new CommandLine(new CommandLineHost(Console.Out, Console.Error, Environment.GetEnvironmentVariable, Console.ReadLine, + => new CommandLine(new CommandLineHost(Console.Out, Console.Error, Environment.GetEnvironmentVariable, IsInputRedirected, Console.ReadLine, Console.ReadKey, AgentPipeClient.SendAsync, MsiUpdateInstaller.ApplyAsync, QqqBrowserCallback.ForwardFromHandlerAsync)).RunAsync(args); + + + + /// Says whether standard input is a file or a pipe instead of a console. It exists only because a property cannot be passed as a method reference. + internal static bool IsInputRedirected() => Console.IsInputRedirected; } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs index f37475a..9ec1f9a 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs @@ -8,18 +8,19 @@ using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; /// -/// The one-time enrollment code is a secret. It comes from an environment variable or a prompt, never from the command line; -/// it goes to the service in the enrollment request and nowhere else; and nothing the tool prints ever contains it, whether -/// the enrollment works, is refused or cannot be sent. +/// The one-time enrollment code is a secret. It comes from an environment variable or from standard input (piped in, or +/// typed at a prompt without being shown), never from the command line; it goes to the service in the enrollment request +/// and nowhere else; and nothing the tool prints ever contains it, whether the enrollment works, is refused or cannot be sent. /// public sealed class CliEnrollmentCodeTests { private const string Code = "synthetic-code-4471"; private const string Server = "https://qqq.example.test"; + private const string Prompt = "Enrollment code: \n"; - /// With the variable set, the code is taken from QQQ_PRINT_ENROLLMENT_CODE and no prompt is shown and nothing is read from standard input, so an unattended script never blocks. + /// With the variable set, the code is taken from QQQ_PRINT_ENROLLMENT_CODE: no prompt is written, no line and no key is read, so an unattended script never blocks. [Fact] public async Task CodeInTheEnvironment_IsUsedWithoutPrompting() { @@ -31,18 +32,20 @@ public sealed class CliEnrollmentCodeTests Assert.Equal(0, exitCode); Assert.Equal("QQQ_PRINT_ENROLLMENT_CODE", Assert.Single(cli.VariablesRead)); Assert.Equal(0, cli.LinesRead); + Assert.Equal(0, cli.KeysRead); Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode); Assert.Equal("Enrolled.\n", cli.Output); + Assert.Equal("", cli.Error); } - /// With the variable missing or blank, the tool prompts on standard output and uses the line the operator types, exactly as typed. + /// With the variable missing or blank and standard input redirected, the code is the line that is piped in. The prompt goes to standard error and its line is ended there, so standard output holds the service's reply and nothing else, and no key is read from a console that is not there. [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] - public async Task NoCodeInTheEnvironment_PromptsAndUsesTheTypedLine(string? variable) + public async Task CodePipedIn_IsReadAsALineWithThePromptOnStandardError(string? variable) { using CliFixture cli = new() { Reply = "Enrolled." }; cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = variable; @@ -52,47 +55,127 @@ public sealed class CliEnrollmentCodeTests Assert.Equal(0, exitCode); Assert.Equal(1, cli.LinesRead); + Assert.Equal(0, cli.KeysRead); Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent)); - Assert.Equal("Enrollment code: Enrolled.\n", cli.Output); - Assert.Equal("", cli.Error); + Assert.Equal("Enrolled.\n", cli.Output); + Assert.Equal(Prompt, cli.Error); } - /// When no code is available (standard input is closed, or the operator enters a blank line), enrollment fails with one line on standard error and exit code 1, and no request reaches the service. + /// At a console the code is read key by key up to Enter, and every key is read without being shown. Standard input is not read as a line, and the prompt line is ended on standard error because the Enter was not shown either. + [Fact] + public async Task CodeTypedAtTheConsole_IsReadWithoutBeingShown() + { + using CliFixture cli = new() { Reply = "Enrolled.", InputRedirected = false }; + cli.Type(Code); + cli.Press(ConsoleKey.Enter, '\r'); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(Code.Length + 1, cli.KeysRead); + Assert.Equal(0, cli.KeysShown); + Assert.Equal(0, cli.LinesRead); + Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent)); + Assert.Equal("Enrolled.\n", cli.Output); + Assert.Equal(Prompt, cli.Error); + } + + + + /// While typing, Backspace removes the last character and does nothing on an empty line, and keys that produce no printable character (arrows, function keys, Tab, Ctrl combinations) are ignored, so the code sent is what the operator meant to type. + [Fact] + public async Task TypingAtTheConsole_HonorsBackspaceAndIgnoresKeysWithoutACharacter() + { + using CliFixture cli = new() { InputRedirected = false }; + cli.Press(ConsoleKey.Backspace, '\b'); + cli.Type("synthetic-cods"); + cli.Press(ConsoleKey.Backspace, '\b'); + cli.Press(ConsoleKey.Backspace, '\b'); + cli.Press(ConsoleKey.LeftArrow); + cli.Press(ConsoleKey.F5); + cli.Press(ConsoleKey.Tab, '\t'); + cli.Press(ConsoleKey.A, '\u0001'); + cli.Type("de-4471"); + cli.Press(ConsoleKey.Enter, '\r'); + cli.Type("typed-after-enter"); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode); + Assert.Equal(0, cli.KeysShown); + Assert.Equal("typed-after-enter".Length, cli.Keys.Count); + } + + + + /// White space around the code is dropped, whichever way it arrives, and white space inside it is kept. A code never begins or ends with white space, but a shell can add some: cmd's "echo CODE | ..." pipes a trailing space. [Theory] - [InlineData(false, null)] - [InlineData(true, "")] - [InlineData(true, " ")] - public async Task NoCodeAtAll_FailsWithoutContactingTheService(bool typed, string? line) + [InlineData("variable", " synthetic-code-4471 ", "synthetic-code-4471")] + [InlineData("piped", "synthetic-code-4471 ", "synthetic-code-4471")] + [InlineData("piped", "\tsynthetic code 4471\t", "synthetic code 4471")] + [InlineData("typed", " synthetic-code-4471 ", "synthetic-code-4471")] + public async Task WhiteSpaceAroundTheCode_IsDropped(string source, string given, string sent) { using CliFixture cli = new(); - if(typed) + Supply(cli, source, given); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(new PipeRequest("enroll", Server, sent), Assert.Single(cli.Sent)); + } + + + + /// When no code is available (redirected input is at its end or holds a blank line, or the operator presses only Enter or spaces), enrollment fails: the prompt line is ended, then one line on standard error says why, the exit code is 1, standard output is empty and no request reaches the service. + [Theory] + [InlineData("piped", null)] + [InlineData("piped", "")] + [InlineData("piped", " ")] + [InlineData("typed", "")] + [InlineData("typed", " ")] + public async Task NoCodeAtAll_FailsWithoutContactingTheService(string source, string? given) + { + using CliFixture cli = new(); + if(given is not null) { - cli.TypedLines.Enqueue(line); + Supply(cli, source, given); } int exitCode = await cli.RunAsync("enroll", "--server", Server); Assert.Equal(1, exitCode); Assert.Empty(cli.Sent); - Assert.Equal("Enrollment code: ", cli.Output); - Assert.Equal("Enrollment code is required.\n", cli.Error); + Assert.Equal("", cli.Output); + Assert.Equal(Prompt + "Enrollment code is required.\n", cli.Error); } - /// The code is never printed, whichever way it arrived and however the enrollment ends: accepted, refused by the service, timed out, or failed to send. + /// + /// The code is never printed, whichever way it arrived and however the enrollment ends: accepted, refused by the service, + /// timed out, or failed to send. The fake service's replies do not contain the code, and the real service's cannot: its + /// reply to an enrollment is the new device's identifier, or "Error:" followed by its own description of the failure, + /// and it copies neither the request nor the server's response body into either. So the reply is printed as it comes, + /// with no filtering to test. + /// [Theory] - [InlineData(true, "accepted")] - [InlineData(false, "accepted")] - [InlineData(true, "refused")] - [InlineData(false, "refused")] - [InlineData(true, "timeout")] - [InlineData(false, "timeout")] - [InlineData(true, "failure")] - [InlineData(false, "failure")] - public async Task Code_NeverAppearsInOutput(bool fromEnvironment, string outcome) + [InlineData("variable", "accepted")] + [InlineData("piped", "accepted")] + [InlineData("typed", "accepted")] + [InlineData("variable", "refused")] + [InlineData("piped", "refused")] + [InlineData("typed", "refused")] + [InlineData("variable", "timeout")] + [InlineData("piped", "timeout")] + [InlineData("typed", "timeout")] + [InlineData("variable", "failure")] + [InlineData("piped", "failure")] + [InlineData("typed", "failure")] + public async Task Code_NeverAppearsInOutput(string source, string outcome) { using CliFixture cli = new() { @@ -104,14 +187,7 @@ public sealed class CliEnrollmentCodeTests _ => null, }, }; - if(fromEnvironment) - { - cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = Code; - } - else - { - cli.TypedLines.Enqueue(Code); - } + Supply(cli, source, Code); int exitCode = await cli.RunAsync("enroll", "--server", Server); @@ -122,7 +198,7 @@ public sealed class CliEnrollmentCodeTests - /// A code put on the command line is refused, not used: nothing is sent, and the refusal does not repeat the code, so a mistake does not also copy the secret into captured error output. + /// A code put on the command line is refused, not used: nothing is sent, nothing is read, and the refusal does not repeat the code, so a mistake does not also copy the secret into captured error output. [Theory] [InlineData("enroll", "--server", Server, Code)] [InlineData("enroll", "--server", Server, "--code", Code)] @@ -140,5 +216,27 @@ public sealed class CliEnrollmentCodeTests Assert.Equal("", cli.Output); Assert.DoesNotContain(Code, cli.Error, StringComparison.Ordinal); Assert.Equal(0, cli.LinesRead); + Assert.Equal(0, cli.KeysRead); + } + + + + /// Makes the given text arrive the named way: in the variable, as the line redirected standard input holds, or as keys typed at a console and ended with Enter. + private static void Supply(CliFixture cli, string source, string text) + { + switch(source) + { + case "variable": + cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = text; + break; + case "piped": + cli.TypedLines.Enqueue(text); + break; + default: + cli.InputRedirected = false; + cli.Type(text); + cli.Press(ConsoleKey.Enter, '\r'); + break; + } } } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs index a67203d..c015af4 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliFixture.cs @@ -40,7 +40,12 @@ internal sealed class CliFixture : IDisposable - /// The lines an operator would type, in order; when they run out, standard input is at its end. + /// Whether standard input is a file or a pipe (the default here, as in a script) or a console an operator types at. + internal bool InputRedirected { get; set; } = true; + + + + /// The lines redirected standard input holds, in order; when they run out, standard input is at its end. internal Queue TypedLines { get; } = new(); @@ -50,6 +55,21 @@ internal sealed class CliFixture : IDisposable + /// The keys an operator presses at the console, in order. + internal Queue Keys { get; } = new(); + + + + /// How many keys were read from the console. + internal int KeysRead { get; private set; } + + + + /// How many of those keys were read in a way that would have shown them on the screen. + internal int KeysShown { get; private set; } + + + /// The reply the fake service gives to every request. internal string Reply { get; set; } = "Synthetic service reply."; @@ -92,7 +112,24 @@ internal sealed class CliFixture : IDisposable /// Runs one invocation of the command line against the fakes and returns its exit code. internal Task RunAsync(params string[] args) - => new CommandLine(new CommandLineHost(_output, _error, ReadVariable, ReadLine, SendAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args); + => new CommandLine(new CommandLineHost(_output, _error, ReadVariable, () => InputRedirected, ReadLine, ReadKey, SendAsync, ApplyUpdateAsync, ForwardCallbackAsync)).RunAsync(args); + + + + /// Queues the keys for typing the given text at the console, without the Enter that ends the line. + internal void Type(string text) + { + foreach(char character in text) + { + Keys.Enqueue(new ConsoleKeyInfo(character, ConsoleKey.None, shift: false, alt: false, control: false)); + } + } + + + + /// Queues one key that produces the given character, such as Enter ('\r') or Backspace ('\b'), or none ('\0') for an arrow or function key. + internal void Press(ConsoleKey key, char character = '\0') + => Keys.Enqueue(new ConsoleKeyInfo(character, key, shift: false, alt: false, control: false)); @@ -114,6 +151,16 @@ internal sealed class CliFixture : IDisposable + /// Hands out the next pressed key and notes whether it was asked for without echo. Running out of keys is a failure, so a read loop that never sees Enter fails the test instead of hanging it. + private ConsoleKeyInfo ReadKey(bool intercept) + { + KeysRead++; + KeysShown += intercept ? 0 : 1; + return Keys.Count > 0 ? Keys.Dequeue() : throw new InvalidOperationException("The fixture has no more keys to press."); + } + + + /// Records the request, then replies or fails as scripted. private Task SendAsync(PipeRequest request) { diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs index 4d277e5..3ffc0c7 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs @@ -74,6 +74,28 @@ public sealed class CliProcessTests + /// The real executable, with no enrollment code in its environment and standard input closed, reads redirected input as a line, finds none, and stops there: the prompt and the reason are on standard error, standard output is empty and the exit code is 1. It fails before any request would be sent, so the service is not contacted. + [Fact] + public async Task Enroll_WithNoCodeAndClosedInput_FailsBeforeContactingTheService() + { + (int exitCode, string output, string error) = await RunAsync(input: null, "enroll", "--server", "https://qqq.example.test"); + + Assert.Equal(1, exitCode); + Assert.Equal("", output); + Assert.Equal("Enrollment code: \nEnrollment code is required.\n", error); + } + + + + /// The real binding for "is standard input redirected" reports the console's own answer for input, not for output or error. + [Fact] + public void InputRedirectionBinding_ReportsTheConsoleState() + { + Assert.Equal(Console.IsInputRedirected, Program.IsInputRedirected()); + } + + + /// /// Starts the executable with the given arguments and waits for it to end, returning its exit code and what it wrote, with /// line endings normalized. Standard input carries the given line, if any, and is then closed. The enrollment code diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs index b05a072..43d0338 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs @@ -28,8 +28,8 @@ public sealed class CliUsageTests Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. - The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or typed at a prompt; - it is never accepted on the command line. + The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input: + typed at a prompt, where it is not shown, or piped in. It is never accepted on the command line. Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. """; -- 2.54.0 From 26942e3ce2fb97ed4bb0e38de859819664c99737 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:50:11 -0600 Subject: [PATCH 08/13] fix(cli): write the usage with the platform's line ends The usage is a multi-line literal, so its line ends were those of the source checkout: the built executable wrote bare line feeds inside the text and one carriage-return pair at the end. The text is now normalized once, where it is defined. The process tests compare the real executable's output byte for byte, line ends included, and a new one requires every line end written to either stream to be the platform's. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/CommandLine.cs | 10 ++++-- .../CliProcessTests.cs | 33 ++++++++++++++----- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index 5667ac4..fb9889a 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -22,8 +22,12 @@ internal sealed class CommandLine(CommandLineHost host) - /// The help text: printed on standard output when asked for, and on standard error after a refused command line. - internal const string Usage = """ + /// + /// The help text: printed on standard output when asked for, and on standard error after a refused command line. Its + /// line ends are made the platform's here, because the literal carries whatever this source file was checked out + /// with and a console or a captured file should not get a mixture. + /// + internal static readonly string Usage = """ Usage: qqq-print-agent Commands: @@ -41,7 +45,7 @@ internal sealed class CommandLine(CommandLineHost host) The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input: typed at a prompt, where it is not shown, or piped in. It is never accepted on the command line. Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. - """; + """.ReplaceLineEndings(); diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs index 3ffc0c7..ef3f756 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs @@ -29,12 +29,29 @@ public sealed class CliProcessTests (int exitCode, string output, string error) = await RunAsync(input: null, argument); Assert.Equal(0, exitCode); - Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); + Assert.Equal(CommandLine.Usage + Environment.NewLine, output); Assert.Equal("", error); } + /// Every line of the usage the real executable writes, to either stream, ends the way this platform ends lines. The help text is a multi-line literal whose line ends follow the source checkout, so without care a Windows console would get bare line feeds with one carriage return at the very end. + [Theory] + [InlineData("--help")] + [InlineData("status")] + public async Task Usage_IsWrittenWithThePlatformLineEnds(string argument) + { + (_, string output, string error) = await RunAsync(input: null, argument); + + string written = output + error; + Assert.True(written.Split(Environment.NewLine).Length > 15, "The usage should span many lines."); + string withoutLineEnds = written.Replace(Environment.NewLine, "", StringComparison.Ordinal); + Assert.DoesNotContain('\n', withoutLineEnds); + Assert.DoesNotContain('\r', withoutLineEnds); + } + + + /// With no arguments at all the real executable also prints the usage and exits 0. [Fact] public async Task NoArguments_ExitsZeroWithUsageOnStandardOutput() @@ -42,7 +59,7 @@ public sealed class CliProcessTests (int exitCode, string output, string error) = await RunAsync(input: null); Assert.Equal(0, exitCode); - Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", output); + Assert.Equal(CommandLine.Usage + Environment.NewLine, output); Assert.Equal("", error); } @@ -56,7 +73,7 @@ public sealed class CliProcessTests Assert.Equal(1, exitCode); Assert.Equal("", output); - Assert.Equal("Unknown command.\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", error); + Assert.Equal("Unknown command." + Environment.NewLine + CommandLine.Usage + Environment.NewLine, error); } @@ -69,7 +86,7 @@ public sealed class CliProcessTests Assert.Equal(1, exitCode); Assert.Equal("", output); - Assert.Equal("Unknown command.\n" + CommandLine.Usage.ReplaceLineEndings("\n") + "\n", error); + Assert.Equal("Unknown command." + Environment.NewLine + CommandLine.Usage + Environment.NewLine, error); } @@ -82,7 +99,7 @@ public sealed class CliProcessTests Assert.Equal(1, exitCode); Assert.Equal("", output); - Assert.Equal("Enrollment code: \nEnrollment code is required.\n", error); + Assert.Equal("Enrollment code: " + Environment.NewLine + "Enrollment code is required." + Environment.NewLine, error); } @@ -97,8 +114,8 @@ public sealed class CliProcessTests /// - /// Starts the executable with the given arguments and waits for it to end, returning its exit code and what it wrote, with - /// line endings normalized. Standard input carries the given line, if any, and is then closed. The enrollment code + /// Starts the executable with the given arguments and waits for it to end, returning its exit code and exactly what it + /// wrote, line ends included. Standard input carries the given line, if any, and is then closed. The enrollment code /// variable is removed from the child's environment, so the result does not depend on the machine running the test. A /// process that has not finished within a minute is killed, so a hang fails the test instead of blocking the run. /// @@ -129,7 +146,7 @@ public sealed class CliProcessTests } process.StandardInput.Close(); await process.WaitForExitAsync(limit.Token); - return (process.ExitCode, (await output).ReplaceLineEndings("\n"), (await error).ReplaceLineEndings("\n")); + return (process.ExitCode, await output, await error); } finally { -- 2.54.0 From 9c52b2e74528c75ed10da39faa75886598e53c58 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:53:32 -0600 Subject: [PATCH 09/13] fix(cli)!: say why a command line is refused; never take an option name as a value Refusals had one generic reason per command. Each now gets a fixed sentence built only from the tool's own command and option names, never from what was typed: - "'printers' takes no arguments." - "'expose' accepts only --printer and --exposed." - "--server is required." - "--server needs a value." - "--printer may be given only once." - "--exposed must be true or false." - "The options --service, --legacy-compat, --data-dir and --once were removed in 2.0: the command line only manages the installed service." when any of the four appears anywhere, so a 1.x script learns why it fails. - "Unknown command." as before. A value that begins with "--" is refused as a missing value. Until now "enroll --server --server" sent the server "--server", and "expose --printer --exposed --exposed true" sent the printer "--exposed". A help flag in last place after a real command (printers --help, enroll --server URL -h) prints the usage on standard output and exits 0 instead of being refused. After an unknown word, or in the middle of a command line, it is still an ordinary argument. --exposed accepts exactly the word true or false in any letter case. Padded values (" true") were accepted by bool.TryParse and are now refused. The usage text says the help flags also work after a command. Tests: CliArgumentRefusalTests asserts the exact reason for every malformed combination, the removed-option sentence for every placement of the four options, the trailing help flag, and that a refusal reads no variable, no line and no key. Usage_DoesNotMentionTheRemovedLegacyMode is removed: the pinned usage text already holds that. BREAKING CHANGE: refusal messages changed; " --help" exits 0; padded true/false is refused; an option name is not accepted as a value. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/CommandLine.cs | 103 ++++++---- .../CliArgumentRefusalTests.cs | 191 +++++++++++++----- .../CliServiceCommandTests.cs | 4 +- .../Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs | 20 +- 4 files changed, 209 insertions(+), 109 deletions(-) diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index fb9889a..b6244e8 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -38,7 +38,7 @@ internal sealed class CommandLine(CommandLineHost host) sign-out End the service's QQQ session. service-status Show the service's connection status. snapshot Show the service's state as JSON: connection, printers, recent jobs and logs. - help Show this text (also --help, -h). + help Show this text (also --help or -h, alone or after a command). Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. @@ -63,6 +63,16 @@ internal sealed class CommandLine(CommandLineHost host) + /// What a command line is told when it uses an option of the legacy mode that 2.0 removed, so a script written for 1.x learns why it fails. + internal const string RemovedOptionsReason = "The options --service, --legacy-compat, --data-dir and --once were removed in 2.0: the command line only manages the installed service."; + + + + /// The options of the removed legacy mode. They are recognized only to explain the refusal. + private static readonly HashSet s_removedOptions = new(StringComparer.Ordinal) { "--service", "--legacy-compat", "--data-dir", "--once" }; + + + /// The names of the operator commands, exposed so a test can hold the help text to the commands that really exist. internal static IReadOnlyCollection CommandNames => s_commands.Keys; @@ -111,45 +121,30 @@ internal sealed class CommandLine(CommandLineHost host) /// /// Carries out an operator command: help is printed here, and any other command is checked against the table, turned into - /// one pipe request and sent to the service. The reply is printed as the service wrote it. A reply that starts with - /// "Error:" is the service refusing or failing the request, so it exits 1 for every command. + /// one pipe request and sent to the service. The reply is printed on standard output as the service wrote it, also when + /// it is a refusal. A reply that starts with "Error:" is the service refusing or failing the request, so it exits 1 + /// for every command. /// private async Task ManageServiceAsync(string[] args) { - /////////////////////////////////////////////////////////////////////////// - // help is decided by the first word alone: "help enroll" is a person // - // asking how to enroll, and answering costs nothing and sends nothing // - /////////////////////////////////////////////////////////////////////////// - if(args is [] or ["help" or "--help" or "-h", ..]) + if(AsksForHelp(args)) { host.Output.WriteLine(Usage); return 0; } - if(!s_commands.TryGetValue(args[0], out (string Operation, string[] Options) command)) + Dictionary options = new(StringComparer.Ordinal); + string? problem = FindProblem(args, options); + if(problem is not null) { - return RefuseArguments("Unknown command."); - } - Dictionary? options = ReadOptions(args, command.Options); - if(options is null) - { - return RefuseArguments($"Invalid arguments for '{args[0]}'."); - } - bool? exposed = null; - if(options.TryGetValue("--exposed", out string? text)) - { - if(!bool.TryParse(text, out bool parsed)) - { - return RefuseArguments("--exposed must be true or false."); - } - exposed = parsed; + return RefuseArguments(problem); } //////////////////////////////////////////////////////////////////////////// // the enrollment code is asked for last, once the command line is known // // to be valid, so a mistyped command never prompts for a single-use code // //////////////////////////////////////////////////////////////////////////// - PipeRequest request = new(command.Operation, options.GetValueOrDefault("--server"), args[0] is "enroll" ? ReadEnrollmentCode() : null, - options.GetValueOrDefault("--printer"), exposed); + PipeRequest request = new(s_commands[args[0]].Operation, options.GetValueOrDefault("--server"), args[0] is "enroll" ? ReadEnrollmentCode() : null, + options.GetValueOrDefault("--printer"), options.TryGetValue("--exposed", out string? choice) ? IsWord(choice, "true") : null); string response = await host.SendAsync(request); host.Output.WriteLine(response); bool failed = response.StartsWith("Error:", StringComparison.Ordinal); @@ -162,6 +157,16 @@ internal sealed class CommandLine(CommandLineHost host) + /// + /// Says whether the command line is a request for help: no arguments, a help word in first place whatever follows + /// ("help enroll" is a person asking how to enroll), or a help flag in last place after a real command + /// ("printers --help"). Answering costs nothing and sends nothing. + /// + private static bool AsksForHelp(string[] args) + => args is [] or ["help" or "--help" or "-h", ..] || (s_commands.ContainsKey(args[0]) && args[^1] is "--help" or "-h"); + + + /// /// Refuses a command line: the reason and the help text go to standard error and the exit code is 1. The reason never /// repeats what was typed. A refused command line can hold a secret in the wrong place (an enrollment code given as an @@ -177,29 +182,55 @@ internal sealed class CommandLine(CommandLineHost host) /// - /// Reads the "--name value" pairs that follow a command, in any order. Every option of a command is required exactly - /// once, so the argument count must match, each name must be one of the command's own, no name may repeat and no value - /// may be blank. Anything else returns null, and the caller refuses the whole command line rather than guess. + /// Checks the command line and reads the "--name value" pairs that follow the command, in any order, into the given + /// dictionary. It returns null when the command line is acceptable, and otherwise the reason it is not, which the + /// caller refuses with rather than guess what was meant. Every option of a command is required exactly once, with a + /// value that is not blank and is not itself an option name, so a forgotten value cannot swallow the next option. + /// Each reason is assembled only from this class's own command and option names, never from an argument that did not + /// match one of them, so it cannot repeat a secret that was typed in the wrong place. /// - private static Dictionary? ReadOptions(string[] args, string[] names) + private static string? FindProblem(string[] args, Dictionary options) { - if(args.Length != 1 + (2 * names.Length)) + if(args.Any(s_removedOptions.Contains)) { - return null; + return RemovedOptionsReason; + } + if(!s_commands.TryGetValue(args[0], out (string Operation, string[] Options) command)) + { + return "Unknown command."; } - Dictionary values = new(StringComparer.Ordinal); for(int index = 1; index < args.Length; index += 2) { - if(!names.Contains(args[index], StringComparer.Ordinal) || string.IsNullOrWhiteSpace(args[index + 1]) || !values.TryAdd(args[index], args[index + 1])) + string name = args[index]; + if(!command.Options.Contains(name, StringComparer.Ordinal)) { - return null; + return command.Options.Length == 0 ? $"'{args[0]}' takes no arguments." : $"'{args[0]}' accepts only {string.Join(" and ", command.Options)}."; } + if(options.ContainsKey(name)) + { + return $"{name} may be given only once."; + } + if(index + 1 == args.Length || string.IsNullOrWhiteSpace(args[index + 1]) || args[index + 1].StartsWith("--", StringComparison.Ordinal)) + { + return $"{name} needs a value."; + } + options[name] = args[index + 1]; } - return values; + string? missing = command.Options.FirstOrDefault(option => !options.ContainsKey(option)); + if(missing is not null) + { + return $"{missing} is required."; + } + return options.TryGetValue("--exposed", out string? choice) && !IsWord(choice, "true") && !IsWord(choice, "false") ? "--exposed must be true or false." : null; } + /// Compares an option value with a fixed word, ignoring letter case and nothing else: "TRUE" is true, " true" is not. + private static bool IsWord(string text, string word) => string.Equals(text, word, StringComparison.OrdinalIgnoreCase); + + + /// /// Reads the one-time enrollment code from the environment, or else from standard input, so the code never appears in /// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs index 3ed6d85..6272f32 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliArgumentRefusalTests.cs @@ -7,81 +7,99 @@ namespace Qqq.PrintAgent.Cli.Tests; /// /// Malformed command lines. A command accepts exactly its own options, each once and each with a value, and nothing else. -/// Anything different is refused before the service is contacted and before the enrollment code is asked for: the reason and -/// the usage go to standard error, standard output stays empty and the exit code is 1. The tool never guesses what was meant. +/// Anything different is refused before the service is contacted and before the enrollment code is asked for: one line +/// that says what is wrong, then the usage, on standard error; nothing on standard output; exit code 1. The reason names +/// only the tool's own commands and options, never what was typed, and the tool never guesses what was meant. /// public sealed class CliArgumentRefusalTests { - /// A command that takes no options refuses any extra word, including help flags after the command and every option of the removed legacy mode (--legacy-compat, --data-dir, --once, --service). + private const string Server = "https://qqq.example.test"; + private const string Printer = "synthetic-queue-1"; + + + + /// A command that takes no options says so when anything follows it. [Theory] [InlineData("printers", "extra")] - [InlineData("printers", "--help")] - [InlineData("printers", "--legacy-compat")] - [InlineData("printers", "--legacy-compat", "--data-dir", "C:\\synthetic")] - [InlineData("run", "--once")] - [InlineData("run", "--once", "--legacy-compat")] - [InlineData("run", "--data-dir", "C:\\synthetic")] - [InlineData("run", "--service")] - [InlineData("sign-out", "--service")] + [InlineData("printers", "--server", Server)] + [InlineData("run", "now")] [InlineData("sign-out", "now")] - [InlineData("service-status", "--service")] - [InlineData("service-status", "-h")] - [InlineData("snapshot", "--data-dir", "C:\\synthetic")] + [InlineData("service-status", "--verbose")] [InlineData("snapshot", "")] - public async Task CommandWithoutOptions_RefusesAnythingExtra(params string[] args) + [InlineData("snapshot", "--help", "extra")] + public async Task CommandWithoutOptions_RefusesAnythingAfterIt(params string[] args) { - await AssertRefusedAsync($"Invalid arguments for '{args[0]}'.", args); + await AssertRefusedAsync($"'{args[0]}' takes no arguments.", args); } - /// Enrolling requires exactly --server with a value: a missing, blank, repeated, misspelled or positional server, any other option, and any trailing word are all refused. + /// An argument in an option's place that is not one of the command's options is refused with the options the command does accept: a positional value, a misspelled or differently cased option, another command's option, or a trailing word. [Theory] - [InlineData("enroll")] - [InlineData("enroll", "--server")] - [InlineData("enroll", "--server", "")] - [InlineData("enroll", "--server", " ")] - [InlineData("enroll", "https://qqq.example.test")] - [InlineData("enroll", "https://qqq.example.test", "--server")] - [InlineData("enroll", "--Server", "https://qqq.example.test")] - [InlineData("enroll", "--printer", "synthetic-queue-1")] - [InlineData("enroll", "--server", "https://qqq.example.test", "--server", "https://other.example.test")] - [InlineData("enroll", "--server", "https://qqq.example.test", "extra")] - [InlineData("enroll", "--server", "https://qqq.example.test", "--service")] - [InlineData("enroll", "--server", "https://qqq.example.test", "--legacy-compat")] - [InlineData("enroll", "--server", "https://qqq.example.test", "--data-dir", "C:\\synthetic")] - [InlineData("enroll", "--legacy-compat", "--server", "https://qqq.example.test")] - public async Task Enroll_RefusesAnythingButOneServer(params string[] args) + [InlineData("'enroll' accepts only --server.", "enroll", Server)] + [InlineData("'enroll' accepts only --server.", "enroll", Server, "--server")] + [InlineData("'enroll' accepts only --server.", "enroll", "--Server", Server)] + [InlineData("'enroll' accepts only --server.", "enroll", "--printer", Printer)] + [InlineData("'enroll' accepts only --server.", "enroll", "--server", Server, "extra")] + [InlineData("'enroll' accepts only --server.", "enroll", "--code", "synthetic-code-4471", "--server", Server)] + [InlineData("'expose' accepts only --printer and --exposed.", "expose", Printer, "true")] + [InlineData("'expose' accepts only --printer and --exposed.", "expose", "--printer", Printer, "--server", Server)] + [InlineData("'expose' accepts only --printer and --exposed.", "expose", "--printer", Printer, "--exposed", "true", "extra")] + [InlineData("'expose' accepts only --printer and --exposed.", "expose", "--Exposed", "true", "--printer", Printer)] + public async Task UnexpectedArgument_IsRefusedWithTheOptionsTheCommandAccepts(string reason, params string[] args) { - await AssertRefusedAsync("Invalid arguments for 'enroll'.", args); + await AssertRefusedAsync(reason, args); } - /// Sharing a printer requires exactly --printer and --exposed, each once with a value: either one missing, blank or repeated, any other option, and any trailing word are all refused. + /// A required option that is absent is named. [Theory] - [InlineData("expose")] - [InlineData("expose", "--printer", "synthetic-queue-1")] - [InlineData("expose", "--exposed", "true")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed")] - [InlineData("expose", "--printer", "--exposed", "true")] - [InlineData("expose", "--printer", "", "--exposed", "true")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", " ")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--printer", "synthetic-queue-2")] - [InlineData("expose", "--exposed", "true", "--exposed", "false")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--server", "https://qqq.example.test")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "extra")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "--service")] - [InlineData("expose", "--printer", "synthetic-queue-1", "--exposed", "true", "--legacy-compat")] - [InlineData("expose", "synthetic-queue-1", "true")] - public async Task Expose_RefusesAnythingButOnePrinterAndOneChoice(params string[] args) + [InlineData("--server is required.", "enroll")] + [InlineData("--printer is required.", "expose")] + [InlineData("--printer is required.", "expose", "--exposed", "true")] + [InlineData("--exposed is required.", "expose", "--printer", Printer)] + public async Task MissingOption_IsNamed(string reason, params string[] args) { - await AssertRefusedAsync("Invalid arguments for 'expose'.", args); + await AssertRefusedAsync(reason, args); } - /// The choice must be the word true or false; a number, yes or no, or any other word is refused with a message that says so. + /// An option with nothing after it, with a blank value, or followed by another option name is refused as needing a value. An option name is never taken as a value, so a forgotten value cannot make the next option disappear into it. + [Theory] + [InlineData("--server needs a value.", "enroll", "--server")] + [InlineData("--server needs a value.", "enroll", "--server", "")] + [InlineData("--server needs a value.", "enroll", "--server", " ")] + [InlineData("--server needs a value.", "enroll", "--server", "--server")] + [InlineData("--server needs a value.", "enroll", "--server", "--anything")] + [InlineData("--printer needs a value.", "expose", "--printer", "--exposed", "true")] + [InlineData("--printer needs a value.", "expose", "--printer", "--exposed", "--exposed", "true")] + [InlineData("--printer needs a value.", "expose", "--printer", "", "--exposed", "true")] + [InlineData("--exposed needs a value.", "expose", "--printer", Printer, "--exposed")] + [InlineData("--exposed needs a value.", "expose", "--printer", Printer, "--exposed", " ")] + [InlineData("--exposed needs a value.", "expose", "--exposed", "--printer", Printer)] + public async Task OptionWithoutAValue_IsRefused(string reason, params string[] args) + { + await AssertRefusedAsync(reason, args); + } + + + + /// An option given twice is refused, whether or not the two values agree; the tool does not pick one. + [Theory] + [InlineData("--server may be given only once.", "enroll", "--server", Server, "--server", "https://other.example.test")] + [InlineData("--server may be given only once.", "enroll", "--server", Server, "--server", Server)] + [InlineData("--printer may be given only once.", "expose", "--printer", Printer, "--printer", "synthetic-queue-2")] + [InlineData("--exposed may be given only once.", "expose", "--exposed", "true", "--exposed", "false", "--printer", Printer)] + public async Task RepeatedOption_IsRefused(string reason, params string[] args) + { + await AssertRefusedAsync(reason, args); + } + + + + /// The choice must be the word true or false, in any letter case and with nothing around it. A number, yes or no, any other word, and true or false padded with white space are refused with a message that says so, wherever the option stands. [Theory] [InlineData("yes")] [InlineData("no")] @@ -89,15 +107,79 @@ public sealed class CliArgumentRefusalTests [InlineData("0")] [InlineData("on")] [InlineData("truee")] + [InlineData(" true")] + [InlineData("true ")] + [InlineData("\tfalse")] public async Task Expose_RefusesAChoiceThatIsNotTrueOrFalse(string choice) { - await AssertRefusedAsync("--exposed must be true or false.", "expose", "--printer", "synthetic-queue-1", "--exposed", choice); - await AssertRefusedAsync("--exposed must be true or false.", "expose", "--exposed", choice, "--printer", "synthetic-queue-1"); + await AssertRefusedAsync("--exposed must be true or false.", "expose", "--printer", Printer, "--exposed", choice); + await AssertRefusedAsync("--exposed must be true or false.", "expose", "--exposed", choice, "--printer", Printer); } - /// Runs the arguments against a command line whose enrollment code is available, and requires a complete refusal: exit code 1, the reason and the usage on standard error, nothing on standard output, nothing sent, and neither the environment nor standard input consulted. + /// Every option of the legacy mode removed in 2.0 is refused with one fixed sentence that names all four and says they are gone, wherever it appears and whatever else is on the command line, so a script written for 1.x learns why it no longer runs. + [Theory] + [InlineData("--legacy-compat")] + [InlineData("--service")] + [InlineData("--legacy-compat", "run", "--once")] + [InlineData("run", "--once")] + [InlineData("run", "--legacy-compat", "--once", "--data-dir", "C:\\synthetic")] + [InlineData("printers", "--data-dir", "C:\\synthetic")] + [InlineData("sign-out", "--service")] + [InlineData("service-status", "--service")] + [InlineData("enroll", "--service", "--server", Server)] + [InlineData("enroll", "--server", Server, "--legacy-compat")] + [InlineData("enroll", "--server", "--service")] + [InlineData("expose", "--printer", Printer, "--exposed", "true", "--service")] + [InlineData("unknown-word", "--once")] + public async Task RemovedLegacyOption_IsRefusedWithTheReasonItIsGone(params string[] args) + { + await AssertRefusedAsync("The options --service, --legacy-compat, --data-dir and --once were removed in 2.0: the command line only manages the installed service.", args); + } + + + + /// A help flag in last place after a real command is a request for help, not a mistake: the usage goes to standard output, the exit code is 0, nothing is sent and no enrollment code is asked for, even when the rest of the command line would have been refused. + [Theory] + [InlineData("printers", "--help")] + [InlineData("printers", "-h")] + [InlineData("enroll", "--help")] + [InlineData("enroll", "--server", Server, "-h")] + [InlineData("enroll", "--server", "--help")] + [InlineData("expose", "--printer", Printer, "--exposed", "maybe", "--help")] + [InlineData("run", "--once", "--help")] + public async Task HelpFlagAfterACommand_PrintsTheUsageAndSucceeds(params string[] args) + { + using CliFixture cli = new(); + cli.TypedLines.Enqueue("synthetic-code-4471"); + + int exitCode = await cli.RunAsync(args); + + Assert.Equal(0, exitCode); + Assert.Equal(CommandLine.Usage.ReplaceLineEndings("\n") + "\n", cli.Output.ReplaceLineEndings("\n")); + Assert.Equal("", cli.Error); + Assert.Empty(cli.Sent); + Assert.Empty(cli.VariablesRead); + Assert.Equal(0, cli.LinesRead); + } + + + + /// A help flag helps only in last place after a real command. After a word that is not a command it does not turn the refusal into a success, and in the middle of a command line it is an argument like any other. + [Theory] + [InlineData("Unknown command.", "unknown-word", "--help")] + [InlineData("Unknown command.", "--printer-worker", "-h")] + [InlineData("'printers' takes no arguments.", "printers", "--help", "extra")] + [InlineData("'enroll' accepts only --server.", "enroll", "-h", "--server", Server)] + public async Task HelpFlagElsewhere_DoesNotRescueABadCommandLine(string reason, params string[] args) + { + await AssertRefusedAsync(reason, args); + } + + + + /// Runs the arguments against a command line whose enrollment code is available every way it could be asked for, and requires a complete refusal: exit code 1, the reason and the usage on standard error, nothing on standard output, nothing sent, and the environment, standard input and the console all left unread. private static async Task AssertRefusedAsync(string reason, params string[] args) { using CliFixture cli = new(); @@ -112,5 +194,6 @@ public sealed class CliArgumentRefusalTests Assert.Empty(cli.Sent); Assert.Empty(cli.VariablesRead); Assert.Equal(0, cli.LinesRead); + Assert.Equal(0, cli.KeysRead); } } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs index 6c038d1..9bdf9fc 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliServiceCommandTests.cs @@ -54,10 +54,12 @@ public sealed class CliServiceCommandTests - /// Sharing or hiding a printer sends the printer and the choice, and nothing else. The two options may come in either order, and true or false is accepted in any letter case. + /// Sharing or hiding a printer sends the printer and the choice, and nothing else. The two options may come in either order, and true or false is accepted in any letter case (PowerShell writes $true as "True"). [Theory] [InlineData(true, "expose", "--printer", "synthetic-queue-1", "--exposed", "true")] [InlineData(false, "expose", "--printer", "synthetic-queue-1", "--exposed", "false")] + [InlineData(true, "expose", "--printer", "synthetic-queue-1", "--exposed", "True")] + [InlineData(false, "expose", "--printer", "synthetic-queue-1", "--exposed", "FALSE")] [InlineData(true, "expose", "--exposed", "TRUE", "--printer", "synthetic-queue-1")] [InlineData(false, "expose", "--exposed", "False", "--printer", "synthetic-queue-1")] public async Task Expose_SendsThePrinterAndTheChoice(bool exposed, params string[] args) diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs index 43d0338..15e5808 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs @@ -24,7 +24,7 @@ public sealed class CliUsageTests sign-out End the service's QQQ session. service-status Show the service's connection status. snapshot Show the service's state as JSON: connection, printers, recent jobs and logs. - help Show this text (also --help, -h). + help Show this text (also --help or -h, alone or after a command). Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. @@ -57,15 +57,12 @@ public sealed class CliUsageTests - /// A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, the option that selected the removed legacy mode is no longer a word the tool knows, and --printer-worker is not a role of this executable: the service starts its own executable as the printer worker. + /// A first word that is not a command is refused: standard error gets the reason and the usage, standard output stays empty, nothing is sent and the exit code is 1. Command names are case-sensitive, the service's own operation names are not commands, and --printer-worker is not a role of this executable: the service starts its own executable as the printer worker. [Theory] [InlineData("status")] [InlineData("Printers")] [InlineData("--printer-worker")] [InlineData("--printer-worker", "extra")] - [InlineData("--legacy-compat")] - [InlineData("--legacy-compat", "run", "--once")] - [InlineData("--service")] [InlineData("--version")] [InlineData("")] public async Task UnknownCommand_PrintsUsageOnStandardErrorAndFails(params string[] args) @@ -109,19 +106,6 @@ public sealed class CliUsageTests - /// The usage no longer describes the removed legacy mode or any option that existed only for it. - [Theory] - [InlineData("legacy")] - [InlineData("--data-dir")] - [InlineData("--once")] - [InlineData("--service")] - public void Usage_DoesNotMentionTheRemovedLegacyMode(string removed) - { - Assert.DoesNotContain(removed, CommandLine.Usage, StringComparison.OrdinalIgnoreCase); - } - - - /// The real entry point, with the real console and pipe client bound, answers help with exit code 0 and never needs the service for it. This is the only test that runs the production composition in this process. [Fact] public async Task RealEntryPoint_AnswersHelpWithoutTheService() -- 2.54.0 From e2b39650f3614882ae836b3d9c96be5c17a70ef0 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 14:55:18 -0600 Subject: [PATCH 10/13] docs: bring the command-line documentation in line with the review changes - CHANGELOG.md: the command-line entry is now a list of what an operator or script can notice: the removed mode and the sentence its options get, the printer-worker role gone, help after a command, the new usage text, refusal wording with the usage, strict arguments, the enrollment prompt on standard error without echo, trimming, and the Error: exit code. - docs/ADMINISTRATION.md: a service "Error:" reply is printed on standard output with exit code 1, and standard error carries only the command line's own failures, the prompt and refusals; how the enrollment code is read; which values --exposed takes; the refusal reasons; help after a command; --printer-worker. - docs/security/threat-model.md: the device-token sentence now says no path the shipped programs can reach sends it outside a session; the bearer constructor still ships in Core until it is deleted. The enrollment code arrives by variable or standard input, never echoed. - docs/FUNCTIONAL-AUDIT.md: a dated note under the table for the three rows that describe the removed foreground mode and cite deleted tests. The rows are left as written. - CONTRIBUTING.md and docs/adr/0003-version-2.md: an assembly that has reached its release bar is recorded at the bar, which is why the command line is at 100. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- CHANGELOG.md | 42 ++++++++++++++++++++++++----------- CONTRIBUTING.md | 2 +- docs/ADMINISTRATION.md | 10 +++++---- docs/FUNCTIONAL-AUDIT.md | 2 ++ docs/adr/0003-version-2.md | 2 +- docs/security/threat-model.md | 4 ++-- 6 files changed, 41 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df72a20..5424fc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,19 +13,35 @@ capability gets the ordinary logout, and the log says the provider session was n `sign-out` cannot open the companion's callback inbox, so it still ends only the QQQ session and says so. No change to pairing, history or the printing protocol. -Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the installed service over its pipe. The -`--legacy-compat` mode is removed with everything that existed for it: the separate per-user data directory -(`--data-dir`), the command line's worker lock, the run-once claim pass (`run --once`), the isolated enroll and -expose paths, and the `--service` flag. It was the last code that sent a device token outside a QQQ session. -`--help`, `-h`, `help` and no arguments print the usage on standard output and exit 0 (`--help` and `-h` used to -exit 1); an unknown command prints it on standard error and exits 1. Arguments are checked strictly: a command -accepts exactly its own options, each once, and anything else is refused without contacting the service and -without repeating what was typed. `service-status` and `snapshot` now exit 1 when the service replies with an -error, as the other commands already did. State left in `%LOCALAPPDATA%\QqqPrintAgent` by the removed mode is no -longer read; see [Administrator operations](docs/ADMINISTRATION.md#command-line). The executable is -no longer a printer worker: `--printer-worker` is an unknown command. Only the removed mode ever started it that -way; the service starts its own executable as the worker, in 1.x as now. Its two remaining internal roles (MSI -update helper, browser sign-in callback) are unchanged. +Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the installed service over its pipe. + +- The `--legacy-compat` mode is removed with everything that existed for it: the separate per-user data directory + (`--data-dir`), the command line's worker lock, the run-once claim pass (`run --once`), the isolated enroll and + expose paths, and the `--service` flag. It was the last path the shipped programs could reach that sent a device + token outside a QQQ session. A command line that uses one of the four options is refused with a sentence saying + they were removed in 2.0. State the mode left in `%LOCALAPPDATA%\QqqPrintAgent` is no longer read; see + [Administrator operations](docs/ADMINISTRATION.md#command-line). +- The executable is no longer a printer worker: `--printer-worker` is an unknown command. Only the removed mode + ever started it that way; the service starts its own executable as the worker, in 1.x as now. Its two remaining + internal roles (MSI update helper, browser sign-in callback) are unchanged. +- Help: `--help` and `-h` print the usage on standard output and exit 0 (they used to exit 1), as `help` and no + arguments already did, and so does `--help` or `-h` after a command (`printers --help`). The usage text is new: + one line per command, where the enrollment code comes from, and the exit codes. It is written with the + platform's line ends. +- Refusals: an unknown command, and any command line a command does not accept, exits 1 with one line saying what + is wrong followed by the usage, on standard error (an unknown command used to print the old usage on standard + output). The reasons are new and fixed: for example `--server is required.`, `--printer needs a value.`, + `--exposed may be given only once.`, `'run' takes no arguments.`. A refusal never repeats what was typed. +- Arguments are strict. A command accepts exactly its own options, each once, each with a value that is not blank + and does not begin with `--`; extra words used to be ignored. `--exposed` takes `true` or `false` in any letter + case and nothing else (padded values used to be accepted). Nothing is sent, and no enrollment code is asked + for, when a command line is refused. +- Enrollment code: the prompt `Enrollment code: ` is written to standard error, not standard output, and its line + is ended there, so a script that pipes the code in captures only the service's reply. At a console the code is + typed without being shown. White space around the code is dropped, whether it comes from + `QQQ_PRINT_ENROLLMENT_CODE` or standard input. +- `service-status` and `snapshot` exit 1 when the service replies with `Error:`, as the other commands already + did. The reply itself is still printed on standard output. ## 1.2.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bdcf8ff..f0ea0c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,7 @@ Publish ordinary branches and pull requests to the [primary Gitea repository](ht - Do not include secrets, document contents, customer labels or local journals in issues, fixtures or commits. - Disclose substantial AI assistance in the PR and include a model-naming Co-Authored-By trailer when appropriate. -Line coverage is gated per assembly ([ADR-0003](docs/adr/0003-version-2.md)). `build/Verify.ps1` merges the suites' reports and fails when an assembly is below its minimum in `build/minimum-coverage.json`. The minimums are a floor that only moves up: when a change adds tests, raise the entry in the same change to the measured percentage rounded down, less one point (a few timing-dependent lines differ between runs); never lower one to make a change pass. The release bar is 100% for Core and the CLI and 90% for the Windows layer, so a green gate today means "within a point of the recorded baseline", not "fully covered". Code a test cannot reach (native calls, process hooks) goes in a thin adapter marked `[ExcludeFromCodeCoverage(Justification = "...")]`, with the decisions around it kept in covered code. Elevated desktop tests are separate from hosted CI because they need an interactive administrator session. +Line coverage is gated per assembly ([ADR-0003](docs/adr/0003-version-2.md)). `build/Verify.ps1` merges the suites' reports and fails when an assembly is below its minimum in `build/minimum-coverage.json`. The minimums are a floor that only moves up: when a change adds tests, raise the entry in the same change to the measured percentage rounded down, less one point (a few timing-dependent lines differ between runs); never lower one to make a change pass. An assembly that has reached its release bar is recorded at the bar, with no point of slack: that is why the CLI stands at 100. The release bar is 100% for Core and the CLI and 90% for the Windows layer, so for an assembly still below its bar a green gate means "within a point of the recorded baseline", not "fully covered". Code a test cannot reach (native calls, process hooks) goes in a thin adapter marked `[ExcludeFromCodeCoverage(Justification = "...")]`, with the decisions around it kept in covered code. Elevated desktop tests are separate from hosted CI because they need an interactive administrator session. ## UI and hardware tests diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index c93120b..ee68120 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -41,13 +41,15 @@ Use the built-in AppKit activity log for shared service and companion events, wi | `sign-out` | Ends its QQQ session (the identity provider's browser session is ended only by Sign out in the companion) | | `service-status` | Reports its connection status | | `snapshot` | Reports its state as JSON: connection, printers, recent jobs and logs | -| `help`, `--help`, `-h`, or no arguments | Nothing; the usage is printed | +| `help`, `--help`, `-h`, or no arguments; `--help` or `-h` after a command | Nothing; the usage is printed | -The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable, or typed at a prompt when the variable is not set. It is never accepted as an argument and never printed. +The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, after the prompt `Enrollment code: ` on standard error: at a console it is typed without being shown (Backspace corrects, Enter ends), and when input is redirected one line is read, so a script can pipe the code in and standard output holds only the service's reply. White space around the code is dropped. The code is never accepted as an argument and never printed. -The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Replies and requested usage go to standard output; failures, and the usage shown for a refused command line, go to standard error. A command accepts exactly the options shown, each once; anything else is refused before the service is contacted, and the refusal does not repeat what was typed. +The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Standard output carries what the service replied, including an `Error:` reply (the exit code, not the stream, tells a script it failed), and usage that was asked for. Standard error carries the command line's own failures (the service unreachable, a timeout, no enrollment code), the enrollment prompt, and the reason and usage for a refused command line. -Version 2.0 removed `--legacy-compat` and the options that existed for it (`--data-dir`, `--once`, `--service`). If that mode was ever used on a machine, its separate per-user state is still in `%LOCALAPPDATA%\QqqPrintAgent` (`connection.dpapi`, `journal.db`, `worker.lock`). Nothing reads it any more; delete it once the device it enrolled has been revoked in QQQ. Leave `auth-callback.log` in that folder: the browser sign-in helper still writes it. +A command accepts exactly the options shown, each once, in any order, each with a value that is not blank and does not begin with `--`. `--exposed` takes the word `true` or `false` in any letter case. Anything else is refused before the service is contacted and before a code is asked for, with one line saying what is wrong (`--server is required.`, `--printer needs a value.`, `'run' takes no arguments.` and so on) followed by the usage. The refusal names only the tool's own commands and options and never repeats what was typed, because a mistyped command line can contain an enrollment code. + +Version 2.0 removed `--legacy-compat` and the options that existed for it (`--data-dir`, `--once`, `--service`); a command line that uses one is refused with a sentence saying so. The executable is also no longer a printer worker (`--printer-worker`): the service starts its own executable for that. If that mode was ever used on a machine, its separate per-user state is still in `%LOCALAPPDATA%\QqqPrintAgent` (`connection.dpapi`, `journal.db`, `worker.lock`). Nothing reads it any more; delete it once the device it enrolled has been revoked in QQQ. Leave `auth-callback.log` in that folder: the browser sign-in helper still writes it. ## Credentials and network diff --git a/docs/FUNCTIONAL-AUDIT.md b/docs/FUNCTIONAL-AUDIT.md index 76e18ca..c567722 100644 --- a/docs/FUNCTIONAL-AUDIT.md +++ b/docs/FUNCTIONAL-AUDIT.md @@ -43,6 +43,8 @@ The audit originally found backend liveness defects and missing day-to-day contr | Poll interval was ignored and CLI timeouts exited successfully. | Runtime honors a 1–20 second bounded interval; foreground Ctrl+C is the only successful cancellation path. Other CLI cancellations/timeouts exit 1. | Timeout regression passes; reconnect wakes the interval early. | | Arbitrary branding accents could make white AppKit text unreadable. | JSON load and direct application enforce unrounded white-text contrast of at least 4.5:1; lighter accents fall back to default teal. Main heading follows the active theme. | Tests include the #767676 pass / #777777 fail boundary. See [branding policy](BRANDING.md). Theme, scaling and assistive-technology acceptance remain separate. | +Note added 2026-11-10, for version 2.0. Three rows above record the command line as it was on the audit date and no longer describe the product: "CLI enrollment could overwrite service credentials under the wrong Windows identity", "Native driver calls could block the service indefinitely" (where it says the CLI uses a disposable child) and "Poll interval was ignored and CLI timeouts exited successfully" (where it speaks of foreground Ctrl+C). Version 2.0 removed the command line's foreground mode (`--legacy-compat`, its per-user data directory and worker lock, and `run --once` with its Ctrl+C path) and its printer-worker role. The default-directory, shared-directory rejection and lock-contention tests the first row cites were deleted with that mode. What still holds from those rows: service commands use the pipe, which is now all the command line does; the service starts the disposable printer child, and only the service; and a command-line timeout or cancellation exits 1, now held by `CliServiceCommandTests`. The rows themselves are left as written. + ## Boundaries retained - Device connections are outbound HTTPS; HTTP is only a loopback development exception. No inbound firewall rule or local HTTP management endpoint is added. diff --git a/docs/adr/0003-version-2.md b/docs/adr/0003-version-2.md index 6cf93bd..8910322 100644 --- a/docs/adr/0003-version-2.md +++ b/docs/adr/0003-version-2.md @@ -20,7 +20,7 @@ A baseline audit on 2026-11-10 measured merged line coverage of 87% for Core, 69 **The management pipe gets a versioned contract.** Requests name the server they address, replies are typed instead of matched by text prefix, and a client or service that does not understand the other's version says so. -**Coverage is gated.** `build/Verify.ps1` fails when an assembly falls below its minimum in `build/minimum-coverage.json`. Each minimum is the measured percentage rounded down to a whole number, less one point: a few lines in timing-dependent waits are reached on some runs and not others (five lines of the Windows layer moved between two runs of the same commit), and a minimum set at the measured value would fail at random. Minimums only move up, by the same rule, in the change that adds the tests. The release bar is 100% for Core, the view-model assembly and the CLI, and 90% for the Windows layer, where the remainder is native printing, installer and service-control code behind thin adapters marked `[ExcludeFromCodeCoverage]` with a written reason. The 90% figure deviates from K22-TEST-10; an exception record for it is to be proposed to the standards register and is not yet filed. K22-TEST-10 also asks for 80% coverage of changed lines; nothing measures that yet, and it is open work for this release. +**Coverage is gated.** `build/Verify.ps1` fails when an assembly falls below its minimum in `build/minimum-coverage.json`. Each minimum is the measured percentage rounded down to a whole number, less one point: a few lines in timing-dependent waits are reached on some runs and not others (five lines of the Windows layer moved between two runs of the same commit), and a minimum set at the measured value would fail at random. Minimums only move up, by the same rule, in the change that adds the tests. An assembly that has reached its release bar is recorded at the bar, not a point under it: the command line is at 100, where every line is reached by tests that do not depend on timing, and a point of slack would only hide a regression. The release bar is 100% for Core, the view-model assembly and the CLI, and 90% for the Windows layer, where the remainder is native printing, installer and service-control code behind thin adapters marked `[ExcludeFromCodeCoverage]` with a written reason. The 90% figure deviates from K22-TEST-10; an exception record for it is to be proposed to the standards register and is not yet filed. K22-TEST-10 also asks for 80% coverage of changed lines; nothing measures that yet, and it is open work for this release. **Test doubles are hand-written fakes at boundaries.** No mocking library is added. The polling path that only tests reach is removed once its tests run against the realtime path. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 73868dc..6999097 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -8,9 +8,9 @@ The signed 1.0.1 release uses the realtime and native-authentication boundaries The remote-control adapter accepts only inventory refresh and cancellation of one locally journaled spooler job. Desired pause/disconnect state is revisioned and persists by canonical server URL and device identity; older or conflicting revisions cannot resume a device. An independently processed authenticated WSS channel carries controls and receipts while documents stream over separate same-origin HTTPS requests. There is no job/control polling fallback. A paused device claims no new work. A disconnected device retains control traffic and in-flight receipts; already-submitted printing is not recalled. Reconnect is a transport refresh, never an OS or service restart. See [the realtime contract and operational limits](../REALTIME.md). -The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. The command line has no server transport: the `--legacy-compat` bearer diagnostics were removed in 2.0, so no shipped code path sends the device token outside a native session, and the command line keeps no credentials or journal of its own. +The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. The command line has no server transport: the `--legacy-compat` bearer diagnostics were removed in 2.0, so no path the shipped programs can reach sends the device token outside a native session (the bearer constructor that mode used still ships in Core until it is deleted), and the command line keeps no credentials or journal of its own. -The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or a prompt; a command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. +The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or standard input (typed at a console without echo, or piped in), never as an argument, and the CLI prints it nowhere; a command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. Sign-out also ends the identity provider's browser session. The companion sends only the fixed registered callback with `sign-out`; the service refuses any other value, asks QQQ to log out with `nativeLogout.postLogoutRedirectUri`, and returns the provider end-session request to the companion over the administrator-only pipe. That request carries the provider's ID token hint (sensitive, bounded to 32 KiB, no whitespace or control characters), so it is never logged, the record prints redacted, and only the provider host is logged. Core refuses the data unless the issuer equals the one QQQ advertises, the end-session endpoint is HTTPS on the issuer's origin and identical to the provider's own discovery, and the callback is the one requested. The browser return is accepted only on the exact callback with the state this sign-out generated. Browser sign-in also sends `max_age=0` beside `prompt=login`. -- 2.54.0 From 95df11194e41c8be21a219131d7df8276a1e3a20 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 15:12:12 -0600 Subject: [PATCH 11/13] fix(cli): prompt for the enrollment code only at a console The prompt was written to standard error whenever the variable was not set, including when the code was piped in. Windows PowerShell 5.1 turns any standard error output of a native program into an error record, and with ErrorActionPreference Stop and standard error redirected the line "Enrollment code: " ended the script as a NativeCommandError, after the single-use code had been sent. - Redirected input is read as one line with no prompt and no line end. A scripted enrollment that succeeds, by pipe or by the variable, writes nothing to standard error. With no code available, the reason is the only line there. - At a console the prompt is still written to standard error, and its line is now ended in a finally, so a failure while reading keys starts its message on a new line. - The key-by-key read also ends on a key that carries a carriage return or line feed without being the Enter key (Ctrl+M, or a line end a terminal delivers as a bare character). It used to keep waiting. The usage text says the code is prompted for only at a Windows console, that redirected input is read without a prompt, and that an unattended caller must set the variable or redirect input. Tests: a successful piped and a successful variable enrollment write nothing to standard error; the piped and no-code cases expect no prompt; the typed line ends on Ctrl+M and on bare carriage return and line feed keys; a key-read failure follows an ended prompt line. The process test with closed input now expects the reason alone, which also excludes a binding that mistakes redirected input for a console. InputRedirectionBinding_ReportsTheConsoleState says in its summary that it only executes the binding and names the tests that prove each branch. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- src/Qqq.PrintAgent.Cli/CommandLine.cs | 61 ++++++++----- src/Qqq.PrintAgent.Cli/CommandLineHost.cs | 4 +- .../CliEnrollmentCodeTests.cs | 89 +++++++++++++++---- .../CliProcessTests.cs | 12 ++- .../Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs | 4 +- 5 files changed, 125 insertions(+), 45 deletions(-) diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index b6244e8..3c5295d 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -43,7 +43,9 @@ internal sealed class CommandLine(CommandLineHost host) Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input: - typed at a prompt, where it is not shown, or piped in. It is never accepted on the command line. + at a Windows console it is prompted for and not shown; redirected input is read as one line, without a prompt. + An unattended caller must set the variable or redirect input, or the prompt waits for a key. + The code is never accepted on the command line. Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. """.ReplaceLineEndings(); @@ -233,7 +235,8 @@ internal sealed class CommandLine(CommandLineHost host) /// /// Reads the one-time enrollment code from the environment, or else from standard input, so the code never appears in - /// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. + /// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. With + /// the variable or redirected input nothing is written, so standard error stays empty unless something fails. /// Surrounding white space is dropped, because a code never has any and a shell can add it (cmd's "echo CODE | ..." /// sends a trailing space). /// @@ -242,15 +245,14 @@ internal sealed class CommandLine(CommandLineHost host) string? code = host.ReadEnvironmentVariable(EnrollmentCodeVariable); if(string.IsNullOrWhiteSpace(code)) { - /////////////////////////////////////////////////////////////////////////// - // the prompt goes to standard error, so a script that pipes the code in // - // and captures standard output gets the service's reply and nothing // - // else. neither way of reading echoes the line end, so the prompt line // - // is ended here, before the reply or an error message is written // - /////////////////////////////////////////////////////////////////////////// - host.Error.Write("Enrollment code: "); - code = host.IsInputRedirected() ? host.ReadLine() : ReadWithoutEcho(); - host.Error.WriteLine(); + ////////////////////////////////////////////////////////////////////////////// + // redirected input is read silently. a prompt would be the only thing on // + // standard error in a successful scripted enrollment, and Windows // + // PowerShell turns any standard error output of a native program into an // + // error, which with ErrorActionPreference Stop ends the script after the // + // single-use code has already been spent // + ////////////////////////////////////////////////////////////////////////////// + code = host.IsInputRedirected() ? host.ReadLine() : PromptWithoutEcho(); } return !string.IsNullOrWhiteSpace(code) ? code.Trim() : throw new InvalidOperationException("Enrollment code is required."); } @@ -258,24 +260,35 @@ internal sealed class CommandLine(CommandLineHost host) /// - /// Reads one line from the console key by key without showing it, so a code typed at the prompt is not left on the - /// screen or in a terminal recording. Enter ends the line, Backspace removes the last character typed, and keys that - /// produce no character (arrows, function keys) are ignored. + /// Prompts at the console and reads one line key by key without showing it, so a typed code is not left on the screen + /// or in a terminal recording. The prompt goes to standard error, so it appears even when standard output is captured. + /// Enter ends the line, and so does a key that carries a carriage return or line feed without being the Enter key + /// (Ctrl+M, or a line end pasted by a terminal). Backspace removes the last character typed, and keys that produce no + /// printable character (arrows, function keys) are ignored. The line end that ended the read was not shown either, so + /// the prompt line is ended here, also when reading fails, before anything else is written. /// - private string ReadWithoutEcho() + private string PromptWithoutEcho() { - StringBuilder typed = new(); - for(ConsoleKeyInfo key = host.ReadKey(true); key.Key != ConsoleKey.Enter; key = host.ReadKey(true)) + host.Error.Write("Enrollment code: "); + try { - if(key.Key == ConsoleKey.Backspace) + StringBuilder typed = new(); + for(ConsoleKeyInfo key = host.ReadKey(true); key.Key != ConsoleKey.Enter && key.KeyChar is not ('\r' or '\n'); key = host.ReadKey(true)) { - typed.Length = Math.Max(0, typed.Length - 1); - } - else if(!char.IsControl(key.KeyChar)) - { - typed.Append(key.KeyChar); + if(key.Key == ConsoleKey.Backspace) + { + typed.Length = Math.Max(0, typed.Length - 1); + } + else if(!char.IsControl(key.KeyChar)) + { + typed.Append(key.KeyChar); + } } + return typed.ToString(); + } + finally + { + host.Error.WriteLine(); } - return typed.ToString(); } } diff --git a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs index af678d7..02b7133 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLineHost.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLineHost.cs @@ -12,9 +12,9 @@ namespace Qqq.PrintAgent.Cli; /// runs in a test without the real console, the installed service or its pipe. supplies the real ones. /// /// Standard output: service replies, and usage that was asked for. -/// Standard error: failures, usage shown because the arguments were wrong, and the enrollment prompt. +/// Standard error: failures, usage shown because the arguments were wrong, and the enrollment prompt when the code is typed at a console. A command that succeeds without that prompt writes nothing here. /// Reads one environment variable; the enrollment code arrives this way so it stays out of the command line and shell history. -/// Says whether standard input is a file or a pipe instead of a console, which decides how the enrollment code is read. +/// Says whether standard input is a file or a pipe instead of a console, which decides how the enrollment code is read and whether it is prompted for. /// Reads one line of redirected standard input, for an enrollment code that is piped in; null at end of input. /// Reads one key from the console, for an enrollment code that is typed; the argument says whether to keep the key off the screen. /// Sends one request to the installed service over its administrator pipe and returns the reply text. diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs index 9ec1f9a..e2b4fc4 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs @@ -8,9 +8,10 @@ using Qqq.PrintAgent.Windows; namespace Qqq.PrintAgent.Cli.Tests; /// -/// The one-time enrollment code is a secret. It comes from an environment variable or from standard input (piped in, or -/// typed at a prompt without being shown), never from the command line; it goes to the service in the enrollment request -/// and nowhere else; and nothing the tool prints ever contains it, whether the enrollment works, is refused or cannot be sent. +/// The one-time enrollment code is a secret. It comes from an environment variable or from standard input (piped in +/// without a prompt, or typed at a console prompt without being shown), never from the command line; it goes to the +/// service in the enrollment request and nowhere else; and nothing the tool prints ever contains it, whether the +/// enrollment works, is refused or cannot be sent. /// public sealed class CliEnrollmentCodeTests { @@ -40,12 +41,12 @@ public sealed class CliEnrollmentCodeTests - /// With the variable missing or blank and standard input redirected, the code is the line that is piped in. The prompt goes to standard error and its line is ended there, so standard output holds the service's reply and nothing else, and no key is read from a console that is not there. + /// With the variable missing or blank and standard input redirected, the code is the line that is piped in, read without a prompt: standard output holds the service's reply and nothing else, standard error stays empty, and no key is read from a console that is not there. [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] - public async Task CodePipedIn_IsReadAsALineWithThePromptOnStandardError(string? variable) + public async Task CodePipedIn_IsReadAsALineWithoutAPrompt(string? variable) { using CliFixture cli = new() { Reply = "Enrolled." }; cli.Variables["QQQ_PRINT_ENROLLMENT_CODE"] = variable; @@ -58,12 +59,30 @@ public sealed class CliEnrollmentCodeTests Assert.Equal(0, cli.KeysRead); Assert.Equal(new PipeRequest("enroll", Server, Code), Assert.Single(cli.Sent)); Assert.Equal("Enrolled.\n", cli.Output); - Assert.Equal(Prompt, cli.Error); + Assert.Equal("", cli.Error); } - /// At a console the code is read key by key up to Enter, and every key is read without being shown. Standard input is not read as a line, and the prompt line is ended on standard error because the Enter was not shown either. + /// A scripted enrollment that succeeds writes nothing at all to standard error, whether the code came from the variable or was piped in. Windows PowerShell treats any standard error output of a native program as an error, and with ErrorActionPreference set to Stop that would end the script after the single-use code was already spent. + [Theory] + [InlineData("variable")] + [InlineData("piped")] + public async Task SuccessfulScriptedEnrollment_WritesNothingToStandardError(string source) + { + using CliFixture cli = new() { Reply = "Enrolled device synthetic-device-7." }; + Supply(cli, source, Code); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(0, cli.Error.Length); + Assert.Equal("Enrolled device synthetic-device-7.\n", cli.Output); + } + + + + /// At a console the operator is prompted on standard error and the code is read key by key up to Enter, every key without being shown. Standard input is not read as a line, and the prompt line is ended on standard error because the Enter was not shown either. [Fact] public async Task CodeTypedAtTheConsole_IsReadWithoutBeingShown() { @@ -111,6 +130,46 @@ public sealed class CliEnrollmentCodeTests + /// The typed line also ends on a key that carries a line-end character without being the Enter key: Ctrl+M, which a console reports as the M key with a carriage return, and a bare carriage return or line feed delivered by a terminal that pastes or forwards text. Keys after it are left unread. + [Theory] + [InlineData(ConsoleKey.M, '\r')] + [InlineData(ConsoleKey.None, '\r')] + [InlineData(ConsoleKey.None, '\n')] + [InlineData(ConsoleKey.J, '\n')] + public async Task TypingAtTheConsole_EndsOnALineEndCharacterWithoutTheEnterKey(ConsoleKey key, char character) + { + using CliFixture cli = new() { Reply = "Enrolled.", InputRedirected = false }; + cli.Type(Code); + cli.Press(key, character); + cli.Type("typed-after-the-line-end"); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(0, exitCode); + Assert.Equal(Code, Assert.Single(cli.Sent).EnrollmentCode); + Assert.Equal("typed-after-the-line-end".Length, cli.Keys.Count); + Assert.Equal(Prompt, cli.Error); + } + + + + /// When reading keys fails, the prompt line is ended before the failure is reported, so the message starts on its own line instead of running on from "Enrollment code: ". Nothing is sent. + [Fact] + public async Task KeyReadFailure_EndsThePromptLineBeforeTheMessage() + { + using CliFixture cli = new() { InputRedirected = false }; + cli.Type("synthetic-co"); + + int exitCode = await cli.RunAsync("enroll", "--server", Server); + + Assert.Equal(1, exitCode); + Assert.Empty(cli.Sent); + Assert.Equal("", cli.Output); + Assert.Equal(Prompt + "The fixture has no more keys to press.\n", cli.Error); + } + + + /// White space around the code is dropped, whichever way it arrives, and white space inside it is kept. A code never begins or ends with white space, but a shell can add some: cmd's "echo CODE | ..." pipes a trailing space. [Theory] [InlineData("variable", " synthetic-code-4471 ", "synthetic-code-4471")] @@ -130,14 +189,14 @@ public sealed class CliEnrollmentCodeTests - /// When no code is available (redirected input is at its end or holds a blank line, or the operator presses only Enter or spaces), enrollment fails: the prompt line is ended, then one line on standard error says why, the exit code is 1, standard output is empty and no request reaches the service. + /// When no code is available, enrollment fails with one line on standard error that says why, exit code 1, nothing on standard output and no request to the service. With redirected input (at its end, or holding a blank line) that line is all standard error gets; at a console (only Enter or spaces pressed) it follows the ended prompt line. [Theory] - [InlineData("piped", null)] - [InlineData("piped", "")] - [InlineData("piped", " ")] - [InlineData("typed", "")] - [InlineData("typed", " ")] - public async Task NoCodeAtAll_FailsWithoutContactingTheService(string source, string? given) + [InlineData("piped", null, "")] + [InlineData("piped", "", "")] + [InlineData("piped", " ", "")] + [InlineData("typed", "", Prompt)] + [InlineData("typed", " ", Prompt)] + public async Task NoCodeAtAll_FailsWithoutContactingTheService(string source, string? given, string prompt) { using CliFixture cli = new(); if(given is not null) @@ -150,7 +209,7 @@ public sealed class CliEnrollmentCodeTests Assert.Equal(1, exitCode); Assert.Empty(cli.Sent); Assert.Equal("", cli.Output); - Assert.Equal(Prompt + "Enrollment code is required.\n", cli.Error); + Assert.Equal(prompt + "Enrollment code is required.\n", cli.Error); } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs index ef3f756..39b9e73 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliProcessTests.cs @@ -91,7 +91,7 @@ public sealed class CliProcessTests - /// The real executable, with no enrollment code in its environment and standard input closed, reads redirected input as a line, finds none, and stops there: the prompt and the reason are on standard error, standard output is empty and the exit code is 1. It fails before any request would be sent, so the service is not contacted. + /// The real executable, with no enrollment code in its environment and standard input closed, sees that input is redirected, reads it as a line without prompting, finds none, and stops there: the reason is the only thing on standard error, standard output is empty and the exit code is 1. It fails before any request would be sent, so the service is not contacted. A binding that took redirected input for a console would prompt and then fail reading a key, which this output excludes. [Fact] public async Task Enroll_WithNoCodeAndClosedInput_FailsBeforeContactingTheService() { @@ -99,12 +99,18 @@ public sealed class CliProcessTests Assert.Equal(1, exitCode); Assert.Equal("", output); - Assert.Equal("Enrollment code: " + Environment.NewLine + "Enrollment code is required." + Environment.NewLine, error); + Assert.Equal("Enrollment code is required." + Environment.NewLine, error); } - /// The real binding for "is standard input redirected" reports the console's own answer for input, not for output or error. + /// + /// Executes the real binding for "is standard input redirected" in this process, and nothing more: it compares the + /// binding with the property it should read, so it would not notice most wrong bindings. What proves the two branches + /// is elsewhere. The redirected branch is proved by Enroll_WithNoCodeAndClosedInput_FailsBeforeContactingTheService, + /// which runs the real executable with redirected input. The console branch is proved against fake keys in + /// CliEnrollmentCodeTests; no test here has a real console to type at. + /// [Fact] public void InputRedirectionBinding_ReportsTheConsoleState() { diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs index 15e5808..528649c 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliUsageTests.cs @@ -29,7 +29,9 @@ public sealed class CliUsageTests Every command is carried out by the installed print service, which owns the sign-in, the pairing and all printing. Run from an administrator prompt, and sign in through the companion app first. The enrollment code is read from the QQQ_PRINT_ENROLLMENT_CODE environment variable, or else from standard input: - typed at a prompt, where it is not shown, or piped in. It is never accepted on the command line. + at a Windows console it is prompted for and not shown; redirected input is read as one line, without a prompt. + An unattended caller must set the variable or redirect input, or the prompt waits for a key. + The code is never accepted on the command line. Exit code: 0 on success; 1 when the arguments are wrong, the service cannot be reached or the service reports an error. """; -- 2.54.0 From 12caed50df999f7105eab6873f5fa8132de7804b Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 15:12:13 -0600 Subject: [PATCH 12/13] docs: the enrollment prompt appears only at a console; say where "not shown" holds docs/ADMINISTRATION.md, docs/security/threat-model.md and the CHANGELOG entry now say: - Redirected input is read without a prompt, and a successful scripted enrollment writes nothing to standard error. - "Not shown" holds at a Windows console. A terminal that gives native programs a pipe instead of a console (the default Git Bash window) is read as redirected input, and the terminal may echo what is typed; use the variable there. - An unattended caller that has a console nobody can type at (a scheduled task) must set the variable or redirect input, or the command waits. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- CHANGELOG.md | 11 +++++++---- docs/ADMINISTRATION.md | 6 ++++-- docs/security/threat-model.md | 2 +- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5424fc4..79c542f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,10 +36,13 @@ Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the install and does not begin with `--`; extra words used to be ignored. `--exposed` takes `true` or `false` in any letter case and nothing else (padded values used to be accepted). Nothing is sent, and no enrollment code is asked for, when a command line is refused. -- Enrollment code: the prompt `Enrollment code: ` is written to standard error, not standard output, and its line - is ended there, so a script that pipes the code in captures only the service's reply. At a console the code is - typed without being shown. White space around the code is dropped, whether it comes from - `QQQ_PRINT_ENROLLMENT_CODE` or standard input. +- Enrollment code: there is a prompt only when the code is typed at a Windows console. It is written to standard + error, not standard output, the code is not shown while it is typed, and the prompt line is ended afterwards. + When the code is piped in or comes from `QQQ_PRINT_ENROLLMENT_CODE` nothing is prompted: standard output holds + only the service's reply and a successful enrollment writes nothing to standard error. A terminal that gives + programs a pipe instead of a console (the default Git Bash window) is read as redirected input and may echo + what is typed; an unattended caller whose console nobody types at must set the variable or redirect input. + White space around the code is dropped, whether it comes from the variable or standard input. - `service-status` and `snapshot` exit 1 when the service replies with `Error:`, as the other commands already did. The reply itself is still printed on standard output. diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index ee68120..a413305 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -43,9 +43,11 @@ Use the built-in AppKit activity log for shared service and companion events, wi | `snapshot` | Reports its state as JSON: connection, printers, recent jobs and logs | | `help`, `--help`, `-h`, or no arguments; `--help` or `-h` after a command | Nothing; the usage is printed | -The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, after the prompt `Enrollment code: ` on standard error: at a console it is typed without being shown (Backspace corrects, Enter ends), and when input is redirected one line is read, so a script can pipe the code in and standard output holds only the service's reply. White space around the code is dropped. The code is never accepted as an argument and never printed. +The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, in one of two ways. When input is redirected, one line is read with no prompt, so a script can pipe the code in: standard output holds only the service's reply and, on success, standard error stays empty (Windows PowerShell treats anything a native program writes to standard error as an error). When input is a Windows console, the prompt `Enrollment code: ` is written to standard error and the code is typed without being shown (Backspace corrects, Enter ends). White space around the code is dropped. The code is never accepted as an argument and never printed. -The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Standard output carries what the service replied, including an `Error:` reply (the exit code, not the stream, tells a script it failed), and usage that was asked for. Standard error carries the command line's own failures (the service unreachable, a timeout, no enrollment code), the enrollment prompt, and the reason and usage for a refused command line. +Two limits of that rule. "Not shown" holds at a Windows console. A terminal that gives native programs a pipe instead of a console (the default Git Bash window, for example) counts as redirected input: there is no prompt, the tool cannot stop the terminal echoing what is typed, and the line may stay on the screen; use the variable there. And an unattended caller that has a console nobody can type at (a scheduled task, for example) must set the variable or redirect input, or the command waits at the prompt for a key that never comes. + +The exit code is 0 on success and 1 otherwise: wrong arguments, a service that cannot be reached or is not the installed one, a timeout, or a reply from the service that begins with `Error:`. Standard output carries what the service replied, including an `Error:` reply (the exit code, not the stream, tells a script it failed), and usage that was asked for. Standard error carries the command line's own failures (the service unreachable, a timeout, no enrollment code), the enrollment prompt when the code is typed at a console, and the reason and usage for a refused command line; a command that succeeds without that prompt writes nothing to it. A command accepts exactly the options shown, each once, in any order, each with a value that is not blank and does not begin with `--`. `--exposed` takes the word `true` or `false` in any letter case. Anything else is refused before the service is contacted and before a code is asked for, with one line saying what is wrong (`--server is required.`, `--printer needs a value.`, `'run' takes no arguments.` and so on) followed by the usage. The refusal names only the tool's own commands and options and never repeats what was typed, because a mistyped command line can contain an enrollment code. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 6999097..7deff14 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -10,7 +10,7 @@ The remote-control adapter accepts only inventory refresh and cancellation of on The native QQQ session adapter requires discovery before credentials and never treats a native control 404 as legacy permission. After support is negotiated, 404 does not remove restrictions. Authorization denial becomes authorization-required, without inferring that every 401/403 proves revocation. New claims wait for an authenticated, bound QQQ user and valid control state. Existing installations without a protected QQQ session wait for explicit sign-in; device proof alone cannot authorize normal service printing. The command line has no server transport: the `--legacy-compat` bearer diagnostics were removed in 2.0, so no path the shipped programs can reach sends the device token outside a native session (the bearer constructor that mode used still ships in Core until it is deleted), and the command line keeps no credentials or journal of its own. -The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or standard input (typed at a console without echo, or piped in), never as an argument, and the CLI prints it nowhere; a command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. +The service stores only the QQQ session cookie and stable authoritative identity under service-identity DPAPI, and periodically resumes the standard session. Passwords stay in the companion; provider refresh/access tokens remain server-side. CLI operations use the existing authenticated service pipe. The enrollment code reaches the CLI only through an environment variable or standard input, never as an argument, and the CLI prints it nowhere. Typed at a Windows console it is read without echo; redirected input is read as a line, and that includes a terminal that hands native programs a pipe instead of a console (the default Git Bash window, for example), where the terminal itself may echo what is typed and the variable should be used instead. An unattended caller with a console nobody types at must set the variable or redirect input, or the command waits. A command line the CLI refuses is never echoed, because it can carry a misplaced enrollment code or a sign-in callback address. The private browser callback is fixed and MSI-owned, forwarding bounded data only into an active same-user/session companion inbox after executable verification. It carries a short-lived authorization code, never a session cookie or PKCE verifier. Core validates exact advertised redirect, random state, PKCE and single-use expiry; when the server advertises `nonceValidation: REQUIRED` it also sends only that attempt's own authorization nonce as `expectedNonce` (never a callback-supplied or regenerated value) and refuses any other non-empty nonce policy; no callback creates an authentication attempt. Provider registration, installed callback delivery and long-duration renewal remain deployment qualifications. Sign-out also ends the identity provider's browser session. The companion sends only the fixed registered callback with `sign-out`; the service refuses any other value, asks QQQ to log out with `nativeLogout.postLogoutRedirectUri`, and returns the provider end-session request to the companion over the administrator-only pipe. That request carries the provider's ID token hint (sensitive, bounded to 32 KiB, no whitespace or control characters), so it is never logged, the record prints redacted, and only the provider host is logged. Core refuses the data unless the issuer equals the one QQQ advertises, the end-session endpoint is HTTPS on the issuer's origin and identical to the provider's own discovery, and the callback is the one requested. The browser return is accepted only on the exact callback with the state this sign-out generated. Browser sign-in also sends `max_age=0` beside `prompt=login`. -- 2.54.0 From 7af216fcc4196d8f24fc8253c1f1cb385cdd0906 Mon Sep 17 00:00:00 2001 From: James Maes Date: Tue, 10 Nov 2026 15:46:41 -0600 Subject: [PATCH 13/13] fix(cli): drop a leading byte-order mark from the enrollment code Windows PowerShell 5.1 on a machine whose console code page is UTF-8 puts a byte-order mark in front of text it pipes to a native program. The line read keeps it as U+FEFF, which is not white space, so trimming left it in place, the blank check passed, and the service was sent a code with a leading mark that the server would reject as unknown. The code from every source is now trimmed, stripped of a leading U+FEFF and trimmed again. A variable or an input line that holds only a mark and white space counts as holding no code. Tests: marked codes from a pipe, the variable and the console are sent without the mark; mark-only sources fail as "Enrollment code is required." and send nothing. The mark is written as an escape in the sources. The comment, the administration guide and a test summary said Windows PowerShell treats any standard error output of a native program as an error. It does so when standard error is redirected or captured (2>&1, a file, the ISE, remoting); they now say that. The guide and the changelog mention the mark. Co-Authored-By: Claude Fable 5.2 Signed-off-by: James Maes --- CHANGELOG.md | 3 +- docs/ADMINISTRATION.md | 2 +- src/Qqq.PrintAgent.Cli/CommandLine.cs | 31 +++++++++++++------ .../CliEnrollmentCodeTests.cs | 14 +++++++-- 4 files changed, 35 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79c542f..9357d59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,8 @@ Command line (2.0, breaking). `qqq-print-agent.exe` now only manages the install only the service's reply and a successful enrollment writes nothing to standard error. A terminal that gives programs a pipe instead of a console (the default Git Bash window) is read as redirected input and may echo what is typed; an unattended caller whose console nobody types at must set the variable or redirect input. - White space around the code is dropped, whether it comes from the variable or standard input. + White space around the code and a leading byte-order mark are dropped, whether it comes from the variable or + standard input. - `service-status` and `snapshot` exit 1 when the service replies with `Error:`, as the other commands already did. The reply itself is still printed on standard output. diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index a413305..ba25410 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -43,7 +43,7 @@ Use the built-in AppKit activity log for shared service and companion events, wi | `snapshot` | Reports its state as JSON: connection, printers, recent jobs and logs | | `help`, `--help`, `-h`, or no arguments; `--help` or `-h` after a command | Nothing; the usage is printed | -The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, in one of two ways. When input is redirected, one line is read with no prompt, so a script can pipe the code in: standard output holds only the service's reply and, on success, standard error stays empty (Windows PowerShell treats anything a native program writes to standard error as an error). When input is a Windows console, the prompt `Enrollment code: ` is written to standard error and the code is typed without being shown (Backspace corrects, Enter ends). White space around the code is dropped. The code is never accepted as an argument and never printed. +The enrollment code is read from the `QQQ_PRINT_ENROLLMENT_CODE` environment variable. When the variable is not set it is read from standard input, in one of two ways. When input is redirected, one line is read with no prompt, so a script can pipe the code in: standard output holds only the service's reply and, on success, standard error stays empty (when a script redirects or captures standard error, with `2>&1`, a file, the ISE or remoting, Windows PowerShell turns each line a native program writes there into an error). When input is a Windows console, the prompt `Enrollment code: ` is written to standard error and the code is typed without being shown (Backspace corrects, Enter ends). White space around the code is dropped, and so is a leading byte-order mark, which Windows PowerShell 5.1 puts in front of piped text when the console code page is UTF-8. The code is never accepted as an argument and never printed. Two limits of that rule. "Not shown" holds at a Windows console. A terminal that gives native programs a pipe instead of a console (the default Git Bash window, for example) counts as redirected input: there is no prompt, the tool cannot stop the terminal echoing what is typed, and the line may stay on the screen; use the variable there. And an unattended caller that has a console nobody can type at (a scheduled task, for example) must set the variable or redirect input, or the command waits at the prompt for a key that never comes. diff --git a/src/Qqq.PrintAgent.Cli/CommandLine.cs b/src/Qqq.PrintAgent.Cli/CommandLine.cs index 3c5295d..71e5ae5 100644 --- a/src/Qqq.PrintAgent.Cli/CommandLine.cs +++ b/src/Qqq.PrintAgent.Cli/CommandLine.cs @@ -237,28 +237,39 @@ internal sealed class CommandLine(CommandLineHost host) /// Reads the one-time enrollment code from the environment, or else from standard input, so the code never appears in /// the command line or shell history. It is passed to the service and nowhere else: this class never prints it. With /// the variable or redirected input nothing is written, so standard error stays empty unless something fails. - /// Surrounding white space is dropped, because a code never has any and a shell can add it (cmd's "echo CODE | ..." - /// sends a trailing space). + /// What a shell adds around the code is dropped whichever way it arrives, and a source that holds nothing else counts + /// as holding no code. /// private string ReadEnrollmentCode() { - string? code = host.ReadEnvironmentVariable(EnrollmentCodeVariable); - if(string.IsNullOrWhiteSpace(code)) + string code = WithoutShellAdditions(host.ReadEnvironmentVariable(EnrollmentCodeVariable)); + if(code.Length == 0) { ////////////////////////////////////////////////////////////////////////////// // redirected input is read silently. a prompt would be the only thing on // - // standard error in a successful scripted enrollment, and Windows // - // PowerShell turns any standard error output of a native program into an // - // error, which with ErrorActionPreference Stop ends the script after the // - // single-use code has already been spent // + // standard error in a successful scripted enrollment. when a script // + // redirects or captures standard error (2>&1, 2>file, the ISE, remoting), // + // Windows PowerShell turns each line a native program writes there into an // + // error record, which with ErrorActionPreference Stop ends the script // + // after the single-use code has already been spent // ////////////////////////////////////////////////////////////////////////////// - code = host.IsInputRedirected() ? host.ReadLine() : PromptWithoutEcho(); + code = WithoutShellAdditions(host.IsInputRedirected() ? host.ReadLine() : PromptWithoutEcho()); } - return !string.IsNullOrWhiteSpace(code) ? code.Trim() : throw new InvalidOperationException("Enrollment code is required."); + return code.Length > 0 ? code : throw new InvalidOperationException("Enrollment code is required."); } + /// + /// Drops what a shell can put around a code that never has any of it: surrounding white space (cmd's "echo CODE | ..." + /// pipes a trailing space) and a leading byte-order mark (Windows PowerShell 5.1 puts one in front of piped text when + /// the console code page is UTF-8). The mark is not white space, so it is removed between two trims; left in, the + /// code would pass the blank check and the server would reject it as unknown. Nothing at all returns an empty string. + /// + private static string WithoutShellAdditions(string? text) => (text ?? "").Trim().TrimStart('\uFEFF').Trim(); + + + /// /// Prompts at the console and reads one line key by key without showing it, so a typed code is not left on the screen /// or in a terminal recording. The prompt goes to standard error, so it appears even when standard output is captured. diff --git a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs index e2b4fc4..675119b 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/CliEnrollmentCodeTests.cs @@ -64,7 +64,7 @@ public sealed class CliEnrollmentCodeTests - /// A scripted enrollment that succeeds writes nothing at all to standard error, whether the code came from the variable or was piped in. Windows PowerShell treats any standard error output of a native program as an error, and with ErrorActionPreference set to Stop that would end the script after the single-use code was already spent. + /// A scripted enrollment that succeeds writes nothing at all to standard error, whether the code came from the variable or was piped in. When a script redirects or captures standard error (2>&1, a file, the ISE, remoting), Windows PowerShell turns each line a native program writes there into an error record, and with ErrorActionPreference set to Stop that would end the script after the single-use code was already spent. [Theory] [InlineData("variable")] [InlineData("piped")] @@ -170,12 +170,16 @@ public sealed class CliEnrollmentCodeTests - /// White space around the code is dropped, whichever way it arrives, and white space inside it is kept. A code never begins or ends with white space, but a shell can add some: cmd's "echo CODE | ..." pipes a trailing space. + /// What a shell puts around the code is dropped, whichever way it arrives, and white space inside it is kept. A code never begins or ends with white space or a byte-order mark, but a shell can add them: cmd's "echo CODE | ..." pipes a trailing space, and Windows PowerShell 5.1 with a UTF-8 console code page pipes a leading byte-order mark, which is not white space and would otherwise reach the server as part of the code. [Theory] [InlineData("variable", " synthetic-code-4471 ", "synthetic-code-4471")] [InlineData("piped", "synthetic-code-4471 ", "synthetic-code-4471")] [InlineData("piped", "\tsynthetic code 4471\t", "synthetic code 4471")] [InlineData("typed", " synthetic-code-4471 ", "synthetic-code-4471")] + [InlineData("piped", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")] + [InlineData("piped", " \uFEFF synthetic-code-4471 ", "synthetic-code-4471")] + [InlineData("variable", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")] + [InlineData("typed", "\uFEFFsynthetic-code-4471", "synthetic-code-4471")] public async Task WhiteSpaceAroundTheCode_IsDropped(string source, string given, string sent) { using CliFixture cli = new(); @@ -189,13 +193,17 @@ public sealed class CliEnrollmentCodeTests - /// When no code is available, enrollment fails with one line on standard error that says why, exit code 1, nothing on standard output and no request to the service. With redirected input (at its end, or holding a blank line) that line is all standard error gets; at a console (only Enter or spaces pressed) it follows the ended prompt line. + /// When no code is available, enrollment fails with one line on standard error that says why, exit code 1, nothing on standard output and no request to the service. With redirected input (at its end, or holding a blank line) that line is all standard error gets; at a console (only Enter or spaces pressed) it follows the ended prompt line. A source that holds only a byte-order mark, with or without white space, holds no code either: a mark alone is never sent as a code. [Theory] [InlineData("piped", null, "")] [InlineData("piped", "", "")] [InlineData("piped", " ", "")] [InlineData("typed", "", Prompt)] [InlineData("typed", " ", Prompt)] + [InlineData("piped", "\uFEFF", "")] + [InlineData("piped", " \uFEFF ", "")] + [InlineData("variable", "\uFEFF", "")] + [InlineData("typed", "\uFEFF ", Prompt)] public async Task NoCodeAtAll_FailsWithoutContactingTheService(string source, string? given, string prompt) { using CliFixture cli = new(); -- 2.54.0