diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f6390c..541986d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ ## Unreleased +In-app update, service controls and the pipe's identity check (2.0). The installed product behaves as before. This +change does not alter the Windows Installer command line, the files, owners and access lists that are checked or +the order they are checked in, what an installer exit code means, the calls made to the service control manager, +or the decision whether the other end of the management pipe is the installed service. It changes where that code +lives, so that tests can run it: + +- The update steps (the staging checks, preparing the helper, the hand-off, applying and recording the outcome) + moved from `MsiUpdateInstaller` into `MsiUpdateSteps`, which reaches Windows only through `IPathSecurity` (owners + and access lists) and the new `IProcessHost` (the current process, a process by its id, a program started, a + file's version). `MsiUpdateInstaller` keeps the two entry points the command line tool and the companion call, + and the rules that need nothing from Windows. +- `MsiUpdateService` is given its release source (`IMsiReleaseSource`, which `GitHubMsiReleaseClient` implements), + the pipe and the update steps. The companion's constructor binds the real ones, as before. +- `AgentServiceControl` passes its four actions to `AgentServiceActions`, which reaches the service control + manager through `IServiceManager` and measures its 30 second wait on a clock it is given. +- `AgentPipePeer` makes its decision from facts it is given through `IPipePeerFacts`: which process serves the + pipe, the service's state and process, and that process's account and program. +- `MsiUpdateInstaller.PrepareHelper`, `StartHelper`, `ValidateStagingDirectory` and `UpdatesDirectory` are no + longer public members. Nothing outside the Windows library called them. +- Tests run each of these against hand-written fakes in temporary folders, and the real Windows adapters against + a harmless child program, a pipe the test serves itself, the test process and a built-in Windows service that + is only read. No test starts Windows Installer, asks the release feed, connects to the installed service's + pipe or starts or stops a service. The minimum line coverage of the Windows library in + `build/minimum-coverage.json` rises from 87 to 95. With this change the library measured between 96.06% + and 96.14% of its lines over four runs (4,539 to 4,543 of 4,725), which puts it above its release bar of 90. + Version 2 of the management pipe: the contract's gaps are closed (2.0). The contract is a set of types that nothing serves or sends yet, so none of the first seven items changes what the installed product does; they change what the service and its clients will be able to build on. The last two are about logging. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dbb927f..e78010d 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. An assembly that has reached its release bar is recorded at the bar, with no point of slack: that is why the CLI and the presentation assembly stand at 100. Every line added to `src/Qqq.PrintAgent.Presentation` needs a test in `tests/Qqq.PrintAgent.Presentation.Tests` that asserts its behavior, with hand-written fakes, an injected clock and no real pipe (quick loop: `dotnet test tests/Qqq.PrintAgent.Presentation.Tests -c Release -p:Platform=x64`). The release bar is 100% for Core, the presentation assembly 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. +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 Core, the CLI and the presentation assembly stand at 100. The Windows layer's bar is 90, and the layer is above it: there the minimum keeps following the rule, and it never drops below 90. Every line added to `src/Qqq.PrintAgent.Presentation` needs a test in `tests/Qqq.PrintAgent.Presentation.Tests` that asserts its behavior, with hand-written fakes, an injected clock and no real pipe (quick loop: `dotnet test tests/Qqq.PrintAgent.Presentation.Tests -c Release -p:Platform=x64`). The release bar is 100% for Core, the presentation assembly and the CLI and 90% for the Windows layer. Every assembly is at or above its bar: the Windows layer's minimum is 95, set when it measured between 96.06% and 96.14% over four runs (4,539 to 4,543 of 4,725 lines). A green gate therefore means "at or above the release bar", which for the Windows layer is 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/build/minimum-coverage.json b/build/minimum-coverage.json index b530eb5..499e1f8 100644 --- a/build/minimum-coverage.json +++ b/build/minimum-coverage.json @@ -1,6 +1,6 @@ { "Qqq.PrintAgent.Core": 100, "Qqq.PrintAgent.Presentation": 100, - "Qqq.PrintAgent.Windows": 87, + "Qqq.PrintAgent.Windows": 95, "qqq-print-agent": 100 } diff --git a/docs/AUDIT-2026-11-10.md b/docs/AUDIT-2026-11-10.md index f1473c2..eee38ee 100644 --- a/docs/AUDIT-2026-11-10.md +++ b/docs/AUDIT-2026-11-10.md @@ -197,7 +197,7 @@ Found by the reviews of the legacy polling removal, the enrollment fix, the desi | W30 | Nit | Code that only the removed legacy mode and the removed polling path reached still ships in Core and Windows: the bearer-token transport, the in-memory download and submit, the HTTP fallbacks for a missing realtime channel | Closed by pull request 35 (`b868e9e`): the bearer-token transport, the in-memory download and submit and the HTTP fallbacks are deleted; the API client is built only from a signed-in session | | C13 | Low | A claim nested past 1,024 levels cannot be identified, so it is never refused and stops the lane. The server's 2,000-character cap on options cannot produce one; a depth cap on the server would be the durable fix | Open (server) | -Found by the retrospective reviews of 2026-11-10 and by the review of the printing seams step, or seen while verifying. Pull requests 28, 29, 35, 37 and 38 had merged with a final fix round their reviewer had not seen, and pull requests 30 and 31 with no review (ADR-0004, "About the process"). Review A covered pull requests 37, 38, 31 and 30; review B covered the last fix rounds of pull requests 29, 35 and 28; both read `release/2.0` at `c3efed4`. Neither found a blocker. The printing seams step merged afterwards as pull request 42 (`e2ca086`). The review of its first head found five pieces of older behavior (W44 to W46, W57 and W58); the step changed nothing that reaches Windows, so all five are in `release/2.0` as they were. Every citation below was read at `6f0237d` and holds at `e2ca086`. Pull requests 40 and 41 changed none of the source files cited by line. Pull request 42 rewrote `WindowsPrinters*.cs` and `PrinterWorkerHost.cs`, so the rows that cite them (W44, W46, W48, W57, W58) were given the line numbers of `e2ca086`, as the two `CHANGELOG.md` citations carry those of `077148f`, which pull request 42 did not move. Some of those rows have since been brought up to a later tree; the end of this paragraph says which. Severity is the reviewer's. "Not rated" marks an item that no reviewer has rated. Review A's findings about documents (its 14 to 21) are answered in ADR-0004, "Resolved after the retrospective reviews", and by the status corrections in this file. Review B's finding 8 is W26. C22, C23 and W49 to W55 are the nits left open by the reviews of pull requests 40 and 41, which merged afterwards with the reviewed head and the verdict in their descriptions. Those descriptions name no places; where a row gives one, it was found by reading the code. W56 to W58 and C24 were added in the fix round after the review of the change that wrote this table. W59 to W64 are what pull request 42 left open that had no row; C25 and W65 are two further places with the effect of W44. W66 to W69 were found while W44 was fixed, were not there before as rows, and no reviewer has rated them; each says whether it was tested or only read. W70 to W72 come from the review of that fix (no blocker, 3 should-fix, 9 nits): its should-fix S1 and its nits 2 and 9, with the reviewer's severity. That fix, the change that gave a printer backend three reads, moved lines in `IsolatedPrinterBackend.cs`, `WindowsPrinters.cs`, `WindowsPrinters.Files.cs`, `PrinterWorkerHost.cs` and the worker fixture's `Program.cs`. The open rows that cite those files by line (W45, W46, W48 and W57 to W61) therefore carry the line numbers of that change's tree, the head its review's fix round ended on, and no longer those of `e2ca086`; so do W70, W71 and W73. Only the numbers were changed in those rows. The closed rows W44 and C25, and W65, keep the numbers of `e2ca086`, at which they say they were read. C24 is not touched: its numbers were already behind `release/2.0` before that change. W73 comes from the confirmation review of that fix round (no blocker, 1 should-fix, 4 nits): its nit 1. "The contract and redaction fixes that followed the retrospective review" in a status below is one change, merged as one pull request: the fixes to the version 2 pipe contract and to the log's redaction that closed W31 to W42, C14 and W56, together with the fix round after their own review. W74 and the rows after it were found by that review, which found no blocker; what it found in rows that already existed is recorded in their statuses. +Found by the retrospective reviews of 2026-11-10 and by the review of the printing seams step, or seen while verifying. Pull requests 28, 29, 35, 37 and 38 had merged with a final fix round their reviewer had not seen, and pull requests 30 and 31 with no review (ADR-0004, "About the process"). Review A covered pull requests 37, 38, 31 and 30; review B covered the last fix rounds of pull requests 29, 35 and 28; both read `release/2.0` at `c3efed4`. Neither found a blocker. The printing seams step merged afterwards as pull request 42 (`e2ca086`). The review of its first head found five pieces of older behavior (W44 to W46, W57 and W58); the step changed nothing that reaches Windows, so all five are in `release/2.0` as they were. Every citation below was read at `6f0237d` and holds at `e2ca086`. Pull requests 40 and 41 changed none of the source files cited by line. Pull request 42 rewrote `WindowsPrinters*.cs` and `PrinterWorkerHost.cs`, so the rows that cite them (W44, W46, W48, W57, W58) were given the line numbers of `e2ca086`, as the two `CHANGELOG.md` citations carry those of `077148f`, which pull request 42 did not move. Some of those rows have since been brought up to a later tree; the end of this paragraph says which. Severity is the reviewer's. "Not rated" marks an item that no reviewer has rated. Review A's findings about documents (its 14 to 21) are answered in ADR-0004, "Resolved after the retrospective reviews", and by the status corrections in this file. Review B's finding 8 is W26. C22, C23 and W49 to W55 are the nits left open by the reviews of pull requests 40 and 41, which merged afterwards with the reviewed head and the verdict in their descriptions. Those descriptions name no places; where a row gives one, it was found by reading the code. W56 to W58 and C24 were added in the fix round after the review of the change that wrote this table. W59 to W64 are what pull request 42 left open that had no row; C25 and W65 are two further places with the effect of W44. W66 to W69 were found while W44 was fixed, were not there before as rows, and no reviewer has rated them; each says whether it was tested or only read. W70 to W72 come from the review of that fix (no blocker, 3 should-fix, 9 nits): its should-fix S1 and its nits 2 and 9, with the reviewer's severity. That fix, the change that gave a printer backend three reads, moved lines in `IsolatedPrinterBackend.cs`, `WindowsPrinters.cs`, `WindowsPrinters.Files.cs`, `PrinterWorkerHost.cs` and the worker fixture's `Program.cs`. The open rows that cite those files by line (W45, W46, W48 and W57 to W61) therefore carry the line numbers of that change's tree, the head its review's fix round ended on, and no longer those of `e2ca086`; so do W70, W71 and W73. Only the numbers were changed in those rows. The closed rows W44 and C25, and W65, keep the numbers of `e2ca086`, at which they say they were read. C24 is not touched: its numbers were already behind `release/2.0` before that change. W73 comes from the confirmation review of that fix round (no blocker, 1 should-fix, 4 nits): its nit 1. "The contract and redaction fixes that followed the retrospective review" in a status below is one change, merged as one pull request: the fixes to the version 2 pipe contract and to the log's redaction that closed W31 to W42, C14 and W56, together with the fix round after their own review. W74 and the rows after it were found by that review, which found no blocker; what it found in rows that already existed is recorded in their statuses. W77 to W81 are what the review of the update, service-control and pipe-peer seams (plan step 8 of the build) left open after its fix round; their line numbers are those of that step's head. | ID | Severity | Finding | Status | | --- | --- | --- | --- | @@ -263,12 +263,17 @@ Found by the retrospective reviews of 2026-11-10 and by the review of the printi | W75 | Nit | Two ways around the contract's checks remained inside the assembly, outside what the fixes claimed. `ManagementError.FromWire` was internal and took a code, a message and details as given, so code in the service's own assembly could send text that is not a code, an empty message, or details for a code that carries none; only a comment said that the parser alone calls it. `ManagementReply` and `ManagementRequest` were positional records: a reply could be built with any version, with an error beside a result or with neither, and a request with any text as its operation or its server (review of the contract and redaction fixes, nit 5) | Closed in the fix round after that review (2026-11-10). A request and a reply have no public constructor and no member that can be set; they are built by `ManagementRequest.For` and by `ManagementReply.Success` and `Failure`, which the parser uses too. A request is always version 2, with an operation shaped like a name and a server named by a full identifier or not at all; a reply is always version 2, with exactly one of a result and an error. `ManagementOperations.Check` no longer asks about the version or the spelling of the identifier, because no request can have another. The parser's way into an error takes the error object as JSON and nothing else. The text on the wire is unchanged: no golden file changed. Left as it is: that way in is internal, so code in the assembly that builds a JSON object for the purpose can still have an error read from it; and the parser's two result records, `ManagementRequestParse` and `ManagementReplyParse`, can be built by hand, which nothing sends | | W76 | Nit | A server's name may begin with a hyphen, and may be spelled like an option of the command line: `-h`, `--server` and `-` all pass `ServerName.Check`, which matches the rule ADR-0004 states. The name rule is about what a name is; nothing in it knows the command line. The command line is where it matters: a name given as the value of `--server`, or as the new name in a rename, must be taken as a value and not as an option (review of the contract and redaction fixes, nit 10, second part) | Open, for the step that builds the command line's server commands: it either takes such a name as a value however it is spelled, or the rule is changed to refuse a leading hyphen. A test holds that the rule accepts these names today, so the choice is made on purpose | | C27 | Nit | Core's one definition of a shown character goes by Unicode category (`ServerText.cs:30-31`), and its comment says it is false for characters that hide text. By category some characters are shown that draw nothing: the Hangul fillers (U+3164, U+115F, U+1160, U+FFA0) are letters, the blank Braille pattern (U+2800) is a symbol, and the combining grapheme joiner (U+034F) and the variation selectors are marks. Each passes every rule built on the definition, so one of them can be a whole error message (the service's check that a message says something takes it for text), a whole identity value in a reply, or a whole value in the session client's problem details and log lines. Core's definition was not changed by the contract fixes (review of the contract and redaction fixes, nit 6) | Open for Core's definition, which that fix round did not change: a message and an identity value made only of such characters are still carried. Closed for a server's name, where it is a trap for the operator, by the contract's own rule: `ServerName.Check` refuses a name in which nothing draws (`ShowsNothing`), which is a name made only of those characters, of combining marks and of spaces | +| W77 | Should-fix | No test can tell whose account is read. With the peer's process still held, reading the account from the calling process instead of from the peer passes every test (`WindowsPeerProcess.cs:35`, the handle given to `OpenProcessToken`); the same change made without holding the peer's process is caught, by the test that the process stays held. Every process a test without administrator rights can open runs under the test's own account, so the two readings agree. Only an authentication against a process of another account tells them apart: the first elevated authentication against the installed service, which runs as SYSTEM. The decision that the account must be SYSTEM is tested against the fake (review of plan step 8) | Open; in the upgrade qualification entry of `docs/TODO.md` | +| W78 | Should-fix | No test fails when the real service handle's refresh does nothing (`WindowsManagedService.cs:27`). The adapter is read against a built-in service whose state does not change during the test, and controls are sent only to a name no service has. That the wait refreshes before each look is tested against the fake. Only starting or restarting a real service shows whether the adapter reads afresh. Read, not run: with a refresh that did nothing the wait would see the first state for 30 seconds and report that the service did not start (review of plan step 8) | Open; in the upgrade qualification entry of `docs/TODO.md` | +| W79 | Should-fix | Each authentication of the pipe peer leaves two service handles to the finalizer. `WindowsPeerService.ReadStatus` reads `ServiceController.ServiceHandle` (`WindowsPeerService.cs:22`), which opens a new handle on every call and hands it to the caller; the status is read twice per authentication and neither handle is closed. Disposing the controller does not close them. The code is as it was in 1.2.1 (`AgentPipePeer.ReadStatus` there). Read, not measured: a companion that asks the service every few seconds holds open service handles until the garbage collector runs. Found by the author of plan step 8 and confirmed by its review | Open | +| W80 | Nit | When the update session's folder fails its second check, the one made after the folder is created, the empty folder is left under the updates folder (`MsiUpdateService.cs:186-187`): nothing was downloaded into it, and removing it is refused by the same check. `NothingIsDownloadedIntoAFolderThatCannotBeTrusted` pins this. An administrator finds an empty folder with a random name (found by the author of plan step 8 and confirmed by its review) | Open | +| W81 | Nit | The link check of the recorded outcome before it is written (`MsiUpdateSteps.Apply.cs:201`, on `last-result.json`) has no refusing test: with the check removed every test passes. The path is a file, so showing the refusal needs a file symbolic link, which Windows lets a test create only with a privilege or in developer mode; the other link checks are shown with junctions, which are folders (review of plan step 8) | Open | ### Repository | ID | Requirement | Finding | Status | | --- | --- | --- | --- | -| R1 | K22-TEST-10, -02 | Coverage collected, never gated; no exclusion attributes | Gate closed by pull request 20 (`1431d8c`). Core, the command line and the presentation assembly are at 100% and gated there (pull requests 29, 28 and 34). Windows is gated at 86 since pull request 42 and measured 87.47% on its reviewed head, against a release bar of 90; the exception record for that bar (EX-0016, standards pull request 58) has the status "Proposed, awaiting approval". Exclusions now exist and each carries a written reason: four adapter classes in Core; in the Windows layer nine one-line members (`AgentBrandingInstaller.cs`, `AgentStartup.cs`, `QqqBrowserCallback.Paths.cs`, `QqqBrowserCallback.Trace.cs`) and, since pull request 42, six adapter classes (`WindowsSpooler`, `WindowsGdiPrinter`, `WindowsPrinterSettings`, `WindowsPdfRenderer`, `WindowsSpoolerJobQueue`, `ParentProcessWatch`). Counted at `e2ca086`. Changed-line coverage unmeasured | +| R1 | K22-TEST-10, -02 | Coverage collected, never gated; no exclusion attributes | Gate closed by pull request 20 (`1431d8c`). Core, the command line and the presentation assembly are at 100% and gated there (pull requests 29, 28 and 34). Windows was gated at 86 with pull request 42, when it measured 87.47% on that pull request's reviewed head, and at 87 with pull request 49. Since plan step 8 of the build (the update, service-control and pipe-peer seams) it is gated at 95 and measured between 96.06% and 96.14% over four runs (4,539 to 4,543 of 4,725 lines), above its release bar of 90; the exception record for that bar (EX-0016, standards pull request 58) has the status "Proposed, awaiting approval". Exclusions now exist and each carries a written reason: four adapter classes in Core; in the Windows layer nine one-line members (`AgentBrandingInstaller.cs`, `AgentStartup.cs`, `QqqBrowserCallback.Paths.cs`, `QqqBrowserCallback.Trace.cs`) and, since pull request 42, six adapter classes (`WindowsSpooler`, `WindowsGdiPrinter`, `WindowsPrinterSettings`, `WindowsPdfRenderer`, `WindowsSpoolerJobQueue`, `ParentProcessWatch`). Counted at `e2ca086`. Changed-line coverage unmeasured | | R2 | K22-TEST-25, -23 | No fuzz targets, `docs/security/fuzzing.md` or `assurance.json` | Open | | R3 | K22-TEST-03 | UI tests are not in the release checklist | Open | | R4 | K22-CI, K22-REPO | Requirements written for GitHub; the repository's primary host is Gitea, which ran no checks for it | Open; CI is owned by the Gitea CI work | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 40cb33c..e697d31 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -59,6 +59,29 @@ The journal carries a schema version in SQLite's `PRAGMA user_version`: 0 for a Tests build the state an earlier release left with `LegacyStateBuilder`: the journal from a script of that release's own statements (`tests/Qqq.PrintAgent.Cli.Tests/Fixtures/journal-1.2.1.sql`, transcribed from tag `v1.2.1`, and `journal-oldest.sql`, the oldest shape the history shows), and the pairing file in the serialization and protection 1.x used. `JournalProbe` answers what the tests ask from outside the product: the version, the schema as SQLite records it, a digest of each table's rows and a hash of every file. A new release that changes what is stored gets a fixture of the journal the release before it leaves. `JournalUpgradeTests` runs the upgrade on what an installation can leave besides a cleanly closed journal: a 1.2.1 journal whose rows are only in the log of a killed service (`LegacyStateBuilder.WithJournalLeftByAKill`), each shape between the oldest and 1.2.1, including 1.0.x without the certificate exception table, and a 1.2.1 state folder under the service loop with one job left in SUBMITTING and one in RECEIVED, which the start records as OUTCOME_UNKNOWN and FAILED. +## Testing code that reaches Windows + +Code in the Windows library that asks Windows for something a test must not touch (the print service, Windows Installer, the machine state folder, Program Files, the task scheduler, the all-users Start menu) is in three parts. A public static entry point binds the real Windows and holds no rule. A class of rules takes everything it needs from Windows through an interface, and the folders it works in as values, so a test runs the rules against a hand-written fake in a temporary folder. A real adapter behind the interface only asks Windows and passes on what it said, failures included. + +| Entry point | Rules | What the rules get from Windows | Fake in `tests/Qqq.PrintAgent.Cli.Tests` | +| --- | --- | --- | --- | +| `MsiUpdateInstaller` (`ApplyAsync`, `ReadLastOutcomeMessage`) | `MsiUpdateSteps`, in the places of `MsiUpdatePlaces` | `IPathSecurity` (owners, access lists, who is asking), `IProcessHost` (the current process, a process by id, a program started, a file's version) | `FakePathSecurity`, `FakeProcessHost`; `MsiUpdateSetup` builds the folders | +| `MsiUpdateService` (public constructor) | `MsiUpdateService` (internal constructor) | `IMsiReleaseSource`, the pipe as a function, `MsiUpdateSteps` | `FakeMsiReleaseSource` | +| `AgentServiceControl` | `AgentServiceActions` | `IServiceManager`, `IProcessHost`, a `TimeProvider` | `FakeServiceManager`, `ManualTimeProvider` | +| `AgentPipePeer.Installed.Authenticate(pipe)`, the bound check itself, which `AgentPipeClient` calls | `AgentPipePeer.Authenticate(pipe, facts, installedService)` | `IPipePeerFacts` (the pipe's server process, a service's state and process, a process's account and program) | `FakePipePeerFacts` | + +Sign-in startup (`AgentStartup`, `AgentStartupTasks`, `ITaskScheduler`) and the branded shortcut (`AgentBrandingInstaller`, `AgentBrandingShortcuts`, `IShortcutShell`, `IShortcutRecord`) are built the same way. + +Rules for this kind of code: + +- A fake behaves as Windows does wherever a rule depends on it, and says so in its summary. A service handle remembers the state it read until it is refreshed; an id no running process has cannot be opened; a program file or a folder that does not exist cannot be started or read; the program of a process that has ended cannot be read. What .NET 10 reports for that last read depends on whether anything else still holds the ended process: Windows error 299 while another handle keeps it, which is what `FakeProcess` does unless a test says otherwise, and an invalid-operation failure ("has exited") when nothing holds it, which a test sets on the fake. The second is the update helper's own situation, and the only one it takes for a companion that has closed; each case has a test in `MsiUpdateApplyTests`. When a fake and Windows disagree, fix the fake first and then see which tests still pass. +- A real adapter is tested for real whenever that changes nothing on the computer: a program starter against the worker fixture's stand-in mode (`Qqq.PrintAgent.WorkerFixture.exe --stand-in`), file and access-list code in temporary folders, links as junctions made with `mklink /J`, token facts against the test process, a pipe the test serves itself under a name of its own (with the stand-in as its client where the two ends must be different processes), and service reads against the built-in remote procedure call service (`RpcSs`), which is only read. Controls are sent only to a service name no service has, which Windows refuses. +- One older suite names the print service itself. `AgentPipeSecurityTests` runs the real peer check against a pipe the test serves, and the peer check asks Windows for the service `QqqPrintAgent`. On a computer without the product there is no such service. On a computer with the product installed, Windows refuses to open the service for a test run without administrator rights; in an elevated run the service is opened and its status is read. Nothing else is sent to it: it is not started, stopped or changed, and its pipe is not contacted. The test's outcome is the same refusal in every case. +- `[ExcludeFromCodeCoverage(Justification = "...")]` is for a member that only passes a call on to rules bound to a real place of this computer. The justification names what the member binds and where the rules and the binding are tested. A class that decides something is never excluded. +- What an entry point is bound to is a value a test can read, and a test compares it with the real place: `MsiUpdateInstaller.Installed.Places` with `MsiUpdatePlaces.Installed()`, the companion's `MsiUpdateService` with the installed service's pipe and `MsiUpdateInstaller.Installed`, `AgentServiceControl.Installed.ServiceName`, and `AgentPipePeer.Installed` with the Windows facts and the service program under Program Files. The peer check has no entry point besides that value: `AgentPipeClient` calls `AgentPipePeer.Installed.Authenticate`, so the Windows facts and the service program are named in one place, the value the test reads, and there is no pass-through in between that could hand the rules others. The entry points of `MsiUpdateInstaller` and `AgentServiceControl` are one line each, excluded from coverage, that passes the call on to the bound value and names no place of its own. No test can tell whether such a line, or the client's call, uses the bound value or builds another one, because no test may reach the installed product; that is checked by reading: none of them names facts, a place or a program. +- A test of these rules never starts Windows Installer, asks the release feed, connects to the installed service's pipe, starts or stops a service, or writes under Program Files or the machine state folder. `MsiUpdateInstaller.ApplyAsync`, `AgentServiceControl.StartAsync` and `RestartAsync` must not be called from a test for that reason. +- An `await` on code under test that would wait forever if the code were wrong gets a limit (`MsiUpdateSetup.Patience`), so the test fails instead of hanging the run. + ## Local server and CLI Use a disposable native QQQ host from the sibling qbit-printing project, using qbit-printing 1.0.0 on QQQ 4.1.0-RC.21 and advertising native printing API 2.3. Sign in through the companion's advertised QQQ authentication flow before using normal CLI commands. The service owns the session, device proof and unattended printing. A bearer-only demo is not a compatible realtime host. @@ -110,6 +133,6 @@ MSI ProductVersion is numeric; assembly/package informational version may contai `MainWindow.Updates` wires AppKit `UpdateCoordinator`/`ContentDialogPrompter` to Windows `MsiUpdateService : IUpdateService`. The persisted startup-check preference, version/channel display, splash duration and help/credits use the shared shell. The UI serializes manual/startup checks; confirmation is required before apply. -`GitHubMsiReleaseClient` reads the fixed QRun-IO release feed, applies strict version/channel/minimum policy and validates bounded release assets and SHA-256. `MsiUpdateInstaller` validates protected staging, ACLs and reparse boundaries, copies the installed self-contained CLI for handoff, rechecks the MSI and uses Windows Installer for all components. The runtime's `prepare-update`/`resume-after-update` operations coordinate a bounded claim pause while preserving heartbeats: `prepare-update` stops new claims, answers "Ready for update." once every job already claimed has finished, answers that it is not ready when that takes more than 25 seconds, and answers that preparation was interrupted when printing was resumed or a sign-in, sign-out or enrollment began while it waited; the pause lifts by itself after 10 minutes. No server-supplied executable, per-user replacement package or persistent privileged updater is involved. See the [threat model](security/threat-model.md) for trust and failure boundaries. +`GitHubMsiReleaseClient` reads the fixed QRun-IO release feed, applies strict version/channel/minimum policy and validates bounded release assets and SHA-256. `MsiUpdateSteps`, which the installed product reaches through `MsiUpdateInstaller`, validates protected staging, ACLs and reparse boundaries, copies the installed self-contained CLI for handoff, rechecks the MSI and uses Windows Installer for all components. The runtime's `prepare-update`/`resume-after-update` operations coordinate a bounded claim pause while preserving heartbeats: `prepare-update` stops new claims, answers "Ready for update." once every job already claimed has finished, answers that it is not ready when that takes more than 25 seconds, and answers that preparation was interrupted when printing was resumed or a sign-in, sign-out or enrollment began while it waited; the pause lifts by itself after 10 minutes. No server-supplied executable, per-user replacement package or persistent privileged updater is involved. See the [threat model](security/threat-model.md) for trust and failure boundaries. Historical 0.1.3-rc.1 verification: locked restore, zero-warning Release build, **36 Core + 127 Windows/CLI tests (163 total)**. Synthetic release/download/hash/request/ACL/version/maintenance tests do not install an MSI. Installed shell and actual upgrade acceptance remain separate gates; use [session state](SESSION-STATE.md) for current verification. Completed protected update stages are retained for manual administrator review. diff --git a/docs/SESSION-STATE.md b/docs/SESSION-STATE.md index 0d0d122..6cddd84 100644 --- a/docs/SESSION-STATE.md +++ b/docs/SESSION-STATE.md @@ -6,7 +6,7 @@ Version 2.0 (several servers at once, a connection wizard, enforced quality gate - Merged on `release/2.0` up to `e2ca086`: eighteen pull requests, 20, 21, 25, 24, 27, 28, 29, 30, 31, 33, 34, 35, 37, 38, 39, 40, 41 and 42. Pull request 40 fixed the realtime channel's shutdown race; pull request 41 put sign-in startup, the branded shortcut and the browser hand-off behind tested seams; pull request 42 put every Windows printing call behind a tested seam, changing nothing that reaches Windows. The service still holds one server; version 2 of the management pipe exists as types that nothing serves yet. - Snapshot, 2026-11-10: the Gitea prerelease `snapshot-2.0.0-rc.1` at commit `6f0237d`, unsigned. `build/Verify.ps1` passed on that commit: 766 Core tests, 1,117 Windows and command-line tests, 352 presentation tests, none failed; line coverage Core 100% (2,130 lines), command line 100% (117), presentation 100% (922), Windows 74.84% (3,172 of 4,238). It has not been installed anywhere, the interactive desktop suite has not been run on it, nothing has been printed with it, and the upgrade from 1.2.x is not qualified. -- Coverage minimums now in `build/minimum-coverage.json` (at `e2ca086`): Core 100, presentation 100, command line 100, Windows 86. `build/Verify.ps1` on the reviewed head of pull request 42 measured Core 100% of 2,141 lines and Windows 87.47% (3,835 of 4,384), with 773 Core, 1,521 Windows and command-line and 352 presentation tests. The Windows bar of 90 is a release bar; its exception record is EX-0016 in the standards repository (pull request 58, open), whose status is "Proposed, awaiting approval". +- Coverage minimums now in `build/minimum-coverage.json`: Core 100, presentation 100, command line 100, Windows 95. The Windows minimum was 86 at `e2ca086` and 87 after pull request 49; it is 95 with the change that put the update installer, the update service, the service controls and the pipe-peer check behind tested seams (plan step 8 of the build). `build/Verify.ps1` on that change measured Core 100% of 2,311 lines, the command line 100% of 120, the presentation assembly 100% of 936 and Windows between 96.06% and 96.14% over four runs (4,539 to 4,543 of 4,725), with 1,174 Core, 2,321 Windows and command-line and 360 presentation tests. The Windows layer is therefore above its release bar of 90, and the minimum keeps it there. The bar's exception record is EX-0016 in the standards repository (pull request 58, open), whose status is "Proposed, awaiting approval". - Review gate (the owner asked on 2026-11-10 that the process be changed; the terms were taken under the standing instruction): no head merges that the reviewer has not seen; see "About the process" in [ADR-0004](adr/0004-multi-server-runtime.md). Pull requests 28, 29, 35, 37 and 38 merged with an unseen final fix round and 30 and 31 with no review; two retrospective reviews followed, and their open findings are in [the audit](AUDIT-2026-11-10.md). - Hardware check (release condition, [ADR-0003](adr/0003-version-2.md)): an early check after the printing seams step and a final check on the release candidate, on a Zebra ZT411 and a Canon office printer, each print approved by the owner. The printing seams step merged as pull request 42, so the early check is due. Neither check has been run. diff --git a/docs/TODO.md b/docs/TODO.md index 21de225..38bff55 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -12,7 +12,31 @@ - [ ] Hardware check, final (release condition): on the release candidate, through the installed service, same two printers, each print approved by the owner. "Ready to merge to `main`" is held until it is recorded in [ACCEPTANCE.md](ACCEPTANCE.md), with "the spooler accepted the job" and "paper came out" as separate statements. Not run. - [ ] Standards exception EX-0016 (the Windows coverage bar of 90%): in standards pull request 58, which is open; its status is "Proposed, awaiting approval". - [ ] Open findings from the two retrospective reviews of 2026-11-10 and from the review of the printing seams step: listed in [the audit](AUDIT-2026-11-10.md) under "Found by the retrospective reviews". The should-fix findings about the pipe contract close before anything serves the contract. -- [ ] Qualify the upgrade from 1.2.x to 2.0. Not done: the 2026-11-10 snapshot (`snapshot-2.0.0-rc.1`) was not installed anywhere. The qualification also has to cover what pull request 41 left unverified: no elevated MSI run has exercised the new branding and startup code, so the real machine registry key, the installer's custom actions, and shell and folder creation as SYSTEM are unexercised, and its real-shell tests ran only on the development PC's Windows build. +- [ ] Qualify the upgrade from 1.2.x to 2.0. Not done: the 2026-11-10 snapshot (`snapshot-2.0.0-rc.1`) was not installed anywhere. The qualification also has to cover what pull request 41 left unverified: no elevated MSI run has exercised the new branding and startup code, so the real machine registry key, the installer's custom actions, and shell and folder creation as SYSTEM are unexercised, and its real-shell tests ran only on the development PC's Windows build. It also has to cover what the review of the update, service-control and pipe-peer seams (plan step 8, 2026-11-10) listed as shown only by an elevated run on the installed product; none of it has been run: + - The upgrade is finished by 1.2.1's own updater, not by 2.0's ([ADR-0004](adr/0004-multi-server-runtime.md), "Recorded while reviewing the update and pipe-peer seams"). Run a real 1.2.1 installation's in-app update to a 2.0 build and check what that helper needs from 2.0 after the installer exits: + - the companion, the service and the command line tool at their three paths under `%ProgramFiles%\QQQ Print Agent`, each carrying the release as its product version, with identical build metadata, so that the old helper records success; + - the service named `QqqPrintAgent`, running as SYSTEM from its service path and serving the pipe `QqqPrintAgent`, so that the old helper's peer check passes; + - an answer of one line to the old helper's version 1 request `resume-after-update`, the only request it sends after the installer exits, and printing not left paused afterwards; + - `last-result.json` as the old helper wrote it, and its line in the machine activity log, shown by the 2.0 companion it reopens; + - the companion reopened by the old helper from `App\Qqq.PrintAgent.exe`. + - Not read in that review and to be checked before this run: what 1.2.1's release client needs from the published 2.0 release before the installer starts (the feed entry, the asset names and the checksum). + - The first real authentication through the new adapters, from an elevated command line tool or companion against the installed service. No unit test has any of these: + - `GetNamedPipeServerProcessId` asked by a client whose server is another process (a test now shows the reverse, the server's end with a child as client); + - `ServiceController.ServiceHandle` opening with full access, and `QueryServiceStatusEx` returning state 4 and the pipe server's id; + - `OpenProcessToken` on a process of another account reporting SYSTEM (audit W77); + - the main module equal to `%ProgramFiles%\QQQ Print Agent\Service\Qqq.PrintAgent.Service.exe`. + - The two refusals for real: the same command without elevation gives "not the installed Windows print service", and the service stopped during a command gives "stopped or restarted". + - The 2.0 updater itself, which needs a 2.0 build that updates to a later 2.0 build: + - the real access lists under `C:\ProgramData\QqqPrintAgent\updates\` and on the installed `Cli` tree passing the trust check; + - the helper's own program path equal to the staged path; + - the companion's id and start time agreeing between the companion and the helper; + - Windows Installer able to open the MSI while the helper holds it with read sharing; + - exit codes 0, 1602 and 3010; + - the three version resources read; + - `last-result.json` read back by the reopened companion; + - `resume-after-update` accepted through the peer check. + - The service controls on the real service: a refresh that really reads again (audit W78), stop, wait and start through real pending states, "Unavailable" without elevation, and the Services console with its elevation prompt. + - The Windows-layer suite run once elevated and once as SYSTEM or on the hosted runner: the token assertions, the administrator branch of `InstalledProductsStepsAreBoundToThisComputer`, the shell start without a desktop, and `mklink /J`. ## Released: 1.2.1 — 2026-11-06 diff --git a/docs/adr/0003-version-2.md b/docs/adr/0003-version-2.md index 2a286f1..9545649 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. 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. The exception record for it is EX-0016 in the KofTwentyTwo standards repository, in pull request 58, which is open (head `7a58fb4` on 2026-11-10). The record's status is "Proposed, awaiting approval": an earlier wording was approved, a review then corrected the wording, and the corrected wording has not been approved. It lists K22-TEST-10 and, in part, K22-CODE-CS-11; it states a release bar of 90 and the minimum "73 at commit `6f0237d`"; and it makes a check on real printers a condition of releasing 2.0. Until it is approved, the deviation is not covered by an approved exception. The 90% is a release bar and not what the gate holds today. The recorded minimum for the Windows layer was 73 at `6f0237d` (74.84% measured) and has since risen to 80 with pull request 41 and to 86 with pull request 42 (`build/minimum-coverage.json` at `e2ca086`), against 87.47% measured (3,835 of 4,384 lines) on the reviewed head of pull request 42. 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. Above a release bar that is below 100, which is the Windows layer's case, the minimum keeps following the rule (the measured percentage rounded down, less one point), and once the bar has been reached it never drops below the bar; this sentence was taken on 2026-11-10 under the owner's standing instruction for this work (take the recommended option, record it, keep going), and the owner can overrule it. 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. The exception record for it is EX-0016 in the KofTwentyTwo standards repository, in pull request 58, which is open (head `7a58fb4` on 2026-11-10). The record's status is "Proposed, awaiting approval": an earlier wording was approved, a review then corrected the wording, and the corrected wording has not been approved. It lists K22-TEST-10 and, in part, K22-CODE-CS-11; it states a release bar of 90 and the minimum "73 at commit `6f0237d`"; and it makes a check on real printers a condition of releasing 2.0. Until it is approved, the deviation is not covered by an approved exception. The 90% is a release bar, and since 2026-11-10 the gate holds the Windows layer above it. The recorded minimum for the Windows layer was 73 at `6f0237d` (74.84% measured). It rose to 80 with pull request 41, to 86 with pull request 42 (87.47% measured, 3,835 of 4,384 lines, on its reviewed head) and to 87 with pull request 49. It is 95 with the change that put the update installer, the update service, the service controls and the pipe-peer check behind tested seams (plan step 8 of the build), which measured between 96.06% and 96.14% over four runs (4,539 to 4,543 of 4,725 lines). 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. @@ -32,7 +32,7 @@ The native printing API, wire payload and WebSocket subprotocol do not change: e One LocalSystem service holding credentials for several servers has a larger blast radius than one. Isolation between connections is a security boundary and belongs in the [threat model](../security/threat-model.md) before the multi-server service merges. -Until the release bar is reached, a green gate means "no worse than the recorded minimum", not "fully covered". +Until an assembly's release bar is reached, a green gate means "no worse than the recorded minimum", not "fully covered". Every gated assembly has now reached its bar, the Windows layer last, on 2026-11-10. For the Windows layer a green gate still does not mean "fully covered": its bar is 90, and what is not covered is the excluded adapters and the lines the coverage report lists. ## Release condition: the hardware check diff --git a/docs/adr/0004-multi-server-runtime.md b/docs/adr/0004-multi-server-runtime.md index 8b25cc4..381fa5d 100644 --- a/docs/adr/0004-multi-server-runtime.md +++ b/docs/adr/0004-multi-server-runtime.md @@ -375,6 +375,35 @@ The journal's schema version and its one-time migration (plan step 5 of the buil - The consequence, stated plainly: after version 1 no journal has rows without a scope. The later step that introduces several servers will find none, and needs no rule for them. Rows adopted under a readable pairing become that pairing's rows, which are the first server's after the upgrade, and cannot be told apart afterwards from rows that pairing wrote itself. Rows adopted under the unpaired name or an "unreadable" name belong to no server, as the earlier sentence says of those names. - Considered and not taken: taking the adoption out of version 1, so that the rows stay under no scope until the step that introduces several servers assigns them to no server. It would hide jobs that every build since `v0.1.6-rc.1` shows on the same journal, and the only journals it would treat differently are ones no 1.x release leaves behind. +## Recorded while reviewing the update and pipe-peer seams, 2026-11-10 + +The update installer, the update service, the service controls and the pipe-peer check were put behind tested seams (plan step 8 of the build) and reviewed independently before they merged. The review changed no decision of this record. It found a constraint on a later step that this record did not state. It is recorded here on 2026-11-10, from that review and from reading the 1.2.1 source. It is a finding about released code and not a decision, and nothing in it was run. + +**An upgrade from 1.2.x is finished by the updater of 1.2.x.** When an installed 1.2.x updates itself to 2.0, the code that runs is its own: its companion downloads the 2.0 MSI, and a copy of its command line tool, the helper, starts Windows Installer and finishes the update after the 2.0 files are in place. 2.0 therefore has to satisfy what that helper does after the installer exits. An MSI installed by hand runs no helper. Read at tag `v1.2.1` with `git show`: `MsiUpdateInstaller.Apply.cs`, `MsiUpdateInstaller.Paths.cs`, `AgentPipeClient.cs`, `AgentPipePeer.cs`, `AgentPipeFraming.cs` and `PipeRequest.cs` under `src/Qqq.PrintAgent.Windows`, each identical at `v1.2.0`. + +After Windows Installer exits, the 1.2.1 helper does four things in this order. The last three are each attempted whatever came before, and a failure in any of them is swallowed. + +1. Only after exit code 0, it reads the product version of `App\Qqq.PrintAgent.exe`, `Service\Qqq.PrintAgent.Service.exe` and `Cli\qqq-print-agent.exe` under `%ProgramFiles%\QQQ Print Agent`. Each must be readable and carry the requested release in front of any `+`, and the three version strings must be identical, build metadata included. If not, the helper reports the update as failed, with exit code 1, although 2.0 is installed. +2. It writes the outcome to `%ProgramData%\QqqPrintAgent\updates\last-result.json` (the time, the release, the exit code and a message), after its own check that the machine state folder is protected, and writes one line to the machine activity log. The 2.0 companion shows that outcome when it reopens. +3. It sends one request to the service, `resume-after-update`, and waits for one line in answer. This is the only request it sends after the installer exits. It connects to the pipe named `QqqPrintAgent`, waiting three seconds at most. Before it sends anything it runs the 1.2.1 peer check: the service named `QqqPrintAgent` must be running and hosted by the process that serves the pipe, and that process must run as SYSTEM from `%ProgramFiles%\QQQ Print Agent\Service\Qqq.PrintAgent.Service.exe`. The request is one line in the version 1 form, UTF-8, ended by a line feed. As 1.2.1's `PipeRequest` and its JSON options write it, the line is `{"operation":"resume-after-update","confirmDuplicateRisk":false,"claimLegacyDevice":false,"startNewPairing":false}`. The answer is read up to its line feed, within 35 seconds for the whole exchange, and its content is ignored. +4. It starts `%ProgramFiles%\QQQ Print Agent\App\Qqq.PrintAgent.exe` with no arguments, in that program's own folder, after checking that the path holds no link and that the file and every folder up to Program Files have a trusted owner and access list. + +What 2.0 must keep for that helper: + +- The three programs at those three paths, each carrying the release as its product version, with identical build metadata. Otherwise a completed upgrade is reported to the operator as failed. +- A service named `QqqPrintAgent` that runs as SYSTEM from that service path and serves a pipe named `QqqPrintAgent`. Otherwise the helper's peer check refuses and the request is never sent. +- An answer to the version 1 request `resume-after-update`: a pause that is in force is lifted, and one line comes back. The step that retires version 1 of the pipe must keep answering this one request in its version 1 form for as long as an upgrade from 1.2.x is supported. The helper sends nothing else after the installer exits. +- The form of `last-result.json`, which the 2.0 companion reads. + +What an unanswered request costs, as read at `v1.2.1` and at the head of that step: + +- The review expected printing to stay paused after the upgrade until the pause expires, which is ten minutes. The code does not bear that out for a service the installer has replaced. The pause is a field of the running service process (`_updatePauseUntil`, in 1.2.1 and here) and is not stored, and the installer stops the old process and starts the new one (`ServiceControl` with `Stop="both"` in `installer/Package.wxs`). A 2.0 service that the installer started begins without a pause, whether or not it answers. +- The expectation becomes true as soon as a later step stores the pause or keeps the service process across an update. The request is then the only thing that lifts the pause before it expires. +- Where the paused 1.2.x process survives the installer, as after an install that failed or was cancelled before the service was stopped, it is the 1.2.x service that answers. +- What is certain today is smaller. A 2.0 service that accepts the connection and neither answers with a line nor closes it holds the helper for up to 35 seconds before the companion is reopened. + +The qualification of the upgrade from 1.2.x, which is open in `docs/TODO.md`, has to run a real 1.2.1 installation's own update to a 2.0 build and look at each of the four steps. + ## Decisions taken while working, per the owner's direction About the runtime: diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 8779383..78b1831 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -121,10 +121,12 @@ Unit/integration fixtures must cover fixed-origin/asset validation, channel/vers The bounded request captures MSI hash/version and the exact parent companion PID/start time. The helper must be running from that staged copy, requires an administrator, and waits at most 30 seconds for the expected installed companion to exit; it never kills it. A verified MSI read handle disallows writes/deletion while Windows Installer runs. Installer arguments use structured `/i`, `/passive`, `/norestart` and a protected `/L*v` log path; the helper waits for Windows Installer without terminating it. -Exit 0 is accepted only when the actual installed companion ProductVersion matches the requested release, ignoring build metadata. Exit 3010 explicitly requires Windows restart and is not reported as fully active; cancellation and other failures are distinct. The helper atomically records a bounded, dated `updates/last-result.json`, writes the shared AppKit log, attempts to clear maintenance pause, and attempts to relaunch the fixed installed companion. The UI can read the last outcome after handoff, when the original coordinator no longer exists. If relaunch fails, protected result/install logs remain for diagnosis. +Exit 0 is accepted only when the actual installed companion, service and command line tool each carry a ProductVersion that matches the requested release, ignoring build metadata, and the three carry the same version including its build metadata. Exit 3010 explicitly requires Windows restart and is not reported as fully active; cancellation and other failures are distinct. The helper atomically records a bounded, dated `updates/last-result.json`, writes the shared AppKit log, attempts to clear maintenance pause, and attempts to relaunch the fixed installed companion. The UI can read the last outcome after handoff, when the original coordinator no longer exists. If relaunch fails, protected result/install logs remain for diagnosis. The runtime's update pause is bounded and keeps heartbeats alive; abandoned handoff does not permanently stop claims. Failed pre-handoff stages are cleaned by the adapter after path checks. Completed stages/helper copies/install logs are retained for administrator review; automatic update-stage retention is not claimed. Pure tests cover request/path/ACL/hash/exit/version policy without invoking an installer; the gate owner reported all 163 tests passing (36 Core + 127 Windows/CLI), locked restore and zero build warnings/errors. This includes synthetic helper tests, not real MSI application or installed UI acceptance. +From 2.0 the steps themselves run in tests, not only their pure rules. The staging checks, the preparation, the hand-off and the apply step (`MsiUpdateSteps`) run in temporary folders against fakes of the folder security and of the processes, and the companion's update flow (`MsiUpdateService`) runs over them with a fake release source and pipe. Each check that guards which file is run (who asks, location, links, owner and access list, size, extension, release, request fields, hash, the helper's own location, the companion's identity) has a test that shows the refusal and that no helper or installer was started; the installer's command line and the held MSI handle are observed at the moment of the start; exit 0 is accepted only when the installed companion, service and command line tool all carry the requested release; and resuming printing and reopening the companion are shown to be attempted whatever happened, with the outcome recorded whenever the helper has the rights to record it. The installer in those tests is a process of the fake. Nothing here starts Windows Installer, so real MSI application, the helper's file locks and installed UI acceptance remain separate qualification, as above. + ### Metadata, history and deployment branding (0.1.5) Local administrators can edit bounded device/printer presentation metadata through the existing protected management pipe. Physical queue identities and Windows destinations remain unchanged. Metadata is machine-local, synchronized under the existing scoped device credential, and displayed as text by the native QQQ UI. The management request limit is 64 Ki characters to accommodate JSON-escaped Unicode descriptions. @@ -139,6 +141,8 @@ Shared Start menu directories use a separate shortcut policy: deletion-only righ Every management client authenticates the connected pipe's process against the installed SCM service PID, LocalSystem identity and fixed installed executable before transmitting request bytes. Retained service/process/token handles and repeated identity checks limit PID-reuse races. Clients request only explicit read/write rights with Anonymous impersonation; the runtime retains one protected first-instance pipe across requests. A substitute endpoint must receive no enrollment code or other command data. +From 2.0 that decision (`AgentPipePeer`) is tested against a fake of the facts it rests on, once for each way the other end is not the service: a service that is not running, one hosted by another process than the one serving the pipe, a pipe served by no process, a process that is not SYSTEM or runs another program, a pipe or a service that names another process when asked a second time, and each fact that cannot be read. A check that could not be carried out is a refusal, and so is a process that cannot be looked at; only a pipe that can no longer say who serves it, or a process that is certainly gone, turns the answer into "the service stopped, try again". The readers of the real facts are tested against a pipe the test serves itself, the test process, a harmless child program and a read-only status query of a built-in Windows service. Two of the properties above are shown on the real readers: the process named for a pipe is the one that serves it and not the one connected to it (the test serves, a child program connects), and the process whose account was read stays held, so that its id still names it after it has ended, until the check lets it go. What the installed product's check is bound to (the Windows facts and the service program under Program Files) is a value the tests read. One thing no test without administrator rights can show, because every process such a test can open runs under the test's own account: that the account read is the peer's and not the caller's (audit W77). The client opens the print service with full access, which Windows grants only to an administrator, so a successful authentication against the installed service needs an elevated client and remains a native qualification requirement, and that requirement includes this. + Canonical machine state accepts only SYSTEM, Administrators and TrustedInstaller ownership and access grants. The initial validation covers existing descendants and rejects links, null DACLs and untrusted inherit-only grants. Existing hostile state is rejected rather than normalized and adopted. Store, log, branding, startup and updater entry points share the invariant; explicitly separate diagnostic directories remain outside machine-state adoption. Administrator changes after successful validation remain within the trusted boundary. Direct MSI and branded installation enforce this invariant before using persisted files. The deferred preflight runs before folder creation; the installation script executes before old-product removal, which remains inside the rollback transaction. Startup definitions are created within validated state, then held against write/deletion while Task Scheduler reads them; the resulting definition is verified. Actual MSI formatting, component reuse, successful installed-peer authentication and hostile-tree rollback are separate native qualification requirements, not conclusions from unit tests. diff --git a/src/Qqq.PrintAgent.Windows/AgentPipeClient.cs b/src/Qqq.PrintAgent.Windows/AgentPipeClient.cs index 7a160ba..f8525a6 100644 --- a/src/Qqq.PrintAgent.Windows/AgentPipeClient.cs +++ b/src/Qqq.PrintAgent.Windows/AgentPipeClient.cs @@ -76,7 +76,7 @@ public static class AgentPipeClient using var connectTimeout = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token); connectTimeout.CancelAfter(connectLimit ?? s_connectLimit); await pipe.ConnectAsync(connectTimeout.Token).ConfigureAwait(false); - using IDisposable peer = (verify ?? AgentPipePeer.Authenticate)(pipe.SafePipeHandle); + using IDisposable peer = (verify ?? AgentPipePeer.Installed.Authenticate)(pipe.SafePipeHandle); writing?.Invoke(); await AgentPipeFraming.WriteAsync(pipe, command, AgentPipeFraming.MaximumCommandCharacters, timeout.Token).ConfigureAwait(false); return await AgentPipeFraming.ReadAsync(pipe, AgentPipeFraming.MaximumResponseCharacters, timeout.Token).ConfigureAwait(false); diff --git a/src/Qqq.PrintAgent.Windows/AgentPipePeer.cs b/src/Qqq.PrintAgent.Windows/AgentPipePeer.cs index 492ea06..1f84a2e 100644 --- a/src/Qqq.PrintAgent.Windows/AgentPipePeer.cs +++ b/src/Qqq.PrintAgent.Windows/AgentPipePeer.cs @@ -4,84 +4,106 @@ */ using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Principal; -using System.ServiceProcess; using Microsoft.Win32.SafeHandles; namespace Qqq.PrintAgent.Windows; -/// Authenticates the connected kernel pipe instance before any request bytes are sent. +/// +/// Authenticates the connected kernel pipe instance before any request bytes are sent. The decision is made here; the +/// facts it is made from (which process serves the pipe, what the service control manager says, what the process is) +/// come through , so each way the other end can fail to be the service is run against a fake. +/// internal sealed class AgentPipePeer : IDisposable { - private readonly ServiceController _service; - private readonly Process _process; - private readonly WindowsIdentity _identity; + /// The name the MSI registers the print service under. + private const string ServiceName = "QqqPrintAgent"; - /// Holds the verified service controller, process handle and identity so they live as long as the connection that relies on them. - private AgentPipePeer(ServiceController service, Process process, WindowsIdentity identity) + /// The state Windows reports for a service that is running. + private const uint ServiceRunning = 4; + + + + /// + /// The check of the installed product: the real Windows facts and the service program at its fixed machine-wide + /// install path. The pipe client authenticates with this value itself, and no member stands between the two that + /// could pass facts or a program of its own, so what the installed product trusts is this one value, which a test + /// reads. + /// + internal static Check Installed { get; } = new(new WindowsPipePeerFacts(), InstalledService); + + + + /// The verified service, held as long as the connection that relies on it. + private readonly IPeerService _service; + + + + /// The verified process, held open so its id cannot be reused while the connection lives. + private readonly IPeerProcess _process; + + + + /// Holds the verified service and process so they live as long as the connection that relies on them. + private AgentPipePeer(IPeerService service, IPeerProcess process) { _service = service; _process = process; - _identity = identity; } + /// The service executable at its fixed machine-wide install path; a process running any other program is not the service. + internal static string InstalledService => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "QQQ Print Agent", "Service", "Qqq.PrintAgent.Service.exe"); + + + /// /// Proves the process at the far end of the pipe really is the installed print service before the client sends anything. /// The Windows service must be running with exactly the pipe server's process id, the process must run as SYSTEM from the /// installed service executable, and the id is read again afterwards so a swap during the checks is detected. Holding the /// process handle open blocks id reuse. Any doubt throws one exception type and everything acquired is released, so every - /// caller sees "not verified, nothing sent" the same way; chooses what the operator is told. + /// caller sees "not verified, nothing sent" the same way; chooses what the operator is told. /// - internal static AgentPipePeer Authenticate(SafePipeHandle pipe) + internal static AgentPipePeer Authenticate(SafePipeHandle pipe, IPipePeerFacts facts, string installedService) { - ServiceController service = new("QqqPrintAgent"); - Process? process = null; - WindowsIdentity? identity = null; + IPeerService service = facts.OpenService(ServiceName); + IPeerProcess? process = null; uint? server = null; try { - uint pid = ServerProcessId(pipe); + uint pid = facts.ServerProcessId(pipe); server = pid; - ServiceStatus status = ReadStatus(service); - if(status.State != 4 || status.ProcessId != pid || pid == 0) + PeerServiceStatus status = service.ReadStatus(); + if(status.State != ServiceRunning || status.ProcessId != pid || pid == 0) { throw Untrusted(); } - process = Process.GetProcessById(checked((int)pid)); - // Force acquisition of the real process handle, preventing PID reuse until disposal. - if(!OpenProcessToken(process.SafeHandle, 8, out SafeAccessTokenHandle token)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - using(token) - { - identity = new WindowsIdentity(token.DangerousGetHandle()); - } - string expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "QQQ Print Agent", "Service", "Qqq.PrintAgent.Service.exe"); - if(!identity.IsSystem || process.HasExited || !string.Equals(process.MainModule?.FileName, expected, StringComparison.OrdinalIgnoreCase) - || ServerProcessId(pipe) != pid || ReadStatus(service).ProcessId != pid) + process = facts.OpenProcess(pid); + bool system = process.RunsAsSystem(); + if(!system || process.HasExited || !string.Equals(process.ProgramPath, installedService, StringComparison.OrdinalIgnoreCase) + || facts.ServerProcessId(pipe) != pid || service.ReadStatus().ProcessId != pid) { throw Untrusted(); } - return new AgentPipePeer(service, process, identity); + return new AgentPipePeer(service, process); } catch(Exception exception) { - identity?.Dispose(); process?.Dispose(); service.Dispose(); - throw Refusal(server, exception); + throw Refusal(facts, server, exception); } } + /// What a failed check tells the operator, judged by the real processes of this computer; see the overload. + internal static UnauthorizedAccessException Refusal(uint? server, Exception found) => Installed.Refusal(server, found); + + + /// /// Chooses what a failed check tells the operator. When the process that was serving the pipe has ended (or the pipe could /// no longer say who serves it), the service stopped or restarted between the connection and the check: nothing is wrong @@ -89,9 +111,9 @@ internal sealed class AgentPipePeer : IDisposable /// installed service, and the answer is the one refusal that reveals nothing about which check failed. A check that threw /// keeps what it threw as the inner exception, for the log. /// - internal static UnauthorizedAccessException Refusal(uint? server, Exception found) + internal static UnauthorizedAccessException Refusal(IPipePeerFacts facts, uint? server, Exception found) { - if(server is not { } pid || Ended(pid)) + if(server is not { } pid || Ended(facts, pid)) { return Stopped(found); } @@ -101,11 +123,11 @@ internal sealed class AgentPipePeer : IDisposable /// Whether no running process has this id any more. A process that cannot be looked at is treated as still running, so doubt never softens the refusal. - private static bool Ended(uint pid) + private static bool Ended(IPipePeerFacts facts, uint pid) { try { - using var process = Process.GetProcessById(checked((int)pid)); + using IPeerProcess process = facts.OpenProcess(pid); return process.HasExited; } catch(Exception exception) when(exception is ArgumentException or InvalidOperationException or Win32Exception or OverflowException) @@ -134,73 +156,37 @@ internal sealed class AgentPipePeer : IDisposable - /// Asks the kernel which process serves this pipe instance; the answer cannot be forged by a process that merely uses the pipe's name. - private static uint ServerProcessId(SafePipeHandle pipe) - { - if(!GetNamedPipeServerProcessId(pipe, out uint pid)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - return pid; - } - - - - /// Reads the service's current state and process id from the service control manager. - private static ServiceStatus ReadStatus(ServiceController service) - { - if(!QueryServiceStatusEx(service.ServiceHandle, 0, out ServiceStatus status, Marshal.SizeOf(), out _)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - return status; - } - - - - /// Releases the identity, the process handle (which allows the id to be reused) and the service controller. + /// Releases the process handle (which allows the id to be reused) and the service. public void Dispose() { - _identity.Dispose(); _process.Dispose(); _service.Dispose(); } - /// SERVICE_STATUS_PROCESS as returned by QueryServiceStatusEx; the layout is marshaled and must not change. - [StructLayout(LayoutKind.Sequential)] - private struct ServiceStatus + /// + /// A check bound to where its facts come from and to the one program it trusts as the service. The installed product + /// has one, ; a test makes its own over a fake. + /// + internal sealed class Check(IPipePeerFacts facts, string serviceProgram) { - internal uint Type; - internal uint State; - internal uint Controls; - internal uint ExitCode; - internal uint ServiceExitCode; - internal uint CheckPoint; - internal uint WaitHint; - internal uint ProcessId; - internal uint Flags; + /// Where this check's facts come from. + internal IPipePeerFacts Facts => facts; + + + + /// The one program this check trusts as the service. + internal string ServiceProgram => serviceProgram; + + + + /// Proves that the far end of the pipe is the service this check is bound to; says what is checked. + internal AgentPipePeer Authenticate(SafePipeHandle pipe) => AgentPipePeer.Authenticate(pipe, facts, serviceProgram); + + + + /// What a failed check tells the operator, judged by this check's facts; says how. + internal UnauthorizedAccessException Refusal(uint? server, Exception found) => AgentPipePeer.Refusal(facts, server, found); } - - - - /// Returns the id of the process that created the server end of a named pipe. - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint processId); - - - - /// Queries the extended status of a service, including the id of the process hosting it. - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool QueryServiceStatusEx(SafeHandle service, int level, out ServiceStatus status, int size, out int needed); - - - - /// Opens the access token of a process so its account can be verified as SYSTEM. - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token); } diff --git a/src/Qqq.PrintAgent.Windows/AgentServiceActions.cs b/src/Qqq.PrintAgent.Windows/AgentServiceActions.cs new file mode 100644 index 0000000..54e9f8d --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/AgentServiceActions.cs @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.ServiceProcess; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The local administrator actions on one Windows service and what they tell the operator: how a state reads, what can +/// be offered in it, when the service is started or stopped and how long it is waited for. The service control manager +/// comes through , the Services console is started through and +/// the wait runs on the given clock, so every action can be run against fakes without touching a service. +/// +internal sealed class AgentServiceActions(IServiceManager services, IProcessHost processes, TimeProvider clock, string serviceName) +{ + /// How long a start or a stop is waited for before the action gives up, so a stuck service stops the action instead of hanging the window. + internal static readonly TimeSpan WaitLimit = TimeSpan.FromSeconds(30); + + + + /// How long the wait pauses between two looks at the service. + internal static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(250); + + + + /// The Windows error for a service name that no installed service has. + private const int ServiceDoesNotExist = 1060; + + + + /// The name of the service these actions are for. + internal string ServiceName => serviceName; + + + + /// Read service state even when the print management pipe is unavailable. + internal AgentServiceStatus GetStatus() + { + try + { + using IManagedService service = services.Open(serviceName); + ServiceControllerStatus state = service.Status; + return new AgentServiceStatus(true, state.ToString(), state == ServiceControllerStatus.Stopped, + state == ServiceControllerStatus.Running && service.CanStop, + state == ServiceControllerStatus.Stopped ? "Start the service to connect and print." : "The Windows service runs independently of this companion."); + } + catch(InvalidOperationException exception) when(exception.InnerException is Win32Exception { NativeErrorCode: ServiceDoesNotExist }) + { + return new AgentServiceStatus(false, "Not installed", false, false, "Install the QQQ Print Agent MSI from the project releases, then reopen this app. Windows Services can confirm the installation."); + } + catch(Exception exception) when(exception is InvalidOperationException or Win32Exception) + { + return new AgentServiceStatus(false, "Unavailable", false, false, "Windows could not read the service state. Use an administrator account and check Windows Services."); + } + } + + + + /// Start an installed stopped service and wait at most 30 seconds. + internal async Task StartAsync() + { + using IManagedService service = services.Open(serviceName); + if(service.Status == ServiceControllerStatus.Stopped) + { + service.Start(); + } + await WaitAsync(service, ServiceControllerStatus.Running).ConfigureAwait(false); + return GetStatus(); + } + + + + /// Restart only after an explicit administrator action; callers must warn about active submissions. + internal async Task RestartAsync() + { + using IManagedService service = services.Open(serviceName); + if(service.Status != ServiceControllerStatus.Stopped) + { + service.Stop(); + await WaitAsync(service, ServiceControllerStatus.Stopped).ConfigureAwait(false); + } + service.Start(); + await WaitAsync(service, ServiceControllerStatus.Running).ConfigureAwait(false); + return GetStatus(); + } + + + + /// Open the native Services console on explicit user request. + internal void OpenServices() + { + ProcessStartInfo start = new(Path.Combine(Environment.SystemDirectory, "mmc.exe")) { UseShellExecute = true }; + start.ArgumentList.Add(Path.Combine(Environment.SystemDirectory, "services.msc")); + using IRunningProcess? process = processes.Start(start); + } + + + + /// Polls the service every 250 ms until it reaches the wanted state, giving up with a clear message after 30 seconds, so a stuck service stops the action instead of hanging the window. + private async Task WaitAsync(IManagedService service, ServiceControllerStatus desired) + { + long started = clock.GetTimestamp(); + while(true) + { + service.Refresh(); + if(service.Status == desired) + { + return; + } + if(clock.GetElapsedTime(started) >= WaitLimit) + { + throw new System.TimeoutException("The service did not reach " + desired + " within 30 seconds. Check Windows Services and the activity log."); + } + await Task.Delay(PollInterval, clock).ConfigureAwait(false); + } + } +} diff --git a/src/Qqq.PrintAgent.Windows/AgentServiceControl.cs b/src/Qqq.PrintAgent.Windows/AgentServiceControl.cs index 77ba36c..042361a 100644 --- a/src/Qqq.PrintAgent.Windows/AgentServiceControl.cs +++ b/src/Qqq.PrintAgent.Windows/AgentServiceControl.cs @@ -3,99 +3,46 @@ * SPDX-License-Identifier: MIT */ -using System.ComponentModel; -using System.Diagnostics; -using System.ServiceProcess; - +using System.Diagnostics.CodeAnalysis; namespace Qqq.PrintAgent.Windows; -/// Explicit local administrator actions for the fixed installed print service. +/// +/// Explicit local administrator actions for the fixed installed print service. This class is the entry point for the +/// installed product: it applies the actions in to the real service control manager, +/// the real processes, the system clock and the installed service's name, and holds no rule of its own. +/// public static class AgentServiceControl { + /// The name the MSI registers the print service under. private const string ServiceName = "QqqPrintAgent"; + /// The actions bound to the real service control manager, the real processes, the system clock and the installed service's name. + internal static AgentServiceActions Installed { get; } = new(new WindowsServiceManager(), new WindowsProcessHost(), TimeProvider.System, ServiceName); + + + /// Read service state even when the print management pipe is unavailable. - public static AgentServiceStatus GetStatus() - { - try - { - using ServiceController service = new(ServiceName); - ServiceControllerStatus state = service.Status; - return new AgentServiceStatus(true, state.ToString(), state == ServiceControllerStatus.Stopped, - state == ServiceControllerStatus.Running && service.CanStop, - state == ServiceControllerStatus.Stopped ? "Start the service to connect and print." : "The Windows service runs independently of this companion."); - } - catch(InvalidOperationException exception) when(exception.InnerException is Win32Exception { NativeErrorCode: 1060 }) - { - return new AgentServiceStatus(false, "Not installed", false, false, "Install the QQQ Print Agent MSI from the project releases, then reopen this app. Windows Services can confirm the installation."); - } - catch(Exception exception) when(exception is InvalidOperationException or Win32Exception) - { - return new AgentServiceStatus(false, "Unavailable", false, false, "Windows could not read the service state. Use an administrator account and check Windows Services."); - } - } + [ExcludeFromCodeCoverage(Justification = "Reads the state of the print service installed on this computer, which differs from one computer to the next and which a test must not depend on. It only passes the call on; how a state reads is tested in AgentServiceActions with a fake of IServiceManager, the real adapter in WindowsServiceManagerTests against a built-in service, and the service name bound here in AgentServiceActionsTests.")] + public static AgentServiceStatus GetStatus() => Installed.GetStatus(); /// Start an installed stopped service and wait at most 30 seconds. - public static async Task StartAsync() - { - using ServiceController service = new(ServiceName); - if(service.Status == ServiceControllerStatus.Stopped) - { - service.Start(); - } - await WaitAsync(service, ServiceControllerStatus.Running).ConfigureAwait(false); - return GetStatus(); - } + [ExcludeFromCodeCoverage(Justification = "Starts the print service installed on this computer, which a test must never do. It only passes the call on; when the service is started and how long it is waited for is tested in AgentServiceActions with a fake of IServiceManager and a manual clock, and the service name bound here in AgentServiceActionsTests.")] + public static Task StartAsync() => Installed.StartAsync(); /// Restart only after an explicit administrator action; callers must warn about active submissions. - public static async Task RestartAsync() - { - using ServiceController service = new(ServiceName); - if(service.Status != ServiceControllerStatus.Stopped) - { - service.Stop(); - await WaitAsync(service, ServiceControllerStatus.Stopped).ConfigureAwait(false); - } - service.Start(); - await WaitAsync(service, ServiceControllerStatus.Running).ConfigureAwait(false); - return GetStatus(); - } + [ExcludeFromCodeCoverage(Justification = "Stops and starts the print service installed on this computer, which a test must never do. It only passes the call on; the order of the stop and the start and how long each is waited for is tested in AgentServiceActions with a fake of IServiceManager and a manual clock, and the service name bound here in AgentServiceActionsTests.")] + public static Task RestartAsync() => Installed.RestartAsync(); /// Open the native Services console on explicit user request. - public static void OpenServices() - { - ProcessStartInfo start = new(Path.Combine(Environment.SystemDirectory, "mmc.exe")) { UseShellExecute = true }; - start.ArgumentList.Add(Path.Combine(Environment.SystemDirectory, "services.msc")); - using var process = Process.Start(start); - } - - - - /// Polls the service every 250 ms until it reaches the wanted state, giving up with a clear message after 30 seconds, so a stuck service stops the action instead of hanging the window. - private static async Task WaitAsync(ServiceController service, ServiceControllerStatus desired) - { - long started = Stopwatch.GetTimestamp(); - while(true) - { - service.Refresh(); - if(service.Status == desired) - { - return; - } - if(Stopwatch.GetElapsedTime(started) >= TimeSpan.FromSeconds(30)) - { - throw new System.TimeoutException("The service did not reach " + desired + " within 30 seconds. Check Windows Services and the activity log."); - } - await Task.Delay(250).ConfigureAwait(false); - } - } + [ExcludeFromCodeCoverage(Justification = "Opens the Services console on the desktop of this computer, which asks for elevation and stays open; a test must not. It only passes the call on; which program is started with which argument is tested in AgentServiceActions with a fake of IProcessHost, and starting a program in WindowsProcessHostTests with a harmless child program.")] + public static void OpenServices() => Installed.OpenServices(); } diff --git a/src/Qqq.PrintAgent.Windows/GitHubMsiReleaseClient.cs b/src/Qqq.PrintAgent.Windows/GitHubMsiReleaseClient.cs index f220095..1835298 100644 --- a/src/Qqq.PrintAgent.Windows/GitHubMsiReleaseClient.cs +++ b/src/Qqq.PrintAgent.Windows/GitHubMsiReleaseClient.cs @@ -13,7 +13,7 @@ using System.Text.Json; namespace Qqq.PrintAgent.Windows; /// Discovers only this application's releases and stages an integrity-checked machine MSI. -public sealed class GitHubMsiReleaseClient : IDisposable +public sealed class GitHubMsiReleaseClient : IMsiReleaseSource { private const long MaximumMsiBytes = 256L * 1024 * 1024; private const int MaximumMetadataBytes = 2 * 1024 * 1024; diff --git a/src/Qqq.PrintAgent.Windows/IManagedService.cs b/src/Qqq.PrintAgent.Windows/IManagedService.cs new file mode 100644 index 0000000..52fde31 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IManagedService.cs @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ServiceProcess; + +namespace Qqq.PrintAgent.Windows; + +/// +/// One Windows service held by name: its state as last read, and the two controls the companion offers. The state is +/// read from Windows once and then remembered, so and describe the same +/// moment until forgets it. Every member that asks Windows fails with +/// carrying Windows' own error when Windows refuses, for a service that does not +/// exist (error 1060) as for one the caller may not control. +/// +internal interface IManagedService : IDisposable +{ + /// The service's state, read from Windows on first use and remembered until . + ServiceControllerStatus Status { get; } + + + + /// Whether the service accepts a stop request in that same remembered state. + bool CanStop { get; } + + + + /// Forgets the remembered state, so the next read asks Windows again. + void Refresh(); + + + + /// Asks Windows to start the service and returns without waiting for it to run. + void Start(); + + + + /// Asks Windows to stop the service and returns without waiting for it to stop. + void Stop(); +} diff --git a/src/Qqq.PrintAgent.Windows/IMsiReleaseSource.cs b/src/Qqq.PrintAgent.Windows/IMsiReleaseSource.cs new file mode 100644 index 0000000..b74bbee --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IMsiReleaseSource.cs @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Windows; + +/// +/// Where the update service finds a newer release and gets its installer from. The installed product uses +/// , which reads the fixed release feed and verifies what it downloads; a test +/// passes a source of its own, so the update flow can be run without the network. Which release is eligible and +/// whether the downloaded bytes are the release's is decided by the source; what happens before and after is decided +/// by . +/// +internal interface IMsiReleaseSource : IDisposable +{ + /// The newest eligible release that is newer than the given version, or null when there is none. + Task FindUpdateAsync(string currentVersion, CancellationToken cancellationToken = default); + + + + /// + /// Downloads the release's installer into the given staging folder, verifies it, and returns the path of the verified + /// file, reporting progress as a fraction of the whole. A download that fails leaves no installer behind. + /// + Task DownloadVerifiedAsync(MsiRelease release, string currentVersion, string stagingDirectory, IProgress? progress = null, CancellationToken cancellationToken = default); +} diff --git a/src/Qqq.PrintAgent.Windows/IPeerProcess.cs b/src/Qqq.PrintAgent.Windows/IPeerProcess.cs new file mode 100644 index 0000000..2b25977 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IPeerProcess.cs @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Windows; + +/// +/// One process held for the pipe client's trust decision. Once has been asked, the process +/// itself is held open until this is disposed, so its id cannot be given to another process while the connection that +/// relies on the decision lives. +/// +internal interface IPeerProcess : IDisposable +{ + /// + /// Opens the process and its access token and says whether it runs as the SYSTEM account. It fails with what Windows + /// reported when the process or its token may not be opened. + /// + bool RunsAsSystem(); + + + + /// True once the process has ended. + bool HasExited { get; } + + + + /// The full path of the program the process runs, or null when it has no main module. Reading it fails with what Windows reported when the process may not be inspected or has ended. + string? ProgramPath { get; } +} diff --git a/src/Qqq.PrintAgent.Windows/IPeerService.cs b/src/Qqq.PrintAgent.Windows/IPeerService.cs new file mode 100644 index 0000000..58a3bfc --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IPeerService.cs @@ -0,0 +1,16 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Windows; + +/// One Windows service held for the pipe client's trust decision, as long as the connection that relies on it lives. +internal interface IPeerService : IDisposable +{ + /// + /// What the service control manager says now: the service's state and the id of the process hosting it. It fails + /// with what Windows reported when the service does not exist or the caller may not open it. + /// + PeerServiceStatus ReadStatus(); +} diff --git a/src/Qqq.PrintAgent.Windows/IPipePeerFacts.cs b/src/Qqq.PrintAgent.Windows/IPipePeerFacts.cs new file mode 100644 index 0000000..dabca74 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IPipePeerFacts.cs @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Microsoft.Win32.SafeHandles; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The Windows facts the pipe client's trust decision rests on: which process serves a pipe, what the service control +/// manager says about a service, and a process to be looked at. An implementation only asks Windows and passes on what +/// it said, failures included; whether those facts add up to "the installed print service" is decided by +/// . +/// +internal interface IPipePeerFacts +{ + /// The id of the process that serves this pipe instance, as the kernel records it. It fails with what Windows reported when the pipe can no longer say. + uint ServerProcessId(SafePipeHandle pipe); + + + + /// Takes hold of the service with the given name. Nothing is asked of Windows yet; a name no service has is refused by the first read. + IPeerService OpenService(string serviceName); + + + + /// + /// Takes hold of the running process with the given id. It throws when no running + /// process has that id, and for an id a process cannot have. + /// + IPeerProcess OpenProcess(uint processId); +} diff --git a/src/Qqq.PrintAgent.Windows/IProcessHost.cs b/src/Qqq.PrintAgent.Windows/IProcessHost.cs new file mode 100644 index 0000000..debf6de --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IProcessHost.cs @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The processes of this computer as the update and service-control rules need them: which program is running the +/// rules, a process found by its id, a program started, and the version a program file carries. An implementation only +/// asks Windows and reports what it said; which program may be started, with what arguments, whose identity is +/// accepted and what an exit code means is decided by the callers ( and +/// ). +/// +internal interface IProcessHost +{ + /// The full path of the program the current process runs, or null when Windows cannot say. + string? CurrentPath { get; } + + + + /// The id of the current process. + int CurrentId { get; } + + + + /// + /// Takes hold of the running process with the given id. It throws when no process + /// has that id, as Windows reports it; what that means is the caller's decision. + /// + IRunningProcess Open(int processId); + + + + /// + /// Starts a program exactly as the start information says and returns the new process, or null when Windows started + /// nothing new. A program that does not exist or that Windows refuses to run fails with what Windows reported. + /// + IRunningProcess? Start(ProcessStartInfo start); + + + + /// The product version recorded in a program file, or null when the file carries none; a file that cannot be read fails with what Windows reported. + string? ProductVersion(string path); +} diff --git a/src/Qqq.PrintAgent.Windows/IRunningProcess.cs b/src/Qqq.PrintAgent.Windows/IRunningProcess.cs new file mode 100644 index 0000000..75ba753 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IRunningProcess.cs @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Windows; + +/// +/// One process the rules hold on to: what identifies it (the program it runs and when it started), whether it has +/// ended, and how it ended. Holding it keeps the answers about that one process, whatever else is started meanwhile. +/// It can be waited for and is never ended through this interface. +/// +internal interface IRunningProcess : IDisposable +{ + /// True once the process has ended. + bool HasExited { get; } + + + + /// The full path of the program the process runs, or null when it has no main module. Reading it fails with what Windows reported when the process may not be inspected or has ended. + string? ProgramPath { get; } + + + + /// When the process started, in universal time ticks. Together with the id it names one process: an id is reused, a start time with it is not. + long StartTicks { get; } + + + + /// The code the process ended with; only meaningful once it has ended. + int ExitCode { get; } + + + + /// Waits until the process has ended or the token is cancelled, which ends the wait with the cancellation and leaves the process running. + Task WaitForExitAsync(CancellationToken cancellationToken); +} diff --git a/src/Qqq.PrintAgent.Windows/IServiceManager.cs b/src/Qqq.PrintAgent.Windows/IServiceManager.cs new file mode 100644 index 0000000..e7e2e36 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/IServiceManager.cs @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +namespace Qqq.PrintAgent.Windows; + +/// +/// The Windows service control manager as the service actions need it: a way to take hold of one service by name. An +/// implementation only asks Windows and passes on what it said; what a state means for the operator, when a service is +/// started or stopped and how long it is waited for is decided by . +/// +internal interface IServiceManager +{ + /// + /// Takes hold of the service with the given name. Nothing is asked of Windows yet, so a name no service has is not + /// refused here but by the first read or control made through the result. + /// + IManagedService Open(string serviceName); +} diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Apply.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Apply.cs index 0777767..014164b 100644 --- a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Apply.cs +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Apply.cs @@ -6,113 +6,17 @@ using System.Diagnostics; using System.Globalization; using System.Security.Cryptography; -using System.Text.Json; -using Qqq.PrintAgent.Core.Printing; namespace Qqq.PrintAgent.Windows; /// -/// Applying part of the updater, which runs only inside the staged helper copy. It re-verifies the request, waits for the -/// companion that asked to close, installs the verified MSI with Windows Installer, checks that all three installed programs -/// carry the requested release, records the outcome, and reopens the companion. It never kills a process or an installer. +/// The rules of the applying step that need nothing from Windows but a file: verifying and holding the staged MSI, the +/// command line Windows Installer is started with, what its exit code means and when an installed version matches. The +/// step itself, which starts the installer and runs only inside the staged helper copy, is +/// . /// public static partial class MsiUpdateInstaller { - /// Runs only inside the protected copied helper; never kills an installer or an application. - public static async Task ApplyAsync(string requestPath) - { - int code = 1; - string message; - string version = "unknown"; - try - { - RequireAdministrator(); - InstallRequest request = ReadRequest(requestPath); - version = request.Version; - string directory = Path.GetDirectoryName(Path.GetFullPath(requestPath))!; - string helper = Path.Combine(directory, "helper", "qqq-print-agent.exe"); - if(!string.Equals(Environment.ProcessPath, helper, StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidOperationException("Apply must run from the verified staged helper copy."); - } - ValidateStagedFile(helper); - await WaitForCompanionExitAsync(request).ConfigureAwait(false); - // Retain this non-writable/non-deletable handle until Windows Installer exits. - using FileStream packageLock = OpenVerifiedPackage(request.PackagePath, request.Sha256); - string installLog = Path.Combine(directory, "install.log"); - ValidateNoReparseComponents(installLog); - ProcessStartInfo start = CreateInstallerStart(request.PackagePath, installLog); - using Process installer = Process.Start(start) ?? throw new InvalidOperationException("Windows Installer could not start."); - await installer.WaitForExitAsync().ConfigureAwait(false); - code = installer.ExitCode; - if(code == 0) - { - ValidateInstalledVersions(request.Version, path => FileVersionInfo.GetVersionInfo(path).ProductVersion); - } - message = DescribeExitCode(code); - } - catch(Exception exception) - { - code = 1; - message = "Update failed before completion: " + AgentActivityLog.Redact(exception.Message); - } - await CompleteAsync(version, code, message).ConfigureAwait(false); - return code; - } - - - - /// - /// Waits up to 30 seconds for the companion that requested the update to exit, so its files can be replaced. It first - /// confirms the process is still the same one (same start time and the installed executable); a different process - /// aborts the update before any installer starts. It never terminates the companion, and a timeout is reported. - /// - private static async Task WaitForCompanionExitAsync(InstallRequest request) - { - Process parent; - try - { - parent = Process.GetProcessById(request.ParentProcessId); - } - catch(ArgumentException) - { - return; - } - using(parent) - { - if(parent.HasExited) - { - return; - } - string? path; - long started; - try - { - path = parent.MainModule?.FileName; - started = parent.StartTime.ToUniversalTime().Ticks; - } - catch(InvalidOperationException) when(parent.HasExited) - { - return; - } - if(started != request.ParentStartTicks || !string.Equals(path, InstalledCompanion, StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidOperationException("The expected companion process identity changed. No installer was started."); - } - using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30)); - try - { - await parent.WaitForExitAsync(timeout.Token).ConfigureAwait(false); - } - catch(OperationCanceledException exception) - { - throw new TimeoutException("The companion did not close within 30 seconds. Close it and retry the update; no process was terminated.", exception); - } - } - } - - - /// /// Opens the staged MSI for reading with sharing that blocks writes and deletes, and checks its size and SHA-256 against the /// request in constant time. The caller keeps the handle open until the installer exits, so the file cannot be swapped @@ -172,134 +76,6 @@ public static partial class MsiUpdateInstaller - /// Checks the installed payload after MSI success without assuming rollback on mismatch. - internal static void ValidateInstalledVersions(string requestedVersion, Func readProductVersion) - { - string? installedBuild = null; - foreach(string executable in new[] - { - InstalledCompanion, - Path.Combine(InstalledRoot, "Service", "Qqq.PrintAgent.Service.exe"), - Path.Combine(InstalledCli, "qqq-print-agent.exe"), - }) - { - string? version; - try - { - version = readProductVersion(executable); - } - catch(Exception exception) when(exception is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) - { - throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " version could not be verified. Inspect the installation log and repair the package.", exception); - } - if(!InstalledVersionMatches(version, requestedVersion)) - { - throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " version does not match the requested release. Inspect the installation log and repair the package."); - } - if(installedBuild is not null && !string.Equals(version, installedBuild, StringComparison.Ordinal)) - { - throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " build version is incoherent with the companion. Inspect the installation log and repair the package."); - } - installedBuild ??= version; - } - } - - - - /// - /// Finishes an update attempt in three independent best-effort steps, so a failure in one never blocks the next: record the - /// outcome and log it, tell the service to resume printing after the maintenance pause, and reopen the installed companion. - /// The installer's own log remains the evidence if any step fails. - /// - private static async Task CompleteAsync(string version, int code, string message) - { - try - { - WriteOutcome(new InstallOutcome(DateTimeOffset.UtcNow, version, code, message)); - var log = AgentActivityLog.Create(AgentStore.DefaultDirectory); - if(code is 0 or 3010) - { - log.Info("[Update] " + message); - } - else - { - log.Error("[Update] " + message); - } - } - catch(Exception) - { - // The independently preserved MSI install.log remains diagnostic evidence. - } - try - { - await AgentPipeClient.SendAsync(new PipeRequest("resume-after-update")).ConfigureAwait(false); - } - catch(Exception) - { - // An abandoned maintenance pause also expires in the service itself. - } - try - { - ValidateInstalledPath(InstalledCompanion); - using var companion = Process.Start(new ProcessStartInfo(InstalledCompanion) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(InstalledCompanion)! }); - } - catch(Exception) - { - // Operator can read the protected outcome/log and open the installed app manually. - } - } - - - - /// Saves the last update outcome by writing a temporary file in the protected folder and moving it over the previous result, so a reader never sees a half-written file. - private static void WriteOutcome(InstallOutcome outcome) - { - ValidateStagingDirectory(UpdatesDirectory); - Directory.CreateDirectory(UpdatesDirectory); - string path = Path.Combine(UpdatesDirectory, "last-result.json"); - ValidateNoReparseComponents(path); - string temporary = Path.Combine(UpdatesDirectory, "result-" + Guid.NewGuid().ToString("N") + ".tmp"); - try - { - using(FileStream stream = new(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { - JsonSerializer.Serialize(stream, outcome, PrintApiClient.JsonOptions); - stream.Flush(flushToDisk: true); - } - File.Move(temporary, path, overwrite: true); - } - finally { File.Delete(temporary); } - } - - - - /// Read-only, bounded last outcome; retained for Settings/log diagnostics rather than consumed. - public static string? ReadLastOutcomeMessage() - { - try - { - string path = Path.Combine(UpdatesDirectory, "last-result.json"); - if(!File.Exists(path)) - { - return null; - } - ValidateStagedFile(path); - if(new FileInfo(path).Length > MaximumRequestBytes) - { - return "The previous update outcome is invalid. Inspect the protected update logs."; - } - using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); - InstallOutcome? result = JsonSerializer.Deserialize(stream, PrintApiClient.JsonOptions); - return result is null ? null : result.CompletedAt.ToString("u", CultureInfo.InvariantCulture) + " — " + result.Message; - } - catch(Exception) - { - return "The previous update outcome could not be read. Inspect the protected update logs."; - } - } - - - - /// The recorded result of one update attempt: when it finished, which release it targeted, the installer's exit code and the message shown to the operator. - private sealed record InstallOutcome(DateTimeOffset CompletedAt, string Version, int ExitCode, string Message); + /// Checks the installed payload at the installed product's paths after MSI success; see . + internal static void ValidateInstalledVersions(string requestedVersion, Func readProductVersion) => Installed.ValidateInstalledVersions(requestedVersion, readProductVersion); } diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Paths.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Paths.cs index eb713fb..ef06cba 100644 --- a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Paths.cs +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.Paths.cs @@ -9,71 +9,13 @@ using System.Security.Principal; namespace Qqq.PrintAgent.Windows; /// -/// Path and permission checks of the updater. The staged files later run with administrator rights, so each path must stay -/// inside the protected folders, contain no link or junction, and be owned and writable only by trusted accounts. Every -/// failure throws; nothing is repaired automatically. +/// Path and permission rules of the updater that are decided from what they are handed: whether a path stays inside a +/// folder, whether anything on the way to it is a link, and whether an owner and access list can be trusted. The checks +/// that apply them to the staging folder and the install folder are in . Every failure +/// throws; nothing is repaired automatically. /// public static partial class MsiUpdateInstaller { - /// Requires installed protected state; permits a not-yet-created staging child. - public static void ValidateStagingDirectory(string path) - { - RequireAdministrator(); - Qqq.PrintAgent.Core.MachineStateDirectory.EnsureForPath(path); - string directory = Path.GetFullPath(path); - ValidateContainedPath(directory, UpdatesDirectory, allowRoot: true); - if(!Directory.Exists(AgentStore.DefaultDirectory)) - { - throw new InvalidOperationException("Install the machine MSI before staging updates."); - } - ValidateNoReparseComponents(directory); - string? current = directory; - while(current is not null && IsContained(current, AgentStore.DefaultDirectory)) - { - if(File.Exists(current)) - { - throw new IOException("An update directory path points to a file."); - } - if(Directory.Exists(current)) - { - ValidateTrustedAcl(new DirectoryInfo(current).GetAccessControl()); - } - current = Path.GetDirectoryName(current); - } - } - - - - /// Requires a staged file to sit in a validated staging folder, be free of links, exist, and have a trusted access list. - private static void ValidateStagedFile(string path) - { - ValidateStagingDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); - ValidateNoReparseComponents(path); - if(!File.Exists(path)) - { - throw new FileNotFoundException("A required staged update file is missing."); - } - ValidateTrustedAcl(new FileInfo(path).GetAccessControl()); - } - - - - /// Requires an installed program path to be inside Program Files, free of links, and trusted at every level up to Program Files, so a user-writable folder cannot supply the program that is run. - private static void ValidateInstalledPath(string path) - { - ValidateNoReparseComponents(path); - string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - string? current = Path.GetFullPath(path); - ValidateContainedPath(current, programFiles, allowRoot: false); - while(current is not null && IsContained(current, programFiles)) - { - ValidateTrustedAcl(Directory.Exists(current) ? new DirectoryInfo(current).GetAccessControl() : new FileInfo(current).GetAccessControl()); - current = Path.GetDirectoryName(current); - } - } - - - /// Requires a path to lie inside a root after full normalization, and optionally not be the root itself, so ".." segments or a different drive cannot escape the protected folder. internal static void ValidateContainedPath(string path, string root, bool allowRoot) { @@ -88,7 +30,7 @@ public static partial class MsiUpdateInstaller /// True when a path is the root or below it, compared on whole path segments so a sibling folder that merely shares the root's name as a prefix does not count. - private static bool IsContained(string path, string root) + internal static bool IsContained(string path, string root) { string full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); string boundary = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); @@ -114,27 +56,6 @@ public static partial class MsiUpdateInstaller - /// Refuses to continue unless the caller is an elevated administrator, and says no installer was started so the operator knows nothing changed. - private static void RequireAdministrator() - { - using var identity = WindowsIdentity.GetCurrent(); - if(!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) - { - throw new UnauthorizedAccessException("Machine updates require an elevated administrator. No installer was started."); - } - } - - - - /// Checks a path's security against trusted accounts, treating the current administrator as one of them. - private static void ValidateTrustedAcl(FileSystemSecurity security) - { - using var identity = WindowsIdentity.GetCurrent(); - ValidateTrustedAcl(security, identity.User?.Value); - } - - - /// /// Requires an explicit access list, a trusted owner, and no allow rule that lets an untrusted account write, delete, change /// permissions or take ownership (inherit-only rules for other objects are ignored). Trusted accounts are SYSTEM, diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.cs index 87aefe2..1bcabbb 100644 --- a/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.cs +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateInstaller.cs @@ -3,152 +3,32 @@ * SPDX-License-Identifier: MIT */ -using System.Diagnostics; -using System.Security.Cryptography; -using System.Text.Json; -using Qqq.PrintAgent.Core.Printing; +using System.Diagnostics.CodeAnalysis; namespace Qqq.PrintAgent.Windows; -/// Stages a protected, disposable CLI copy so updating the installed binaries does not lock the helper. +/// +/// The machine update of the installed product. This class is its entry point: it applies the steps in +/// to the real folder security, the real processes and the installed product's places, and +/// it holds the update rules that need nothing from Windows (containment, links, access lists, request fields, the +/// installer's command line and exit codes), which other parts of the product use as well. +/// public static partial class MsiUpdateInstaller { - /// The protected machine folder where downloaded installers, helper copies and update requests are staged; only administrators can write there. - public static string UpdatesDirectory => Path.Combine(AgentStore.DefaultDirectory, "updates"); + /// The update steps bound to the real folder security, the real processes and the places of the installed product. + internal static MsiUpdateSteps Installed { get; } = new(new WindowsPathSecurity(), new WindowsProcessHost(), MsiUpdatePlaces.Installed()); - /// The fixed machine-wide install folder; update trust decisions compare against it, never against a path supplied by the caller. - private static string InstalledRoot => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "QQQ Print Agent"); + /// Runs only inside the protected copied helper; never kills an installer or an application. + [ExcludeFromCodeCoverage(Justification = "Runs the apply step against this computer: its machine state folder, the installed service's pipe, Windows Installer and the installed companion, none of which a test may touch. It only passes the call on to Installed. The step is tested in MsiUpdateSteps with fakes of IPathSecurity and IProcessHost in temporary folders; that Installed works in the places of MsiUpdatePlaces.Installed, as the process that calls it and for whoever the real process token says is asking, is asserted in MsiUpdateStagingTests, and what those places are in MsiUpdatePlacesTests.")] + public static Task ApplyAsync(string requestPath) => Installed.ApplyAsync(requestPath); - /// The companion executable at its install path; only that process may ask for an update to be prepared. - private static string InstalledCompanion => Path.Combine(InstalledRoot, "App", "Qqq.PrintAgent.exe"); - - - - /// The installed command-line folder that is copied to run the update, so replacing the installed binaries does not lock the running helper. - private static string InstalledCli => Path.Combine(InstalledRoot, "Cli"); - - - - private const int MaximumRequestBytes = 16 * 1024; - - - - /// - /// Prepares an update without applying it: checks that an administrator is asking, that the staging folder and MSI are - /// trusted and of a sane size, that the target is an eligible release, and that the caller is the installed companion. - /// It then copies the installed CLI into a fresh helper folder and writes a request that pins the MSI's hash and the - /// companion's process identity. It returns the request path; nothing is installed here. - /// - public static string PrepareHelper(string verifiedMsiPath, string targetVersion, int parentProcessId) - { - RequireAdministrator(); - string package = Path.GetFullPath(verifiedMsiPath); - string directory = Path.GetDirectoryName(package)!; - ValidateStagingDirectory(directory); - ValidatePackageFile(package); - ValidateTargetVersion(targetVersion); - using var parent = Process.GetProcessById(parentProcessId); - string parentPath = parent.MainModule?.FileName ?? throw new InvalidOperationException("Cannot verify the update's companion process."); - if(!string.Equals(Path.GetFullPath(parentPath), InstalledCompanion, StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidOperationException("Only the installed companion may prepare an update."); - } - ValidateInstalledPath(InstalledCli); - string helper = Path.Combine(directory, "helper"); - if(Directory.Exists(helper)) - { - throw new IOException("This update helper directory already exists. Check again to stage a fresh update."); - } - Directory.CreateDirectory(helper); - CopyHelperTree(InstalledCli, helper); - string helperExecutable = Path.Combine(helper, "qqq-print-agent.exe"); - if(!File.Exists(helperExecutable)) - { - throw new FileNotFoundException("The installed command line tool is missing. Repair the machine MSI first."); - } - using FileStream content = new(package, FileMode.Open, FileAccess.Read, FileShare.Read); - string hash = Convert.ToHexString(SHA256.HashData(content)); - var request = new InstallRequest(package, targetVersion, hash, parentProcessId, parent.StartTime.ToUniversalTime().Ticks); - string requestPath = Path.Combine(directory, "request.json"); - using FileStream output = new(requestPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); - JsonSerializer.Serialize(output, request, PrintApiClient.JsonOptions); - output.Flush(flushToDisk: true); - return requestPath; - } - - - - /// - /// Starts the staged helper copy in apply mode against a prepared request. The request is fully re-validated first and the - /// helper must be a trusted staged file, so a replaced request or helper is refused rather than run with administrator rights. - /// - public static void StartHelper(string requestPath) - { - RequireAdministrator(); - _ = ReadRequest(requestPath); - string helper = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(requestPath))!, "helper", "qqq-print-agent.exe"); - ValidateStagedFile(helper); - ProcessStartInfo start = new(helper) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(helper)! }; - start.ArgumentList.Add("--apply-update"); - start.ArgumentList.Add(Path.GetFullPath(requestPath)); - using Process process = Process.Start(start) ?? throw new InvalidOperationException("Could not start the staged update helper."); - } - - - - /// - /// Copies the installed CLI folder recursively into the helper folder. Every folder and file must have a trusted access - /// list and none may be a link or junction, so a low-privilege user cannot slip a program into the copy that later runs elevated. - /// - private static void CopyHelperTree(string source, string destination) - { - ValidateNoReparseComponents(source); - ValidateTrustedAcl(new DirectoryInfo(source).GetAccessControl()); - foreach(string entry in Directory.EnumerateFileSystemEntries(source)) - { - FileAttributes attributes = File.GetAttributes(entry); - if(attributes.HasFlag(FileAttributes.ReparsePoint)) - { - throw new IOException("Update helper source cannot contain symbolic links or junctions."); - } - string target = Path.Combine(destination, Path.GetFileName(entry)); - if(attributes.HasFlag(FileAttributes.Directory)) - { - Directory.CreateDirectory(target); - CopyHelperTree(entry, target); - } - else - { - ValidateTrustedAcl(new FileInfo(entry).GetAccessControl()); - File.Copy(entry, target, overwrite: false); - } - } - } - - - - /// - /// Reads and validates an update request: a trusted staged file named exactly request.json and no larger than 16 KiB, with - /// fields that pass ValidateRequest and a package file that is still a valid MSI. Anything else is refused as an invalid request. - /// - private static InstallRequest ReadRequest(string requestPath) - { - string path = Path.GetFullPath(requestPath); - ValidateStagedFile(path); - if(!string.Equals(Path.GetFileName(path), "request.json", StringComparison.Ordinal) || new FileInfo(path).Length > MaximumRequestBytes) - { - throw new InvalidDataException("Invalid update request file."); - } - using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); - InstallRequest request = JsonSerializer.Deserialize(stream, PrintApiClient.JsonOptions) ?? throw new InvalidDataException("Empty update request."); - ValidateRequest(request, Path.GetDirectoryName(path)!); - ValidatePackageFile(request.PackagePath); - return request; - } + /// Read-only, bounded last outcome; retained for Settings/log diagnostics rather than consumed. + [ExcludeFromCodeCoverage(Justification = "Reads the recorded outcome in this computer's machine state folder, which exists on some computers and not on others and which a test must not depend on. It only passes the call on to Installed. Reading an outcome is tested in MsiUpdateSteps in a temporary folder; that Installed works in the places of MsiUpdatePlaces.Installed is asserted in MsiUpdateStagingTests, and what those places are in MsiUpdatePlacesTests.")] + public static string? ReadLastOutcomeMessage() => Installed.ReadLastOutcomeMessage(); @@ -172,7 +52,7 @@ public static partial class MsiUpdateInstaller /// Requires the version to parse as a release this updater supports and to meet the minimum, so a malformed or ancient version cannot be installed. - private static void ValidateTargetVersion(string version) + internal static void ValidateTargetVersion(string version) { if(version is null || !MsiReleaseVersion.TryParse(version, out MsiReleaseVersion parsed) || !parsed.MeetsMinimum) { @@ -182,19 +62,6 @@ public static partial class MsiUpdateInstaller - /// Requires the staged package to be a trusted file with an .msi extension and a size between one byte and 256 MiB. - private static void ValidatePackageFile(string package) - { - ValidateStagedFile(package); - long length = new FileInfo(package).Length; - if(length is <= 0 or > 256L * 1024 * 1024 || !string.Equals(Path.GetExtension(package), ".msi", StringComparison.OrdinalIgnoreCase)) - { - throw new InvalidDataException("The staged MSI has an invalid size or extension."); - } - } - - - /// /// What the preparing step records and the applying step re-checks: the staged MSI, its target version and SHA-256, and the /// companion process that asked (by id and start time), so the helper can confirm it is still the same process before it acts. diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdatePlaces.cs b/src/Qqq.PrintAgent.Windows/MsiUpdatePlaces.cs new file mode 100644 index 0000000..b766194 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/MsiUpdatePlaces.cs @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using KofTwentyTwo.AppKit.Logging; +using Qqq.PrintAgent.Core; + +namespace Qqq.PrintAgent.Windows; + +/// +/// Where a machine update works and what it reaches outside itself: the Program Files folder the product is installed +/// under, the machine state folder with the check that it is protected (it throws when the folder cannot be trusted), +/// how the activity log of a state folder is opened, how a request reaches the service, and the clock. The installed +/// product takes its places from ; a test passes temporary folders, a pipe of its own and a +/// clock it moves itself. +/// +internal sealed record MsiUpdatePlaces(string ProgramFiles, string StateDirectory, Action EnsureProtectedState, Func OpenLog, Func> Send, TimeProvider Clock) +{ + /// + /// The places of the installed product, so the entry point cannot bind a weaker check by accident: this computer's + /// Program Files, the machine state folder checked by the machine state guard, the machine activity log, the + /// installed service's pipe and the system clock. + /// + internal static MsiUpdatePlaces Installed() + => new(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), AgentStore.DefaultDirectory, MachineStateDirectory.EnsureForPath, AgentActivityLog.Create, AgentPipeClient.SendAsync, TimeProvider.System); + + + + /// The fixed machine-wide install folder; update trust decisions compare against it, never against a path supplied by the caller. + internal string InstalledRoot => Path.Combine(ProgramFiles, "QQQ Print Agent"); + + + + /// The companion executable at its install path; only that process may ask for an update to be prepared. + internal string InstalledCompanion => Path.Combine(InstalledRoot, "App", "Qqq.PrintAgent.exe"); + + + + /// The service executable at its install path; its version is checked after an install. + internal string InstalledService => Path.Combine(InstalledRoot, "Service", "Qqq.PrintAgent.Service.exe"); + + + + /// The installed command-line folder that is copied to run the update, so replacing the installed binaries does not lock the running helper. + internal string InstalledCli => Path.Combine(InstalledRoot, "Cli"); + + + + /// The protected machine folder where downloaded installers, helper copies and update requests are staged; only administrators can write there. + internal string UpdatesDirectory => Path.Combine(StateDirectory, "updates"); +} diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateService.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateService.cs index 068fa0e..53ad4e2 100644 --- a/src/Qqq.PrintAgent.Windows/MsiUpdateService.cs +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateService.cs @@ -9,14 +9,80 @@ using KofTwentyTwo.AppKit.Updates; namespace Qqq.PrintAgent.Windows; -/// AppKit update flow backed by a coherent machine MSI rather than a per-user executable update. -public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, string assetPrefix = Qqq.PrintAgent.Core.Edition.DefaultAssetPrefix) : IUpdateService, IDisposable +/// +/// AppKit update flow backed by a coherent machine MSI rather than a per-user executable update. The release feed, the +/// service's pipe and the update steps are given to it, so the whole flow (check, download, pause, hand-off, and what +/// is undone when a step fails) can be run against fakes; the companion uses the public constructor, which binds the +/// GitHub release feed, the installed service's pipe and the installed product's update steps. +/// +public sealed class MsiUpdateService : IUpdateService, IDisposable { - private readonly GitHubMsiReleaseClient _releases = new(assetPrefix: assetPrefix); + /// Closes the companion once the update has been handed to the helper, so the installer can replace its files. + private readonly Action _exitApplication; + + + + /// The companion's activity log. + private readonly IActivityLog _log; + + + + /// Where releases are found and their installers downloaded from. + private readonly IMsiReleaseSource _releases; + + + + /// Sends one request to the service and returns its reply. + private readonly Func> _send; + + + + /// The update steps: the staging checks, the preparation and the hand-off to the helper. + private readonly MsiUpdateSteps _installer; + + + + /// The release the last successful check found, which is the only one an install will take. private MsiRelease? _pending; + + + /// The update service of the installed companion: the GitHub release feed for the given asset prefix, the installed service's pipe and the update steps of the installed product. + public MsiUpdateService(Action exitApplication, IActivityLog log, string assetPrefix = Qqq.PrintAgent.Core.Edition.DefaultAssetPrefix) + : this(exitApplication, log, new GitHubMsiReleaseClient(assetPrefix: assetPrefix), AgentPipeClient.SendAsync, MsiUpdateInstaller.Installed) + { + } + + + + /// The update service over a given release source, pipe and update steps. + internal MsiUpdateService(Action exitApplication, IActivityLog log, IMsiReleaseSource releases, Func> send, MsiUpdateSteps installer) + { + _exitApplication = exitApplication; + _log = log; + _releases = releases; + _send = send; + _installer = installer; + } + + + + /// How this update service reaches the print service, so that a test can see which pipe the companion's constructor bound. + internal Func> Send => _send; + + + + /// The update steps this update service uses, so that a test can see which steps the companion's constructor bound. + internal MsiUpdateSteps Steps => _installer; + + + + /// Raised with each step of an update as it begins and with the download's progress, for the companion to show. public event EventHandler? StatusChanged; + + + /// The version of this build, as stamped into the assembly; it is what the release feed's versions are compared with. public string? CurrentVersion { get; } = typeof(MsiUpdateService).Assembly.GetCustomAttribute()?.InformationalVersion; @@ -25,14 +91,7 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s /// True only for the MSI-installed companion (running from its Program Files path with the machine state folder present). /// A development or portable copy cannot replace the service and CLI together, so it is never offered an in-app update. /// - public bool IsSupported - { - get - { - string installed = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "QQQ Print Agent", "App", "Qqq.PrintAgent.exe"); - return string.Equals(Environment.ProcessPath, installed, StringComparison.OrdinalIgnoreCase) && Directory.Exists(AgentStore.DefaultDirectory); - } - } + public bool IsSupported => _installer.RunsAsInstalledCompanion; @@ -83,16 +142,16 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s // The service finishes the jobs it has already claimed before it answers, or answers that it is not ready. paused = true; StatusChanged?.Invoke(this, new UpdateStatusEventArgs("Waiting for active printing to finish…")); - string response = await AgentPipeClient.SendAsync(new PipeRequest("prepare-update")).ConfigureAwait(false); + string response = await _send(new PipeRequest("prepare-update")).ConfigureAwait(false); if(!string.Equals(response, "Ready for update.", StringComparison.Ordinal)) { throw new InvalidOperationException(PreparationNotCompleted(response)); } cancellationToken.ThrowIfCancellationRequested(); - MsiUpdateInstaller.StartHelper(request); + _installer.StartHelper(request); handedOff = true; - log.Info("[Companion] Verified update handed to Windows Installer; closing the companion."); - exitApplication(); + _log.Info("[Companion] Verified update handed to Windows Installer; closing the companion."); + _exitApplication(); return null; } catch(Exception exception) @@ -122,10 +181,10 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s /// private async Task StageAsync(MsiRelease release, IProgress? progress, CancellationToken token) { - string staging = Path.Combine(MsiUpdateInstaller.UpdatesDirectory, Guid.NewGuid().ToString("N")); - MsiUpdateInstaller.ValidateStagingDirectory(staging); + string staging = Path.Combine(_installer.UpdatesDirectory, Guid.NewGuid().ToString("N")); + _installer.ValidateStagingDirectory(staging); Directory.CreateDirectory(staging); - MsiUpdateInstaller.ValidateStagingDirectory(staging); + _installer.ValidateStagingDirectory(staging); StatusChanged?.Invoke(this, new UpdateStatusEventArgs("Downloading the update…")); IProgress downloadProgress = new Progress(value => { @@ -137,7 +196,7 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s { string package = await _releases.DownloadVerifiedAsync(release, CurrentVersion ?? "", staging, downloadProgress, token).ConfigureAwait(false); StatusChanged?.Invoke(this, new UpdateStatusEventArgs("Update verified. Preparing Windows Installer…")); - return await Task.Run(() => MsiUpdateInstaller.PrepareHelper(package, release.Version, Environment.ProcessId), token).ConfigureAwait(false); + return await Task.Run(() => _installer.PrepareHelper(package, release.Version, _installer.CurrentProcessId), token).ConfigureAwait(false); } catch { @@ -157,7 +216,7 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s { try { - MsiUpdateInstaller.ValidateStagingDirectory(directory); + _installer.ValidateStagingDirectory(directory); Stack pending = new(); pending.Push(directory); while(pending.TryPop(out string? current)) @@ -179,18 +238,18 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s } catch(Exception exception) { - log.Warning("[Companion] Unapplied update staging could not be removed: " + Describe(exception)); + _log.Warning("[Companion] Unapplied update staging could not be removed: " + Describe(exception)); } } /// Tells the service to lift the maintenance pause after an update was abandoned; best effort, since the service also expires an abandoned pause on its own. - private static async Task ResumePrintingAsync() + private async Task ResumePrintingAsync() { try { - await AgentPipeClient.SendAsync(new PipeRequest("resume-after-update")).ConfigureAwait(false); + await _send(new PipeRequest("resume-after-update")).ConfigureAwait(false); } catch(Exception) { @@ -222,6 +281,6 @@ public sealed class MsiUpdateService(Action exitApplication, IActivityLog log, s - /// Releases the release-feed client. + /// Releases the release source. public void Dispose() => _releases.Dispose(); } diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Apply.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Apply.cs new file mode 100644 index 0000000..428d481 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Apply.cs @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using KofTwentyTwo.AppKit.Logging; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Windows; + +/// +/// Applying part of the updater, which runs only inside the staged helper copy. It re-verifies the request, waits for the +/// companion that asked to close, installs the verified MSI with Windows Installer, checks that all three installed programs +/// carry the requested release, records the outcome, and reopens the companion. It never kills a process or an installer. +/// +internal sealed partial class MsiUpdateSteps +{ + /// How long the helper waits for the companion that asked for the update to close before it gives up without installing. + internal static readonly TimeSpan CompanionExitLimit = TimeSpan.FromSeconds(30); + + + + /// Runs only inside the protected copied helper; never kills an installer or an application. + internal async Task ApplyAsync(string requestPath) + { + int code = 1; + string message; + string version = "unknown"; + try + { + RequireAdministrator(); + MsiUpdateInstaller.InstallRequest request = ReadRequest(requestPath); + version = request.Version; + string directory = Path.GetDirectoryName(Path.GetFullPath(requestPath))!; + string helper = Path.Combine(directory, "helper", "qqq-print-agent.exe"); + if(!string.Equals(processes.CurrentPath, helper, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Apply must run from the verified staged helper copy."); + } + ValidateStagedFile(helper); + await WaitForCompanionExitAsync(request).ConfigureAwait(false); + // Retain this non-writable/non-deletable handle until Windows Installer exits. + using FileStream packageLock = MsiUpdateInstaller.OpenVerifiedPackage(request.PackagePath, request.Sha256); + string installLog = Path.Combine(directory, "install.log"); + MsiUpdateInstaller.ValidateNoReparseComponents(installLog); + ProcessStartInfo start = MsiUpdateInstaller.CreateInstallerStart(request.PackagePath, installLog); + using IRunningProcess installer = processes.Start(start) ?? throw new InvalidOperationException("Windows Installer could not start."); + await installer.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); + code = installer.ExitCode; + if(code == 0) + { + ValidateInstalledVersions(request.Version, processes.ProductVersion); + } + message = MsiUpdateInstaller.DescribeExitCode(code); + } + catch(Exception exception) + { + code = 1; + message = "Update failed before completion: " + AgentActivityLog.Redact(exception.Message); + } + await CompleteAsync(version, code, message).ConfigureAwait(false); + return code; + } + + + + /// + /// Waits up to 30 seconds for the companion that requested the update to exit, so its files can be replaced. It first + /// confirms the process is still the same one (same start time and the installed executable); a different process + /// aborts the update before any installer starts. It never terminates the companion, and a timeout is reported. + /// + private async Task WaitForCompanionExitAsync(MsiUpdateInstaller.InstallRequest request) + { + IRunningProcess parent; + try + { + parent = processes.Open(request.ParentProcessId); + } + catch(ArgumentException) + { + return; + } + using(parent) + { + if(parent.HasExited) + { + return; + } + string? path; + long started; + try + { + path = parent.ProgramPath; + started = parent.StartTicks; + } + catch(InvalidOperationException) when(parent.HasExited) + { + return; + } + if(started != request.ParentStartTicks || !string.Equals(path, places.InstalledCompanion, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("The expected companion process identity changed. No installer was started."); + } + using CancellationTokenSource timeout = new(CompanionExitLimit, places.Clock); + try + { + await parent.WaitForExitAsync(timeout.Token).ConfigureAwait(false); + } + catch(OperationCanceledException exception) + { + throw new TimeoutException("The companion did not close within 30 seconds. Close it and retry the update; no process was terminated.", exception); + } + } + } + + + + /// Checks the installed payload after MSI success without assuming rollback on mismatch. + internal void ValidateInstalledVersions(string requestedVersion, Func readProductVersion) + { + string? installedBuild = null; + foreach(string executable in new[] { places.InstalledCompanion, places.InstalledService, Path.Combine(places.InstalledCli, "qqq-print-agent.exe") }) + { + string? version; + try + { + version = readProductVersion(executable); + } + catch(Exception exception) when(exception is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) + { + throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " version could not be verified. Inspect the installation log and repair the package.", exception); + } + if(!MsiUpdateInstaller.InstalledVersionMatches(version, requestedVersion)) + { + throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " version does not match the requested release. Inspect the installation log and repair the package."); + } + if(installedBuild is not null && !string.Equals(version, installedBuild, StringComparison.Ordinal)) + { + throw new InvalidOperationException("Windows Installer returned success, but the installed " + Path.GetFileName(executable) + " build version is incoherent with the companion. Inspect the installation log and repair the package."); + } + installedBuild ??= version; + } + } + + + + /// + /// Finishes an update attempt in three independent best-effort steps, so a failure in one never blocks the next: record the + /// outcome and log it, tell the service to resume printing after the maintenance pause, and reopen the installed companion. + /// The installer's own log remains the evidence if any step fails. + /// + private async Task CompleteAsync(string version, int code, string message) + { + try + { + WriteOutcome(new InstallOutcome(places.Clock.GetUtcNow(), version, code, message)); + IActivityLog log = places.OpenLog(places.StateDirectory); + if(code is 0 or 3010) + { + log.Info("[Update] " + message); + } + else + { + log.Error("[Update] " + message); + } + } + catch(Exception) + { + // The independently preserved MSI install.log remains diagnostic evidence. + } + try + { + await places.Send(new PipeRequest("resume-after-update")).ConfigureAwait(false); + } + catch(Exception) + { + // An abandoned maintenance pause also expires in the service itself. + } + try + { + ValidateInstalledPath(places.InstalledCompanion); + using IRunningProcess? companion = processes.Start(new ProcessStartInfo(places.InstalledCompanion) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(places.InstalledCompanion)! }); + } + catch(Exception) + { + // Operator can read the protected outcome/log and open the installed app manually. + } + } + + + + /// Saves the last update outcome by writing a temporary file in the protected folder and moving it over the previous result, so a reader never sees a half-written file. + private void WriteOutcome(InstallOutcome outcome) + { + ValidateStagingDirectory(UpdatesDirectory); + Directory.CreateDirectory(UpdatesDirectory); + string path = Path.Combine(UpdatesDirectory, "last-result.json"); + MsiUpdateInstaller.ValidateNoReparseComponents(path); + string temporary = Path.Combine(UpdatesDirectory, "result-" + Guid.NewGuid().ToString("N") + ".tmp"); + try + { + using(FileStream stream = new(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + JsonSerializer.Serialize(stream, outcome, PrintApiClient.JsonOptions); + stream.Flush(flushToDisk: true); + } + File.Move(temporary, path, overwrite: true); + } + finally { File.Delete(temporary); } + } + + + + /// Read-only, bounded last outcome; retained for Settings/log diagnostics rather than consumed. + internal string? ReadLastOutcomeMessage() + { + try + { + string path = Path.Combine(UpdatesDirectory, "last-result.json"); + if(!File.Exists(path)) + { + return null; + } + ValidateStagedFile(path); + if(new FileInfo(path).Length > MaximumRequestBytes) + { + return "The previous update outcome is invalid. Inspect the protected update logs."; + } + using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + InstallOutcome? result = JsonSerializer.Deserialize(stream, PrintApiClient.JsonOptions); + return result is null ? null : result.CompletedAt.ToString("u", CultureInfo.InvariantCulture) + " — " + result.Message; + } + catch(Exception) + { + return "The previous update outcome could not be read. Inspect the protected update logs."; + } + } + + + + /// The recorded result of one update attempt: when it finished, which release it targeted, the installer's exit code and the message shown to the operator. + private sealed record InstallOutcome(DateTimeOffset CompletedAt, string Version, int ExitCode, string Message); +} diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Paths.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Paths.cs new file mode 100644 index 0000000..a94c5ed --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.Paths.cs @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Security.AccessControl; + +namespace Qqq.PrintAgent.Windows; + +/// +/// Path and permission checks of the updater. The staged files later run with administrator rights, so each path must stay +/// inside the protected folders, contain no link or junction, and be owned and writable only by trusted accounts. Every +/// failure throws; nothing is repaired automatically. +/// +internal sealed partial class MsiUpdateSteps +{ + /// Requires installed protected state; permits a not-yet-created staging child. + internal void ValidateStagingDirectory(string path) + { + RequireAdministrator(); + places.EnsureProtectedState(path); + string directory = Path.GetFullPath(path); + MsiUpdateInstaller.ValidateContainedPath(directory, UpdatesDirectory, allowRoot: true); + if(!Directory.Exists(places.StateDirectory)) + { + throw new InvalidOperationException("Install the machine MSI before staging updates."); + } + MsiUpdateInstaller.ValidateNoReparseComponents(directory); + string? current = directory; + while(current is not null && MsiUpdateInstaller.IsContained(current, places.StateDirectory)) + { + if(File.Exists(current)) + { + throw new IOException("An update directory path points to a file."); + } + if(Directory.Exists(current)) + { + ValidateTrustedAcl(security.ReadDirectorySecurity(current)); + } + current = Path.GetDirectoryName(current); + } + } + + + + /// Requires a staged file to sit in a validated staging folder, be free of links, exist, and have a trusted access list. + private void ValidateStagedFile(string path) + { + ValidateStagingDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); + MsiUpdateInstaller.ValidateNoReparseComponents(path); + if(!File.Exists(path)) + { + throw new FileNotFoundException("A required staged update file is missing."); + } + ValidateTrustedAcl(security.ReadFileSecurity(path)); + } + + + + /// Requires an installed program path to be inside Program Files, free of links, and trusted at every level up to Program Files, so a user-writable folder cannot supply the program that is run. + private void ValidateInstalledPath(string path) + { + MsiUpdateInstaller.ValidateNoReparseComponents(path); + string? current = Path.GetFullPath(path); + MsiUpdateInstaller.ValidateContainedPath(current, places.ProgramFiles, allowRoot: false); + while(current is not null && MsiUpdateInstaller.IsContained(current, places.ProgramFiles)) + { + ValidateTrustedAcl(Directory.Exists(current) ? security.ReadDirectorySecurity(current) : security.ReadFileSecurity(current)); + current = Path.GetDirectoryName(current); + } + } + + + + /// Refuses to continue unless the caller is an elevated administrator, and says no installer was started so the operator knows nothing changed. + private void RequireAdministrator() + { + if(!security.IsAdministrator) + { + throw new UnauthorizedAccessException("Machine updates require an elevated administrator. No installer was started."); + } + } + + + + /// Checks a path's security against trusted accounts, treating the current administrator as one of them. + private void ValidateTrustedAcl(FileSystemSecurity descriptor) => MsiUpdateInstaller.ValidateTrustedAcl(descriptor, security.CurrentUserSid); +} diff --git a/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.cs b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.cs new file mode 100644 index 0000000..4901607 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/MsiUpdateSteps.cs @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text.Json; +using Qqq.PrintAgent.Core.Printing; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The steps of a machine update and every check that guards them: who may ask, which folders and files are trusted, +/// which program is copied and started, what the request says and what Windows Installer's answer means. Owners and +/// access lists come through , processes through , and the folders, +/// the pipe, the log and the clock are given in , so every step can be run against fakes in +/// temporary folders without starting Windows Installer. The rules that need nothing from Windows (containment, links, +/// access lists, request fields, the installer's command line and exit codes) stay in . +/// This part stages a protected, disposable CLI copy so updating the installed binaries does not lock the helper. +/// +internal sealed partial class MsiUpdateSteps(IPathSecurity security, IProcessHost processes, MsiUpdatePlaces places) +{ + /// The largest update request or recorded outcome that is read; anything larger is not one this product wrote. + private const int MaximumRequestBytes = 16 * 1024; + + + + /// The places these steps work in and what they reach outside themselves, so that a test can see which places an entry point bound them to. + internal MsiUpdatePlaces Places => places; + + + + /// The protected machine folder where downloaded installers, helper copies and update requests are staged; only administrators can write there. + internal string UpdatesDirectory => places.UpdatesDirectory; + + + + /// + /// True only for the MSI-installed companion (running from its Program Files path with the machine state folder present). + /// A development or portable copy cannot replace the service and CLI together, so it is never offered an in-app update. + /// + internal bool RunsAsInstalledCompanion + => string.Equals(processes.CurrentPath, places.InstalledCompanion, StringComparison.OrdinalIgnoreCase) && Directory.Exists(places.StateDirectory); + + + + /// The id of the process these steps run in, which is the companion's when it prepares an update. + internal int CurrentProcessId => processes.CurrentId; + + + + /// + /// Prepares an update without applying it: checks that an administrator is asking, that the staging folder and MSI are + /// trusted and of a sane size, that the target is an eligible release, and that the caller is the installed companion. + /// It then copies the installed CLI into a fresh helper folder and writes a request that pins the MSI's hash and the + /// companion's process identity. It returns the request path; nothing is installed here. + /// + internal string PrepareHelper(string verifiedMsiPath, string targetVersion, int parentProcessId) + { + RequireAdministrator(); + string package = Path.GetFullPath(verifiedMsiPath); + string directory = Path.GetDirectoryName(package)!; + ValidateStagingDirectory(directory); + ValidatePackageFile(package); + MsiUpdateInstaller.ValidateTargetVersion(targetVersion); + using IRunningProcess parent = processes.Open(parentProcessId); + string parentPath = parent.ProgramPath ?? throw new InvalidOperationException("Cannot verify the update's companion process."); + if(!string.Equals(Path.GetFullPath(parentPath), places.InstalledCompanion, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Only the installed companion may prepare an update."); + } + ValidateInstalledPath(places.InstalledCli); + string helper = Path.Combine(directory, "helper"); + if(Directory.Exists(helper)) + { + throw new IOException("This update helper directory already exists. Check again to stage a fresh update."); + } + Directory.CreateDirectory(helper); + CopyHelperTree(places.InstalledCli, helper); + string helperExecutable = Path.Combine(helper, "qqq-print-agent.exe"); + if(!File.Exists(helperExecutable)) + { + throw new FileNotFoundException("The installed command line tool is missing. Repair the machine MSI first."); + } + using FileStream content = new(package, FileMode.Open, FileAccess.Read, FileShare.Read); + string hash = Convert.ToHexString(SHA256.HashData(content)); + var request = new MsiUpdateInstaller.InstallRequest(package, targetVersion, hash, parentProcessId, parent.StartTicks); + string requestPath = Path.Combine(directory, "request.json"); + using FileStream output = new(requestPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + JsonSerializer.Serialize(output, request, PrintApiClient.JsonOptions); + output.Flush(flushToDisk: true); + return requestPath; + } + + + + /// + /// Starts the staged helper copy in apply mode against a prepared request. The request is fully re-validated first and the + /// helper must be a trusted staged file, so a replaced request or helper is refused rather than run with administrator rights. + /// + internal void StartHelper(string requestPath) + { + RequireAdministrator(); + _ = ReadRequest(requestPath); + string helper = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(requestPath))!, "helper", "qqq-print-agent.exe"); + ValidateStagedFile(helper); + ProcessStartInfo start = new(helper) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(helper)! }; + start.ArgumentList.Add("--apply-update"); + start.ArgumentList.Add(Path.GetFullPath(requestPath)); + using IRunningProcess process = processes.Start(start) ?? throw new InvalidOperationException("Could not start the staged update helper."); + } + + + + /// + /// Copies the installed CLI folder recursively into the helper folder. Every folder and file must have a trusted access + /// list and none may be a link or junction, so a low-privilege user cannot slip a program into the copy that later runs elevated. + /// + private void CopyHelperTree(string source, string destination) + { + MsiUpdateInstaller.ValidateNoReparseComponents(source); + ValidateTrustedAcl(security.ReadDirectorySecurity(source)); + foreach(string entry in Directory.EnumerateFileSystemEntries(source)) + { + FileAttributes attributes = File.GetAttributes(entry); + if(attributes.HasFlag(FileAttributes.ReparsePoint)) + { + throw new IOException("Update helper source cannot contain symbolic links or junctions."); + } + string target = Path.Combine(destination, Path.GetFileName(entry)); + if(attributes.HasFlag(FileAttributes.Directory)) + { + Directory.CreateDirectory(target); + CopyHelperTree(entry, target); + } + else + { + ValidateTrustedAcl(security.ReadFileSecurity(entry)); + File.Copy(entry, target, overwrite: false); + } + } + } + + + + /// + /// Reads and validates an update request: a trusted staged file named exactly request.json and no larger than 16 KiB, with + /// fields that pass and a package file that is still a valid MSI. Anything else is refused as an invalid request. + /// + private MsiUpdateInstaller.InstallRequest ReadRequest(string requestPath) + { + string path = Path.GetFullPath(requestPath); + ValidateStagedFile(path); + if(!string.Equals(Path.GetFileName(path), "request.json", StringComparison.Ordinal) || new FileInfo(path).Length > MaximumRequestBytes) + { + throw new InvalidDataException("Invalid update request file."); + } + using FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + MsiUpdateInstaller.InstallRequest request = JsonSerializer.Deserialize(stream, PrintApiClient.JsonOptions) ?? throw new InvalidDataException("Empty update request."); + MsiUpdateInstaller.ValidateRequest(request, Path.GetDirectoryName(path)!); + ValidatePackageFile(request.PackagePath); + return request; + } + + + + /// Requires the staged package to be a trusted file with an .msi extension and a size between one byte and 256 MiB. + private void ValidatePackageFile(string package) + { + ValidateStagedFile(package); + long length = new FileInfo(package).Length; + if(length is <= 0 or > 256L * 1024 * 1024 || !string.Equals(Path.GetExtension(package), ".msi", StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidDataException("The staged MSI has an invalid size or extension."); + } + } +} diff --git a/src/Qqq.PrintAgent.Windows/PeerServiceStatus.cs b/src/Qqq.PrintAgent.Windows/PeerServiceStatus.cs new file mode 100644 index 0000000..e39b774 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/PeerServiceStatus.cs @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Runtime.InteropServices; + +namespace Qqq.PrintAgent.Windows; + +/// +/// What the service control manager says about a service at one moment: its state as Windows numbers it (4 is +/// running) and the id of the process hosting it (0 when none does). +/// +[StructLayout(LayoutKind.Auto)] +internal readonly record struct PeerServiceStatus(uint State, uint ProcessId); diff --git a/src/Qqq.PrintAgent.Windows/WindowsManagedService.cs b/src/Qqq.PrintAgent.Windows/WindowsManagedService.cs new file mode 100644 index 0000000..50f3e26 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsManagedService.cs @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ServiceProcess; + +namespace Qqq.PrintAgent.Windows; + +/// +/// One real Windows service behind . Every member passes the call to the service +/// controller it was given and passes on what comes back, refusals included. +/// +internal sealed class WindowsManagedService(ServiceController controller) : IManagedService +{ + /// The state the controller read, or reads now. + public ServiceControllerStatus Status => controller.Status; + + + + /// Whether the service accepts a stop request, from the same reading. + public bool CanStop => controller.CanStop; + + + + /// Makes the controller forget what it read. + public void Refresh() => controller.Refresh(); + + + + /// Sends the start request. + public void Start() => controller.Start(); + + + + /// Sends the stop request. + public void Stop() => controller.Stop(); + + + + /// Lets go of the service without changing it. + public void Dispose() => controller.Dispose(); +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsPeerProcess.cs b/src/Qqq.PrintAgent.Windows/WindowsPeerProcess.cs new file mode 100644 index 0000000..51a4f2c --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsPeerProcess.cs @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; +using Microsoft.Win32.SafeHandles; + +namespace Qqq.PrintAgent.Windows; + +/// +/// One real process behind . Asking for its account opens the process itself, and that +/// handle stays open until this is disposed, which prevents Windows from giving the process id to another process +/// meanwhile. Every member passes on what Windows says, failures included. +/// +internal sealed class WindowsPeerProcess(Process process) : IPeerProcess +{ + /// The access right that allows a process token to be read. + private const uint TokenQuery = 8; + + + + /// The account the process runs as, once it has been asked for; kept until this is disposed. + private WindowsIdentity? _identity; + + + + /// Opens the process and its token, and says whether the token is the SYSTEM account's. + public bool RunsAsSystem() + { + // Force acquisition of the real process handle, preventing PID reuse until disposal. + if(!OpenProcessToken(process.SafeHandle, TokenQuery, out SafeAccessTokenHandle token)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + using(token) + { + _identity?.Dispose(); + _identity = new WindowsIdentity(token.DangerousGetHandle()); + } + return _identity.IsSystem; + } + + + + /// Whether the process has ended. + public bool HasExited => process.HasExited; + + + + /// The file of the process's main module. + public string? ProgramPath => process.MainModule?.FileName; + + + + /// Releases the account and the process handle, after which the process id may be reused. + public void Dispose() + { + _identity?.Dispose(); + process.Dispose(); + } + + + + /// Opens the access token of a process so its account can be verified as SYSTEM. + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool OpenProcessToken(SafeProcessHandle process, uint access, out SafeAccessTokenHandle token); +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsPeerService.cs b/src/Qqq.PrintAgent.Windows/WindowsPeerService.cs new file mode 100644 index 0000000..fd20bb9 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsPeerService.cs @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.ServiceProcess; + +namespace Qqq.PrintAgent.Windows; + +/// +/// One real Windows service behind . Its status is read through the service controller's own +/// handle, which Windows opens with full access to the service and therefore gives only to an administrator: a caller +/// who may not control the service is refused here, before anything is read. Nothing here is excluded from coverage: +/// the tests show the refusal with a name no service has, and read a built-in service's status with +/// through a handle of their own that may only read. +/// +internal sealed class WindowsPeerService(ServiceController controller) : IPeerService +{ + /// Opens the service with the controller's full-access handle and reads its state and process id. + public PeerServiceStatus ReadStatus() => Query(controller.ServiceHandle); + + + + /// Lets go of the service without changing it. + public void Dispose() => controller.Dispose(); + + + + /// Reads the service's current state and process id from the service control manager through an open service handle. + internal static PeerServiceStatus Query(SafeHandle service) + { + if(!QueryServiceStatusEx(service, 0, out ServiceStatus status, Marshal.SizeOf(), out _)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + return new PeerServiceStatus(status.State, status.ProcessId); + } + + + + /// SERVICE_STATUS_PROCESS as returned by QueryServiceStatusEx; the layout is marshaled and must not change. + [StructLayout(LayoutKind.Sequential)] + private struct ServiceStatus + { + /// The kind of service. + internal uint Type; + + + + /// The current state; 4 is running. + internal uint State; + + + + /// The control codes the service accepts. + internal uint Controls; + + + + /// The Windows error the service reported when it started or stopped. + internal uint ExitCode; + + + + /// The service's own error code. + internal uint ServiceExitCode; + + + + /// The progress counter of a pending start, stop, pause or continue. + internal uint CheckPoint; + + + + /// How long the pending operation is expected to take, in milliseconds. + internal uint WaitHint; + + + + /// The id of the process hosting the service; 0 when none does. + internal uint ProcessId; + + + + /// Whether the service runs in a system process. + internal uint Flags; + } + + + + /// Queries the extended status of a service, including the id of the process hosting it. + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool QueryServiceStatusEx(SafeHandle service, int level, out ServiceStatus status, int size, out int needed); +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsPipePeerFacts.cs b/src/Qqq.PrintAgent.Windows/WindowsPipePeerFacts.cs new file mode 100644 index 0000000..e79ab6f --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsPipePeerFacts.cs @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.ServiceProcess; +using Microsoft.Win32.SafeHandles; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The real Windows behind : the kernel's record of which process serves a pipe, a service +/// by name and a process by id. It decides nothing about trust. Nothing here is excluded from coverage: the tests ask +/// it about a pipe they serve themselves, a service name no service has and the test process. +/// +internal sealed class WindowsPipePeerFacts : IPipePeerFacts +{ + /// Asks the kernel which process serves this pipe instance; the answer cannot be forged by a process that merely uses the pipe's name. + public uint ServerProcessId(SafePipeHandle pipe) + { + if(!GetNamedPipeServerProcessId(pipe, out uint pid)) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + return pid; + } + + + + /// Holds the named service on this computer; Windows is asked only when its status is read. + public IPeerService OpenService(string serviceName) => new WindowsPeerService(new ServiceController(serviceName)); + + + + /// Finds the running process with the id; Windows' own refusal for an id no running process has is passed on. + public IPeerProcess OpenProcess(uint processId) => new WindowsPeerProcess(Process.GetProcessById(checked((int)processId))); + + + + /// Returns the id of the process that created the server end of a named pipe. + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint processId); +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsProcessHost.cs b/src/Qqq.PrintAgent.Windows/WindowsProcessHost.cs new file mode 100644 index 0000000..02cca05 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsProcessHost.cs @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The real Windows behind . It reads the identity of the current process, finds a process +/// by id, starts the program it is given and reads a file's version resource; it decides nothing. Nothing here is +/// excluded from coverage: the program to start is a parameter, so the tests start a harmless child program in place +/// of Windows Installer, the companion and the Services console, and the other members only read. +/// +internal sealed class WindowsProcessHost : IProcessHost +{ + /// The path of the program this process runs. + public string? CurrentPath => Environment.ProcessPath; + + + + /// The id of this process. + public int CurrentId => Environment.ProcessId; + + + + /// Finds the process with the id; Windows' own refusal for an id no process has is passed on. + public IRunningProcess Open(int processId) => new WindowsRunningProcess(Process.GetProcessById(processId)); + + + + /// Starts the program as described; nothing is added to or taken from the start information. + public IRunningProcess? Start(ProcessStartInfo start) => Process.Start(start) is Process process ? new WindowsRunningProcess(process) : null; + + + + /// Reads the product version from the file's version resource. + public string? ProductVersion(string path) => FileVersionInfo.GetVersionInfo(path).ProductVersion; +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsRunningProcess.cs b/src/Qqq.PrintAgent.Windows/WindowsRunningProcess.cs new file mode 100644 index 0000000..e508ec1 --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsRunningProcess.cs @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; + +namespace Qqq.PrintAgent.Windows; + +/// +/// One real process behind . Every member passes on what Windows says about the process +/// it was given, failures included, and none ends it. Nothing here is excluded from coverage: the tests hold a +/// harmless child program through it. +/// +internal sealed class WindowsRunningProcess(Process process) : IRunningProcess +{ + /// Whether the process has ended. + public bool HasExited => process.HasExited; + + + + /// The file of the process's main module. + public string? ProgramPath => process.MainModule?.FileName; + + + + /// The start time in universal time ticks. + public long StartTicks => process.StartTime.ToUniversalTime().Ticks; + + + + /// The exit code of the ended process. + public int ExitCode => process.ExitCode; + + + + /// Waits for the process to end, or for the token. + public Task WaitForExitAsync(CancellationToken cancellationToken) => process.WaitForExitAsync(cancellationToken); + + + + /// Lets go of the process without ending it. + public void Dispose() => process.Dispose(); +} diff --git a/src/Qqq.PrintAgent.Windows/WindowsServiceManager.cs b/src/Qqq.PrintAgent.Windows/WindowsServiceManager.cs new file mode 100644 index 0000000..c94125c --- /dev/null +++ b/src/Qqq.PrintAgent.Windows/WindowsServiceManager.cs @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ServiceProcess; + +namespace Qqq.PrintAgent.Windows; + +/// +/// The real service control manager behind . It holds a service by name and decides +/// nothing. Nothing here is excluded from coverage: the service name is a parameter, so the tests read a built-in +/// Windows service and send the controls to a name no service has, which changes nothing on the computer. +/// +internal sealed class WindowsServiceManager : IServiceManager +{ + /// Holds the named service on this computer; Windows is asked only when the result is used. + public IManagedService Open(string serviceName) => new WindowsManagedService(new ServiceController(serviceName)); +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTests.cs index 861a605..0b1f180 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTests.cs @@ -96,7 +96,7 @@ public sealed class AgentPipePeerTests { using SafePipeHandle closed = new(IntPtr.Zero, ownsHandle: false); - UnauthorizedAccessException refusal = Assert.Throws(() => AgentPipePeer.Authenticate(closed)); + UnauthorizedAccessException refusal = Assert.Throws(() => AgentPipePeer.Installed.Authenticate(closed)); Assert.Equal(ServiceStopped, refusal.Message); Assert.NotNull(refusal.InnerException); diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTrustTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTrustTests.cs new file mode 100644 index 0000000..45ffad0 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentPipePeerTrustTests.cs @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Microsoft.Win32.SafeHandles; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Whether the companion and the command line tool trust the process at the other end of the management pipe. They +/// send credentials and administrator commands down that pipe, so the tests go through each way the other end can +/// fail to be the installed print service and check that it is refused, that everything acquired for the check is +/// released, and that the operator is told the right one of two things: repair, when something that is not the +/// service answered, or try again, when the service went away during the check. The facts come from a fake; no pipe, +/// service or process of this computer is looked at. +/// +public sealed class AgentPipePeerTrustTests +{ + /// The one refusal for an endpoint that is not the installed service. + private const string NotTheService = "The local endpoint is not the installed Windows print service. No request was sent. Check Windows Services and repair the machine installation if needed."; + + + + /// The refusal for a service that went away during the check. + private const string ServiceStopped = "The Windows print service stopped or restarted before it could be verified. No request was sent. Wait a moment and try again; check Windows Services if this continues."; + + + + /// + /// The other end is trusted when the pipe is served by the process that hosts the running print service, that + /// process runs as SYSTEM from the installed service program, and both the pipe and the service still name that + /// process when asked a second time. The facts are asked in that order, the service by its fixed name, and the + /// service and the process stay held until the connection ends, when the process is let go first. + /// + [Fact] + public void RunningSystemServiceThatServesThePipeIsTrustedAndHeldUntilTheConnectionEnds() + { + FakePipePeerFacts facts = new(); + AgentPipePeer peer = Authenticate(facts); + Assert.Equal(new[] { "OpenService QqqPrintAgent", "ServerProcessId", "ReadStatus", "OpenProcess 5120", "RunsAsSystem", "HasExited", "ProgramPath", "ServerProcessId", "ReadStatus" }, facts.Calls, StringComparer.Ordinal); + Assert.Equal(2, facts.OpenHandles); + peer.Dispose(); + Assert.Equal(new[] { "Dispose process", "Dispose service" }, facts.Calls[^2..], StringComparer.Ordinal); + Assert.Equal(0, facts.OpenHandles); + } + + + + /// Windows reports a program path in whatever case it was started with; the installed service program is recognized either way. + [Fact] + public void InstalledServiceProgramIsRecognizedWhateverTheCaseOfItsPath() + { + FakePipePeerFacts facts = new() { ProgramPath = FakePipePeerFacts.ServiceProgram.ToUpperInvariant() }; + using AgentPipePeer peer = Authenticate(facts); + Assert.Equal(2, facts.OpenHandles); + } + + + + /// + /// Each way a running process at the other end is not the installed service gets the one refusal that does not say + /// which check failed, with nothing inside it, and nothing stays held: a service that is not running, a service + /// hosted by another process than the one serving the pipe, a pipe served by no process, a process that does not + /// run as SYSTEM, a process running another program or none, and a pipe or a service that names another process + /// when asked again. + /// + [Theory] + [InlineData("service-stopped")] + [InlineData("service-starting")] + [InlineData("service-stopping")] + [InlineData("service-paused")] + [InlineData("service-hosted-elsewhere")] + [InlineData("pipe-served-by-no-process")] + [InlineData("not-system")] + [InlineData("another-installed-program")] + [InlineData("same-name-elsewhere")] + [InlineData("no-program")] + [InlineData("pipe-names-another-process-when-asked-again")] + [InlineData("service-names-another-process-when-asked-again")] + public void ProcessThatIsNotTheInstalledServiceIsRefused(string how) + { + FakePipePeerFacts facts = new(); + switch(how) + { + case "service-stopped": + facts.Statuses[0] = new PeerServiceStatus(1, FakePipePeerFacts.ServicePid); + break; + case "service-starting": + facts.Statuses[0] = new PeerServiceStatus(2, FakePipePeerFacts.ServicePid); + break; + case "service-stopping": + facts.Statuses[0] = new PeerServiceStatus(3, FakePipePeerFacts.ServicePid); + break; + case "service-paused": + facts.Statuses[0] = new PeerServiceStatus(7, FakePipePeerFacts.ServicePid); + break; + case "service-hosted-elsewhere": + facts.Statuses[0] = new PeerServiceStatus(FakePipePeerFacts.Running, 6000); + break; + case "pipe-served-by-no-process": + facts.ServerPids[0] = 0; + facts.Statuses[0] = new PeerServiceStatus(FakePipePeerFacts.Running, 0); + break; + case "not-system": + facts.IsSystem = false; + break; + case "another-installed-program": + facts.ProgramPath = @"C:\Program Files\QQQ Print Agent\Cli\qqq-print-agent.exe"; + break; + case "same-name-elsewhere": + facts.ProgramPath = @"C:\Users\Public\QQQ Print Agent\Service\Qqq.PrintAgent.Service.exe"; + break; + case "no-program": + facts.ProgramPath = null; + break; + case "pipe-names-another-process-when-asked-again": + facts.ServerPids.Add(6000); + break; + default: + facts.Statuses.Add(new PeerServiceStatus(FakePipePeerFacts.Running, 6000)); + break; + } + UnauthorizedAccessException refusal = Assert.Throws(() => Authenticate(facts)); + Assert.Equal(NotTheService, refusal.Message); + Assert.Null(refusal.InnerException); + Assert.Equal(0, facts.OpenHandles); + if((how.StartsWith("service-", StringComparison.Ordinal) && !how.EndsWith("again", StringComparison.Ordinal)) || how.StartsWith("pipe-served", StringComparison.Ordinal)) + { + Assert.DoesNotContain("RunsAsSystem", facts.Calls, StringComparer.Ordinal); + } + } + + + + /// + /// A check that could not be carried out is not a pass. While the process that serves the pipe is still running, + /// or cannot be looked at, the answer stays the one refusal, with what stopped the check kept inside for the log: + /// a service whose status cannot be read (it is not installed, or the caller may not control it), a process that + /// cannot be opened, an account or a program that cannot be read, and a pipe that cannot say who serves it when + /// asked again. A process that cannot be opened is refused the same way whether Windows said so with an error of + /// its own or .NET with an invalid-operation failure: neither is the sign that the process has ended, so the + /// failure neither escapes as it is nor turns the answer into "try again". + /// + [Theory] + [InlineData("service-unreadable")] + [InlineData("process-unopenable")] + [InlineData("process-unopenable-as-an-invalid-operation")] + [InlineData("account-unreadable")] + [InlineData("program-unreadable")] + [InlineData("pipe-silent-when-asked-again")] + public void CheckThatCouldNotBeCarriedOutIsRefusedWithItsCauseInside(string how) + { + FakePipePeerFacts facts = new(); + Exception cause = how switch + { + "service-unreadable" => new InvalidOperationException("Synthetic: service 'QqqPrintAgent' was not found on computer '.'."), + "process-unopenable-as-an-invalid-operation" => new InvalidOperationException("Synthetic: the process cannot be looked at."), + _ => new Win32Exception(5, "Synthetic: access is denied."), + }; + switch(how) + { + case "service-unreadable": + facts.ServiceFailure = cause; + break; + case "process-unopenable": + case "process-unopenable-as-an-invalid-operation": + facts.OpenFailure = cause; + break; + case "account-unreadable": + facts.AccountFailure = cause; + break; + case "program-unreadable": + facts.ProgramFailure = cause; + break; + default: + facts.PipeFailure = (2, cause); + break; + } + UnauthorizedAccessException refusal = Assert.Throws(() => Authenticate(facts)); + Assert.Equal(NotTheService, refusal.Message); + Assert.Same(cause, refusal.InnerException); + Assert.Equal(0, facts.OpenHandles); + } + + + + /// + /// When the service went away during the check there is nothing to mistrust, so the operator is told to wait and + /// try again, not to repair: the pipe can no longer say who serves it, the process that served it is gone or has + /// ended, or a check failed against a process that has ended since. What was found is kept inside, and nothing + /// stays held. + /// + [Theory] + [InlineData("pipe-cannot-say")] + [InlineData("process-gone")] + [InlineData("process-ended")] + [InlineData("not-system-and-ended")] + public void ServiceThatWentAwayDuringTheCheckIsReportedAsStopped(string how) + { + FakePipePeerFacts facts = new(); + switch(how) + { + case "pipe-cannot-say": + facts.PipeFailure = (1, new Win32Exception(233, "Synthetic: no process is on the other end of the pipe.")); + break; + case "process-gone": + facts.ProcessRuns = false; + break; + case "process-ended": + facts.HasExited = true; + break; + default: + facts.IsSystem = false; + facts.HasExited = true; + break; + } + UnauthorizedAccessException refusal = Assert.Throws(() => Authenticate(facts)); + Assert.Equal(ServiceStopped, refusal.Message); + Assert.NotNull(refusal.InnerException); + Assert.Equal(0, facts.OpenHandles); + if(string.Equals(how, "pipe-cannot-say", StringComparison.Ordinal)) + { + Assert.Same(facts.PipeFailure!.Value.Failure, refusal.InnerException); + Assert.Equal(new[] { "OpenService QqqPrintAgent", "ServerProcessId", "Dispose service" }, facts.Calls, StringComparer.Ordinal); + } + } + + + + /// + /// Everything acquired for the check is released before the refusal is chosen: the process and then the service + /// are let go, and only then is the process looked up again, through a handle of its own, to see whether it has + /// ended. + /// + [Fact] + public void WhatWasAcquiredIsReleasedBeforeTheRefusalIsChosen() + { + FakePipePeerFacts facts = new() { IsSystem = false }; + _ = Assert.Throws(() => Authenticate(facts)); + Assert.Equal(new[] { "OpenService QqqPrintAgent", "ServerProcessId", "ReadStatus", "OpenProcess 5120", "RunsAsSystem", "Dispose process", "Dispose service", "OpenProcess 5120", "HasExited", "Dispose process" }, facts.Calls, StringComparer.Ordinal); + } + + + + /// + /// The second look at the service asks only which process hosts it. A service that has begun to stop since the + /// first look and is still hosted by the verified process is trusted as before: that process is held by then, so + /// its id cannot have passed to another, and a service that has stopped names no process at all. + /// + [Fact] + public void SecondLookAtTheServiceComparesOnlyTheProcessThatHostsIt() + { + FakePipePeerFacts facts = new(); + facts.Statuses.Add(new PeerServiceStatus(3, FakePipePeerFacts.ServicePid)); + using AgentPipePeer peer = Authenticate(facts); + Assert.Equal(2, facts.Calls.Count(call => string.Equals(call, "ReadStatus", StringComparison.Ordinal))); + Assert.Equal(2, facts.OpenHandles); + } + + + + /// + /// The installed product's check is bound to the real Windows facts and trusts only the service program at its fixed + /// place under this computer's Program Files. Only the binding is read here; Windows is asked nothing. + /// + [Fact] + public void InstalledProductsCheckIsBoundToWindowsAndTheServiceProgramUnderProgramFiles() + { + _ = Assert.IsType(AgentPipePeer.Installed.Facts); + Assert.Equal(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "QQQ Print Agent", "Service", "Qqq.PrintAgent.Service.exe"), AgentPipePeer.Installed.ServiceProgram); + } + + + + /// + /// A bound check asks its own facts and trusts its own program and no other. Over the same facts, the check bound + /// to the program the process runs trusts the other end, and the check bound to another program refuses it. A + /// refusal is judged by the same facts: for an id no process can have, which Windows itself would leave in doubt, + /// facts that say the process is gone give "try again". + /// + [Fact] + public void BoundCheckAsksItsOwnFactsAndTrustsItsOwnProgram() + { + using SafePipeHandle pipe = new(IntPtr.Zero, ownsHandle: false); + FakePipePeerFacts facts = new(); + using(new AgentPipePeer.Check(facts, FakePipePeerFacts.ServiceProgram).Authenticate(pipe)) + { + Assert.Equal(2, facts.OpenHandles); + } + UnauthorizedAccessException refusal = Assert.Throws(() => new AgentPipePeer.Check(facts, @"C:\Program Files\QQQ Print Agent\Cli\qqq-print-agent.exe").Authenticate(pipe)); + Assert.Equal(NotTheService, refusal.Message); + Assert.Equal(0, facts.OpenHandles); + facts.ProcessRuns = false; + Assert.Equal(ServiceStopped, new AgentPipePeer.Check(facts, FakePipePeerFacts.ServiceProgram).Refusal(uint.MaxValue, new InvalidOperationException("Synthetic: a check that threw.")).Message); + Assert.Equal("OpenProcess 4294967295", facts.Calls[^1]); + } + + + + /// Runs the check against the given facts. The pipe handle is never used by the fake, so a closed one stands in for it. + private static AgentPipePeer Authenticate(FakePipePeerFacts facts) + { + using SafePipeHandle pipe = new(IntPtr.Zero, ownsHandle: false); + return AgentPipePeer.Authenticate(pipe, facts, FakePipePeerFacts.ServiceProgram); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/AgentServiceActionsTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/AgentServiceActionsTests.cs new file mode 100644 index 0000000..5221b26 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/AgentServiceActionsTests.cs @@ -0,0 +1,322 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.ServiceProcess; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// What the companion's service controls do and say, run against a service that exists only in memory and a clock the +/// test moves: how each state reads and what is offered in it, when the service is started or stopped, in which order, +/// and how long it is waited for. No test here reads, starts or stops a service of this computer. +/// +public sealed class AgentServiceActionsTests +{ + /// The name of the service the actions under test are for. + private const string Name = "SyntheticPrintService"; + + + + /// What is said about a service that is not stopped. + private const string Independent = "The Windows service runs independently of this companion."; + + + + /// What is said about a stopped service. + private const string StartIt = "Start the service to connect and print."; + + + + /// The pause between two looks at the service while it is waited for. + private static readonly TimeSpan Poll = TimeSpan.FromMilliseconds(250); + + + + /// + /// The state is shown under Windows' own name for it. Only a stopped service can be started, only a running one + /// that accepts a stop can be restarted, and a stopped one is the only one the operator is told to start. Whether a + /// stop is accepted is asked only of a running service, and the service is let go again. + /// + [Theory] + [InlineData(ServiceControllerStatus.Running, true, false, true, Independent)] + [InlineData(ServiceControllerStatus.Running, false, false, false, Independent)] + [InlineData(ServiceControllerStatus.Stopped, true, true, false, StartIt)] + [InlineData(ServiceControllerStatus.StartPending, true, false, false, Independent)] + [InlineData(ServiceControllerStatus.StopPending, true, false, false, Independent)] + [InlineData(ServiceControllerStatus.Paused, true, false, false, Independent)] + public void StateIsShownWithWhatCanBeDoneInIt(ServiceControllerStatus state, bool acceptsStop, bool canStart, bool canRestart, string guidance) + { + var setup = new Setup { Services = { State = state, AcceptsStop = acceptsStop } }; + Assert.Equal(new AgentServiceStatus(true, state.ToString(), canStart, canRestart, guidance), setup.Actions.GetStatus()); + Assert.Equal(state == ServiceControllerStatus.Running ? new[] { "Open " + Name, "Status", "CanStop", "Dispose" } : ["Open " + Name, "Status", "Dispose"], setup.Services.Calls, StringComparer.Ordinal); + } + + + + /// A service name that no installed service has (Windows error 1060) reads as not installed, with where to get the installer. + [Fact] + public void ServiceThatDoesNotExistReadsAsNotInstalled() + { + var setup = new Setup { Services = { Refusal = FakeServiceManager.NotInstalled() } }; + Assert.Equal(new AgentServiceStatus(false, "Not installed", false, false, "Install the QQQ Print Agent MSI from the project releases, then reopen this app. Windows Services can confirm the installation."), setup.Actions.GetStatus()); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// Any other refusal from Windows reads as unavailable, never as not installed: access denied, a refusal without an error, and a bare Windows error. + [Theory] + [InlineData("access-denied")] + [InlineData("no-error")] + [InlineData("bare-error")] + public void OtherRefusalsReadAsUnavailable(string refusal) + { + var setup = new Setup(); + setup.Services.Refusal = refusal switch + { + "access-denied" => FakeServiceManager.Refused(5), + "no-error" => new InvalidOperationException("Synthetic: the service controller is not usable."), + _ => new Win32Exception(1060), + }; + Assert.Equal(new AgentServiceStatus(false, "Unavailable", false, false, "Windows could not read the service state. Use an administrator account and check Windows Services."), setup.Actions.GetStatus()); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// A failure that is not a refusal from Windows is not turned into a state; it reaches the caller, and the service is still let go. + [Fact] + public void FailureThatIsNotARefusalFromWindowsIsNotHidden() + { + var setup = new Setup { Services = { Refusal = new IOException("Synthetic: something else failed.") } }; + Assert.Same(setup.Services.Refusal, Assert.Throws(setup.Actions.GetStatus)); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// + /// A stopped service is started once and then looked at every 250 ms, with a fresh reading each time, until it + /// runs; the state reported at the end is read anew. + /// + [Fact] + public async Task StoppedServiceIsStartedAndWaitedForUntilItRuns() + { + var setup = new Setup(); + setup.Become(ServiceControllerStatus.StartPending, ServiceControllerStatus.StartPending, ServiceControllerStatus.Running); + Task start = setup.Actions.StartAsync(); + await setup.PassPollsAsync(2); + Assert.Equal(new AgentServiceStatus(true, "Running", false, true, Independent), await start.WaitAsync(MsiUpdateSetup.Patience)); + Assert.Equal(new[] { "Open " + Name, "Status", "Start", "Refresh", "Status", "Refresh", "Status", "Refresh", "Status", "Open " + Name, "Status", "CanStop", "Dispose", "Dispose" }, setup.Services.Calls, StringComparer.Ordinal); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// A service that already runs, or is already on its way, is not started again; it is only waited for. + [Theory] + [InlineData(ServiceControllerStatus.Running)] + [InlineData(ServiceControllerStatus.StartPending)] + public async Task ServiceThatIsNotStoppedIsNotStartedAgain(ServiceControllerStatus state) + { + var setup = new Setup { Services = { State = state } }; + setup.Become(ServiceControllerStatus.Running); + Assert.True((await setup.Actions.StartAsync().WaitAsync(MsiUpdateSetup.Patience)).CanRestart); + Assert.DoesNotContain("Start", setup.Services.Calls, StringComparer.Ordinal); + Assert.Equal(0, setup.Clock.PendingTimers); + } + + + + /// + /// A service that does not come up is waited for for 30 seconds and no longer: after 119 looks a quarter of a second + /// apart the action is still waiting, and at 30 seconds it fails and says which state was not reached. + /// + [Fact] + public async Task ServiceThatDoesNotStartWithinThirtySecondsIsReported() + { + var setup = new Setup(); + Task start = setup.Actions.StartAsync(); + await setup.PassPollsAsync(119); + await MsiUpdateSetup.UntilAsync(() => setup.Clock.HasTimerDueIn(Poll)); + Assert.False(start.IsCompleted); + setup.Clock.Advance(Poll); + System.TimeoutException failure = await Assert.ThrowsAsync(() => start.WaitAsync(MsiUpdateSetup.Patience)); + Assert.Equal("The service did not reach Running within 30 seconds. Check Windows Services and the activity log.", failure.Message); + Assert.Equal(121, setup.Services.Calls.Count(call => string.Equals(call, "Refresh", StringComparison.Ordinal))); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// + /// The state is looked at before the limit: a service that is found running at the look that falls on the 30th + /// second, the 121st, is in time, and the action succeeds. + /// + [Fact] + public async Task ServiceThatRunsAtTheLookOnTheThirtiethSecondIsInTime() + { + var setup = new Setup(); + setup.Become([.. Enumerable.Repeat(ServiceControllerStatus.StartPending, 120), ServiceControllerStatus.Running]); + Task start = setup.Actions.StartAsync(); + await setup.PassPollsAsync(120); + Assert.Equal("Running", (await start.WaitAsync(MsiUpdateSetup.Patience)).State); + Assert.Equal(121, setup.Services.Calls.Count(call => string.Equals(call, "Refresh", StringComparison.Ordinal))); + Assert.Equal(0, setup.Clock.PendingTimers); + } + + + + /// A restart stops a service that is not stopped, running or paused alike, waits until it has stopped, and only then starts it and waits until it runs. + [Theory] + [InlineData(ServiceControllerStatus.Running)] + [InlineData(ServiceControllerStatus.Paused)] + public async Task ServiceThatIsNotStoppedIsStoppedAndStartedOnlyOnceItHasStopped(ServiceControllerStatus state) + { + var setup = new Setup { Services = { State = state } }; + setup.Become(ServiceControllerStatus.StopPending, ServiceControllerStatus.Stopped, ServiceControllerStatus.StartPending, ServiceControllerStatus.Running); + Task restart = setup.Actions.RestartAsync(); + await setup.PassPollsAsync(2); + Assert.Equal(new AgentServiceStatus(true, "Running", false, true, Independent), await restart.WaitAsync(MsiUpdateSetup.Patience)); + Assert.Equal(new[] { "Open " + Name, "Status", "Stop", "Refresh", "Status", "Refresh", "Status", "Start", "Refresh", "Status", "Refresh", "Status", "Open " + Name, "Status", "CanStop", "Dispose", "Dispose" }, setup.Services.Calls, StringComparer.Ordinal); + } + + + + /// A restart of a service that is already stopped only starts it; nothing is stopped. + [Fact] + public async Task StoppedServiceIsOnlyStartedByARestart() + { + var setup = new Setup(); + setup.Become(ServiceControllerStatus.Running); + Assert.Equal("Running", (await setup.Actions.RestartAsync().WaitAsync(MsiUpdateSetup.Patience)).State); + Assert.Equal(new[] { "Open " + Name, "Status", "Start", "Refresh", "Status", "Open " + Name, "Status", "CanStop", "Dispose", "Dispose" }, setup.Services.Calls, StringComparer.Ordinal); + } + + + + /// A service that does not stop within 30 seconds is reported as not having stopped, and is not started on top of that. + [Fact] + public async Task ServiceThatDoesNotStopWithinThirtySecondsIsNotStarted() + { + var setup = new Setup { Services = { State = ServiceControllerStatus.Running } }; + Task restart = setup.Actions.RestartAsync(); + await setup.PassPollsAsync(120); + System.TimeoutException failure = await Assert.ThrowsAsync(() => restart.WaitAsync(MsiUpdateSetup.Patience)); + Assert.Equal("The service did not reach Stopped within 30 seconds. Check Windows Services and the activity log.", failure.Message); + Assert.DoesNotContain("Start", setup.Services.Calls, StringComparer.Ordinal); + Assert.Equal(0, setup.Services.OpenHandles); + } + + + + /// + /// What Windows refuses is not dressed up: a service that will not accept a stop, and a service that is not + /// installed, fail the action with Windows' own refusal, nothing is started, and the service is let go. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task RefusalFromWindowsFailsTheActionAsItIs(bool notInstalled) + { + var setup = new Setup { Services = { State = ServiceControllerStatus.Running, AcceptsStop = false } }; + setup.Services.Refusal = notInstalled ? FakeServiceManager.NotInstalled() : null; + InvalidOperationException restart = await Assert.ThrowsAsync(setup.Actions.RestartAsync); + Assert.Equal(notInstalled ? 1060 : 1052, Assert.IsType(restart.InnerException).NativeErrorCode); + if(notInstalled) + { Assert.Same(setup.Services.Refusal, await Assert.ThrowsAsync(setup.Actions.StartAsync)); } + Assert.DoesNotContain("Start", setup.Services.Calls, StringComparer.Ordinal); + Assert.Equal(0, setup.Services.OpenHandles); + Assert.Equal(0, setup.Clock.PendingTimers); + } + + + + /// + /// The Services console is opened by starting the management console of the Windows system folder with the services + /// snap-in from that same folder as its one argument, through the shell so that Windows can ask for elevation. That + /// Windows hands back no process for it is not an error. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ServicesConsoleIsOpenedFromTheSystemFolderThroughTheShell(bool windowsHandsBackAProcess) + { + var setup = new Setup(); + if(!windowsHandsBackAProcess) + { setup.Processes.OnStart = _ => null; } + setup.Actions.OpenServices(); + System.Diagnostics.ProcessStartInfo start = Assert.Single(setup.Processes.Started); + Assert.Equal(Path.Combine(Environment.SystemDirectory, "mmc.exe"), start.FileName); + Assert.Equal(new[] { Path.Combine(Environment.SystemDirectory, "services.msc") }, start.ArgumentList, StringComparer.Ordinal); + Assert.True(start.UseShellExecute); + Assert.Equal(0, setup.Processes.OpenHandles); + Assert.Empty(setup.Services.Calls); + } + + + + /// The installed product's controls are for the service the MSI registers, by its fixed name. Only the name is read; the service is not. + [Fact] + public void InstalledProductControlsTheServiceTheMsiRegisters() + { + Assert.Equal("QqqPrintAgent", AgentServiceControl.Installed.ServiceName); + } + + + + /// The actions under test over a service, processes and a clock that exist only in memory. + private sealed class Setup + { + /// Builds the actions over the fakes. + internal Setup() + { + Actions = new AgentServiceActions(Services, Processes, Clock, Name); + } + + + + /// The service control manager fake; its one service is stopped unless a test says otherwise. + internal FakeServiceManager Services { get; } = new(); + + + + /// The process fake. + internal FakeProcessHost Processes { get; } = new(); + + + + /// The clock, which moves only when a test advances it. + internal ManualTimeProvider Clock { get; } = new(); + + + + /// The actions under test. + internal AgentServiceActions Actions { get; } + + + + /// Says which states the service moves through, one each time it is looked at again. + internal void Become(params ServiceControllerStatus[] states) + { + foreach(ServiceControllerStatus state in states) + { Services.Next.Enqueue(state); } + } + + + + /// Lets the given number of pauses between two looks pass: each time, waits until the action has begun a pause of exactly 250 ms and then moves the clock by that much. + internal async Task PassPollsAsync(int polls) + { + for(int poll = 0; poll < polls; poll++) + { + await MsiUpdateSetup.UntilAsync(() => Clock.HasTimerDueIn(Poll)); + Clock.Advance(Poll); + } + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakeActivityLog.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakeActivityLog.cs new file mode 100644 index 0000000..a79377a --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakeActivityLog.cs @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using KofTwentyTwo.AppKit.Logging; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// An activity log that keeps its entries in memory, each as the level in capitals, a space and the message, so a test +/// can check both what was written and how severe it was said to be. It can be told to refuse every entry, the way a +/// log on a failed disk does. +/// +internal sealed class FakeActivityLog : IActivityLog +{ + /// Every entry written, in order. + internal List Entries { get; } = []; + + + + /// When set, every write fails with this. + internal Exception? Failure { get; set; } + + + + /// No folder: nothing is written to disk. + public string LogDirectory => ""; + + + + /// No file: nothing is written to disk. + public string CurrentLogFilePath => ""; + + + + /// Records an informational entry. + public void Info(string message) => Write("INFO " + message); + + + + /// Records a warning. + public void Warning(string message) => Write("WARN " + message); + + + + /// Records an error; the exception, when one is given, is not part of the entry. + public void Error(string message, Exception? exception = null) => Write("ERROR " + message); + + + + /// Keeps the entry, or fails as the test asked. + private void Write(string entry) + { + if(Failure is not null) + { throw Failure; } + lock(Entries) + { Entries.Add(entry); } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakeMsiReleaseSource.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakeMsiReleaseSource.cs new file mode 100644 index 0000000..29afc21 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakeMsiReleaseSource.cs @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// A release source that exists only in memory: it offers the release a test gives it and "downloads" by writing the +/// bytes the test chose into the staging folder it is handed, under a new name each time, as the real client does. It +/// can be told to fail a check or a download, and it honours cancellation the way the real one does, by ending with +/// the cancellation. Nothing reaches the network. +/// +internal sealed class FakeMsiReleaseSource : IMsiReleaseSource +{ + /// The release a check finds; null when the installed version is the newest. + internal MsiRelease? Offered { get; set; } + + + + /// When set, a check fails with this. + internal Exception? CheckFailure { get; set; } + + + + /// The installed version each check was made for, in order. + internal List Checks { get; } = []; + + + + /// When set, a download fails with this after the staging folder has been made. + internal Exception? DownloadFailure { get; set; } + + + + /// What a downloaded installer holds. + internal byte[] Content { get; set; } = [0xD0, 0xCF, 0x11, 0xE0, 9, 8, 7]; + + + + /// The fractions of the whole a download reports as it goes. + internal double[] Progress { get; set; } = [0.5, 1.0]; + + + + /// Every download asked for, in order: the release, the installed version it was asked for and the staging folder. + internal List<(MsiRelease Release, string CurrentVersion, string Directory)> Downloads { get; } = []; + + + + /// Called during a download with the staging folder, so a test can put something there or cancel while the download is under way. + internal Action? WhileDownloading { get; set; } + + + + /// True once the source has been released. + internal bool Disposed { get; private set; } + + + + /// Notes the check and answers with the offered release, or fails as the test asked. + public Task FindUpdateAsync(string currentVersion, CancellationToken cancellationToken = default) + { + Checks.Add(currentVersion); + cancellationToken.ThrowIfCancellationRequested(); + return CheckFailure is not null ? Task.FromException(CheckFailure) : Task.FromResult(Offered); + } + + + + /// Notes the download, makes the staging folder, writes the installer into it under a new name and reports progress; or fails as the test asked, leaving no installer. + public Task DownloadVerifiedAsync(MsiRelease release, string currentVersion, string stagingDirectory, IProgress? progress = null, CancellationToken cancellationToken = default) + { + Downloads.Add((release, currentVersion, stagingDirectory)); + Directory.CreateDirectory(stagingDirectory); + WhileDownloading?.Invoke(stagingDirectory); + cancellationToken.ThrowIfCancellationRequested(); + if(DownloadFailure is not null) + { return Task.FromException(DownloadFailure); } + string package = Path.Combine(stagingDirectory, "QqqPrintAgent-v" + release.Version + "-x64-" + Guid.NewGuid().ToString("N") + ".msi"); + File.WriteAllBytes(package, Content); + foreach(double fraction in Progress) + { progress?.Report(fraction); } + return Task.FromResult(package); + } + + + + /// Notes that the source was released. + public void Dispose() => Disposed = true; +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakePathSecurity.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakePathSecurity.cs index 880b50c..9202208 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/FakePathSecurity.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakePathSecurity.cs @@ -12,7 +12,9 @@ namespace Qqq.PrintAgent.Cli.Tests; /// /// Folder ownership and access lists as a test describes them. A folder has the descriptor the test gave it, or a trusted /// one when the test said nothing; a folder the rules create is made as an ordinary folder on disk and remembered with the -/// descriptor the rules asked for, so a test can check that descriptor. Nothing is read from Windows. +/// descriptor the rules asked for, so a test can check that descriptor. A folder or file that does not exist cannot be +/// read, as with the real one. No owner or access list is read from Windows; the disk is asked only whether the folder +/// or file is there. /// internal sealed class FakePathSecurity : IPathSecurity { @@ -41,6 +43,11 @@ internal sealed class FakePathSecurity : IPathSecurity + /// Asked for the descriptor of a folder or file the test did not list, for a path whose name a test cannot know in advance; no function, or null from it, means a trusted one. + internal Func? Unlisted { get; set; } + + + /// Every folder or file whose descriptor was read, in order. internal List Reads { get; } = []; @@ -70,11 +77,13 @@ internal sealed class FakePathSecurity : IPathSecurity - /// Returns the descriptor the test set for the folder, or a trusted one. + /// Returns the descriptor the test set for the folder, or a trusted one; a folder that does not exist cannot be read, as on a real disk. public FileSystemSecurity ReadDirectorySecurity(string directory) { Reads.Add(directory); - return Descriptors.TryGetValue(directory, out FileSystemSecurity? descriptor) ? descriptor : Descriptor(); + if(!Directory.Exists(directory)) + { throw new DirectoryNotFoundException("Synthetic: no such folder to read a security descriptor from: " + directory); } + return Descriptors.TryGetValue(directory, out FileSystemSecurity? descriptor) ? descriptor : Unlisted?.Invoke(directory) ?? Descriptor(); } @@ -85,7 +94,7 @@ internal sealed class FakePathSecurity : IPathSecurity Reads.Add(file); if(!File.Exists(file)) { throw new FileNotFoundException("Synthetic: no such file to read a security descriptor from.", file); } - return Descriptors.TryGetValue(file, out FileSystemSecurity? descriptor) ? descriptor : Descriptor(); + return Descriptors.TryGetValue(file, out FileSystemSecurity? descriptor) ? descriptor : Unlisted?.Invoke(file) ?? Descriptor(); } diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakePipePeerFacts.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakePipePeerFacts.cs new file mode 100644 index 0000000..739d16f --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakePipePeerFacts.cs @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using Microsoft.Win32.SafeHandles; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The facts about the other end of a pipe as a test describes them. Unless a test says otherwise they are those of +/// the installed print service: the pipe is served by the process the running service is hosted in, and that process +/// runs as SYSTEM from the service's program. A test changes one fact, or makes one question fail, and every question +/// asked is recorded in order. Where a fact is asked twice a test can give a different second answer, the way the +/// real one changes when the service is replaced during the check. It fails as Windows does where the decision depends +/// on it: an id no running process has cannot be opened. Nothing is read from Windows. +/// +internal sealed class FakePipePeerFacts : IPipePeerFacts +{ + /// The process id of the service in these tests. + internal const uint ServicePid = 5120; + + + + /// The program the installed service runs. + internal const string ServiceProgram = @"C:\Program Files\QQQ Print Agent\Service\Qqq.PrintAgent.Service.exe"; + + + + /// The state Windows reports for a running service. + internal const uint Running = 4; + + + + /// The answers to "which process serves the pipe", in the order asked; the last one repeats. + internal List ServerPids { get; } = [ServicePid]; + + + + /// When set, the pipe cannot say who serves it from the given question on (1 is the first). + internal (int From, Exception Failure)? PipeFailure { get; set; } + + + + /// The answers of the service control manager, in the order asked; the last one repeats. + internal List Statuses { get; } = [new(Running, ServicePid)]; + + + + /// When set, the service's status cannot be read: every read fails with this. + internal Exception? ServiceFailure { get; set; } + + + + /// False when no running process has the id any more, which Windows reports as an argument failure. + internal bool ProcessRuns { get; set; } = true; + + + + /// When set, the process cannot be opened although it may be running: every attempt fails with this. + internal Exception? OpenFailure { get; set; } + + + + /// Whether the process runs as SYSTEM. + internal bool IsSystem { get; set; } = true; + + + + /// When set, the process's account cannot be read: asking fails with this. + internal Exception? AccountFailure { get; set; } + + + + /// Whether the process has ended although a handle to it could still be opened. + internal bool HasExited { get; set; } + + + + /// The program the process runs; null plays a process without a main module. + internal string? ProgramPath { get; set; } = ServiceProgram; + + + + /// When set, the process's program cannot be read: asking fails with this. + internal Exception? ProgramFailure { get; set; } + + + + /// Every question asked and every handle let go, in order. + internal List Calls { get; } = []; + + + + /// How many service and process handles are held and not yet let go. + internal int OpenHandles { get; private set; } + + + + /// How many times the pipe was asked who serves it. + private int _pipeQuestions; + + + + /// How many times the service's status was read. + private int _statusReads; + + + + /// Answers who serves the pipe, with the next answer the test gave, or fails as the test asked. + public uint ServerProcessId(SafePipeHandle pipe) + { + Calls.Add("ServerProcessId"); + _pipeQuestions++; + if(PipeFailure is { } failure && _pipeQuestions >= failure.From) + { throw failure.Failure; } + return ServerPids[Math.Min(_pipeQuestions, ServerPids.Count) - 1]; + } + + + + /// Hands out a handle to the named service; nothing is read yet. + public IPeerService OpenService(string serviceName) + { + Calls.Add("OpenService " + serviceName); + OpenHandles++; + return new Service(this); + } + + + + /// Hands out a handle to the process with the id, or fails the way Windows does when none runs under it or it may not be opened. + public IPeerProcess OpenProcess(uint processId) + { + Calls.Add("OpenProcess " + processId); + if(OpenFailure is not null) + { throw OpenFailure; } + if(!ProcessRuns) + { throw new ArgumentException($"Synthetic: process with an Id of {processId} is not running.", nameof(processId)); } + OpenHandles++; + return new Process(this); + } + + + + /// One handle to the service. + private sealed class Service(FakePipePeerFacts facts) : IPeerService + { + /// Answers with the next status the test gave, or fails as the test asked. + public PeerServiceStatus ReadStatus() + { + facts.Calls.Add("ReadStatus"); + facts._statusReads++; + return facts.ServiceFailure is not null ? throw facts.ServiceFailure : facts.Statuses[Math.Min(facts._statusReads, facts.Statuses.Count) - 1]; + } + + + + /// Lets the handle go. + public void Dispose() + { + facts.Calls.Add("Dispose service"); + facts.OpenHandles--; + } + } + + + + /// One handle to the process. + private sealed class Process(FakePipePeerFacts facts) : IPeerProcess + { + /// Whether the process has ended. + public bool HasExited + { + get + { + facts.Calls.Add("HasExited"); + return facts.HasExited; + } + } + + + + /// The program the process runs, or the failure the test asked for. + public string? ProgramPath + { + get + { + facts.Calls.Add("ProgramPath"); + return facts.ProgramFailure is not null ? throw facts.ProgramFailure : facts.ProgramPath; + } + } + + + + /// Whether the process runs as SYSTEM, or the failure the test asked for. + public bool RunsAsSystem() + { + facts.Calls.Add("RunsAsSystem"); + return facts.AccountFailure is not null ? throw facts.AccountFailure : facts.IsSystem; + } + + + + /// Lets the handle go. + public void Dispose() + { + facts.Calls.Add("Dispose process"); + facts.OpenHandles--; + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakeProcess.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakeProcess.cs new file mode 100644 index 0000000..59c7e79 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakeProcess.cs @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// One process that exists only in memory: the program it runs, when it started, whether it has ended and with what +/// code. Each time it is opened it hands out a separate handle, as Windows does, and counts the handles that have not +/// been let go. It behaves as a real process does where the update rules depend on it: its exit code cannot be read +/// before it has ended, a wait for it ends with a cancellation when the token is cancelled first, and its program path +/// cannot be read once it has ended. What .NET 10 says about that read depends on whether anything else still holds +/// the ended process. While another handle keeps it, the read fails with Windows error 299, because its memory can no +/// longer be read; that is what this fake does unless a test says otherwise. When nothing else holds it, which is the +/// update helper's own situation, the read fails with an invalid-operation failure saying that the process has +/// exited; a test plays that by setting together with . +/// +internal sealed class FakeProcess(int id, string? program, long startTicks) +{ + /// Completed when the process ends, which is what a wait for it waits on. + private readonly TaskCompletionSource _ended = new(TaskCreationOptions.RunContinuationsAsynchronously); + + + + /// The exit code, once the process has ended. + private int? _exitCode; + + + + /// The process id. + internal int Id => id; + + + + /// The program the process runs; null plays a process that has no main module. + internal string? Program { get; set; } = program; + + + + /// When the process started, in universal time ticks. + internal long StartTicks { get; set; } = startTicks; + + + + /// True once the process has ended. + internal bool HasExited => _exitCode is not null; + + + + /// How many handles to this process are open: handed out and not yet let go. + internal int OpenHandles { get; private set; } + + + + /// How many times a wait for the process to end was begun. + internal int Waits { get; private set; } + + + + /// When set, reading the program path fails with this, the way Windows refuses to let a process be inspected. + internal Exception? InspectionFailure { get; set; } + + + + /// When true, the process ends at the moment its program path is read, so the read fails: with when a test set one, and otherwise the way it does for a process that has ended. + internal bool ExitsWhenInspected { get; set; } + + + + /// Ends the process with the given code and releases every wait for it. + internal void Exit(int code) + { + _exitCode = code; + _ended.TrySetResult(); + } + + + + /// Opens one more handle to the process. + internal IRunningProcess Open() + { + OpenHandles++; + return new Handle(this); + } + + + + /// One handle to the process. Like a real one it is of no use once it has been let go. + private sealed class Handle(FakeProcess process) : IRunningProcess + { + /// True once this handle has been let go. + private bool _disposed; + + + + /// Whether the process has ended. + public bool HasExited => Live().HasExited; + + + + /// The program path, read the way Windows reads it: not when inspection is refused, and not from a process that has ended. For an ended process this plays the case in which something else still holds it, so that its memory can no longer be read (error 299); the case in which nothing holds it is a failure the test sets. + public string? ProgramPath + { + get + { + FakeProcess live = Live(); + if(live.ExitsWhenInspected) + { live.Exit(0); } + if(live.InspectionFailure is not null) + { throw live.InspectionFailure; } + if(live.HasExited) + { throw new Win32Exception(299, "Synthetic: only part of a ReadProcessMemory or WriteProcessMemory request was completed."); } + return live.Program; + } + } + + + + /// The start time in universal time ticks. + public long StartTicks => Live().StartTicks; + + + + /// The exit code, which a process that is still running does not have. + public int ExitCode => Live()._exitCode ?? throw new InvalidOperationException("Synthetic: process must exit before requested information can be determined."); + + + + /// Waits for the process to end; a token cancelled first ends the wait with the cancellation and leaves the process running. + public Task WaitForExitAsync(CancellationToken cancellationToken) + { + FakeProcess live = Live(); + live.Waits++; + return live._ended.Task.WaitAsync(cancellationToken); + } + + + + /// Lets the handle go; letting it go twice is harmless, as with a real one. + public void Dispose() + { + if(!_disposed) + { + _disposed = true; + process.OpenHandles--; + } + } + + + + /// The process, as long as this handle is still held. + private FakeProcess Live() => _disposed ? throw new InvalidOperationException("Synthetic: no process is associated with this object.") : process; + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakeProcessHost.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakeProcessHost.cs new file mode 100644 index 0000000..7d8d09f --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakeProcessHost.cs @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The processes of a computer that exists only in memory. A test says which processes are running, which program the +/// rules themselves run as and what version each program file carries; every program the rules start is recorded and +/// nothing is started. It fails the way Windows does where the rules depend on it: an id no process has cannot be +/// opened, a program file that does not exist cannot be started, and a file that does not exist has no version to read. +/// Whether a program file exists is read from the disk only for the files a test made in its temporary folders; the +/// two programs of the Windows system folder the rules start are simply taken to exist, so that no test depends on +/// what this computer has installed. +/// +internal sealed class FakeProcessHost : IProcessHost +{ + /// The program the rules run as. + public string? CurrentPath { get; set; } + + + + /// The id of the process the rules run in. + public int CurrentId { get; set; } = 4242; + + + + /// The processes that can be opened, by id. + internal Dictionary Running { get; } = []; + + + + /// Every id the rules asked to open, in order. + internal List Opened { get; } = []; + + + + /// Called while a process is being opened, with its id, so a test can act at the moment the rules look at a process. + internal Action? WhileOpening { get; set; } + + + + /// Every start the rules asked for, in order, exactly as they described it. + internal List Started { get; } = []; + + + + /// Every process a start produced, in order; null where the start produced none. + internal List Produced { get; } = []; + + + + /// + /// What a start produces: by default a process that has already ended with code 0. A test replaces it to choose the + /// exit code, to keep the process running, to look at the files while the program "runs", or to produce nothing. + /// + internal Func OnStart { get; set; } = start => Ended(start.FileName, 0); + + + + /// The product version of each program file; a file that is listed with null carries none. + internal Dictionary Versions { get; } = new(StringComparer.OrdinalIgnoreCase); + + + + /// Every file whose version was read, in order. + internal List VersionsRead { get; } = []; + + + + /// + /// The programs of the Windows system folder that exist on this computer in memory, whatever the real one has: + /// Windows Installer and the management console, which are the two the rules start from there. The disk is not + /// asked about them. + /// + internal HashSet SystemPrograms { get; } = new(StringComparer.OrdinalIgnoreCase) + { + Path.Combine(Environment.SystemDirectory, "msiexec.exe"), + Path.Combine(Environment.SystemDirectory, "mmc.exe"), + }; + + + + /// A process that has already ended with the given code. + internal static FakeProcess Ended(string program, int code) + { + FakeProcess process = new(id: 7000, program, startTicks: 1); + process.Exit(code); + return process; + } + + + + /// Registers a running process and returns it. + internal FakeProcess Run(int id, string? program, long startTicks) + { + FakeProcess process = new(id, program, startTicks); + Running[id] = process; + return process; + } + + + + /// How many handles the rules still hold, to processes they opened or started. + internal int OpenHandles => Running.Values.Sum(process => process.OpenHandles) + Produced.Sum(process => process?.OpenHandles ?? 0); + + + + /// Opens the process with the id; an id no process has is refused the way Windows refuses it. + public IRunningProcess Open(int processId) + { + Opened.Add(processId); + WhileOpening?.Invoke(processId); + return Running.TryGetValue(processId, out FakeProcess? process) ? process.Open() : throw new ArgumentException($"Synthetic: process with an Id of {processId} is not running.", nameof(processId)); + } + + + + /// Records the start and produces what the test chose; a program file that does not exist cannot be started, as on a real disk. A system program exists when it is listed in , and any other file when the test made it. + public IRunningProcess? Start(ProcessStartInfo start) + { + Started.Add(start); + if(!SystemPrograms.Contains(start.FileName) && !File.Exists(start.FileName)) + { throw new Win32Exception(2, "Synthetic: the system cannot find the file specified."); } + FakeProcess? process = OnStart(start); + Produced.Add(process); + return process?.Open(); + } + + + + /// The version the test gave the file; a file the test did not list does not exist. + public string? ProductVersion(string path) + { + VersionsRead.Add(path); + return Versions.TryGetValue(path, out string? version) ? version : throw new FileNotFoundException("Synthetic: no such program file to read a version from.", path); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/FakeServiceManager.cs b/tests/Qqq.PrintAgent.Cli.Tests/FakeServiceManager.cs new file mode 100644 index 0000000..2d1141c --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/FakeServiceManager.cs @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.ServiceProcess; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// A service control manager with one service that exists only in memory. A test says what state the service is in, +/// whether it accepts a stop, and which states it moves through as it is looked at again; every call made is recorded +/// in order. It behaves as the real one does where the service actions depend on it: a handle remembers the state it +/// read until it is refreshed, a service that is not stopped cannot be started and one that is stopped cannot be +/// stopped, and a refusal from Windows is an invalid-operation failure that carries Windows' error. No service of +/// this computer is read or controlled. +/// +internal sealed class FakeServiceManager : IServiceManager +{ + /// The state the service is really in, whatever a handle remembers. + internal ServiceControllerStatus State { get; set; } = ServiceControllerStatus.Stopped; + + + + /// Whether the service accepts a stop request while it runs. + internal bool AcceptsStop { get; set; } = true; + + + + /// When set, Windows refuses every read and control of the service with this. + internal Exception? Refusal { get; set; } + + + + /// The states the service moves through: each time a handle is refreshed, the service takes the next one, if any is left. + internal Queue Next { get; } = new(); + + + + /// Every call made, in order: "Open" with the service name, then "Status", "CanStop", "Refresh", "Start", "Stop" and "Dispose". + internal List Calls { get; } = []; + + + + /// How many handles are held and not yet let go. + internal int OpenHandles { get; private set; } + + + + /// The refusal Windows gives for a service name no installed service has. + internal static InvalidOperationException NotInstalled() => Refused(1060); + + + + /// A refusal from Windows with the given error, as the service controller reports one. + internal static InvalidOperationException Refused(int error) => new("Synthetic: Windows refused the service request.", new Win32Exception(error)); + + + + /// Hands out a handle to the service; nothing is read yet, as with the real one. + public IManagedService Open(string serviceName) + { + Calls.Add("Open " + serviceName); + OpenHandles++; + return new Handle(this); + } + + + + /// One handle to the service, with the state it last read. + private sealed class Handle(FakeServiceManager manager) : IManagedService + { + /// The state and whether a stop is accepted, as read on first use and kept until the handle is refreshed. + private (ServiceControllerStatus State, bool CanStop)? _read; + + + + /// The remembered state. + public ServiceControllerStatus Status + { + get + { + manager.Calls.Add("Status"); + return Read().State; + } + } + + + + /// Whether a stop is accepted in the remembered state. + public bool CanStop + { + get + { + manager.Calls.Add("CanStop"); + return Read().CanStop; + } + } + + + + /// Forgets what was read; the service has meanwhile moved to its next state, if the test gave it one. + public void Refresh() + { + manager.Calls.Add("Refresh"); + _read = null; + if(manager.Next.TryDequeue(out ServiceControllerStatus next)) + { manager.State = next; } + } + + + + /// Starts a stopped service, which then is starting; Windows refuses to start one that is not stopped. + public void Start() + { + manager.Calls.Add("Start"); + if(manager.Refusal is not null) + { throw manager.Refusal; } + if(manager.State != ServiceControllerStatus.Stopped) + { throw Refused(1056); } + manager.State = ServiceControllerStatus.StartPending; + } + + + + /// Stops a running service, which then is stopping; Windows refuses to stop one that is stopped or that does not accept a stop. + public void Stop() + { + manager.Calls.Add("Stop"); + if(manager.Refusal is not null) + { throw manager.Refusal; } + if(manager.State == ServiceControllerStatus.Stopped) + { throw Refused(1062); } + if(!manager.AcceptsStop) + { throw Refused(1052); } + manager.State = ServiceControllerStatus.StopPending; + } + + + + /// Lets the handle go. + public void Dispose() + { + manager.Calls.Add("Dispose"); + manager.OpenHandles--; + } + + + + /// Reads the service once and remembers the answer, or is refused as the test asked. + private (ServiceControllerStatus State, bool CanStop) Read() + { + if(manager.Refusal is not null) + { throw manager.Refusal; } + return _read ??= (manager.State, manager.AcceptsStop && manager.State == ServiceControllerStatus.Running); + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateApplyTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateApplyTests.cs new file mode 100644 index 0000000..06abe61 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateApplyTests.cs @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.Text.Json; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Applying an update inside the staged helper. This step starts Windows Installer on a machine MSI with administrator +/// rights, so the tests check that every guard runs before the installer is started (who runs it, from where, on which +/// request, for which companion, on which bytes), what the installer is started with, what its answer is taken to +/// mean, and that the outcome is recorded, printing resumed and the companion reopened whatever happened. The +/// installer is a process of the fake: Windows Installer is never started. +/// +public sealed class MsiUpdateApplyTests +{ + /// How every failure before the installer finished begins. + private const string Failed = "Update failed before completion: "; + + + + /// The file name of Windows Installer's program. + private const string Installer = "msiexec.exe"; + + + + /// The file name of the companion. + private const string Companion = "Qqq.PrintAgent.exe"; + + + + /// + /// A verified MSI is installed by the system's own msiexec, started without a shell and with exactly the six + /// arguments of a passive install that never restarts by itself and logs into the session folder. While the + /// installer runs the MSI can be neither rewritten nor deleted. The helper returns the installer's exit code. + /// + [Fact] + public async Task VerifiedMsiIsInstalledByTheSystemInstallerWhileItsBytesAreHeld() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + List whileInstalling = []; + setup.WhileStarting = start => + { + if(IsInstaller(start)) + { + whileInstalling.Add(Throws(() => File.WriteAllBytes(setup.Package, [9, 9])) ? "cannot be rewritten" : "REWRITTEN"); + whileInstalling.Add(Throws(() => File.Delete(setup.Package)) ? "cannot be deleted" : "DELETED"); + } + }; + Assert.Equal(0, await setup.ApplyAsync(request)); + ProcessStartInfo installer = setup.Processes.Started[0]; + Assert.Equal(Path.Combine(Environment.SystemDirectory, Installer), installer.FileName); + Assert.Equal(new[] { "/i", setup.Package, "/passive", "/norestart", "/L*v", Path.Combine(setup.Session, "install.log") }, installer.ArgumentList, StringComparer.Ordinal); + Assert.Equal((false, true, ""), (installer.UseShellExecute, installer.CreateNoWindow, installer.Arguments)); + Assert.Equal(new[] { "cannot be rewritten", "cannot be deleted" }, whileInstalling, StringComparer.Ordinal); + File.WriteAllBytes(setup.Package, [9, 9]); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// After a successful install the three installed programs are checked for the requested release, the outcome is + /// recorded with the time, the release, the exit code and the message, and written to the activity log of the machine + /// state folder as information; then printing is resumed and the installed companion reopened, in that order, the + /// companion without a shell, in its own folder and with no arguments. + /// + [Fact] + public async Task SuccessfulInstallIsVerifiedRecordedLoggedResumedAndTheCompanionReopened() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + File.WriteAllText(setup.OutcomePath, "an earlier outcome"); + Assert.Equal(0, await setup.ApplyAsync(request)); + const string message = "Update installed successfully. Open the companion to verify service status."; + Assert.Equal(new[] { setup.Places.InstalledCompanion, setup.Places.InstalledService, setup.InstalledTool }, setup.Processes.VersionsRead, StringComparer.Ordinal); + JsonElement outcome = JsonDocument.Parse(File.ReadAllText(setup.OutcomePath)).RootElement; + Assert.Equal((MsiUpdateSetup.Now, MsiUpdateSetup.Version, 0, message), + (outcome.GetProperty("completedAt").GetDateTimeOffset(), outcome.GetProperty("version").GetString(), outcome.GetProperty("exitCode").GetInt32(), outcome.GetProperty("message").GetString())); + Assert.Equal(new[] { Path.GetFileName(setup.OutcomePath) }, Directory.EnumerateFiles(setup.Places.UpdatesDirectory).Select(file => Path.GetFileName(file)).ToArray()); + Assert.Equal("2026-11-10 12:00:00Z — " + message, setup.Steps.ReadLastOutcomeMessage()); + Assert.Equal(new[] { setup.State }, setup.LogsOpened, StringComparer.Ordinal); + Assert.Equal(new[] { "INFO [Update] " + message }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + ProcessStartInfo companion = setup.Processes.Started[1]; + Assert.Equal((setup.Places.InstalledCompanion, false, Path.GetDirectoryName(setup.Places.InstalledCompanion), 0, ""), + (companion.FileName, companion.UseShellExecute, companion.WorkingDirectory, companion.ArgumentList.Count, companion.Arguments)); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// The helper waits for Windows Installer however long it takes, holding the MSI, and only then records an outcome; + /// nothing in the rules can end the installer. + /// + [Fact] + public async Task HelperWaitsForTheInstallerToFinish() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + FakeProcess running = new(id: 7100, Installer, startTicks: 2); + setup.Processes.OnStart = start => IsInstaller(start) ? running : FakeProcessHost.Ended(start.FileName, 0); + Task apply = setup.ApplyAsync(request); + await MsiUpdateSetup.UntilAsync(() => running.Waits == 1); + await Task.Delay(50); + Assert.False(apply.IsCompleted); + Assert.False(File.Exists(setup.OutcomePath)); + Assert.True(Throws(() => File.WriteAllBytes(setup.Package, [9, 9]))); + Assert.Empty(setup.Sent); + running.Exit(1602); + Assert.Equal(1602, await apply); + Assert.Equal(new[] { "resume-after-update" }, setup.Sent, StringComparer.Ordinal); + } + + + + /// + /// An exit code other than 0 is returned as it is and described for what it is: a required restart is logged as + /// information and says the new version is not yet fully active, a cancellation and any other code are logged as + /// errors. The installed versions are checked only after exit code 0. Printing is resumed and the companion reopened + /// in every case. + /// + [Theory] + [InlineData(3010, "INFO", "Update installed, but Windows requires a restart to finish replacing files. Restart Windows before treating the new version as fully active.")] + [InlineData(1602, "ERROR", "Windows Installer canceled the update. The previous installation may remain; inspect the version and service status before retrying.")] + [InlineData(1603, "ERROR", "Windows Installer did not report a completed update (exit 1603). Inspect the private installation log and service status before retrying.")] + public async Task OtherExitCodesAreReturnedAndDescribedForWhatTheyAre(int code, string level, string message) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + setup.ExitCodes[Installer] = code; + Assert.Equal(code, await setup.ApplyAsync(request)); + Assert.Empty(setup.Processes.VersionsRead); + Assert.Equal(new[] { level + " [Update] " + message }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(code, JsonDocument.Parse(File.ReadAllText(setup.OutcomePath)).RootElement.GetProperty("exitCode").GetInt32()); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + } + + + + /// + /// Exit code 0 is not yet success: when an installed program does not carry the requested release, or cannot be + /// read, the helper returns 1 and records an error that names the program and says the installer returned success. + /// + [Theory] + [InlineData("0.3.1", "Windows Installer returned success, but the installed Qqq.PrintAgent.Service.exe version does not match the requested release. Inspect the installation log and repair the package.")] + [InlineData(null, "Windows Installer returned success, but the installed Qqq.PrintAgent.Service.exe version could not be verified. Inspect the installation log and repair the package.")] + public async Task InstallThatLeftAnotherVersionIsAFailure(string? serviceVersion, string message) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + if(serviceVersion is null) + { _ = setup.Processes.Versions.Remove(setup.Places.InstalledService); } + else + { setup.Processes.Versions[setup.Places.InstalledService] = serviceVersion; } + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.Equal(new[] { "ERROR [Update] " + Failed + message }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + } + + + + /// + /// Someone who is not an administrator cannot apply an update: the helper returns 1 and the installer is never + /// started. The outcome cannot be recorded either, since that needs the same rights, but printing is still resumed + /// and the companion reopened. + /// + [Fact] + public async Task NonAdministratorCannotApply() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + setup.Security.IsAdministrator = false; + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.Equal(new[] { "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + Assert.False(File.Exists(setup.OutcomePath)); + Assert.Empty(setup.LogsOpened); + } + + + + /// + /// Each thing that must hold before the installer may be started stops the update when it does not: the helper + /// returns 1, records why with the release it could read, and Windows Installer is never started. + /// + [Theory] + [InlineData("request-emptied", "unknown", "Empty update request.")] + [InlineData("request-writable", "unknown", "An update path allows modification by an untrusted identity. Repair the MSI directory permissions.")] + [InlineData("not-the-helper", MsiUpdateSetup.Version, "Apply must run from the verified staged helper copy.")] + [InlineData("no-program-path", MsiUpdateSetup.Version, "Apply must run from the verified staged helper copy.")] + [InlineData("helper-writable", MsiUpdateSetup.Version, "An update path allows modification by an untrusted identity. Repair the MSI directory permissions.")] + [InlineData("helper-missing", MsiUpdateSetup.Version, "A required staged update file is missing.")] + [InlineData("msi-changed", MsiUpdateSetup.Version, "The staged update changed or failed its checksum. Download it again.")] + [InlineData("log-is-a-junction", MsiUpdateSetup.Version, "Update paths cannot contain symbolic links or junctions.")] + public async Task UpdateThatFailsAGuardNeverStartsTheInstaller(string broken, string recordedVersion, string reason) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + switch(broken) + { + case "request-emptied": + File.WriteAllText(request, "null"); + break; + case "request-writable": + setup.Security.Descriptors[request] = MsiUpdateSetup.WritableByUsers(); + break; + case "not-the-helper": + setup.Processes.CurrentPath = setup.InstalledTool; + break; + case "no-program-path": + setup.Processes.CurrentPath = null; + break; + case "helper-writable": + setup.Security.Descriptors[setup.Helper] = MsiUpdateSetup.WritableByUsers(); + break; + case "helper-missing": + File.Move(setup.Helper, setup.Helper + ".moved"); + break; + case "msi-changed": + File.WriteAllBytes(setup.Package, [.. setup.PackageBytes.Reverse()]); + break; + default: + Directory.CreateDirectory(Path.Combine(setup.Root, "elsewhere")); + MsiUpdateSetup.MakeJunction(Path.Combine(setup.Session, "install.log"), Path.Combine(setup.Root, "elsewhere")); + break; + } + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + JsonElement outcome = JsonDocument.Parse(File.ReadAllText(setup.OutcomePath)).RootElement; + Assert.Equal((recordedVersion, 1, Failed + reason), (outcome.GetProperty("version").GetString(), outcome.GetProperty("exitCode").GetInt32(), outcome.GetProperty("message").GetString())); + Assert.Equal(new[] { "ERROR [Update] " + Failed + reason }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(new[] { "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + } + + + + /// + /// The process with the companion's id must still be the companion that asked: one that started at another time, or + /// that runs another program, has taken over the id, and the installer is not started. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ProcessThatIsNoLongerTheCompanionThatAskedStopsTheUpdate(bool startedAtAnotherTime) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + if(startedAtAnotherTime) + { setup.Companion.StartTicks++; } + else + { setup.Companion.Program = setup.InstalledTool; } + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(new[] { "ERROR [Update] " + Failed + "The expected companion process identity changed. No installer was started." }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(0, setup.Companion.Waits); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// A companion that is still open is waited for, and the installer is started only once it has closed. The companion + /// is recognized whatever the case of the path Windows reports for it. + /// + [Fact] + public async Task InstallerIsStartedOnlyOnceTheCompanionHasClosed() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + setup.Companion.Program = setup.Places.InstalledCompanion.ToUpperInvariant(); + Task apply = setup.ApplyAsync(request); + await MsiUpdateSetup.UntilAsync(() => setup.Companion.Waits == 1); + await Task.Delay(50); + Assert.False(apply.IsCompleted); + Assert.Empty(setup.Processes.Started); + setup.Companion.Exit(0); + Assert.Equal(0, await apply); + Assert.Equal(new[] { Installer, Companion }, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// The MSI is checked against the request and held only once the companion has closed, not while it is waited + /// for: during the wait the MSI is not yet held, and bytes that change in it then are found when it is checked + /// afterwards, so the installer is never started on them. This records the order the helper works in today. + /// + [Fact] + public async Task MsiIsCheckedAndHeldOnlyOnceTheCompanionHasClosed() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + Task apply = setup.ApplyAsync(request); + await MsiUpdateSetup.UntilAsync(() => setup.Companion.Waits == 1); + Assert.False(Throws(() => File.WriteAllBytes(setup.Package, [.. setup.PackageBytes.Reverse()])), "The MSI was already held while the companion was still waited for."); + setup.Companion.Exit(0); + Assert.Equal(1, await apply); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(new[] { "ERROR [Update] " + Failed + "The staged update changed or failed its checksum. Download it again." }, setup.Log.Entries, StringComparer.Ordinal); + } + + + + /// + /// A companion that does not close is waited for for 30 seconds and no longer: just before that the helper is still + /// waiting and has started nothing; at 30 seconds it gives up, says that no process was terminated, and the installer + /// is never started. The companion is left running. + /// + [Fact] + public async Task CompanionThatStaysOpenForThirtySecondsStopsTheUpdate() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + Task apply = setup.ApplyAsync(request); + await MsiUpdateSetup.UntilAsync(() => setup.Companion.Waits == 1 && setup.Clock.PendingTimers == 1); + Assert.True(setup.Clock.HasTimerDueIn(TimeSpan.FromSeconds(30))); + setup.Clock.Advance(TimeSpan.FromSeconds(29.9)); + await Task.Delay(50); + Assert.False(apply.IsCompleted); + Assert.Empty(setup.Processes.Started); + setup.Clock.Advance(TimeSpan.FromSeconds(0.1)); + Assert.Equal(1, await apply); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(new[] { "ERROR [Update] " + Failed + "The companion did not close within 30 seconds. Close it and retry the update; no process was terminated." }, setup.Log.Entries, StringComparer.Ordinal); + Assert.False(setup.Companion.HasExited); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// A companion that has already closed is not waited for, whether its process is gone, has ended, or ends while it + /// is looked at and reading its identity fails with an invalid-operation failure for that reason; the installer is + /// started. The last is what .NET 10 reports when nothing else holds the ended process, which is the helper's own + /// situation: it looks the companion up by its id and keeps no handle to it while it reads. + /// + [Theory] + [InlineData("gone")] + [InlineData("ended")] + [InlineData("ends-and-the-read-says-so")] + public async Task CompanionThatHasAlreadyClosedIsNotWaitedFor(string how) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: string.Equals(how, "gone", StringComparison.Ordinal)); + if(string.Equals(how, "ended", StringComparison.Ordinal)) + { setup.Companion.Exit(0); } + if(string.Equals(how, "ends-and-the-read-says-so", StringComparison.Ordinal)) + { + setup.Companion.ExitsWhenInspected = true; + setup.Companion.InspectionFailure = new InvalidOperationException("Synthetic: cannot process request because the process has exited."); + } + Assert.Equal(0, await setup.ApplyAsync(request)); + Assert.Equal(new[] { Installer, Companion }, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(0, setup.Companion.Waits); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// + /// A companion that closes at the very moment its program is read, while something else still holds its process, + /// is reported by .NET 10 with Windows error 299 and not as an invalid operation, and the helper does not take + /// that for a closed companion. The update stops there, with no installer started, and can be run again. Nothing + /// in the helper holds the companion, so this is the rarer of the two cases: another program must have the + /// process open at that moment. This records what the helper does today. + /// + [Fact] + public async Task CompanionThatClosesWhileItsProgramIsReadStopsTheUpdateWithoutInstalling() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + setup.Companion.ExitsWhenInspected = true; + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.True(setup.Companion.HasExited); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(new[] { "ERROR [Update] " + Failed + "Synthetic: only part of a ReadProcessMemory or WriteProcessMemory request was completed." }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// A running process with the companion's id that Windows will not let the helper inspect cannot be confirmed as the companion, so the installer is not started. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CompanionThatCannotBeInspectedStopsTheUpdate(bool accessDenied) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(companionClosed: false); + setup.Companion.InspectionFailure = accessDenied ? new Win32Exception(5, "Synthetic: access is denied.") : new InvalidOperationException("Synthetic: the process cannot be inspected."); + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.DoesNotContain(Installer, setup.StartedPrograms, StringComparer.Ordinal); + Assert.Equal(new[] { "ERROR [Update] " + Failed + setup.Companion.InspectionFailure.Message }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// When Windows starts nothing for the installer the update fails and says so; printing is resumed and the companion reopened. + [Fact] + public async Task InstallerThatDoesNotStartFailsTheUpdate() + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + _ = setup.StartsNothing.Add(Installer); + Assert.Equal(1, await setup.ApplyAsync(request)); + Assert.Equal(new[] { "ERROR [Update] " + Failed + "Windows Installer could not start." }, setup.Log.Entries, StringComparer.Ordinal); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + File.WriteAllBytes(setup.Package, [9, 9]); + } + + + + /// + /// The three closing steps do not depend on each other or on the result: a log that cannot be written, a service + /// that cannot be reached and a companion that cannot be started each leave the others to run and the exit code as + /// it was. + /// + [Theory] + [InlineData("log")] + [InlineData("pipe")] + [InlineData("companion")] + public async Task ClosingStepsDoNotDependOnEachOther(string failing) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + setup.ExitCodes[Installer] = 3010; + setup.Log.Failure = string.Equals(failing, "log", StringComparison.Ordinal) ? new IOException("Synthetic: the log's disk failed.") : null; + setup.PipeFailure = string.Equals(failing, "pipe", StringComparison.Ordinal) ? new TimeoutException("Synthetic: the service did not answer.") : null; + if(string.Equals(failing, "companion", StringComparison.Ordinal)) + { _ = setup.StartsNothing.Add(Companion); } + Assert.Equal(3010, await setup.ApplyAsync(request)); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update", "start " + Companion }, setup.Journal, StringComparer.Ordinal); + Assert.True(File.Exists(setup.OutcomePath)); + } + + + + /// The companion is reopened only from an install folder that can be trusted: when ordinary users may write to the companion or to a folder above it, nothing is started in its place. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public async Task CompanionIsNotReopenedFromAFolderOrdinaryUsersMayWriteTo(int level) + { + using var setup = new MsiUpdateSetup(); + string request = setup.PrepareAndRunAsHelper(); + setup.Security.Descriptors[new[] { setup.Places.InstalledCompanion, Path.GetDirectoryName(setup.Places.InstalledCompanion)!, setup.Places.InstalledRoot, setup.ProgramFiles }[level]] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(0, await setup.ApplyAsync(request)); + Assert.Equal(new[] { "start " + Installer, "send resume-after-update" }, setup.Journal, StringComparer.Ordinal); + } + + + + /// Without a recorded outcome there is nothing to show. + [Fact] + public void NoRecordedOutcomeShowsNothing() + { + using var setup = new MsiUpdateSetup(); + Assert.Null(setup.Steps.ReadLastOutcomeMessage()); + Directory.CreateDirectory(setup.Places.UpdatesDirectory); + File.WriteAllText(setup.OutcomePath, "null"); + Assert.Null(setup.Steps.ReadLastOutcomeMessage()); + } + + + + /// + /// A recorded outcome that cannot be trusted is not shown: one larger than 16 KiB is called invalid, and one that is + /// not an outcome, that ordinary users may write to, or that is read by someone who is not an administrator is + /// reported as unreadable, with nothing of its content. + /// + [Theory] + [InlineData("oversize", "The previous update outcome is invalid. Inspect the protected update logs.")] + [InlineData("garbage", "The previous update outcome could not be read. Inspect the protected update logs.")] + [InlineData("writable", "The previous update outcome could not be read. Inspect the protected update logs.")] + [InlineData("not-administrator", "The previous update outcome could not be read. Inspect the protected update logs.")] + public void RecordedOutcomeThatCannotBeTrustedIsNotShown(string broken, string shown) + { + using var setup = new MsiUpdateSetup(); + const string valid = """{"completedAt":"2026-11-10T12:00:00+00:00","version":"0.3.2-rc.1","exitCode":0,"message":"planted text"}"""; + File.WriteAllText(setup.OutcomePath, broken switch + { + "oversize" => valid + new string(' ', 16 * 1024), + "garbage" => "planted text that is not an outcome", + _ => valid, + }); + if(broken is "writable" or "not-administrator") + { + Assert.Equal("2026-11-10 12:00:00Z — planted text", setup.Steps.ReadLastOutcomeMessage()); + setup.Security.Descriptors[setup.OutcomePath] = string.Equals(broken, "writable", StringComparison.Ordinal) ? MsiUpdateSetup.WritableByUsers() : FakePathSecurity.Descriptor(); + setup.Security.IsAdministrator = !string.Equals(broken, "not-administrator", StringComparison.Ordinal); + } + Assert.Equal(shown, setup.Steps.ReadLastOutcomeMessage()); + } + + + + /// True when the start is of Windows Installer's program. + private static bool IsInstaller(ProcessStartInfo start) => string.Equals(Path.GetFileName(start.FileName), Installer, StringComparison.OrdinalIgnoreCase); + + + + /// True when the action fails with the given kind of exception. + private static bool Throws(Action action) where T : Exception + { + try + { + action(); + return false; + } + catch(T) + { + return true; + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs index 1bf7d86..c9320f2 100644 --- a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateInstallerTests.cs @@ -34,14 +34,16 @@ public sealed class MsiUpdateInstallerTests /// /// An install request is honored only for an eligible target version (0.1.2-rc.1 is refused, 0.1.3-rc.1 accepted), an .msi - /// file inside the staging directory, a well-formed 64-character hash and a real parent process id. The last two are also - /// broken independently of the first two, so a valid request cannot mask a missing hash or process check. + /// file directly inside the staging directory (neither outside it nor in a folder below it), a well-formed 64-character + /// hash and a real parent process id. The last two are also broken independently of the first two, so a valid request + /// cannot mask a missing hash or process check. /// [Theory] [InlineData("0.1.2-rc.1", "package.msi", false)] [InlineData("0.1.3-rc.1", "package.msi", true)] [InlineData("0.1.3", "package.exe", false)] [InlineData("0.1.3", "../other/package.msi", false)] + [InlineData("0.1.3", "sub/package.msi", false)] public void RequestRequiresEligibleVersionAndSameDirectoryPackage(string version, string filename, bool valid) { string directory = Path.Combine(Path.GetTempPath(), "qqq-update-request"); diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePlacesTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePlacesTests.cs new file mode 100644 index 0000000..19844fb --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePlacesTests.cs @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using KofTwentyTwo.AppKit.Logging; +using Qqq.PrintAgent.Core; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Where the installed product's update works. The factory decides which folders are trusted and which checks guard +/// them, so it is pinned here: nothing is created, read or checked on this computer, and neither the log nor the pipe +/// is opened; the factory only names two folders and binds four things, and none of them is called. +/// +public sealed class MsiUpdatePlacesTests +{ + /// + /// The installed product updates under this computer's Program Files and its machine state folder, which is the + /// folder the guard protects, with the guard's own check, the machine activity log, the installed service's pipe and + /// the system clock. + /// + [Fact] + public void InstalledProductIsBoundToProgramFilesTheGuardedStateFolderTheLogThePipeAndTheClock() + { + var places = MsiUpdatePlaces.Installed(); + Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), places.ProgramFiles); + Assert.Equal(MachineStateDirectory.Root, places.StateDirectory); + Assert.Equal>(MachineStateDirectory.EnsureForPath, places.EnsureProtectedState); + Assert.Equal>(AgentActivityLog.Create, places.OpenLog); + Assert.Equal>>(AgentPipeClient.SendAsync, places.Send); + Assert.Same(TimeProvider.System, places.Clock); + } + + + + /// Every path the update trusts is named from the two folders given: the three installed programs' places under Program Files and the updates folder under the machine state. + [Fact] + public void EveryTrustedPathIsNamedFromTheTwoFoldersGiven() + { + var places = new MsiUpdatePlaces(@"X:\Programs", @"Y:\State", _ => { }, _ => new FakeActivityLog(), _ => Task.FromResult(""), TimeProvider.System); + Assert.Equal(@"X:\Programs\QQQ Print Agent", places.InstalledRoot); + Assert.Equal(@"X:\Programs\QQQ Print Agent\App\Qqq.PrintAgent.exe", places.InstalledCompanion); + Assert.Equal(@"X:\Programs\QQQ Print Agent\Service\Qqq.PrintAgent.Service.exe", places.InstalledService); + Assert.Equal(@"X:\Programs\QQQ Print Agent\Cli", places.InstalledCli); + Assert.Equal(@"Y:\State\updates", places.UpdatesDirectory); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePrepareTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePrepareTests.cs new file mode 100644 index 0000000..bb71f65 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdatePrepareTests.cs @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Security.Cryptography; +using System.Text.Json; +using Qqq.PrintAgent.Core.Printing; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Preparing an update and handing it to the helper. The prepared helper later installs an MSI with administrator +/// rights, so the tests check each thing that decides which file that will be and which program will do it: who asks, +/// where the MSI is and who may change it, which release it is, which process asked, where the helper is copied from, +/// and that a request or helper changed after preparation is refused before anything is started. Everything runs in +/// temporary folders against fakes; no program is started. +/// +public sealed class MsiUpdatePrepareTests +{ + /// What someone who is not an administrator is told. + private const string NotAdministrator = "Machine updates require an elevated administrator. No installer was started."; + + + + /// What a path that lets ordinary users write is refused with. + private const string Writable = "An update path allows modification by an untrusted identity. Repair the MSI directory permissions."; + + + + /// + /// A prepared update has a helper folder holding a copy of the whole installed command line folder, and a request + /// that names the staged MSI, the release, the MSI's SHA-256 and the companion that asked by process id and start + /// time. Nothing is started, and the companion's process is let go again. + /// + [Fact] + public void PreparedUpdateHasACopiedHelperAndARequestPinningTheMsiAndTheCompanion() + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + Assert.Equal(setup.RequestPath, request); + MsiUpdateInstaller.InstallRequest written = JsonSerializer.Deserialize(File.ReadAllText(request), PrintApiClient.JsonOptions)!; + Assert.Equal(new MsiUpdateInstaller.InstallRequest(setup.Package, MsiUpdateSetup.Version, Convert.ToHexString(SHA256.HashData(setup.PackageBytes)), MsiUpdateSetup.CompanionId, MsiUpdateSetup.CompanionStarted), written); + Assert.Equal(new[] { "qqq-print-agent.dll", "qqq-print-agent.exe", Path.Combine("runtimes", "win-x64", "native.dll") }, + Directory.EnumerateFiles(setup.HelperDirectory, "*", SearchOption.AllDirectories).Select(file => Path.GetRelativePath(setup.HelperDirectory, file)).Order(StringComparer.Ordinal).ToArray()); + Assert.Equal(File.ReadAllText(setup.InstalledTool), File.ReadAllText(setup.Helper)); + Assert.Equal(new[] { MsiUpdateSetup.CompanionId }, setup.Processes.Opened); + Assert.Equal(0, setup.Processes.OpenHandles); + Assert.Empty(setup.Processes.Started); + } + + + + /// + /// Before anything is copied, the owner and access list of the installed command line folder are read at every level + /// up to Program Files, and while copying, those of every folder and file that is copied. + /// + [Fact] + public void EveryInstalledFolderAndCopiedFileIsCheckedForWhoMayChangeIt() + { + using var setup = new MsiUpdateSetup(); + _ = setup.Prepare(); + string cli = setup.Places.InstalledCli; + foreach(string path in new[] { setup.ProgramFiles, setup.Places.InstalledRoot, cli, setup.InstalledTool, Path.Combine(cli, "qqq-print-agent.dll"), Path.Combine(cli, "runtimes"), Path.Combine(cli, "runtimes", "win-x64"), Path.Combine(cli, "runtimes", "win-x64", "native.dll") }) + { + Assert.Contains(path, setup.Security.Reads, StringComparer.Ordinal); + } + Assert.DoesNotContain(setup.Root, setup.Security.Reads, StringComparer.Ordinal); + } + + + + /// Someone who is not an administrator cannot prepare an update, and nothing is created. + [Fact] + public void NonAdministratorCannotPrepare() + { + using var setup = new MsiUpdateSetup(); + setup.Security.IsAdministrator = false; + Assert.Equal(NotAdministrator, Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + Assert.Empty(setup.Processes.Opened); + } + + + + /// An MSI that is not inside the updates folder is refused, wherever else it is. + [Fact] + public void MsiOutsideTheUpdatesFolderIsRefused() + { + using var setup = new MsiUpdateSetup(); + string elsewhere = Path.Combine(setup.Root, "Downloads", "package.msi"); + Directory.CreateDirectory(Path.GetDirectoryName(elsewhere)!); + File.WriteAllBytes(elsewhere, setup.PackageBytes); + InvalidDataException refusal = Assert.Throws(() => setup.Steps.PrepareHelper(elsewhere, MsiUpdateSetup.Version, MsiUpdateSetup.CompanionId)); + Assert.Equal("Update paths must remain inside the protected staging directory.", refusal.Message); + Assert.False(Directory.Exists(Path.Combine(setup.Root, "Downloads", "helper"))); + } + + + + /// A session folder that ordinary users may write to is refused, because the MSI could be swapped after it was checked. + [Fact] + public void SessionOrdinaryUsersMayWriteToIsRefused() + { + using var setup = new MsiUpdateSetup(); + setup.Security.Descriptors[setup.Session] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(Writable, Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// An MSI that ordinary users may write to is refused. + [Fact] + public void MsiOrdinaryUsersMayWriteToIsRefused() + { + using var setup = new MsiUpdateSetup(); + setup.Security.Descriptors[setup.Package] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(Writable, Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// A junction where the MSI should be is refused as a link, before it is looked at as a file. + [Fact] + public void JunctionWhereTheMsiShouldBeIsRefusedAsALink() + { + using var setup = new MsiUpdateSetup(); + string elsewhere = Path.Combine(setup.Root, "elsewhere"); + Directory.CreateDirectory(elsewhere); + File.Delete(setup.Package); + MsiUpdateSetup.MakeJunction(setup.Package, elsewhere); + Assert.Equal("Update paths cannot contain symbolic links or junctions.", Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// An MSI that is missing is reported as a missing staged file. + [Fact] + public void MissingMsiIsRefused() + { + using var setup = new MsiUpdateSetup(); + File.Delete(setup.Package); + Assert.Equal("A required staged update file is missing.", Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// + /// An MSI that is empty, that is larger than 256 MiB or that does not end in .msi is refused. The large one is a + /// file whose length is set without writing it, so the test costs no time. + /// + [Theory] + [InlineData("package.msi", 0L)] + [InlineData("package.msi", (256L * 1024 * 1024) + 1)] + [InlineData("package.exe", 10L)] + [InlineData("package", 10L)] + public void MsiOfTheWrongSizeOrNameIsRefused(string name, long length) + { + using var setup = new MsiUpdateSetup(); + string package = Path.Combine(setup.Session, name); + using(FileStream stream = new(package, FileMode.Create, FileAccess.Write, FileShare.None)) + { stream.SetLength(length); } + InvalidDataException refusal = Assert.Throws(() => setup.Steps.PrepareHelper(package, MsiUpdateSetup.Version, MsiUpdateSetup.CompanionId)); + Assert.Equal("The staged MSI has an invalid size or extension.", refusal.Message); + AssertNothingPrepared(setup); + Assert.Empty(setup.Processes.Opened); + } + + + + /// A release this updater does not support (older than 0.1.3, or no version at all) is refused before the companion is looked at. + [Theory] + [InlineData("0.1.2")] + [InlineData("0.1.2-rc.9")] + [InlineData("latest")] + [InlineData("")] + public void ReleaseThatIsNotEligibleIsRefused(string version) + { + using var setup = new MsiUpdateSetup(); + InvalidDataException refusal = Assert.Throws(() => setup.Steps.PrepareHelper(setup.Package, version, MsiUpdateSetup.CompanionId)); + Assert.Equal("The update version is not an eligible release.", refusal.Message); + AssertNothingPrepared(setup); + Assert.Empty(setup.Processes.Opened); + } + + + + /// A process id that no running process has is refused with what Windows says about it. + [Fact] + public void CompanionThatIsNotRunningIsRefused() + { + using var setup = new MsiUpdateSetup(); + _ = Assert.Throws(() => setup.Steps.PrepareHelper(setup.Package, MsiUpdateSetup.Version, 999_999)); + AssertNothingPrepared(setup); + } + + + + /// A process whose program cannot be told is refused. + [Fact] + public void CompanionWithoutAProgramPathIsRefused() + { + using var setup = new MsiUpdateSetup(); + setup.Companion.Program = null; + Assert.Equal("Cannot verify the update's companion process.", Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// Only the companion at its install path may prepare an update: a copy elsewhere, or another installed program, may not. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ProcessThatIsNotTheInstalledCompanionIsRefused(bool anotherInstalledProgram) + { + using var setup = new MsiUpdateSetup(); + setup.Companion.Program = anotherInstalledProgram ? setup.InstalledTool : Path.Combine(setup.Root, "Downloads", "Qqq.PrintAgent.exe"); + Assert.Equal("Only the installed companion may prepare an update.", Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// Windows reports a program path in whatever case it was started with, and may report it unnormalized; the installed companion is recognized either way. + [Fact] + public void InstalledCompanionIsRecognizedWhateverTheCaseOfItsPath() + { + using var setup = new MsiUpdateSetup(); + setup.Companion.Program = Path.Combine(setup.Places.InstalledRoot, "Cli", "..", "App", "QQQ.PRINTAGENT.EXE").ToUpperInvariant(); + Assert.Equal(setup.RequestPath, setup.Prepare()); + } + + + + /// The installed command line folder is refused when ordinary users may write to it or to a folder above it, up to and including Program Files. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void InstalledFolderOrdinaryUsersMayWriteToIsRefused(int level) + { + using var setup = new MsiUpdateSetup(); + setup.Security.Descriptors[new[] { setup.Places.InstalledCli, setup.Places.InstalledRoot, setup.ProgramFiles }[level]] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(Writable, Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// An installed command line folder that is really a junction to somewhere else is refused. + [Fact] + public void InstalledFolderThatIsAJunctionIsRefused() + { + using var setup = new MsiUpdateSetup(); + string real = Path.Combine(setup.Root, "elsewhere"); + Directory.Move(setup.Places.InstalledCli, real); + MsiUpdateSetup.MakeJunction(setup.Places.InstalledCli, real); + Assert.Equal("Update paths cannot contain symbolic links or junctions.", Assert.Throws(() => setup.Prepare()).Message); + AssertNothingPrepared(setup); + } + + + + /// A helper folder left by an earlier preparation in the same session is never reused or overwritten. + [Fact] + public void HelperFolderThatAlreadyExistsIsNotReused() + { + using var setup = new MsiUpdateSetup(); + Directory.CreateDirectory(setup.HelperDirectory); + File.WriteAllText(setup.Helper, "left by someone else"); + Assert.Equal("This update helper directory already exists. Check again to stage a fresh update.", Assert.Throws(() => setup.Prepare()).Message); + Assert.Equal("left by someone else", File.ReadAllText(setup.Helper)); + Assert.False(File.Exists(setup.RequestPath)); + } + + + + /// + /// The request is created new and never written over one that is already there: a request left in the session + /// fails the preparation with what Windows says about a file that exists, and stays exactly as it was. + /// + [Fact] + public void RequestThatAlreadyExistsIsNotOverwritten() + { + using var setup = new MsiUpdateSetup(); + File.WriteAllText(setup.RequestPath, "left by someone else"); + IOException refusal = Assert.Throws(() => setup.Prepare()); + Assert.Equal(unchecked((int)0x80070050), refusal.HResult); + Assert.Equal("left by someone else", File.ReadAllText(setup.RequestPath)); + Assert.Empty(setup.Processes.Started); + } + + + + /// A junction inside the installed command line folder stops the copy, so nothing is copied from where it points, and no request is written. + [Fact] + public void JunctionInsideTheInstalledFolderStopsTheCopy() + { + using var setup = new MsiUpdateSetup(); + string elsewhere = Path.Combine(setup.Root, "elsewhere"); + Directory.CreateDirectory(elsewhere); + File.WriteAllText(Path.Combine(elsewhere, "planted.dll"), "synthetic planted program"); + MsiUpdateSetup.MakeJunction(Path.Combine(setup.Places.InstalledCli, "linked"), elsewhere); + Assert.Equal("Update helper source cannot contain symbolic links or junctions.", Assert.Throws(() => setup.Prepare()).Message); + Assert.Empty(Directory.EnumerateFiles(setup.HelperDirectory, "planted.dll", SearchOption.AllDirectories)); + Assert.False(File.Exists(setup.RequestPath)); + } + + + + /// A file or a folder inside the installed command line folder that ordinary users may write to stops the copy before that file is copied, and no request is written. + [Theory] + [InlineData("qqq-print-agent.dll", "qqq-print-agent.dll")] + [InlineData("runtimes", "runtimes/win-x64/native.dll")] + [InlineData("runtimes/win-x64/native.dll", "runtimes/win-x64/native.dll")] + public void WritableFileOrFolderInsideTheInstalledFolderStopsTheCopy(string writable, string notCopied) + { + using var setup = new MsiUpdateSetup(); + setup.Security.Descriptors[Path.GetFullPath(Path.Combine(setup.Places.InstalledCli, writable))] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(Writable, Assert.Throws(() => setup.Prepare()).Message); + Assert.False(File.Exists(Path.Combine(setup.HelperDirectory, notCopied))); + Assert.False(File.Exists(setup.RequestPath)); + } + + + + /// An installation without its command line tool cannot be updated from the app, and no request is written. + [Fact] + public void InstallationWithoutTheCommandLineToolIsRefused() + { + using var setup = new MsiUpdateSetup(); + File.Delete(setup.InstalledTool); + Assert.Equal("The installed command line tool is missing. Repair the machine MSI first.", Assert.Throws(() => setup.Prepare()).Message); + Assert.False(File.Exists(setup.RequestPath)); + } + + + + /// + /// The hand-off starts the copied helper, and nothing else, without a shell and without a window, in its own folder, + /// with exactly two arguments: the apply switch and the request's full path. The started process is let go. + /// + [Fact] + public void HandOffStartsTheCopiedHelperWithTheRequest() + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + setup.Steps.StartHelper(request); + System.Diagnostics.ProcessStartInfo start = Assert.Single(setup.Processes.Started); + Assert.Equal(setup.Helper, start.FileName); + Assert.Equal(new[] { "--apply-update", request }, start.ArgumentList, StringComparer.Ordinal); + Assert.Equal((false, true, setup.HelperDirectory), (start.UseShellExecute, start.CreateNoWindow, start.WorkingDirectory)); + Assert.Equal("", start.Arguments); + Assert.Equal(0, setup.Processes.OpenHandles); + } + + + + /// Someone who is not an administrator cannot hand off, and nothing is started. + [Fact] + public void NonAdministratorCannotHandOff() + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + setup.Security.IsAdministrator = false; + Assert.Equal(NotAdministrator, Assert.Throws(() => setup.Steps.StartHelper(request)).Message); + Assert.Empty(setup.Processes.Started); + } + + + + /// + /// A request that is not the file the preparation wrote is refused and nothing is started: one under another name, + /// one larger than 16 KiB, one that holds no request, and one whose fields are not acceptable (an MSI outside the + /// session, a hash that is too short or not hexadecimal, a companion without a start time, an older release). + /// + [Theory] + [InlineData("renamed", "Invalid update request file.")] + [InlineData("oversize", "Invalid update request file.")] + [InlineData("null", "Empty update request.")] + [InlineData("package-elsewhere", "Update paths must remain inside the protected staging directory.")] + [InlineData("bad-hash", "Invalid update request fields.")] + [InlineData("hash-not-hexadecimal", "Invalid update request fields.")] + [InlineData("no-start-time", "Invalid update request fields.")] + [InlineData("old-release", "The update version is not an eligible release.")] + public void RequestThatWasChangedIsRefused(string change, string expected) + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + MsiUpdateInstaller.InstallRequest written = JsonSerializer.Deserialize(File.ReadAllText(request), PrintApiClient.JsonOptions)!; + switch(change) + { + case "renamed": + string renamed = Path.Combine(setup.Session, "request-2.json"); + File.Move(request, renamed); + request = renamed; + break; + case "oversize": + File.WriteAllText(request, File.ReadAllText(request) + new string(' ', 16 * 1024)); + break; + case "null": + File.WriteAllText(request, "null"); + break; + case "package-elsewhere": + File.WriteAllText(request, JsonSerializer.Serialize(written with { PackagePath = Path.Combine(setup.Root, "Downloads", "package.msi") }, PrintApiClient.JsonOptions)); + break; + case "bad-hash": + File.WriteAllText(request, JsonSerializer.Serialize(written with { Sha256 = "not-a-hash" }, PrintApiClient.JsonOptions)); + break; + case "hash-not-hexadecimal": + File.WriteAllText(request, JsonSerializer.Serialize(written with { Sha256 = new string('G', 64) }, PrintApiClient.JsonOptions)); + break; + case "no-start-time": + File.WriteAllText(request, JsonSerializer.Serialize(written with { ParentStartTicks = 0 }, PrintApiClient.JsonOptions)); + break; + default: + File.WriteAllText(request, JsonSerializer.Serialize(written with { Version = "0.1.2" }, PrintApiClient.JsonOptions)); + break; + } + InvalidDataException refusal = Assert.Throws(() => setup.Steps.StartHelper(request)); + Assert.Equal(expected, refusal.Message); + Assert.Empty(setup.Processes.Started); + } + + + + /// + /// A request, an MSI or a helper that ordinary users may write to after preparation is refused and nothing is + /// started, and so is a session whose MSI or helper has gone missing. + /// + [Theory] + [InlineData("request.json", false)] + [InlineData("package", false)] + [InlineData("helper/qqq-print-agent.exe", false)] + [InlineData("request.json", true)] + [InlineData("package", true)] + [InlineData("helper/qqq-print-agent.exe", true)] + public void StagedFileThatBecameWritableOrWentMissingIsRefused(string which, bool missing) + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + string file = string.Equals(which, "package", StringComparison.Ordinal) ? setup.Package : Path.GetFullPath(Path.Combine(setup.Session, which)); + if(missing) + { + File.Delete(file); + Assert.Equal("A required staged update file is missing.", Assert.Throws(() => setup.Steps.StartHelper(request)).Message); + } + else + { + setup.Security.Descriptors[file] = MsiUpdateSetup.WritableByUsers(); + Assert.Equal(Writable, Assert.Throws(() => setup.Steps.StartHelper(request)).Message); + } + Assert.Empty(setup.Processes.Started); + } + + + + /// An MSI emptied after preparation is refused at the hand-off, and nothing is started. + [Fact] + public void MsiEmptiedAfterPreparationIsRefused() + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + File.WriteAllBytes(setup.Package, []); + Assert.Equal("The staged MSI has an invalid size or extension.", Assert.Throws(() => setup.Steps.StartHelper(request)).Message); + Assert.Empty(setup.Processes.Started); + } + + + + /// When Windows starts nothing for the helper, the hand-off fails and says so. + [Fact] + public void HelperThatDoesNotStartFailsTheHandOff() + { + using var setup = new MsiUpdateSetup(); + string request = setup.Prepare(); + setup.Processes.OnStart = _ => null; + Assert.Equal("Could not start the staged update helper.", Assert.Throws(() => setup.Steps.StartHelper(request)).Message); + } + + + + /// Nothing of a preparation exists: no helper folder and no request. + private static void AssertNothingPrepared(MsiUpdateSetup setup) + { + Assert.False(Directory.Exists(setup.HelperDirectory)); + Assert.False(File.Exists(setup.RequestPath)); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateServiceFlowTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateServiceFlowTests.cs new file mode 100644 index 0000000..a15e2ef --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateServiceFlowTests.cs @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Reflection; +using System.Security.Cryptography; +using System.Text.Json; +using KofTwentyTwo.AppKit.Updates; +using Qqq.PrintAgent.Core.Printing; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The in-app update as the companion drives it: check, download, prepare, ask the service to pause, hand over to the +/// helper and close. The tests run the real update steps in temporary folders against a release source, a pipe and +/// processes that exist only in memory, and check what is done in which order and what is undone when a step fails: +/// the pause is lifted only when it was asked for, what was staged is removed unless the helper already runs from it, +/// and nothing is installed that the last check did not find. No release feed, service or installer is reached. +/// +public sealed class MsiUpdateServiceFlowTests +{ + /// What a cancelled update says. + private const string Canceled = "The update was canceled. The current version remains installed."; + + + + /// What an install is refused with when no check found a release. + private const string CheckFirst = "Check for updates from the installed app before installing an update."; + + + + /// The file name of the helper the update is handed to. + private const string Helper = "qqq-print-agent.exe"; + + + + /// An in-app update is offered only to the companion at its install path on a computer that has the machine state folder; the path is compared without regard to case. + [Theory] + [InlineData("installed", true, true)] + [InlineData("installed-other-case", true, true)] + [InlineData("copy", true, false)] + [InlineData("unknown", true, false)] + [InlineData("installed", false, false)] + public void UpdateIsOfferedOnlyToTheInstalledCompanion(string runningAs, bool machineState, bool offered) + { + using var flow = new Flow(); + flow.Setup.Processes.CurrentPath = runningAs switch + { + "installed" => flow.Setup.Places.InstalledCompanion, + "installed-other-case" => flow.Setup.Places.InstalledCompanion.ToUpperInvariant(), + "copy" => Path.Combine(flow.Setup.Root, "Downloads", "Qqq.PrintAgent.exe"), + _ => null, + }; + if(!machineState) + { Directory.Delete(flow.Setup.State, recursive: true); } + Assert.Equal(offered, flow.Service.IsSupported); + } + + + + /// A copy that is not the installed companion is told to install the MSI, and the release feed is not asked. + [Fact] + public async Task CheckFromACopyIsRefusedWithoutAskingTheFeed() + { + using var flow = new Flow(); + flow.Setup.Processes.CurrentPath = Path.Combine(flow.Setup.Root, "Downloads", "Qqq.PrintAgent.exe"); + UpdateCheckResult result = await flow.Service.CheckAsync(); + Assert.Equal((null, "Install the machine MSI to check for updates from this app."), (result.AvailableVersion, result.Error)); + Assert.Empty(flow.Releases.Checks); + Assert.Equal(CheckFirst, await flow.Service.DownloadAndApplyAsync()); + } + + + + /// A check asks the feed with this build's version and reports the newer release it finds, or that there is none. + [Fact] + public async Task CheckReportsTheNewerReleaseOrThatThereIsNone() + { + using var flow = new Flow(); + UpdateCheckResult found = await flow.Service.CheckAsync(); + Assert.Equal((Flow.Release.Version, null, true), (found.AvailableVersion, found.Error, found.IsUpdateAvailable)); + flow.Releases.Offered = null; + UpdateCheckResult none = await flow.Service.CheckAsync(); + Assert.Equal((null, null, false), (none.AvailableVersion, none.Error, none.IsUpdateAvailable)); + string thisBuild = typeof(MsiUpdateService).Assembly.GetCustomAttribute()!.InformationalVersion; + Assert.Equal(thisBuild, flow.Service.CurrentVersion); + Assert.Equal(new[] { thisBuild, thisBuild }, flow.Releases.Checks, StringComparer.Ordinal); + } + + + + /// + /// A check that fails is reported as a message, with anything shaped like a credential taken out, and a cancelled + /// one as cancelled. Either way the release an earlier check found is forgotten, so nothing can be installed until + /// a check succeeds again; the same holds for a check that finds nothing. + /// + [Theory] + [InlineData("failed", "The update server refused: token=[REDACTED]")] + [InlineData("canceled", Canceled)] + [InlineData("none", null)] + public async Task CheckThatFindsNothingOrFailsLeavesNothingToInstall(string outcome, string? error) + { + using var flow = new Flow(); + Assert.True((await flow.Service.CheckAsync()).IsUpdateAvailable); + flow.Releases.CheckFailure = outcome switch + { + "failed" => new HttpRequestException("The update server refused: token=synthetic-secret-value"), + "canceled" => new OperationCanceledException("Synthetic: the check was cancelled."), + _ => null, + }; + flow.Releases.Offered = string.Equals(outcome, "none", StringComparison.Ordinal) ? null : Flow.Release; + UpdateCheckResult result = await flow.Service.CheckAsync(); + Assert.Equal((null, error), (result.AvailableVersion, result.Error)); + Assert.Equal(CheckFirst, await flow.Service.DownloadAndApplyAsync()); + Assert.Empty(flow.Releases.Downloads); + Assert.Empty(flow.Setup.Journal); + } + + + + /// Without a check there is nothing to install: nothing is downloaded and the service is not asked for anything. + [Fact] + public async Task InstallWithoutACheckIsRefused() + { + using var flow = new Flow(); + Assert.Equal(CheckFirst, await flow.Service.DownloadAndApplyAsync()); + Assert.Empty(flow.Releases.Downloads); + Assert.Empty(flow.Setup.Journal); + } + + + + /// A release found while this was the installed companion is not installed once it no longer is: the install is refused and nothing is downloaded. + [Fact] + public async Task InstallIsRefusedWhenThisIsNoLongerTheInstalledCompanion() + { + using var flow = new Flow(); + Assert.True((await flow.Service.CheckAsync()).IsUpdateAvailable); + Directory.Delete(flow.Setup.State, recursive: true); + Assert.Equal(CheckFirst, await flow.Service.DownloadAndApplyAsync()); + Assert.Empty(flow.Releases.Downloads); + Assert.Empty(flow.Setup.Journal); + } + + + + /// + /// An update goes: download into a new session folder inside the updates folder, prepare the helper for this + /// companion's own process, ask the service to finish printing and pause, start the copied helper with the request, + /// log the hand-off, close the companion. The service is asked nothing else, and the session stays for the helper. + /// + [Fact] + public async Task UpdateIsDownloadedPreparedPausedHandedToTheHelperAndTheCompanionClosed() + { + using var flow = new Flow(); + _ = await flow.Service.CheckAsync(); + Assert.Null(await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download", "send prepare-update", "start " + Helper, "exit" }, flow.Setup.Journal, StringComparer.Ordinal); + (MsiRelease release, string currentVersion, string session) = Assert.Single(flow.Releases.Downloads); + Assert.Equal((Flow.Release, flow.Service.CurrentVersion), (release, currentVersion)); + Assert.Equal(flow.Setup.Places.UpdatesDirectory, Path.GetDirectoryName(session)); + Assert.Matches("^[0-9a-f]{32}$", Path.GetFileName(session)); + string requestPath = Path.Combine(session, "request.json"); + System.Diagnostics.ProcessStartInfo start = Assert.Single(flow.Setup.Processes.Started); + Assert.Equal(Path.Combine(session, "helper", Helper), start.FileName); + Assert.Equal(new[] { "--apply-update", requestPath }, start.ArgumentList, StringComparer.Ordinal); + MsiUpdateInstaller.InstallRequest request = JsonSerializer.Deserialize(File.ReadAllText(requestPath), PrintApiClient.JsonOptions)!; + Assert.Equal((Flow.Release.Version, Convert.ToHexString(SHA256.HashData(flow.Releases.Content)), MsiUpdateSetup.CompanionId, MsiUpdateSetup.CompanionStarted, session), + (request.Version, request.Sha256, request.ParentProcessId, request.ParentStartTicks, Path.GetDirectoryName(request.PackagePath))); + Assert.Equal(new[] { "INFO [Companion] Verified update handed to Windows Installer; closing the companion." }, flow.Log.Entries, StringComparer.Ordinal); + Assert.Equal(1, flow.Exits); + } + + + + /// + /// The companion is told what is happening, step by step and in order, by the service itself, and the download's + /// progress arrives as whole percentages, both as status text and through the progress the caller passed. + /// + [Fact] + public async Task EachStepAndTheDownloadProgressAreReported() + { + using var flow = new Flow(); + _ = await flow.Service.CheckAsync(); + Collected percentages = new(); + Assert.Null(await flow.Service.DownloadAndApplyAsync(percentages)); + await MsiUpdateSetup.UntilAsync(() => percentages.Snapshot().Length == 2 && flow.Statuses.Snapshot().Length == 5); + Assert.Equal(new[] { 50, 100 }, percentages.Snapshot().Order()); + Assert.Equal(new[] { "Downloading the update…", "Update verified. Preparing Windows Installer…", "Waiting for active printing to finish…" }, + flow.Statuses.Snapshot().Where(status => !status.StartsWith("Downloading the update: ", StringComparison.Ordinal)), StringComparer.Ordinal); + Assert.Equal(new[] { "Downloading the update: 100%", "Downloading the update: 50%" }, flow.Statuses.Snapshot().Where(status => status.StartsWith("Downloading the update: ", StringComparison.Ordinal)).Order(StringComparer.Ordinal), StringComparer.Ordinal); + Assert.All(flow.Senders.Snapshot(), sender => Assert.Same(flow.Service, sender)); + } + + + + /// + /// When the service does not answer that it is ready, the helper is not started: the operator is told what the + /// service said, the service is told to resume printing, what was staged is removed and the companion stays open. + /// The answer must be exactly "Ready for update."; anything else, however close, is not readiness. + /// + [Theory] + [InlineData("Not ready for update: 2 job(s) were still in progress after 25 seconds. They will finish; try the update again afterwards.", "The update was not started, and the current version remains installed. Not ready for update: 2 job(s) were still in progress after 25 seconds. They will finish; try the update again afterwards.")] + [InlineData("Error: Unknown command.", "The service could not prepare for an update, and the current version remains installed. The service answered: Error: Unknown command.")] + [InlineData("ready for update.", "The service could not prepare for an update, and the current version remains installed. The service answered: ready for update.")] + public async Task ServiceThatIsNotReadyStopsTheUpdateAndIsToldToResume(string reply, string shown) + { + using var flow = new Flow(); + flow.Setup.Replies["prepare-update"] = reply; + _ = await flow.Service.CheckAsync(); + Assert.Equal(shown, await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download", "send prepare-update", "send resume-after-update" }, flow.Setup.Journal, StringComparer.Ordinal); + Assert.False(Directory.Exists(flow.Session)); + Assert.Equal(0, flow.Exits); + Assert.Empty(flow.Log.Entries); + } + + + + /// A service that cannot be reached stops the update the same way; that the resume cannot be delivered either changes nothing, because the service ends an abandoned pause by itself. + [Fact] + public async Task ServiceThatCannotBeReachedStopsTheUpdate() + { + using var flow = new Flow(); + flow.Setup.PipeFailure = new TimeoutException("Synthetic: the service did not answer."); + _ = await flow.Service.CheckAsync(); + Assert.Equal("Synthetic: the service did not answer.", await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download", "send prepare-update", "send resume-after-update" }, flow.Setup.Journal, StringComparer.Ordinal); + Assert.False(Directory.Exists(flow.Session)); + Assert.Equal(0, flow.Exits); + } + + + + /// A retry after a stopped update stages afresh, in another session folder, and goes through. + [Fact] + public async Task RetryAfterAStoppedUpdateStagesAfresh() + { + using var flow = new Flow(); + flow.Setup.Replies["prepare-update"] = "Not ready for update: 1 job(s) were still in progress."; + _ = await flow.Service.CheckAsync(); + Assert.NotNull(await flow.Service.DownloadAndApplyAsync()); + flow.Setup.Replies["prepare-update"] = "Ready for update."; + Assert.Null(await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(2, flow.Releases.Downloads.Select(download => download.Directory).Distinct(StringComparer.OrdinalIgnoreCase).Count()); + Assert.Equal(1, flow.Exits); + } + + + + /// + /// A failure before the service was asked to pause leaves printing alone: the service is asked nothing, what was + /// staged is removed, and the operator gets the reason. That holds for a download that fails and for a preparation + /// that is refused because the installed command line folder cannot be trusted. + /// + [Theory] + [InlineData(true, "MSI integrity verification failed. No update was staged.")] + [InlineData(false, "An update path allows modification by an untrusted identity. Repair the MSI directory permissions.")] + public async Task FailureBeforeThePauseLeavesPrintingAloneAndNothingStaged(bool downloadFails, string reason) + { + using var flow = new Flow(); + if(downloadFails) + { flow.Releases.DownloadFailure = new InvalidDataException(reason); } + else + { flow.Setup.Security.Descriptors[flow.Setup.Places.InstalledCli] = MsiUpdateSetup.WritableByUsers(); } + _ = await flow.Service.CheckAsync(); + Assert.Equal(reason, await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download" }, flow.Setup.Journal, StringComparer.Ordinal); + Assert.False(Directory.Exists(flow.Session)); + Assert.Equal(0, flow.Exits); + } + + + + /// + /// The session folder is checked before it is created and again once it exists. An updates folder that cannot be + /// trusted means no folder is created and nothing is downloaded; a session folder that turns out untrusted once it + /// exists means nothing is downloaded into it. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task NothingIsDownloadedIntoAFolderThatCannotBeTrusted(bool onlyOnceCreated) + { + using var flow = new Flow(); + if(onlyOnceCreated) + { flow.Setup.Security.Unlisted = path => string.Equals(Path.GetDirectoryName(path), flow.Setup.Places.UpdatesDirectory, StringComparison.OrdinalIgnoreCase) ? MsiUpdateSetup.WritableByUsers() : null; } + else + { flow.Setup.Security.Descriptors[flow.Setup.Places.UpdatesDirectory] = MsiUpdateSetup.WritableByUsers(); } + Directory.Delete(flow.Setup.Session, recursive: true); + _ = await flow.Service.CheckAsync(); + Assert.Equal("An update path allows modification by an untrusted identity. Repair the MSI directory permissions.", await flow.Service.DownloadAndApplyAsync()); + Assert.Empty(flow.Releases.Downloads); + Assert.Empty(flow.Setup.Journal); + Assert.Equal(onlyOnceCreated ? 1 : 0, Directory.GetDirectories(flow.Setup.Places.UpdatesDirectory).Length); + } + + + + /// + /// An update cancelled during the download or while the helper is being prepared says so, leaves printing alone + /// and removes what was staged. One cancelled after the service has paused also tells the service to resume. In no + /// case is the helper started. + /// + [Theory] + [InlineData("downloading", false)] + [InlineData("preparing", false)] + [InlineData("pausing", true)] + public async Task CancelledUpdateSaysSoAndUndoesWhatItDid(string during, bool paused) + { + using var flow = new Flow(); + using CancellationTokenSource cancel = new(); + flow.Releases.WhileDownloading += _ => Cancel("downloading"); + flow.Setup.Processes.WhileOpening = _ => Cancel("preparing"); + flow.Setup.WhileSending = _ => Cancel("pausing"); + _ = await flow.Service.CheckAsync(); + Assert.Equal(Canceled, await flow.Service.DownloadAndApplyAsync(progress: null, cancel.Token)); + Assert.Equal(paused ? new[] { "download", "send prepare-update", "send resume-after-update" } : ["download"], flow.Setup.Journal, StringComparer.Ordinal); + Assert.False(Directory.Exists(flow.Session)); + Assert.Equal(0, flow.Exits); + + void Cancel(string step) + { + if(string.Equals(step, during, StringComparison.Ordinal)) + { cancel.Cancel(); } + } + } + + + + /// When Windows starts nothing for the helper, the update stops there: printing is resumed, what was staged is removed and the companion stays open. + [Fact] + public async Task HelperThatDoesNotStartStopsTheUpdateAndPrintingIsResumed() + { + using var flow = new Flow(); + _ = flow.Setup.StartsNothing.Add(Helper); + _ = await flow.Service.CheckAsync(); + Assert.Equal("Could not start the staged update helper.", await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download", "send prepare-update", "start " + Helper, "send resume-after-update" }, flow.Setup.Journal, StringComparer.Ordinal); + Assert.False(Directory.Exists(flow.Session)); + Assert.Equal(0, flow.Exits); + } + + + + /// + /// Once the helper has started, a companion that cannot close is reported as exactly that and never as a failed + /// install: printing stays paused for the installer and the session the helper runs from is left in place. + /// + [Fact] + public async Task CompanionThatCannotCloseAfterTheHandOffIsNotReportedAsAFailedInstall() + { + using var flow = new Flow(); + flow.ExitFailure = new InvalidOperationException("Synthetic: the window is gone."); + _ = await flow.Service.CheckAsync(); + Assert.Equal("The installer helper started, but the companion could not close. Check the update outcome and Logs before trying again.", await flow.Service.DownloadAndApplyAsync()); + Assert.Equal(new[] { "download", "send prepare-update", "start " + Helper, "exit" }, flow.Setup.Journal, StringComparer.Ordinal); + Assert.True(File.Exists(Path.Combine(flow.Session, "helper", Helper))); + Assert.True(File.Exists(Path.Combine(flow.Session, "request.json"))); + } + + + + /// + /// A session that holds a junction, directly or in a folder below, is not deleted, because the delete could follow + /// the junction out of the session: it is kept for an administrator, a warning says so, and what the junction points + /// at is untouched. The update's own failure is still what the operator is told. + /// + [Theory] + [InlineData("")] + [InlineData("below")] + public async Task SessionThatHoldsAJunctionIsKeptAndReported(string folder) + { + using var flow = new Flow(); + string elsewhere = Path.Combine(flow.Setup.Root, "elsewhere"); + Directory.CreateDirectory(elsewhere); + File.WriteAllText(Path.Combine(elsewhere, "kept.txt"), "synthetic"); + flow.Releases.WhileDownloading += session => + { + Directory.CreateDirectory(Path.Combine(session, folder)); + MsiUpdateSetup.MakeJunction(Path.Combine(session, folder, "linked"), elsewhere); + }; + flow.Releases.DownloadFailure = new InvalidDataException("MSI integrity verification failed. No update was staged."); + _ = await flow.Service.CheckAsync(); + Assert.Equal("MSI integrity verification failed. No update was staged.", await flow.Service.DownloadAndApplyAsync()); + Assert.True(Directory.Exists(Path.Combine(flow.Session, folder, "linked"))); + Assert.True(File.Exists(Path.Combine(elsewhere, "kept.txt"))); + Assert.Equal(new[] { "WARN [Companion] Unapplied update staging could not be removed: Unapplied update staging contains a link and was retained." }, flow.Log.Entries, StringComparer.Ordinal); + } + + + + /// + /// A session folder is checked again before it is deleted. One that ordinary users may meanwhile write to is not + /// deleted from: it is kept for an administrator and a warning says why, while the operator is still told what + /// stopped the update. + /// + [Fact] + public async Task SessionThatCanNoLongerBeTrustedIsKeptAndReported() + { + using var flow = new Flow(); + flow.Releases.WhileDownloading += session => flow.Setup.Security.Descriptors[session] = MsiUpdateSetup.WritableByUsers(); + flow.Releases.DownloadFailure = new InvalidDataException("MSI integrity verification failed. No update was staged."); + _ = await flow.Service.CheckAsync(); + Assert.Equal("MSI integrity verification failed. No update was staged.", await flow.Service.DownloadAndApplyAsync()); + Assert.True(Directory.Exists(flow.Session)); + Assert.Equal(new[] { "WARN [Companion] Unapplied update staging could not be removed: An update path allows modification by an untrusted identity. Repair the MSI directory permissions." }, flow.Log.Entries, StringComparer.Ordinal); + } + + + + /// Releasing the update service releases its release source. + [Fact] + public void ReleasingTheServiceReleasesTheReleaseSource() + { + using var flow = new Flow(); + flow.Service.Dispose(); + Assert.True(flow.Releases.Disposed); + } + + + + /// + /// The companion's own constructor binds the installed product: the pipe is the installed service's and the update + /// steps are the installed product's own. Only the binding shows that, because neither is called here. A test run + /// is not the installed product, so the update is not offered, a check says to install the MSI and an install says + /// to check first, all without the release feed, the service or this computer's machine state being reached. The + /// asset prefix it is given is the release client's, which refuses one that is not letters and digits. + /// + [Fact] + public async Task CompanionsConstructorBindsTheInstalledProduct() + { + FakeActivityLog log = new(); + using MsiUpdateService service = new(() => { }, log); + Assert.Equal>>(AgentPipeClient.SendAsync, service.Send); + Assert.Same(MsiUpdateInstaller.Installed, service.Steps); + Assert.False(service.IsSupported); + UpdateCheckResult check = await service.CheckAsync(); + Assert.Equal((null, "Install the machine MSI to check for updates from this app."), (check.AvailableVersion, check.Error)); + Assert.Equal(CheckFirst, await service.DownloadAndApplyAsync()); + Assert.Empty(log.Entries); + ArgumentException refused = Assert.Throws(() => new MsiUpdateService(() => { }, log, "9-not-a-prefix")); + Assert.Equal("assetPrefix", refused.ParamName); + } + + + + /// Values reported from other threads, collected so a test can look at them at any time. + private sealed class Collected : IProgress + { + /// What was reported so far. + private readonly List _values = []; + + + + /// Keeps one reported value. + public void Report(T value) + { + lock(_values) + { _values.Add(value); } + } + + + + /// A copy of what was reported so far. + internal T[] Snapshot() + { + lock(_values) + { return [.. _values]; } + } + } + + + + /// + /// One update service over the update steps of a , a release source that offers one + /// newer release, and a service that answers that it is ready. What the release source and the companion's exit do + /// is added to the setup's journal, so one list shows the order of everything that reached the outside. + /// + private sealed class Flow : IDisposable + { + /// The newer release the source offers. Its addresses are never fetched. + internal static readonly MsiRelease Release = new("0.4.0", new Uri("https://github.com/QRun-IO/qqq-print-agent/releases/download/v0.4.0/QqqPrintAgent-v0.4.0-x64.msi"), new Uri("https://github.com/QRun-IO/qqq-print-agent/releases/download/v0.4.0/SHA256SUMS"), 7); + + + + /// Builds the service over the fakes and listens to what it reports. + internal Flow() + { + Setup.Replies["prepare-update"] = "Ready for update."; + Releases.WhileDownloading = _ => Setup.Journal.Add("download"); + Service = new MsiUpdateService(Exit, Log, Releases, Setup.SendAsync, Setup.Steps); + Service.StatusChanged += (sender, status) => + { + Senders.Report(sender); + Statuses.Report(status.Message); + }; + } + + + + /// The update steps in temporary folders, with their fakes. + internal MsiUpdateSetup Setup { get; } = new(); + + + + /// The release source. + internal FakeMsiReleaseSource Releases { get; } = new() { Offered = Release }; + + + + /// The companion's log. + internal FakeActivityLog Log { get; } = new(); + + + + /// The service under test. + internal MsiUpdateService Service { get; } + + + + /// Every status text the service reported, in the order it arrived. + internal Collected Statuses { get; } = new(); + + + + /// Who each status came from. + internal Collected Senders { get; } = new(); + + + + /// How many times the companion was told to close. + internal int Exits { get; private set; } + + + + /// When set, the companion cannot close: telling it to fails with this. + internal Exception? ExitFailure { get; set; } + + + + /// The session folder of the only download so far. + internal string Session => Assert.Single(Releases.Downloads).Directory; + + + + /// Releases the service and removes the temporary folders. + public void Dispose() + { + Service.Dispose(); + Setup.Dispose(); + } + + + + /// The companion's exit: it is noted, and fails when the test said so. + private void Exit() + { + Exits++; + Setup.Journal.Add("exit"); + if(ExitFailure is not null) + { throw ExitFailure; } + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateSetup.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateSetup.cs new file mode 100644 index 0000000..ff4582c --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateSetup.cs @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Diagnostics; +using System.Security.AccessControl; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The update steps under test in temporary folders: a Program Files folder with the installed companion, service and +/// command line tool, a machine state folder with an update session that holds a staged MSI, and fakes for folder +/// security, processes, the pipe, the log and the clock. The companion that asks for the update is a running process of +/// the fake. Everything lives under one temporary root that is removed afterwards; no installer is started, no service +/// or pipe is reached, and nothing under this computer's Program Files or machine state folder is touched. +/// +internal sealed class MsiUpdateSetup : IDisposable +{ + /// The release the staged MSI is said to hold; an eligible one. + internal const string Version = "0.3.2-rc.1"; + + + + /// The process id of the companion that asks for the update. + internal const int CompanionId = 3100; + + + + /// When that companion started, in universal time ticks. + internal const long CompanionStarted = 638_900_000_000_000_000; + + + + /// The instant the manual clock starts at. + internal static readonly DateTimeOffset Now = new(2026, 11, 10, 12, 0, 0, TimeSpan.Zero); + + + + /// How long a test waits for something the code under test must do; long, because the test machine may be busy, and finite, so that code that never does it fails the test instead of hanging it. + internal static readonly TimeSpan Patience = TimeSpan.FromMinutes(1); + + + + /// Creates the folders, the installed programs, the session with its staged MSI, and the steps over the fakes. + internal MsiUpdateSetup() + { + ProgramFiles = Path.Combine(Root, "Program Files"); + State = Path.Combine(Root, "ProgramData", "QqqPrintAgent"); + Session = Path.Combine(State, "updates", Guid.NewGuid().ToString("N")); + Package = Path.Combine(Session, "QqqPrintAgent-v" + Version + "-x64.msi"); + Places = new MsiUpdatePlaces(ProgramFiles, State, Guard, OpenLog, SendAsync, Clock); + foreach(string file in new[] { Places.InstalledCompanion, Places.InstalledService, InstalledTool, Path.Combine(Places.InstalledCli, "qqq-print-agent.dll"), Path.Combine(Places.InstalledCli, "runtimes", "win-x64", "native.dll") }) + { + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + File.WriteAllText(file, "synthetic " + Path.GetFileName(file)); + Processes.Versions[file] = Version + "+reviewed-source"; + } + Directory.CreateDirectory(Session); + File.WriteAllBytes(Package, PackageBytes); + Companion = Processes.Run(CompanionId, Places.InstalledCompanion, CompanionStarted); + Processes.CurrentPath = Places.InstalledCompanion; + Processes.CurrentId = CompanionId; + Processes.OnStart = start => + { + string program = Path.GetFileName(start.FileName); + Journal.Add("start " + program); + WhileStarting?.Invoke(start); + return StartsNothing.Contains(program) ? null : FakeProcessHost.Ended(start.FileName, ExitCodes.GetValueOrDefault(program, 0)); + }; + Steps = new MsiUpdateSteps(Security, Processes, Places); + } + + + + /// The temporary root everything in this setup lives under. + internal string Root { get; } = Path.Combine(Path.GetTempPath(), "qqq-update-steps-" + Guid.NewGuid().ToString("N")); + + + + /// The stand-in for this computer's Program Files folder. + internal string ProgramFiles { get; } + + + + /// The stand-in for the machine state folder. + internal string State { get; } + + + + /// The folder of one update session inside the updates folder. + internal string Session { get; } + + + + /// The staged MSI of that session. + internal string Package { get; } + + + + /// What the staged MSI holds. + internal byte[] PackageBytes { get; } = [0xD0, 0xCF, 0x11, 0xE0, 1, 2, 3, 4, 5, 6]; + + + + /// The folder security fake; every folder and file is trusted unless a test says otherwise. + internal FakePathSecurity Security { get; } = new(); + + + + /// The process fake. + internal FakeProcessHost Processes { get; } = new(); + + + + /// The log the steps are handed when they open the log of the state folder. + internal FakeActivityLog Log { get; } = new(); + + + + /// The clock, which moves only when a test advances it. + internal ManualTimeProvider Clock { get; } = new(Now); + + + + /// The places the steps work in. + internal MsiUpdatePlaces Places { get; } + + + + /// The steps under test. + internal MsiUpdateSteps Steps { get; } + + + + /// The companion that asks for the update, as a running process. + internal FakeProcess Companion { get; } + + + + /// Every path the machine state check was asked about, in order. + internal List Guarded { get; } = []; + + + + /// When set, the machine state check refuses with this. + internal Exception? GuardFailure { get; set; } + + + + /// Every request sent to the service, in order, by operation. + internal List Sent { get; } = []; + + + + /// When set, the service cannot be reached: every request fails with this. + internal Exception? PipeFailure { get; set; } + + + + /// What the service answers to each operation; "Printing resumed." unless a test says otherwise. + internal Dictionary Replies { get; } = new(StringComparer.Ordinal); + + + + /// Called while a request is being sent, with its operation, so a test can act at the moment the service is asked. + internal Action? WhileSending { get; set; } + + + + /// Every state folder whose log was opened, in order. + internal List LogsOpened { get; } = []; + + + + /// What reached the outside, in order: each request sent as "send" and its operation, each program started as "start" and its file name. + internal List Journal { get; } = []; + + + + /// The code each started program ends with, by file name; 0 for a program that is not listed. + internal Dictionary ExitCodes { get; } = new(StringComparer.OrdinalIgnoreCase); + + + + /// Programs, by file name, for which Windows starts nothing. + internal HashSet StartsNothing { get; } = new(StringComparer.OrdinalIgnoreCase); + + + + /// Called while a program is being started, so a test can look at the files as they are while the program runs. + internal Action? WhileStarting { get; set; } + + + + /// The installed command line tool. + internal string InstalledTool => Path.Combine(Places.InstalledCli, "qqq-print-agent.exe"); + + + + /// The folder the installed command line tool is copied to. + internal string HelperDirectory => Path.Combine(Session, "helper"); + + + + /// The copied command line tool that applies the update. + internal string Helper => Path.Combine(HelperDirectory, "qqq-print-agent.exe"); + + + + /// The request the preparing step writes. + internal string RequestPath => Path.Combine(Session, "request.json"); + + + + /// The recorded outcome of the last update. + internal string OutcomePath => Path.Combine(Places.UpdatesDirectory, "last-result.json"); + + + + /// Every program the steps asked to start, by file name, in order. + internal IEnumerable StartedPrograms => Processes.Started.Select(start => Path.GetFileName(start.FileName)); + + + + /// A descriptor that lets ordinary users write, which no update path may have. + internal static FileSystemSecurity WritableByUsers() => FakePathSecurity.Descriptor(alsoAllow: FakePathSecurity.Users, rights: FileSystemRights.Write); + + + + /// Prepares the update as the installed companion does and returns the request path. + internal string Prepare() => Steps.PrepareHelper(Package, Version, CompanionId); + + + + /// Applies the update and returns the helper's exit code. The wait has a limit, so that an apply step that wrongly waits for something that never comes fails the test instead of hanging it. + internal Task ApplyAsync(string request) => Steps.ApplyAsync(request).WaitAsync(Patience); + + + + /// + /// Prepares the update and then becomes the staged helper: the rules now run as the copied command line tool, and the + /// companion has closed unless the test keeps it running. + /// + internal string PrepareAndRunAsHelper(bool companionClosed = true) + { + string request = Prepare(); + Processes.CurrentPath = Helper; + if(companionClosed) + { _ = Processes.Running.Remove(CompanionId); } + return request; + } + + + + /// + /// Makes a junction inside the temporary root with the command interpreter's own mklink, which needs no administrator + /// rights. The target must be a folder inside the root too. + /// + internal static void MakeJunction(string junction, string target) + { + using Process mklink = Process.Start(new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe"), ["/d", "/c", "mklink", "/J", junction, target]) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true })!; + string said = mklink.StandardOutput.ReadToEnd() + mklink.StandardError.ReadToEnd(); + mklink.WaitForExit(); + Assert.True(mklink.ExitCode == 0, "The junction this test needs could not be made in its temporary folder: " + said); + } + + + + /// Waits until the condition holds, for at most a minute, looking again every few milliseconds; a test uses it to see that the code under test has reached a wait. + internal static async Task UntilAsync(Func condition) + { + long started = Stopwatch.GetTimestamp(); + while(!condition()) + { + Assert.True(Stopwatch.GetElapsedTime(started) < TimeSpan.FromMinutes(1), "The condition this test waits for did not come about within a minute."); + await Task.Delay(5); + } + } + + + + /// Removes the temporary root. Junctions in it are removed first, as junctions and without following them, because a recursive delete reports a junction as an error although it removes it. + public void Dispose() + { + if(Directory.Exists(Root)) + { + RemoveJunctions(Root); + Directory.Delete(Root, recursive: true); + } + } + + + + /// Removes every junction below a folder, leaving what each points at alone. + private static void RemoveJunctions(string directory) + { + foreach(string entry in Directory.EnumerateDirectories(directory)) + { + if(File.GetAttributes(entry).HasFlag(FileAttributes.ReparsePoint)) + { Directory.Delete(entry); } + else + { RemoveJunctions(entry); } + } + } + + + + /// The machine state check of this setup: it notes the path and refuses when the test said so. + private void Guard(string path) + { + Guarded.Add(path); + if(GuardFailure is not null) + { throw GuardFailure; } + } + + + + /// Opens the log of a state folder: notes which folder and hands out the fake log. + private FakeActivityLog OpenLog(string directory) + { + LogsOpened.Add(directory); + return Log; + } + + + + /// The pipe of this setup: it notes the operation and answers, or fails when the test said so. + internal Task SendAsync(PipeRequest request) + { + Sent.Add(request.Operation); + Journal.Add("send " + request.Operation); + WhileSending?.Invoke(request.Operation); + return PipeFailure is not null ? Task.FromException(PipeFailure) : Task.FromResult(Replies.GetValueOrDefault(request.Operation, "Printing resumed.")); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateStagingTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateStagingTests.cs new file mode 100644 index 0000000..d021f25 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/MsiUpdateStagingTests.cs @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.Security.Principal; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// Which folder an update may be staged in. Everything staged there later runs with administrator rights, so the folder +/// must be asked for by an administrator, lie inside the updates folder of trusted machine state, be reached through no +/// link, and be owned and writable only by trusted accounts at every level up to the machine state folder. The checks +/// run in temporary folders with a fake of the folder security; the links are real junctions. +/// +public sealed class MsiUpdateStagingTests +{ + /// What someone who is not an administrator is told. + private const string NotAdministrator = "Machine updates require an elevated administrator. No installer was started."; + + + + /// What a path outside the updates folder is refused with. + private const string Outside = "Update paths must remain inside the protected staging directory."; + + + + /// + /// A session folder inside trusted machine state is accepted, whether it exists yet or not, and so is the updates + /// folder itself. The machine state check is asked about the very path, and the owner and access list of every + /// existing folder from the session up to the machine state folder are read, and of nothing above it. + /// + [Fact] + public void SessionInsideTrustedMachineStateIsAccepted() + { + using var setup = new MsiUpdateSetup(); + setup.Steps.ValidateStagingDirectory(setup.Session); + Assert.Equal(new[] { setup.Session }, setup.Guarded, StringComparer.Ordinal); + Assert.Equal(new[] { setup.Session, setup.Places.UpdatesDirectory, setup.State }, setup.Security.Reads, StringComparer.Ordinal); + setup.Security.Reads.Clear(); + setup.Steps.ValidateStagingDirectory(Path.Combine(setup.Places.UpdatesDirectory, "not-yet-created")); + Assert.Equal(new[] { setup.Places.UpdatesDirectory, setup.State }, setup.Security.Reads, StringComparer.Ordinal); + setup.Steps.ValidateStagingDirectory(setup.Places.UpdatesDirectory); + Assert.Equal(Path.Combine(setup.State, "updates"), setup.Steps.UpdatesDirectory); + } + + + + /// Someone who is not an administrator is refused before the machine state is checked or any owner is read. + [Fact] + public void NonAdministratorIsRefusedBeforeAnythingIsChecked() + { + using var setup = new MsiUpdateSetup(); + setup.Security.IsAdministrator = false; + UnauthorizedAccessException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(setup.Session)); + Assert.Equal(NotAdministrator, refusal.Message); + Assert.Empty(setup.Guarded); + Assert.Empty(setup.Security.Reads); + } + + + + /// Machine state that cannot be trusted stops the check with the guard's own refusal, before any owner is read. + [Fact] + public void UntrustedMachineStateStopsTheCheck() + { + using var setup = new MsiUpdateSetup(); + setup.GuardFailure = new UnauthorizedAccessException("Synthetic: the machine print data directory is not trusted."); + Assert.Same(setup.GuardFailure, Assert.Throws(() => setup.Steps.ValidateStagingDirectory(setup.Session))); + Assert.Empty(setup.Security.Reads); + } + + + + /// + /// A folder outside the updates folder is refused: the machine state folder itself, a folder beside the updates + /// folder whose name only begins the same way, and a path that climbs out of it with "..". + /// + [Theory] + [InlineData("")] + [InlineData("updates-other/session")] + [InlineData("updates/../logs")] + [InlineData("updates/session/../../../elsewhere")] + public void FolderOutsideTheUpdatesFolderIsRefused(string relative) + { + using var setup = new MsiUpdateSetup(); + InvalidDataException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(Path.Combine(setup.State, relative))); + Assert.Equal(Outside, refusal.Message); + Assert.Empty(setup.Security.Reads); + } + + + + /// Without a machine state folder there is no installation to update, and that is what is said. + [Fact] + public void MissingMachineStateFolderMeansNoInstallation() + { + using var setup = new MsiUpdateSetup(); + Directory.Delete(setup.State, recursive: true); + InvalidOperationException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(setup.Session)); + Assert.Equal("Install the machine MSI before staging updates.", refusal.Message); + } + + + + /// A session folder that is really a junction to somewhere else is refused, and so is a folder reached through one, before any owner is read. + [Theory] + [InlineData("")] + [InlineData("inside")] + public void FolderReachedThroughAJunctionIsRefused(string below) + { + using var setup = new MsiUpdateSetup(); + string elsewhere = Path.Combine(setup.Root, "elsewhere"); + Directory.CreateDirectory(Path.Combine(elsewhere, "inside")); + string junction = Path.Combine(setup.Places.UpdatesDirectory, "linked"); + MsiUpdateSetup.MakeJunction(junction, elsewhere); + IOException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(Path.Combine(junction, below))); + Assert.Equal("Update paths cannot contain symbolic links or junctions.", refusal.Message); + Assert.Empty(setup.Security.Reads); + } + + + + /// A file where a folder belongs, at the session or above it, is refused. + [Theory] + [InlineData("occupied")] + [InlineData("occupied/session")] + public void FileWhereAFolderBelongsIsRefused(string relative) + { + using var setup = new MsiUpdateSetup(); + File.WriteAllText(Path.Combine(setup.Places.UpdatesDirectory, "occupied"), "synthetic"); + IOException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(Path.Combine(setup.Places.UpdatesDirectory, relative))); + Assert.Equal("An update directory path points to a file.", refusal.Message); + } + + + + /// A folder ordinary users may write to is refused at every level: the session, the updates folder and the machine state folder. + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public void FolderOrdinaryUsersMayWriteToIsRefusedAtEveryLevel(int level) + { + using var setup = new MsiUpdateSetup(); + string folder = new[] { setup.Session, setup.Places.UpdatesDirectory, setup.State }[level]; + setup.Security.Descriptors[folder] = MsiUpdateSetup.WritableByUsers(); + UnauthorizedAccessException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(setup.Session)); + Assert.Equal("An update path allows modification by an untrusted identity. Repair the MSI directory permissions.", refusal.Message); + } + + + + /// + /// A folder the administrator who is asking owns is trusted, because that administrator can change it anyway; a + /// folder some other user owns is not. + /// + [Fact] + public void FolderOwnedByTheAskingAdministratorIsTrustedAndAnotherUsersIsNot() + { + using var setup = new MsiUpdateSetup(); + setup.Security.Descriptors[setup.Session] = FakePathSecurity.Descriptor(owner: setup.Security.CurrentUserSid!); + setup.Steps.ValidateStagingDirectory(setup.Session); + setup.Security.Descriptors[setup.Session] = FakePathSecurity.Descriptor(owner: "S-1-5-21-100-200-300-2002"); + UnauthorizedAccessException refusal = Assert.Throws(() => setup.Steps.ValidateStagingDirectory(setup.Session)); + Assert.Equal("An update path is not owned by a trusted administrator or Windows identity.", refusal.Message); + } + + + + /// + /// The installed product's steps are bound to this computer. They work in exactly the places of the installed + /// product, with the machine state guard, the machine log and the installed service's pipe among them; the binding + /// is only compared, and none of those is called. They stage under the machine state folder, run as the process + /// that calls them, never take a development or test copy for the installed companion, and ask the real process + /// token who is asking. The last is shown with a folder outside the machine state, which nothing is ever read from + /// or created in: without administrator rights the request is refused for that reason, and with them for being + /// outside the updates folder. + /// + [Fact] + public void InstalledProductsStepsAreBoundToThisComputer() + { + Assert.Equal(MsiUpdatePlaces.Installed(), MsiUpdateInstaller.Installed.Places); + Assert.Equal(Path.Combine(Qqq.PrintAgent.Core.MachineStateDirectory.Root, "updates"), MsiUpdateInstaller.Installed.UpdatesDirectory); + Assert.Equal(Environment.ProcessId, MsiUpdateInstaller.Installed.CurrentProcessId); + Assert.False(MsiUpdateInstaller.Installed.RunsAsInstalledCompanion); + using var identity = WindowsIdentity.GetCurrent(); + bool administrator = identity.Groups!.Contains(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null)); + string outside = Path.Combine(Path.GetTempPath(), "qqq-no-such-update-session-" + Guid.NewGuid().ToString("N")); + Exception refusal = Assert.ThrowsAny(() => MsiUpdateInstaller.Installed.ValidateStagingDirectory(outside)); + Assert.Equal(administrator ? typeof(InvalidDataException) : typeof(UnauthorizedAccessException), refusal.GetType()); + Assert.Equal(administrator ? Outside : NotAdministrator, refusal.Message); + Assert.False(Directory.Exists(outside)); + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/WindowsPipePeerFactsTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/WindowsPipePeerFactsTests.cs new file mode 100644 index 0000000..936b9d8 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/WindowsPipePeerFactsTests.cs @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.Principal; +using Microsoft.Win32.SafeHandles; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The real facts behind the pipe client's trust decision, read without the print service: a pipe this test serves +/// itself under a name of its own, a service name no service has, the status of a built-in Windows service read +/// through a handle that may only read, the test process and a harmless child program. Nothing here connects to the +/// print service's pipe, names the print service or changes anything on this computer. +/// +public sealed class WindowsPipePeerFactsTests +{ + /// The remote procedure call service: present and running on every Windows. + private const string BuiltIn = "RpcSs"; + + + + /// The right to ask a process for its exit code and nothing more (PROCESS_QUERY_LIMITED_INFORMATION), which any user has for a process of their own. + private const uint QueryLimitedInformation = 0x1000; + + + + /// The exit code Windows reports for a process that has not ended (STILL_ACTIVE). + private const uint StillActive = 259; + + + + /// The code the harmless child program exits with when it is told to connect to a pipe that is not one of these tests' own. + private const int RefusedPipe = 64; + + + + /// How long a child that is expected to finish may take; generous, because the test machine may be busy. + private static readonly TimeSpan Generous = TimeSpan.FromSeconds(60); + + + + /// How long handles that Windows and this test let go of are given to be gone, before the test looks at what is left. + private static readonly TimeSpan Settle = TimeSpan.FromMilliseconds(500); + + + + /// The fixture program built beside the tests. + private static string StandIn => Path.ChangeExtension(typeof(WorkerFixture.Program).Assembly.Location, ".exe"); + + + + /// The kernel names the process that serves a pipe: for a pipe this test serves, the test process, asked from the client's end. + [Fact] + public async Task ServerOfAPipeIsTheProcessThatServesIt() + { + string name = "qqq-peer-facts-" + Guid.NewGuid().ToString("N"); + await using NamedPipeServerStream server = new(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + await using NamedPipeClientStream client = new(".", name, PipeDirection.InOut, PipeOptions.Asynchronous); + using CancellationTokenSource patience = new(Generous); + await Task.WhenAll(server.WaitForConnectionAsync(patience.Token), client.ConnectAsync(patience.Token)); + Assert.Equal(checked((uint)Environment.ProcessId), new WindowsPipePeerFacts().ServerProcessId(client.SafePipeHandle)); + } + + + + /// + /// The process named is the one that serves the pipe, not the one that uses it. This test serves a pipe and a + /// harmless child program connects to it, so the two ends are different processes: asked about that connection, + /// the answer is the test process and not the child. + /// + [Fact] + public async Task ServerOfAPipeIsNotTheProcessThatConnectedToIt() + { + string name = "qqq-peer-facts-" + Guid.NewGuid().ToString("N"); + await using NamedPipeServerStream server = new(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + using Process client = Process.Start(new ProcessStartInfo(StandIn, ["--stand-in", "connect", name]) { UseShellExecute = false, CreateNoWindow = true })!; + try + { + using CancellationTokenSource patience = new(Generous); + await server.WaitForConnectionAsync(patience.Token); + Assert.NotEqual(Environment.ProcessId, client.Id); + Assert.False(client.HasExited); + Assert.Equal(checked((uint)Environment.ProcessId), new WindowsPipePeerFacts().ServerProcessId(server.SafePipeHandle)); + } + finally + { + client.Kill(); + } + } + + + + /// + /// The harmless child program connects only to a pipe of these tests, whose name begins as theirs do and goes on + /// with letters and digits. Told any other name it connects to nothing, says why and ends with its refusal code: + /// a name that begins otherwise, and a name that begins as the tests' do and then leaves that beginning by a + /// separator and two dots, which Windows reads as the name behind them. No pipe has any of these names, and none + /// is the print service's; a child that did not refuse would wait a minute for the pipe and fail this test. + /// + [Theory] + [InlineData("qqq-other-facts-")] + [InlineData(@"qqq-peer-facts-x\..\qqq-other-facts-")] + [InlineData("qqq-peer-facts-x/../qqq-other-facts-")] + public async Task StandInRefusesToConnectToAPipeThatIsNotOneOfTheTests(string beginning) + { + string name = beginning + Guid.NewGuid().ToString("N"); + using Process client = Process.Start(new ProcessStartInfo(StandIn, ["--stand-in", "connect", name]) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true })!; + try + { + using CancellationTokenSource patience = new(Generous); + string said = await client.StandardError.ReadToEndAsync(patience.Token); + await client.WaitForExitAsync(patience.Token); + Assert.Equal(RefusedPipe, client.ExitCode); + Assert.StartsWith("Refused: ", said, StringComparison.Ordinal); + } + finally + { + client.Kill(); + } + } + + + + /// A handle that is no pipe cannot say who serves it, and what Windows said about that is passed on. + [Fact] + public void HandleThatIsNoPipeFailsWithWhatWindowsSaid() + { + using SafePipeHandle none = new(IntPtr.Zero, ownsHandle: false); + _ = Assert.Throws(() => new WindowsPipePeerFacts().ServerProcessId(none)); + } + + + + /// A service name no service has is not refused when the service is taken hold of but when its status is read, with Windows' own error 1060 inside an invalid-operation failure. + [Fact] + public void NameNoServiceHasIsRefusedWhenItsStatusIsRead() + { + using IPeerService service = new WindowsPipePeerFacts().OpenService("qqq-none-" + Guid.NewGuid().ToString("N")[..12]); + InvalidOperationException refusal = Assert.Throws(() => service.ReadStatus()); + Assert.Equal(1060, Assert.IsType(refusal.InnerException).NativeErrorCode); + } + + + + /// + /// The status of a service is its state and the process hosting it: for the built-in remote procedure call service, + /// read here through a handle this test opened for reading only, the state is running (4) and the process id names + /// a running process. A handle that is no service handle fails with what Windows said. + /// + [Fact] + public void StatusOfABuiltInServiceIsItsStateAndTheProcessHostingIt() + { + using ReadOnlyServiceHandle manager = OpenSCManagerW(null, null, 0x0001); + Assert.False(manager.IsInvalid, "The service control manager could not be opened for connecting, which any user may do."); + using ReadOnlyServiceHandle service = OpenServiceW(manager, BuiltIn, 0x0004); + Assert.False(service.IsInvalid, "The built-in service could not be opened for reading its status, which any user may do."); + PeerServiceStatus status = WindowsPeerService.Query(service); + Assert.Equal(4u, status.State); + Assert.NotEqual(0u, status.ProcessId); + using var host = Process.GetProcessById(checked((int)status.ProcessId)); + Assert.Equal(checked((int)status.ProcessId), host.Id); + using ReadOnlyServiceHandle none = new(); + Assert.Equal(6, Assert.Throws(() => WindowsPeerService.Query(none)).NativeErrorCode); + } + + + + /// + /// The test process is looked at as it is: it has not ended, it runs the program this process runs, and whether it + /// runs as SYSTEM agrees with the account of the process read another way. + /// + [Fact] + public void RunningProcessIsLookedAtAsItIs() + { + using IPeerProcess me = new WindowsPipePeerFacts().OpenProcess(checked((uint)Environment.ProcessId)); + using var identity = WindowsIdentity.GetCurrent(); + Assert.Equal(identity.IsSystem, me.RunsAsSystem()); + Assert.False(me.HasExited); + Assert.Equal(Environment.ProcessPath, me.ProgramPath, ignoreCase: true); + } + + + + /// + /// An id no running process has is refused with an argument failure, which is the sign the trust decision takes for + /// "the service went away", and an id a process cannot have with an overflow, which it does not. + /// + [Fact] + public async Task IdNoRunningProcessHasIsRefusedWithAnArgumentFailure() + { + using Process ended = Process.Start(new ProcessStartInfo(StandIn, ["--stand-in", "exit", "0", "", "0"]) { UseShellExecute = false, CreateNoWindow = true })!; + using CancellationTokenSource patience = new(Generous); + await ended.WaitForExitAsync(patience.Token); + WindowsPipePeerFacts facts = new(); + _ = Assert.Throws(() => facts.OpenProcess(checked((uint)ended.Id))); + _ = Assert.Throws(() => facts.OpenProcess(uint.MaxValue)); + } + + + + /// + /// A process whose account was asked for through the adapter stays held until the adapter lets it go, which is what + /// keeps Windows from giving its id to another process during a check. The process is a harmless child program this + /// test starts and ends itself, and the test keeps no handle of its own to it, so the adapter's is the only one. + /// Once the child has ended, its id still names it for as long as the adapter holds it, and the adapter reports its + /// end; once the adapter has let go, the id no longer names it. + /// + [Fact] + public async Task ProcessThatEndsWhileHeldStaysHeldAndReportsItsEnd() + { + string root = Path.Combine(Path.GetTempPath(), "qqq-peer-facts-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + (int id, DateTime started) = StartChildWithoutKeepingIt(Path.Combine(root, "started.txt")); + try + { + using(IPeerProcess held = new WindowsPipePeerFacts().OpenProcess(checked((uint)id))) + { + using var identity = WindowsIdentity.GetCurrent(); + Assert.Equal(identity.IsSystem, held.RunsAsSystem()); + Assert.False(held.HasExited); + End(id, started); + await Task.Delay(Settle); + Assert.True(NamesAnEndedProcess(id), "The adapter did not keep hold of the process: nothing but its handle could keep the id of the ended child from being released."); + Assert.True(held.HasExited); + } + await MsiUpdateSetup.UntilAsync(() => !NamesAnEndedProcess(id)); + } + finally + { + End(id, started); + } + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + + + /// + /// Starts the stand-in so that it waits until it is ended, and lets go of the handle Windows gave for it at once: a + /// handle kept here would keep the process, and its id, after it has ended, whatever the adapter under test does. + /// The child is known afterwards by its id together with the time it started. + /// + private static (int Id, DateTime Started) StartChildWithoutKeepingIt(string announced) + { + using Process child = Process.Start(new ProcessStartInfo(StandIn, ["--stand-in", "wait", announced]) { UseShellExecute = false, CreateNoWindow = true })!; + return (child.Id, child.StartTime); + } + + + + /// + /// Ends the child this test started and waits until it has ended, through a handle that is let go again. A process + /// that has the child's id and did not start when the child did is another process and is left alone, as is an id + /// no running process has. + /// + private static void End(int id, DateTime started) + { + try + { + using var child = Process.GetProcessById(id); + if(child.StartTime == started) + { + child.Kill(); + Assert.True(child.WaitForExit(Generous), "The child program did not end within a minute of being ended; the machine was too busy for this test."); + } + } + catch(Exception exception) when(exception is ArgumentException or InvalidOperationException or Win32Exception) + { + // No running process has the id, or the one that has it now cannot be looked at and so is not the child. + } + } + + + + /// + /// Whether the id still names a process that has ended: Windows can open it, and it has an exit code. An id that + /// names nothing does not, and neither does one that Windows has meanwhile given to a process that is running. + /// + private static bool NamesAnEndedProcess(int id) + { + using SafeProcessHandle process = OpenProcess(QueryLimitedInformation, inherit: false, id); + return !process.IsInvalid && GetExitCodeProcess(process, out uint code) && code != StillActive; + } + + + + /// Opens a process by its id with the access asked for; the handle is invalid when no process has the id. + [DllImport("kernel32.dll", SetLastError = true)] + private static extern SafeProcessHandle OpenProcess(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, int id); + + + + /// Reads the exit code of a process; 259 while it has not ended. + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetExitCodeProcess(SafeProcessHandle process, out uint code); + + + + /// A handle to the service control manager or to a service, opened by this test with read-only access and closed when disposed. + private sealed class ReadOnlyServiceHandle : SafeHandleZeroOrMinusOneIsInvalid + { + /// An empty handle, which the marshaller fills, or which stands for "no service" when it is not filled. + public ReadOnlyServiceHandle() : base(ownsHandle: true) + { + } + + + + /// Closes the handle. + protected override bool ReleaseHandle() => CloseServiceHandle(handle); + } + + + + /// Opens the service control manager of this computer with the access asked for; 1 is the right to connect. + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern ReadOnlyServiceHandle OpenSCManagerW(string? machine, string? database, uint access); + + + + /// Opens a service with the access asked for; 4 is the right to read its status and nothing more. + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern ReadOnlyServiceHandle OpenServiceW(ReadOnlyServiceHandle manager, string name, uint access); + + + + /// Closes a handle to the service control manager or to a service. + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CloseServiceHandle(IntPtr handle); +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/WindowsProcessHostTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/WindowsProcessHostTests.cs new file mode 100644 index 0000000..129324f --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/WindowsProcessHostTests.cs @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The real process adapter, run without Windows Installer, the companion or the Services console. The program it +/// starts is a parameter, so these tests give it the repository's own child-process fixture, which exits or waits as +/// told and changes nothing; the other members only read: the identity of the test process and the version resource +/// of a file this build produced. +/// +public sealed class WindowsProcessHostTests +{ + /// How long a child that is expected to finish may take; generous, because the test machine may be busy. + private static readonly TimeSpan Generous = TimeSpan.FromSeconds(60); + + + + /// The fixture program built beside the tests. + private static string StandIn => Path.ChangeExtension(typeof(WorkerFixture.Program).Assembly.Location, ".exe"); + + + + /// The current process is the test process: its program path and its id. + [Fact] + public void CurrentProcessIsTheOneRunningTheTest() + { + var host = new WindowsProcessHost(); + Assert.Equal(Environment.ProcessPath, host.CurrentPath); + Assert.Equal(Environment.ProcessId, host.CurrentId); + } + + + + /// A program that is started is held, can be waited for, and is reported as ended with its own exit code. + [Theory] + [InlineData(0)] + [InlineData(1602)] + public async Task StartedProgramIsWaitedForAndReportedWithItsExitCode(int code) + { + using IRunningProcess process = Assert.IsAssignableFrom(new WindowsProcessHost().Start(Start("exit", code.ToString(CultureInfo.InvariantCulture), "printed by the stand-in", "0"))); + using CancellationTokenSource patience = new(Generous); + await process.WaitForExitAsync(patience.Token); + Assert.True(process.HasExited); + Assert.Equal(code, process.ExitCode); + } + + + + /// + /// A running program is found by its id with the path of its program and the same start time the handle from the + /// start reports. A wait whose token is cancelled ends with the cancellation and leaves the program running, and a + /// running program has no exit code. Once the program has ended, its id no longer names a running process. The + /// stand-in leaves its id in a file whose path has a space in it, which also shows that each argument arrives whole. + /// + [Fact] + public async Task RunningProgramIsFoundByItsIdAndAnEndedOneIsNot() + { + string root = Path.Combine(Path.GetTempPath(), "qqq process host " + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string announced = Path.Combine(root, "started here.txt"); + var host = new WindowsProcessHost(); + long before = DateTime.UtcNow.Ticks; + using IRunningProcess started = Assert.IsAssignableFrom(host.Start(Start("wait", announced))); + int id; + try + { + id = await AnnouncedIdAsync(announced); + using IRunningProcess found = host.Open(id); + Assert.False(found.HasExited); + Assert.Equal(StandIn, found.ProgramPath, ignoreCase: true); + Assert.Equal(started.StartTicks, found.StartTicks); + Assert.InRange(found.StartTicks, before - TimeSpan.TicksPerSecond, DateTime.UtcNow.Ticks); + using CancellationTokenSource brief = new(TimeSpan.FromMilliseconds(200)); + _ = await Assert.ThrowsAnyAsync(() => found.WaitForExitAsync(brief.Token)); + Assert.False(found.HasExited); + _ = Assert.Throws(() => found.ExitCode); + } + finally + { + EndStandIn(started); + } + using CancellationTokenSource patience = new(Generous); + await started.WaitForExitAsync(patience.Token); + Assert.True(started.HasExited); + _ = Assert.Throws(() => host.Open(id)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + + + /// + /// A program started through the shell, the way the Services console is, is started too, with its arguments: the + /// stand-in, started hidden, leaves its id in the file it was told to. Nothing is added to the start information, + /// so it is the caller's choice of shell or no shell that Windows gets. + /// + [Fact] + public async Task ProgramStartedThroughTheShellIsStartedWithItsArguments() + { + string root = Path.Combine(Path.GetTempPath(), "qqq process host " + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + string announced = Path.Combine(root, "started here.txt"); + ProcessStartInfo start = new(StandIn) { UseShellExecute = true, WindowStyle = ProcessWindowStyle.Hidden }; + foreach(string argument in new[] { "--stand-in", "wait", announced }) + { + start.ArgumentList.Add(argument); + } + using IRunningProcess? started = new WindowsProcessHost().Start(start); + try + { + using var process = Process.GetProcessById(await AnnouncedIdAsync(announced)); + process.Kill(); + using CancellationTokenSource patience = new(Generous); + await process.WaitForExitAsync(patience.Token); + Assert.True(start.UseShellExecute); + } + finally + { + EndStandIn(started); + } + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + + + /// A program file that does not exist is not started, and what Windows said about it is passed on for the rules to report. + [Fact] + public void ProgramThatDoesNotExistFailsWithWhatWindowsSaid() + { + string missing = Path.Combine(Path.GetTempPath(), "qqq-no-such-program-" + Guid.NewGuid().ToString("N") + ".exe"); + Win32Exception failure = Assert.Throws(() => new WindowsProcessHost().Start(new ProcessStartInfo(missing) { UseShellExecute = false, CreateNoWindow = true })); + Assert.Equal(2, failure.NativeErrorCode); + } + + + + /// + /// The product version is read from the file's version resource: for the library these tests were built with it is + /// the version the build stamped into it, a file without a version resource has none, and a file that does not + /// exist fails with what Windows said. + /// + [Fact] + public void ProductVersionIsReadFromTheFilesVersionResource() + { + string root = Path.Combine(Path.GetTempPath(), "qqq-process-host-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var host = new WindowsProcessHost(); + Assembly library = typeof(MsiUpdateSteps).Assembly; + Assert.Equal(library.GetCustomAttribute()!.InformationalVersion, host.ProductVersion(library.Location)); + string plain = Path.Combine(root, "plain.exe"); + File.WriteAllText(plain, "synthetic: not a program"); + Assert.Null(host.ProductVersion(plain)); + _ = Assert.Throws(() => host.ProductVersion(Path.Combine(root, "missing.exe"))); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + + + /// The start of the stand-in with the given arguments: no shell and no window, as the update starts its programs. + private static ProcessStartInfo Start(params string[] arguments) + { + ProcessStartInfo start = new(StandIn) { UseShellExecute = false, CreateNoWindow = true }; + start.ArgumentList.Add("--stand-in"); + foreach(string argument in arguments) + { + start.ArgumentList.Add(argument); + } + return start; + } + + + + /// + /// Ends the stand-in a test started through the adapter, if it still runs, so that a test that fails before it has + /// learned the child's id does not leave the child waiting forever. The adapter's handle does not tell the id, so + /// the child is recognized as the process that started at the very moment the handle reports and runs the + /// stand-in's program from the file beside these tests; no other process is touched. A stand-in of the same name + /// built in another folder, which another checkout's tests may be running at the same time, is a different file + /// and is left alone. + /// + private static void EndStandIn(IRunningProcess? started) + { + if(started is null) + { return; } + foreach(Process candidate in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(StandIn))) + { + using(candidate) + { + try + { + if(candidate.StartTime.ToUniversalTime().Ticks == started.StartTicks && string.Equals(candidate.MainModule?.FileName, StandIn, StringComparison.OrdinalIgnoreCase)) + { candidate.Kill(); } + } + catch(Exception exception) when(exception is InvalidOperationException or Win32Exception) + { + // That process ended meanwhile, or may not be looked at, and so is not the child this test is waiting on. + } + } + } + } + + + + /// The process id the waiting stand-in left in its file, once it has written it. + private static async Task AnnouncedIdAsync(string file) + { + long started = Stopwatch.GetTimestamp(); + while(true) + { + try + { + if(File.Exists(file) && int.TryParse(await File.ReadAllTextAsync(file), NumberStyles.None, CultureInfo.InvariantCulture, out int id)) + { return id; } + } + catch(IOException) + { + // The stand-in is still writing the file. + } + Assert.True(Stopwatch.GetElapsedTime(started) < Generous, "The stand-in did not start within a minute; the machine was too busy for this test."); + await Task.Delay(20); + } + } +} diff --git a/tests/Qqq.PrintAgent.Cli.Tests/WindowsServiceManagerTests.cs b/tests/Qqq.PrintAgent.Cli.Tests/WindowsServiceManagerTests.cs new file mode 100644 index 0000000..efda280 --- /dev/null +++ b/tests/Qqq.PrintAgent.Cli.Tests/WindowsServiceManagerTests.cs @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026 James Maes + * SPDX-License-Identifier: MIT + */ + +using System.ComponentModel; +using System.ServiceProcess; +using Qqq.PrintAgent.Windows; + +namespace Qqq.PrintAgent.Cli.Tests; + +/// +/// The real service control adapter, run without the print service. The service name is a parameter, so these tests +/// read the state of a built-in Windows service that every Windows has and that cannot be stopped (the remote +/// procedure call service), and send the controls only to a name no service has, which Windows refuses without +/// changing anything. Nothing here starts, stops or changes a service, and the print service is never named. +/// +public sealed class WindowsServiceManagerTests +{ + /// The remote procedure call service: present and running on every Windows, and it accepts no stop. + private const string BuiltIn = "RpcSs"; + + + + /// The Windows error for a service name that no installed service has. + private const int ServiceDoesNotExist = 1060; + + + + /// A built-in service is read as running and as not accepting a stop, and reads the same again after the handle forgot what it had read. + [Fact] + public void BuiltInServiceIsReadAsItIs() + { + using IManagedService service = new WindowsServiceManager().Open(BuiltIn); + Assert.Equal(ServiceControllerStatus.Running, service.Status); + Assert.False(service.CanStop); + service.Refresh(); + Assert.Equal(ServiceControllerStatus.Running, service.Status); + } + + + + /// + /// A name no service has is not refused when the service is taken hold of, nor when the handle forgets its reading, + /// but by every read and every control, each time with an invalid-operation failure that carries Windows' own error + /// 1060. That is the failure the actions read as "not installed", and nothing was started or stopped to get it. + /// + [Fact] + public void NameNoServiceHasIsRefusedByEveryReadAndControl() + { + using IManagedService service = new WindowsServiceManager().Open("qqq-none-" + Guid.NewGuid().ToString("N")[..12]); + service.Refresh(); + foreach(Action use in new Action[] { () => _ = service.Status, () => _ = service.CanStop, service.Start, service.Stop }) + { + InvalidOperationException refusal = Assert.Throws(use); + Assert.Equal(ServiceDoesNotExist, Assert.IsType(refusal.InnerException).NativeErrorCode); + } + } +} diff --git a/tests/Qqq.PrintAgent.WorkerFixture/StandIn.cs b/tests/Qqq.PrintAgent.WorkerFixture/StandIn.cs index a13ce01..c45bf4b 100644 --- a/tests/Qqq.PrintAgent.WorkerFixture/StandIn.cs +++ b/tests/Qqq.PrintAgent.WorkerFixture/StandIn.cs @@ -4,13 +4,16 @@ */ using System.Globalization; +using System.IO.Pipes; namespace Qqq.PrintAgent.WorkerFixture; /// -/// A harmless child program for tests of code that starts a program and waits for it. It fills its error stream, prints -/// what it is told and exits with the code it is told, or it waits until it is killed. It changes nothing on the -/// computer except one file the test names, in which it leaves its process id. +/// A harmless child program for tests of code that starts a program and waits for it, or that asks Windows about +/// another process. It fills its error stream, prints what it is told and exits with the code it is told, or it waits +/// until it is killed, or it connects to a pipe the test serves and stays connected until it is killed. It changes +/// nothing on the computer except one file the test names, in which it leaves its process id, and it connects to no +/// pipe but one of the tests' own. /// internal static class StandIn { @@ -19,10 +22,31 @@ internal static class StandIn + /// How long the connecting behavior waits for the pipe it was told to connect to, in milliseconds; after that it ends with a failure, so a pipe that never comes does not leave it running. + private const int ConnectLimit = 60_000; + + + /// - /// Runs one of two behaviors. --stand-in exit CODE TEXT COUNT writes COUNT characters to the error stream, + /// How the name of every pipe the connecting behavior accepts begins. The tests serve their pipes under such names + /// and the product's pipe has another name, so this program cannot be told to connect to the product. + /// + private const string OwnPipePrefix = "qqq-peer-facts-"; + + + + /// The code the connecting behavior exits with when it is told a pipe name that is not one of the tests' own. It has connected to nothing then. + private const int RefusedPipe = 64; + + + + /// + /// Runs one of three behaviors. --stand-in exit CODE TEXT COUNT writes COUNT characters to the error stream, /// then TEXT to the output stream, and exits with CODE; the error stream comes first, so a parent that does not read /// it never sees TEXT. --stand-in wait FILE writes its process id to FILE and then never exits by itself. + /// --stand-in connect NAME connects as the client of the named pipe NAME on this computer, sends nothing, + /// and then never exits by itself; a NAME that is not one of the tests' own (see ) is + /// refused before anything is connected to, with a sentence on the error stream and the exit code 64. /// internal static int Run(string[] args) { @@ -31,9 +55,29 @@ internal static class StandIn File.WriteAllText(args[2], Environment.ProcessId.ToString(CultureInfo.InvariantCulture)); Thread.Sleep(Timeout.Infinite); } + if(string.Equals(args[1], "connect", StringComparison.Ordinal)) + { + if(!IsOwnPipe(args[2])) + { + Console.Error.Write("Refused: the stand-in connects only to a pipe of the tests, named " + OwnPipePrefix + " and then letters and digits only."); + return RefusedPipe; + } + using NamedPipeClientStream pipe = new(".", args[2], PipeDirection.InOut); + pipe.Connect(ConnectLimit); + Thread.Sleep(Timeout.Infinite); + } Console.Error.Write(new string('e', int.Parse(args[4], CultureInfo.InvariantCulture))); Console.Error.Flush(); Console.Out.Write(args[3]); return int.Parse(args[2], CultureInfo.InvariantCulture); } + + + + /// + /// Whether a pipe name is one of the tests' own: the tests' beginning, then letters and digits and nothing else. + /// The beginning alone would not do. A pipe name is made into a path, and path rules apply to it: a name that + /// begins as the tests' do and goes on with a separator and two dots names another pipe. + /// + private static bool IsOwnPipe(string name) => name.StartsWith(OwnPipePrefix, StringComparison.Ordinal) && name[OwnPipePrefix.Length..].All(char.IsAsciiLetterOrDigit); }