diff --git a/CHANGELOG.md b/CHANGELOG.md index dd07506..0835f50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Explicit screen-reader names for the device filter/list, device details action, + and icon-only main menu; a repeatable 20-device background memory check. +- A development-only `USBGUARD_GUI_ISOLATED_INSTANCE=1` option for running a + demo/test GUI without forwarding activation to the installed application. +- AT-SPI name assertions in the disposable clean-install UI test for the device + filter/list/details and main menu. - A local event history for observed device insertions/removals, authorization outcomes, daemon reconnections and resynchronization gaps. It is capped at 200 entries, stores only categories and timestamps, persists only by opt-in, and @@ -50,6 +56,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Closing native dialogs with animations disabled retains the dialog until the + GTK button callback finishes, avoiding a GObject critical during destruction. - Coverage targets find checkout-local cargo-llvm-cov without shell PATH changes, check graphical prerequisites before running tests, and give pinned install instructions when tools are absent. The diagnostic GUI regression handles diff --git a/Cargo.toml b/Cargo.toml index 5f66045..67ef247 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ keywords = ["usbguard", "usb", "security", "gtk4", "linux"] categories = ["gui"] exclude = [ "docs/", ".github/", "SESSION_HANDOFF.md", - "scripts/clean-install-*", "scripts/verify-clean-install.py", "tests/test_clean_install.py", + "scripts/clean-install-*", "scripts/verify-clean-install.py", "tests/test_clean_install*.py", ] # --------------------------------------------------------------------------- diff --git a/README.md b/README.md index 88cd6eb..f6e5120 100644 --- a/README.md +++ b/README.md @@ -67,17 +67,23 @@ case. * **Live device list** — authorization state with icon *and* text, name, `vendor:product`, serial, and port, sorted by physical topology. Insertion bursts are merged, so a hub full of devices does not freeze the window. +* **Device details** — USB interfaces, physical port path, connection type and state reported by + the daemon, with the source of the rule text stated explicitly. * **Device actions** — allow, block, reject; this session only or permanently; a Cancel button while a password prompt is open, which never times out on its own. * **Policy view** — the ruleset in the order the daemon evaluates it, a rule editor with a guided - mode and a text mode, live preview and validation before anything is sent, and explicit placement + mode and a text mode, live rule-text validation before anything is sent, and explicit placement ("at the end" or "after rule N"). +* **Matching-device preview** — ask USBGuard which connected devices match a new rule's attributes + before saving it. The preview is read-only; conditions and earlier rules can affect the final decision. * **Runtime parameters** — `ImplicitPolicyTarget` and `InsertedDevicePolicy`, changed with confirmation. * **Notifications** — when a device that is not authorized is plugged in, with an *Allow for this session* button where the notification server supports it. * **Background mode** — keeps announcing new devices after the window is closed, with a status icon where the desktop has one, and an optional start at login. +* **Local event history** — the latest 200 observed events, with observation gaps marked and JSON + export containing event types and times only. Keeping history between runs is opt-in. * **`usbguard-gui --diagnose`** — the whole access check as one command whose output you can paste into a bug report. diff --git a/ROADMAP.md b/ROADMAP.md index 0992ddd..2d98232 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -240,8 +240,8 @@ and AUR publication remain deferred; they are not prerequisites for these milest | :--- | :--- | :--- | :--- | | **1** | **Preview matching devices before adding a rule** | A read-only action in both rule-editor modes asks USBGuard which currently connected devices match the attributes. Show results, no matches, errors and cancellation; discard results after edits or closing. State explicitly that conditions and rule precedence are not simulated. No authorization or policy mutation is performed. Test target-independent queries, hostile text, stale replies and failure paths; maintain >=98% application line coverage. | Merged; unreleased | | **2** | **Device details and observed decisions** | Add an accessible per-device details view for USB interfaces/functions, physical port topology, connection type and daemon-reported state/rule text. Label the source and distinguish that device description from the effective policy rule. Show a matched rule only when USBGuard reports an unambiguous, current identity; otherwise say that the API does not provide it. Test missing/malformed fields, hostile strings and invalidation on row replacement/reconnection. | Merged; unreleased | -| **3** | **Local event history** | Show insertions, removals, authorization outcomes and reconnections observed while the app runs. Mark observation gaps; bound retention and make persistence opt-in. Offer export with identifiers obscured and test redaction. | In progress | -| **4** | **Desktop quality** | Measure and reduce memory usage; verify keyboard navigation, screen-reader labels, Wayland and GNOME/KDE behavior. Track repeatable measurements and desktop-specific regressions. | Planned | +| **3** | **Local event history** | Show insertions, removals, authorization outcomes and reconnections observed while the app runs. Mark observation gaps; bound retention and make persistence opt-in. Offer export with identifiers obscured and test redaction. | Merged; unreleased | +| **4** | **Desktop quality** | Measure and reduce memory usage; verify keyboard navigation, screen-reader labels, Wayland and GNOME/KDE behavior. Track repeatable measurements and desktop-specific regressions. | Validated; PR #61 pending merge. Memory baseline, installed Fedora AT-SPI/keyboard and native Weston checks passed. Corrected diagnostic executable passed 7/7 cases on GNOME and Plasma with 10/30 stress cycles and fatal criticals; application coverage 98.0917%. Versioned release-package verification remains a release gate. | All four retain the unprivileged D-Bus architecture. Each completed milestone must pass the existing tests, coverage and packaging gates before release. The first diff --git a/SESSION_HANDOFF.md b/SESSION_HANDOFF.md index b76728f..9703c85 100644 --- a/SESSION_HANDOFF.md +++ b/SESSION_HANDOFF.md @@ -1,77 +1,61 @@ -# Development handoff — 2026-10-25 - -Completed implementation follow-up: the user explicitly requested **98% coverage across the entire -application, including GTK**, plus an edge-case review. The local gate passes at **4841/4928 = 98.2346%**. -The implementation is on -`test/core-coverage-98` (the branch name predates the clarified whole-app scope). - -- Production fixes: cancellable-operation events survive queue backpressure; - Guided → Text releases its preview borrow before GTK's synchronous callbacks; - parameter signals preserve structural denials and disable unknown values; - policy error descriptions escape markup; one tray registration in flight - follows the latest background preference, including rapid off/on changes. -- Unit tests moved to `tests/unit/`, graphical contracts to `tests/gui/`, preserving - all existing tests. `make coverage-app` measures production source across GUI - and headless feature configurations, with private display/buses/user dirs. -- Graphical tests cover real 20/180-second notices. Do not edit the launcher - while it is executing. The 180-second test is intentionally a wall-clock wait. -- New coverage checker rejects omitted GUI files, malformed/duplicate reports, - test-code inflation and percentages that only round to 98%. -- The original zbus migration / real clean-install work below is complete; - these new GUI tests simulate the backend and do not replace its PAM receipts. - - -The requested zbus/ksni migration and clean-install verification are implemented -and locally verified. No translation expansion or AUR publication was undertaken. - -- zbus 6.1 and Rust 1.89 replace the old dependency/compiler baseline. The fixed - SNI/menu implementation runs directly on zbus, replacing ksni and the deprecated - zvariant stack. Architecture, dependency inventory and ADR 0002 describe it. -- All four real GUI/PAM cases pass on Ubuntu 24.04.5, Debian 13.7, Fedora 44 and - Arch rolling: no agent, cancelled authentication, correct-password runtime block - with unchanged permanent rules, daemon restart/GUI reconnection. -- Tests also verify wire properties/actions, both tooltip signals, watcher restart, - mutation error classification and installed artifact identity. Core per-file - coverage stays above 90%; the dependency audit has no findings or notices. -- [Testing](docs/testing.md#zbus-6-and-real-clean-system-validation-2026-10-2425) - and [verification](docs/verification.md#post-012-zbus-6-validation-2026-10-2425) - contain exact scope, reproduction and committed receipts. - -Checkpoint artifacts under ignored `target/zbus6-repro-final` are measured -modified-worktree builds retaining version 0.1.2, distinct from the published -0.1.2 release. The native binary hash in all guest receipts is -`e6f620ab6756d34849a15357b9967fe1b07541a0b509686f3d930484ff53cf82`. -The CI reproduction gate measures the final PR source independently. - -Local test VM disks and evidence remain under `target/clean-install-*`, with -credentials private and never committed. Stop VMs after collecting evidence. -Use generic Debian images with USB support, start the packaged modern Polkit -helper socket when needed, and reload fixture policy after writing it. -Do not enable SUID or disable SELinux to make a test pass. - -No new release/tag is part of this implementation handoff. Publication needs the -usual versioning and release gates. Signed-off-by with the configured Git identity -was explicitly approved for this work; avoid asking for that consent again. - -Developer tools: `/home/onyks/.cargo/bin` and `target/tools/bin` (cargo-deny 0.20.2, -cargo-llvm-cov 0.9.1). Use `/bin/bash`, `login:false`. The host lacks /dev/kvm, -so VM execution uses TCG. Historical detailed pause instructions are preserved -in commit `ccfb96d`; the work described there has now been completed. - -Whole-app evidence: `docs/validation/application-coverage-2026-10-25.json`; -full LLVM JSON `target/coverage-application.json`; HTML -`target/llvm-cov/html/index.html`; logs `target/coverage-98-complete.log`, -`target/coverage-98-verify-final.log`, `target/coverage-98-msrv.log`, -`target/coverage-98-properties.log`. The native test host lacked Xvfb/xdotool: -RPMs were downloaded/extracted under `target/coverage-tools/root` without a host -installation. `make coverage` now discovers both local tool locations automatically, including -the unpacked desktop libraries; no manual PATH/LD_LIBRARY_PATH exports are needed. -Missing dependencies fail before tests with install instructions. Four new tool -discovery/preflight regressions bring the Python suite to 65 tests. The diagnostic -GUI regression now accepts the no-agent CI case and separately checks an IPC -denial with copyable commands. CI installs normal Ubuntu test packages. - -Coverage command follow-up: `make coverage` succeeded without any manually added -PATH or LD_LIBRARY_PATH (`target/coverage-user-entrypoint.log`), still 98.2346%. -`target/coverage-tools-gui.log` verifies the agent-independent diagnostic fixture; -`target/coverage-tools-tests.log` has 13 checker/tool tests and Clippy is clean. +# Development checkpoint — 2026-10-26 + +Continue completing PR #61 (`feat/desktop-quality`), then prepare and publish +0.2.0 through a verified release candidate. The user authorized signed-off commits, +PR management and release/tag publication; DCO consent already exists. + +**Privacy:** never inspect the real host's desktop, applications, services or +physical devices. Use only the marked private VM with synthetic USB, or the +narrow namespace wrapper `target/run-private-tests.py`. No subagents requested. + +## Completed and verified + +- Production fix at pushed `ddd8977`: retain transient dialogs through native + close callbacks, then release at GLib idle. Preferences/About contract verifies + native close and eventual release. Earlier main-window deferral was ineffective + and reverted. Investigation: `docs/validation/desktop-quality-2026-10-26/`. +- Final whole-application coverage: **5500/5607 = 98.0917%**, GUI included. + Receipt identifies source and Rust-test digests. Log: + `target/dialog-lifetime-coverage.log`; HTML `target/llvm-cov/html/index.html`. +- Final native desktop tests passed: GNOME seven cases/10 cycles, Plasma seven + cases/30 cycles, fatal criticals, no debugger, same owner, single notice and + clean exit. Plasma uses its real watcher/tray. Both receipts identify diagnostic + executable SHA256 `d7d4337c009f06e3799f865a4c74e0f8b8b8bb4e6a51591741a405d2b9ad093a`, + NOT an installed release package. Version at build remains 0.1.2. +- The final driver uses atomic AT-SPI root GetChildren during window hiding. + GDB traced the separate stale-index critical to GTK 4.22.5's root handler. + This corrects our observer; it does not fix GTK for other accessibility clients. +- All 17 PR checks passed on ddd8977, including coverage, reproducibility of every + package format, stable/beta/MSRV, lint, audit, DCO and CodeQL. Final subsequent + driver/docs/receipt changes need their own CI before merge. +- Local checks already passed: driver 20 tests, reproducibility 30, dependency + policy 6, i18n 7; audit/deny, lint, pinned strict MkDocs. Markdownlint unavailable. + +## VM and local evidence + +The private Fedora VM is **STOPPED** (graceful shutdown and private QMP socket +checked). Its directory is `target/clean-install-fedora-pr61`; keys/credentials +must never be printed or committed. Evidence archive: +`target/clean-install-fedora-pr61/desktop-accepted-evidence.tar.gz`. +Final raw reports/logs: `target/desktop-{gnome,kde}-atomic-{report.json,app.log}`. +Resume only if needed via `target/start-desktop-test-vm.py` (refuses second writer). + +Host GUI/coverage tests MUST use `target/run-private-tests.py`: empty mount root, +private proc/dev/tmp/run/sys/buses/network, only explicit code/toolchain binds, +software Mesa. Do not use the older whole-root bind or the real desktop. + +## Remaining release work + +1. Commit final observer, verified receipts, updated roadmap/docs; push PR #61, + update its description, mark ready, wait for green exact-head CI and squash + merge with the already-authorized Git identity's Signed-off-by. +2. Prepare 0.2.0 version metadata/changelog/AppStream/Arch version in a new branch. + Include all four completed product milestones in 0.2.0 scope; no more languages + or AUR publication. Draft notes: `target/release-020-notes.md`. +3. Pass CI and merge version PR; require main checks before tagging. Follow + `docs/releasing.md`: publish v0.2.0-rc.1, verify checksums/Sigstore identity, + installed candidate package and pinned Flatpak validation; stable tag at the + same verified commit. Existing native receipts from prior candidates must not + be described as installed 0.2.0 validation. + +No v0.2.0 tag exists at this checkpoint. Stable remains 0.1.2. diff --git a/docs/architecture.md b/docs/architecture.md index de159c1..54d36e7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1851,7 +1851,7 @@ reproduced the native GTK 4.22.5 crash and now passes; see [testing.md](testing. | Burst latency | ≤ 250 ms + render | Guaranteed by `MAX_LATENCY` (§5.4); verified in T3 | | Event loss under burst | zero | T3: final displayed state compared against `usbguard list-devices` | | Polkit resilience | zero timeouts on waits ≤ 10 min | T13 | -| Idle memory | RSS < 110 MB, PSS < 70 MB | `smem`, after 10 minutes in background with 20 devices | +| Idle memory | RSS < 110 MB with Cairo, PSS < 70 MB | `scripts/measure-memory.sh`, after 10 minutes in background with 20 invented devices | | Direct first-party system filesystem access | zero | `strace -f -k` on `/etc`, `/var`, `/sys`, with library accesses attributed separately | | Parser robustness | zero panics over 10⁶ fuzz inputs | `cargo-fuzz` | | Application coverage | ≥ 98% of production lines, GUI and headless configuration included | `make coverage-app` / `cargo-llvm-cov` | @@ -1880,6 +1880,12 @@ substantial fraction of their pages with every other GTK application in the session, so RSS overstates what this program actually costs a running desktop, and PSS is the honest number to hold ourselves to. +**Measured again (2026-10-25, debug build):** with 20 synthetic devices after +600 seconds in background on Fedora 44 / GNOME Shell 50.6 / Wayland (GTK 4.22.5, +libadwaita 1.9.4, Cairo renderer), RSS was 63.4 MiB and PSS 34.4 MiB. Both +targets passed. The procedure and its scope are recorded in +[`docs/testing.md`](testing.md#background-memory-check). + ### 13.3 Phase 0: Upstream Verification Procedure Run before any code depends on §2, and again on every change to the supported diff --git a/docs/testing.md b/docs/testing.md index e165635..b61b68c 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -66,6 +66,131 @@ window and synthetic devices, with no real USBGuard or authentication request. The compositor-specific crash was observed locally on Wayland; headless Xvfb also exercises the explicit focus-preservation assertions. +## Background memory check + +On a Wayland or X11 desktop, run: + +```bash +scripts/measure-memory.sh +``` + +It builds the debug GUI and demo bridge, runs both on a private session bus, +uses 20 invented USB devices and Cairo for a stable renderer baseline, then +reads RSS and PSS from the GUI process's `/proc//smaps_rollup` after ten +minutes. It fails above 110 MiB RSS or 70 MiB PSS. No system USBGuard daemon, +USB policy, authentication, or user settings are touched. The run takes about +ten minutes; for a quick smoke check use `MEMORY_SECONDS=5`. Set +`USBGUARD_GUI_DEMO_DEVICE_COUNT` (7–200) or `MEMORY_RENDERER` to vary the load +or renderer; the RSS budget is enforced only for Cairo. These measurements are +specific to the local kernel, GTK build, and desktop libraries, so compare +them on the same machine and session type. + +`USBGUARD_GUI_ISOLATED_INSTANCE=1` gives development runs a separate +GApplication ID so activating a demo cannot forward to the installed GUI. Pair +it with `USBGUARD_GUI_BUS=session` to use the demo bridge; the instance option +alone does not change which USBGuard bus the client connects to. Release builds +ignore the instance option. + +**Measured 2026-10-25:** RSS 64,912 KiB (63.4 MiB), PSS 35,276 KiB (34.4 MiB), +after 600 seconds with 20 demo devices. Environment: Fedora 44, GNOME Shell +50.6 on Wayland, GTK 4.22.5, libadwaita 1.9.4, Linux 7.2.11, debug build, +Cairo renderer. Both limits passed. This is a repeatable local baseline, not +a GNOME/KDE comparison or a release-binary measurement. + +## Native Wayland guest smoke check + +The marked Fedora 44 guest also checks the installed candidate with Weston +15.0.1's headless backend, Pixman renderer and synthetic input seat. GTK uses +`GDK_BACKEND=wayland` with Cairo, a private session bus/runtime/configuration, +and no X11 fallback. This smoke check disables GTK accessibility; the separate +AT-SPI/Xvfb guest run verifies accessible names and keyboard focus. + +The check allows up to 120 seconds for GTK startup under QEMU TCG and requires +the main `USBGuardGUI` toplevel's configuration acknowledgement, a buffer commit +on that same surface and its matching frame callback. The app must stay alive +for five more seconds. Registry discovery or an empty surface alone cannot +pass. The first exploratory launcher used a five-second deadline and stopped +before GTK finished starting; it was a test timeout, not evidence of a GUI crash. + +For a guest already prepared and validated with the clean-install driver: + +```sh +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + sudo dnf -y install weston +python3 scripts/verify-clean-install.py copy --output target/clean-fedora \ + scripts/clean-install-guest-wayland.py /home/usbguard-test/wayland-test.py +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + dbus-run-session -- python3 /home/usbguard-test/wayland-test.py +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + cat wayland-report.json +python3 scripts/verify-clean-install.py stop --output target/clean-fedora +``` + +The script refuses to run outside the marked VM or as root. Its report records +the installed executable, test-driver and protocol-log SHA-256 digests; raw +logs remain inside the disposable guest. Failed runs remove any stale passing +report. `make test-clean-install-driver` checks the VM guards and incomplete +protocol cases without starting a compositor or examining a live desktop. + +The [Fedora Wayland receipt](validation/desktop-quality-2026-10-25/wayland.json) +matches the same candidate executable as the 5/5 GUI/PAM guest receipt. This is +a native Wayland rendering check; GNOME/KDE shell, tray, portal and interactive +session behavior remain separate milestone acceptance checks. + +### Private GNOME/Plasma guest sessions + +`scripts/clean-install-guest-desktop.py` runs only as the unprivileged test user +inside the marked disposable guest. Prepare the native package and synthetic +USB policy using the clean-install procedure first. Install GNOME Shell, KWin, +Plasma workspace, AT-SPI/Python bindings, dconf, software Mesa and the matching +desktop portal backends inside that guest. No host display, bus, device or +filesystem passthrough is needed. + +Copy both scripts, preserving the helper filename, and run each desktop in a +fresh session bus: + +```sh +python3 scripts/verify-clean-install.py copy --output target/clean-fedora \ + scripts/clean-install-guest-wayland.py /home/usbguard-test/clean-install-guest-wayland.py +python3 scripts/verify-clean-install.py copy --output target/clean-fedora \ + scripts/clean-install-guest-desktop.py /home/usbguard-test/desktop-test.py +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + flock --wait 300 desktop-test.lock dbus-run-session -- python3 desktop-test.py --desktop gnome +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + flock --wait 300 desktop-test.lock dbus-run-session -- python3 desktop-test.py --desktop kde +python3 scripts/verify-clean-install.py ssh --output target/clean-fedora \ + cat desktop-gnome-report.json desktop-kde-report.json +python3 scripts/verify-clean-install.py stop --output target/clean-fedora +``` + +Each run uses private XDG directories/dconf, a virtual Wayland output and software +rendering. Accessible nodes are matched to the exact GUI PID. Checks cover a +rendered main frame, named controls and filtering, the native preferences switch +and persisted value, one background notice, same-process relaunch, and ten +filter/hide/relaunch cycles. GNOME tests the no-watcher path; Plasma registers +with its real watcher and exercises tray activation and menu Quit. The earlier +GUI/PAM fixture supplies the separate Tab/Shift+Tab keyboard assertions. +Window presence is observed with one `GetChildren` request to the exact +application's AT-SPI root. Widget traversal resumes only while a window is +present; a separate cached child-count/index pair can race with hiding. + +The primary GUI runs with `G_DEBUG=fatal-criticals`; any critical/error in its +combined application log also rejects the run. A failed run removes the previous +passing report. Successful reports record the executable, driver, helper and +protocol digests, GTK/compositor versions and SELinux state. `--cycles` accepts +1–100; use the default ten for acceptance. `--binary` allows a diagnostic build +inside the guest without replacing the installed package; its path/hash are +recorded, so that run must not be presented as installed-package evidence. + +The corrected diagnostic executable passed seven cases on +[GNOME Shell 50.6](validation/desktop-quality-2026-10-26/gnome.json) and +[KWin/Plasma 6.7.5](validation/desktop-quality-2026-10-26/kde.json), including +ten GNOME and thirty Plasma hide/relaunch cycles. These are diagnostic-release +executables in the guest home, rather than new installed-package receipts. +The [investigation](validation/desktop-quality-2026-10-26/investigation.md) +distinguishes the fixed dialog lifetime from GTK's stale-index AT-SPI edge case +and records the observer correction. Fatal criticals remain enabled. + ## Reconnection regressions The supervisor is also tested with a bridge whose name stays owned while reads @@ -422,12 +547,13 @@ Polkit and PAM inside disposable QEMU guests: | :---- | :----- | :--------------- | :---- | :------------ | | Ubuntu 24.04.5 | 6.8.0-147-generic | 1.1.2+ds-6build2 | polkit-gnome | 4/4 passed, October 24 | | Debian 13.7 | 6.12.113+deb13-amd64 | 1.1.3+ds-3 | mate-polkit | 4/4 passed, October 25 | -| Fedora 44 | 6.19.10-300.fc44.x86_64 | 1.1.4-1.fc44 | mate-polkit | 4/4 passed, October 25 | +| Fedora 44 (baseline) | 6.19.10-300.fc44.x86_64 | 1.1.4-1.fc44 | mate-polkit | 4/4 passed, October 25 | +| Fedora 44 (desktop-quality candidate) | 6.19.10-300.fc44.x86_64 | 1.1.4-1.fc44 | mate-polkit | 5/5 passed, October 25; AT-SPI and Tab focus | | Arch rolling | 7.2.11-arch1-1 | 1.1.4-11 | polkit-gnome | 4/4 passed, October 25 | -Each suite starts the installed GTK app as the unprivileged test user under -Xvfb/Openbox, with memory settings and a software renderer. It filters the -synthetic USB disk, requests Block / This session only, and checks: +The daemon/Polkit suite starts the installed GTK app as the unprivileged test +user under Xvfb/Openbox, with memory settings and a software renderer. It +filters the synthetic USB disk, requests Block / This session only, and checks: 1. Without an agent, the request is denied, the device stays allowed and the GUI survives. 2. Dismissing the real agent's password dialog denies the request without changing the device. @@ -435,6 +561,16 @@ synthetic USB disk, requests Block / This session only, and checks: current session and leaves the persistent ruleset byte-for-byte unchanged. 4. Restarting both USBGuard services restores persistent allow, and the GUI reconnects and displays the refreshed state. +The desktop-quality candidate adds a fifth check: accessible names are exposed +for the filter, device list, details action and main menu; Tab leaves the filter +and Shift+Tab returns focus to it. + +The guest driver performs the accessibility and keyboard checks only inside the +disposable Xvfb guest; the host desktop is not queried. The original October +24–25 runs predate these assertions and remain evidence for the four +daemon/Polkit cases above. A Fedora 44 run against the desktop-quality candidate +passed all five checks; its package and executable hashes are recorded in +[the desktop-quality validation receipts](validation/desktop-quality-2026-10-25/). The October 25 driver additionally observes actual system-bus calls and denials inside the VM. It asserts the synthetic device ID, block target and `permanent=false`, diff --git a/docs/validation/desktop-quality-2026-10-25/fedora.json b/docs/validation/desktop-quality-2026-10-25/fedora.json new file mode 100644 index 0000000..b8f8f68 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-25/fedora.json @@ -0,0 +1,25 @@ +{ + "distro": "fedora", + "image": "fedora-44.qcow2", + "image_sha256": "28680fe5b371a5a82ebf43a31926e086a168e59949d03969c5093e7071f90b7f", + "serial": "usbguard-clean-test", + "acceleration": "tcg", + "validated_at": "2026-10-25T21:41:10.478250+00:00", + "package": "usbguard-gui-0.1.2-1.x86_64.rpm", + "package_sha256": "91bfe83f045d825c2be8ecea69dbabe1f4cc5a501df96b596dc191d8be82c74b", + "ui": { + "cases": [ + "accessibility and keyboard: labels exposed; Tab/Shift+Tab moves focus", + "no-agent: refused; GUI alive; device unchanged", + "agent-cancel: refused; GUI alive; device unchanged", + "agent-password: runtime block; persistent rules unchanged", + "daemon-restart: GUI reconnected; persistent allow restored" + ], + "os_release": "NAME=\"Fedora Linux\"\nVERSION=\"44 (Cloud Edition)\"\nRELEASE_TYPE=stable\nID=fedora\nVERSION_ID=44\nVERSION_CODENAME=\"\"\nPRETTY_NAME=\"Fedora Linux 44 (Cloud Edition)\"\nANSI_COLOR=\"0;38;2;60;110;180\"\nLOGO=fedora-logo-icon\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:44\"\nHOME_URL=\"https://fedoraproject.org/\"\nDOCUMENTATION_URL=\"https://docs.fedoraproject.org/en-US/fedora/f44/\"\nSUPPORT_URL=\"https://ask.fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=44\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=44\nSUPPORT_END=2027-05-19\nVARIANT=\"Cloud Edition\"\nVARIANT_ID=cloud\n", + "kernel": "6.19.10-300.fc44.x86_64", + "usbguard_package": "usbguard-1.1.4-1.fc44.x86_64", + "binary_sha256": "71b56efffc9d97c6ad9228d8ae03356453c24a40f604d7e6977d6e27ca9fbbbd", + "policy": "Explicit remote-user fixture; real PAM AUTH_SELF, no cached authorization", + "passed": true + } +} diff --git a/docs/validation/desktop-quality-2026-10-25/reproducible.json b/docs/validation/desktop-quality-2026-10-25/reproducible.json new file mode 100644 index 0000000..dbc6668 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-25/reproducible.json @@ -0,0 +1,26 @@ +{ + "scope": "Linux x86_64 GUI binary, unsigned RPM, DEB, Arch package and Flatpak bundle", + "revision": "7b48ba2068b7fd08526473b79820963549add330", + "modified_worktree": false, + "source_date_epoch": 1792961095, + "source_sha256": "2071c126028ee40ba5f49bd3dd45817f17abff36551a8872783b6d5909999734", + "recipe_sha256": "ef5b483d1274d70fe51dc2baab3a0c42f9e5ecd771fa804ca1e5cb4ff80f70e4", + "recipe_archive_sha256": "7ef8af699a41ea53ea1c8f04bcb3751c0bcb375858b902e9143ba8deba03e462", + "builder_image": "d2ccb406bb095c9b4b8d87c8f5ed35f58c743e0f2b221ce8f4fb4b2b39d3886f", + "flatpak_filename": "usbguard-gui-0.1.2.flatpak", + "flatpak_sha256": "a759f3b111a901f358296055cfe53086ead29ebf8f91672cbbed7e845443ac1a", + "flatpak_binary_sha256": "598d657cf76fb86ae7b8617f1881c6e285eba01eb36ddfd9d2335e9abd082014", + "arch_filename": "usbguard-gui-0.1.2-1-x86_64.pkg.tar.zst", + "arch_sha256": "4174287af6751ce31983dc7b7035958b61d86b28a3c0b69d73f18847c65fcb7c", + "deb_filename": "usbguard-gui_0.1.2-1_amd64.deb", + "deb_sha256": "e57307bfce8923d0b3f43bfcb359b75c53134a0ea3d674fcf2210163152ab804", + "rpm_filename": "usbguard-gui-0.1.2-1.x86_64.rpm", + "rpm_sha256": "91bfe83f045d825c2be8ecea69dbabe1f4cc5a501df96b596dc191d8be82c74b", + "binary_sha256": "71b56efffc9d97c6ad9228d8ae03356453c24a40f604d7e6977d6e27ca9fbbbd", + "byte_identical": true, + "build_roots": [ + "/tmp/repro-one", + "/tmp/independent/repro-two" + ], + "compilation_network": "none" +} diff --git a/docs/validation/desktop-quality-2026-10-25/wayland.json b/docs/validation/desktop-quality-2026-10-25/wayland.json new file mode 100644 index 0000000..63dc892 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-25/wayland.json @@ -0,0 +1,26 @@ +{ + "passed": true, + "validated_at": "2026-10-25T22:01:58.147216+00:00", + "scope": "Native Wayland window on headless Weston/Pixman with a synthetic seat; no X11 fallback", + "os_release": "NAME=\"Fedora Linux\"\nVERSION=\"44 (Cloud Edition)\"\nRELEASE_TYPE=stable\nID=fedora\nVERSION_ID=44\nVERSION_CODENAME=\"\"\nPRETTY_NAME=\"Fedora Linux 44 (Cloud Edition)\"\nANSI_COLOR=\"0;38;2;60;110;180\"\nLOGO=fedora-logo-icon\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:44\"\nHOME_URL=\"https://fedoraproject.org/\"\nDOCUMENTATION_URL=\"https://docs.fedoraproject.org/en-US/fedora/f44/\"\nSUPPORT_URL=\"https://ask.fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=44\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=44\nSUPPORT_END=2027-05-19\nVARIANT=\"Cloud Edition\"\nVARIANT_ID=cloud\n", + "kernel": "6.19.10-300.fc44.x86_64", + "compositor": "weston 15.0.1", + "binary_sha256": "71b56efffc9d97c6ad9228d8ae03356453c24a40f604d7e6977d6e27ca9fbbbd", + "window": { + "xdg_surface": 20, + "surface": 18, + "toplevel": 21, + "frame_callback": 26 + }, + "mapped_after_seconds": 8.746, + "alive_after_frame_seconds": 5, + "cases": [ + "main toplevel configured", + "main surface buffer committed", + "matching frame callback received", + "GUI alive for five seconds after frame" + ], + "test_driver_sha256": "61c2d009a182d93fd315b9148863f2f6228b0a6caebb8a9122301c92e2a59562", + "protocol_sha256": "26889ef87036aec0672325f5f497e6a5db539d12195bf7dda4c356bf6e20e79b", + "candidate_receipt": "fedora.json" +} diff --git a/docs/validation/desktop-quality-2026-10-26/coverage.json b/docs/validation/desktop-quality-2026-10-26/coverage.json new file mode 100644 index 0000000..d97d641 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-26/coverage.json @@ -0,0 +1,263 @@ +{ + "date": "2026-10-26", + "revision": "ddd89772555144d749e52a7d6da33c7b5b7747e9", + "command": "make coverage", + "metric": "LLVM production line coverage", + "scope": "All executable src files, GTK and headless builds; tests excluded by location", + "isolation": "Private PID/proc, mounts, network, buses and Xvfb; no host desktop/device inventory", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "gtk": "4.22.5", + "libadwaita": "1.9.4", + "source_sha256": "a2b56e12a89fdf9c64be766113bd9540a592cc4aaeac7da9b547999514c7335f", + "rust_tests_sha256": "eefb22a6e4d8238ba896fbca7d95b287ce1902194fd400afd0e1ff8455c3b6a6", + "digest_format": "Sorted relative POSIX path + NUL + file bytes + NUL, concatenated; SHA-256", + "llvm_json_sha256": "fc31178323c741dec6ca421c5bc9d76c1495db662b5dbd768be03df46d828e4c", + "lines": { + "count": 5607, + "covered": 5500, + "percent": 98.091671125379 + }, + "files": [ + { + "path": "src/cli.rs", + "count": 184, + "covered": 180, + "percent": 97.82608695652173 + }, + { + "path": "src/dbus/bus.rs", + "count": 10, + "covered": 10, + "percent": 100.0 + }, + { + "path": "src/dbus/client.rs", + "count": 152, + "covered": 149, + "percent": 98.02631578947368 + }, + { + "path": "src/dbus/coalesce.rs", + "count": 90, + "covered": 90, + "percent": 100.0 + }, + { + "path": "src/dbus/commands.rs", + "count": 49, + "covered": 49, + "percent": 100.0 + }, + { + "path": "src/dbus/diagnostics.rs", + "count": 141, + "covered": 129, + "percent": 91.48936170212765 + }, + { + "path": "src/dbus/errors.rs", + "count": 82, + "covered": 82, + "percent": 100.0 + }, + { + "path": "src/dbus/proxies.rs", + "count": 3, + "covered": 3, + "percent": 100.0 + }, + { + "path": "src/dbus/supervisor.rs", + "count": 86, + "covered": 72, + "percent": 83.72093023255815 + }, + { + "path": "src/dbus/worker.rs", + "count": 225, + "covered": 223, + "percent": 99.11111111111111 + }, + { + "path": "src/device_store.rs", + "count": 94, + "covered": 94, + "percent": 100.0 + }, + { + "path": "src/main.rs", + "count": 40, + "covered": 40, + "percent": 100.0 + }, + { + "path": "src/model/access.rs", + "count": 37, + "covered": 37, + "percent": 100.0 + }, + { + "path": "src/model/device.rs", + "count": 120, + "covered": 120, + "percent": 100.0 + }, + { + "path": "src/model/error.rs", + "count": 24, + "covered": 24, + "percent": 100.0 + }, + { + "path": "src/model/ids.rs", + "count": 122, + "covered": 122, + "percent": 100.0 + }, + { + "path": "src/model/parameter.rs", + "count": 17, + "covered": 17, + "percent": 100.0 + }, + { + "path": "src/model/rule.rs", + "count": 95, + "covered": 95, + "percent": 100.0 + }, + { + "path": "src/model/target.rs", + "count": 47, + "covered": 46, + "percent": 97.87234042553192 + }, + { + "path": "src/remedy.rs", + "count": 105, + "covered": 104, + "percent": 99.04761904761905 + }, + { + "path": "src/rules/builder.rs", + "count": 56, + "covered": 54, + "percent": 96.42857142857143 + }, + { + "path": "src/rules/lexer.rs", + "count": 97, + "covered": 96, + "percent": 98.96907216494846 + }, + { + "path": "src/rules/mod.rs", + "count": 13, + "covered": 13, + "percent": 100.0 + }, + { + "path": "src/rules/parser.rs", + "count": 245, + "covered": 245, + "percent": 100.0 + }, + { + "path": "src/rules/render.rs", + "count": 91, + "covered": 90, + "percent": 98.9010989010989 + }, + { + "path": "src/runtime.rs", + "count": 11, + "covered": 11, + "percent": 100.0 + }, + { + "path": "src/ui/autostart.rs", + "count": 22, + "covered": 21, + "percent": 95.45454545454545 + }, + { + "path": "src/ui/config.rs", + "count": 94, + "covered": 92, + "percent": 97.87234042553192 + }, + { + "path": "src/ui/device_view.rs", + "count": 461, + "covered": 446, + "percent": 96.74620390455532 + }, + { + "path": "src/ui/diagnostic_dialog.rs", + "count": 82, + "covered": 81, + "percent": 98.78048780487805 + }, + { + "path": "src/ui/history.rs", + "count": 252, + "covered": 249, + "percent": 98.8095238095238 + }, + { + "path": "src/ui/i18n.rs", + "count": 81, + "covered": 80, + "percent": 98.76543209876544 + }, + { + "path": "src/ui/mod.rs", + "count": 139, + "covered": 133, + "percent": 95.68345323741008 + }, + { + "path": "src/ui/notify.rs", + "count": 122, + "covered": 122, + "percent": 100.0 + }, + { + "path": "src/ui/policy_view.rs", + "count": 244, + "covered": 243, + "percent": 99.59016393442623 + }, + { + "path": "src/ui/preferences.rs", + "count": 102, + "covered": 101, + "percent": 99.01960784313727 + }, + { + "path": "src/ui/rule_dialog.rs", + "count": 373, + "covered": 367, + "percent": 98.39142091152814 + }, + { + "path": "src/ui/rule_preview.rs", + "count": 165, + "covered": 158, + "percent": 95.75757575757575 + }, + { + "path": "src/ui/tray.rs", + "count": 317, + "covered": 312, + "percent": 98.42271293375394 + }, + { + "path": "src/ui/window.rs", + "count": 917, + "covered": 900, + "percent": 98.14612868047983 + } + ], + "package_version_at_measurement": "0.1.2" +} diff --git a/docs/validation/desktop-quality-2026-10-26/gnome.json b/docs/validation/desktop-quality-2026-10-26/gnome.json new file mode 100644 index 0000000..6406dcc --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-26/gnome.json @@ -0,0 +1,45 @@ +{ + "passed": true, + "desktop": "gnome", + "validated_at": "2026-10-26T13:46:25.857357+00:00", + "scope": "Private headless gnome/Wayland diagnostic release executable; software rendering and synthetic USB only", + "os_release": "NAME=\"Fedora Linux\"\nVERSION=\"44 (Cloud Edition)\"\nRELEASE_TYPE=stable\nID=fedora\nVERSION_ID=44\nVERSION_CODENAME=\"\"\nPRETTY_NAME=\"Fedora Linux 44 (Cloud Edition)\"\nANSI_COLOR=\"0;38;2;60;110;180\"\nLOGO=fedora-logo-icon\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:44\"\nHOME_URL=\"https://fedoraproject.org/\"\nDOCUMENTATION_URL=\"https://docs.fedoraproject.org/en-US/fedora/f44/\"\nSUPPORT_URL=\"https://ask.fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=44\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=44\nSUPPORT_END=2027-05-19\nVARIANT=\"Cloud Edition\"\nVARIANT_ID=cloud\n", + "kernel": "6.19.10-300.fc44.x86_64", + "binary_sha256": "d7d4337c009f06e3799f865a4c74e0f8b8b8bb4e6a51591741a405d2b9ad093a", + "binary_path": "/home/usbguard-test/usbguard-gui-dialog-fixed", + "fatal_criticals": true, + "stress_cycles": 10, + "gtk_version": "gtk4-4.22.5-2.fc44.x86_64", + "cases": [ + "native Wayland: main surface configured, buffer committed and frame received", + "AT-SPI: named device controls exposed; synthetic device filter responds", + "preferences: native dialog opens and closes without losing the main window", + "background: close hides the window, keeps GUI alive and sends the correct one-time notice", + "single instance: relaunch reopens the original process", + "stress: 10 filter/hide/relaunch cycles retain the original owner", + "GNOME: background without a watcher; Quit exits cleanly" + ], + "window": { + "xdg_surface": 40, + "surface": 10, + "toplevel": 41, + "frame_callback": 50 + }, + "settings_backend": "dconf in private XDG directories and session bus", + "display_size": [ + 1280, + 900 + ], + "compositor_version": "GNOME Shell 50.6", + "selinux": "Enforcing", + "driver_sha256": "1f5939182d91bcaffd066b6e73b32e53163f6b95d96e1ee22f98880e4eaa1d5f", + "wayland_helper_sha256": "61c2d009a182d93fd315b9148863f2f6228b0a6caebb8a9122301c92e2a59562", + "protocol_sha256": "7f87e6b15c34028d3e5e353c17646b9b074fce88649b49277e0d06e3fc03d786", + "executable_kind": "Diagnostic release executable in guest home; not an installed-package receipt", + "package_version_at_build": "0.1.2", + "source_revision": "ddd89772555144d749e52a7d6da33c7b5b7747e9", + "source_sha256": "a2b56e12a89fdf9c64be766113bd9540a592cc4aaeac7da9b547999514c7335f", + "driver_base_revision": "ddd89772555144d749e52a7d6da33c7b5b7747e9", + "driver_modified_worktree": true, + "build_rustc": "rustc 1.99.0 (b940084d7 2026-09-28)" +} diff --git a/docs/validation/desktop-quality-2026-10-26/investigation.md b/docs/validation/desktop-quality-2026-10-26/investigation.md new file mode 100644 index 0000000..e654512 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-26/investigation.md @@ -0,0 +1,121 @@ +# Desktop investigation and final validation — 2026-10-26 + +The final diagnostic executable passed both native desktop suites. The history +below distinguishes the application fix from a test-observer correction; the +linked receipts are not installed-package release validation. + +Private native Wayland sessions in the marked synthetic Fedora guest passed six +functional cases each on GNOME Shell 50.6 and KWin/Plasma 6.7.5. A GNOME run also +emitted an intermittent critical: + +```text +GLib-GObject-CRITICAL: g_object_notify_by_pspec: assertion 'G_IS_OBJECT (object)' failed +``` + +A subsequent GDB run with fatal criticals stopped on the GUI main thread: + +```text +_g_log_abort + g_logv + g_log + signal_emit_valist_unlocked + g_signal_emit_valist + g_signal_emit + button_activate_timeout (libgtk-4.so.1) + g_timeout_dispatch + g_main_context_dispatch_unlocked + g_main_context_iteration + g_application_run +``` + +The attempted repeated-cycle driver also invoked AT-SPI `GrabFocus`, which is +unsupported by the inspected [GTK 4.22.5 component implementation](https://github.com/GNOME/gtk/blob/4.22.5/gtk/a11y/gtkatspicomponent.c). +At that checkpoint, the driver error prevented a valid comparison of baseline +and experimental background-close timing. The follow-up below records the +controlled comparison and exact guest version. + +Raw diagnostics and preliminary six-case reports remain under ignored `target/`; +SESSION_HANDOFF.md records their paths and the exact candidate identity. + +## Controlled follow-up + +The guest package is `gtk4-4.22.5-2.fc44.x86_64`. Removing the unsupported +GrabFocus call made it possible to compare the same formal test against the +installed original (`71b56efffc9d97c6ad9228d8ae03356453c24a40f604d7e6977d6e27ca9fbbbd`) +and the deferred-background-close experiment +(`b2c9367f58969136a8738194c456ad4711426dc197c67e56f97d8f28dba55a30`). +Both stopped with the same GObject critical with fatal criticals enabled. The +ineffective background-close experiment was therefore reverted. + +A breakpoint immediately before each `button_activate_timeout` identified the +first affected control as `GtkButton`, with parent `AdwSheetControls`; it was +the native preferences-dialog Close button. GDB catches the fatal trap and +can then let later GUI steps continue after detaching. Consequently, later +printed hide/relaunch progress does not locate the original critical and is +not clean acceptance evidence. + +A separate minimal GTK/libadwaita program reproduced the critical on an isolated +X11 display too: with animations disabled, drop external references to the +preferences dialog, then activate its native Close button. Holding the dialog +through the callback prevents the critical. References held accidentally by a +test can therefore conceal this lifetime edge case. A Wayland minimal-program +attempt used a timing assumption too short for TCG; that failed timer assertion +does not establish a second application defect. + +The new application candidate retains each transient dialog when `closed` is +emitted and releases that reference at the next GLib idle iteration. This +applies to preferences, About, diagnostics, rule editor and alerts. Native +Close-button contracts cover preferences/About without keeping test references +alive during the callback, and verify that the dialogs are subsequently freed. +The GTK contract passes with fatal criticals. The corrected diagnostic executable +also passed all seven GNOME cases, including ten hide/relaunch cycles with fatal +criticals and no debugger; see [the exact receipt](gnome.json). It is not an +installed-package receipt. No upstream issue or fix is claimed. + +The Plasma run passed preferences and six stress cycles, then found a different +critical: `g_variant_is_object_path: assertion string != NULL failed`. This required +a separate investigation, resolved for the observer below. The +initial Plasma watcher startup also needed a longer property-call deadline under +TCG, before any application had launched. That startup timeout is distinct from +the later primary-GUI critical. + + +## AT-SPI observer follow-up + +The original failed PID's core dump and a later live GDB reproduction both +enter GTK's `handle_accessible_method`, then `g_variant_new_object_path` with a +null path. The immediate caller is GTK's accessibility D-Bus handler, rather +than an application window callback: + +```text +g_variant_is_object_path +g_variant_new_object_path +g_variant_new +handle_accessible_method.part.0 (libgtk-4.so.1) +call_in_idle_cb (libgio-2.0.so.0) +g_idle_dispatch +``` + +This matches the stale-index path in [GTK 4.22.5's root handler](https://github.com/GNOME/gtk/blob/4.22.5/gtk/a11y/gtkatspiroot.c): +the fixture read a child count and requested children separately while the +window was hiding. That root handler can still try to return the last hidden +window's unrealized accessibility path. The fixture now observes the target +application's children atomically with `GetChildren`, using the exact app's +AT-SPI bus name/path, and traverses its widget tree only when a window is +present. It keeps both fatal criticals and the final critical-message gate. +This changes the observer, not GTK, and does not claim to fix GTK for other +clients using stale child indices. + +Final runs with this same observer and executable passed without a debugger: + +| Desktop | Functional cases | Filter/hide/relaunch cycles | Receipt | +| :--- | :--- | :--- | :--- | +| GNOME Shell 50.6 | 7/7 | 10 | [GNOME](gnome.json) | +| KWin/Plasma 6.7.5 | 7/7 | 30 | [Plasma](kde.json) | + +Both kept fatal criticals enabled and verified clean exit, the same application +owner across cycles, and a single background notification. The Plasma run used +its real watcher, tray activation and Quit menu; GNOME exercised no-watcher +behavior. Binary, driver, helper and protocol hashes were checked when collecting +the receipts. Whole-application coverage is [5500/5607 lines](coverage.json), +98.0917%. The private VM was then shut down. diff --git a/docs/validation/desktop-quality-2026-10-26/kde.json b/docs/validation/desktop-quality-2026-10-26/kde.json new file mode 100644 index 0000000..f0cda15 --- /dev/null +++ b/docs/validation/desktop-quality-2026-10-26/kde.json @@ -0,0 +1,45 @@ +{ + "passed": true, + "desktop": "kde", + "validated_at": "2026-10-26T13:42:36.508533+00:00", + "scope": "Private headless kde/Wayland diagnostic release executable; software rendering and synthetic USB only", + "os_release": "NAME=\"Fedora Linux\"\nVERSION=\"44 (Cloud Edition)\"\nRELEASE_TYPE=stable\nID=fedora\nVERSION_ID=44\nVERSION_CODENAME=\"\"\nPRETTY_NAME=\"Fedora Linux 44 (Cloud Edition)\"\nANSI_COLOR=\"0;38;2;60;110;180\"\nLOGO=fedora-logo-icon\nCPE_NAME=\"cpe:/o:fedoraproject:fedora:44\"\nHOME_URL=\"https://fedoraproject.org/\"\nDOCUMENTATION_URL=\"https://docs.fedoraproject.org/en-US/fedora/f44/\"\nSUPPORT_URL=\"https://ask.fedoraproject.org/\"\nBUG_REPORT_URL=\"https://bugzilla.redhat.com/\"\nREDHAT_BUGZILLA_PRODUCT=\"Fedora\"\nREDHAT_BUGZILLA_PRODUCT_VERSION=44\nREDHAT_SUPPORT_PRODUCT=\"Fedora\"\nREDHAT_SUPPORT_PRODUCT_VERSION=44\nSUPPORT_END=2027-05-19\nVARIANT=\"Cloud Edition\"\nVARIANT_ID=cloud\n", + "kernel": "6.19.10-300.fc44.x86_64", + "binary_sha256": "d7d4337c009f06e3799f865a4c74e0f8b8b8bb4e6a51591741a405d2b9ad093a", + "binary_path": "/home/usbguard-test/usbguard-gui-dialog-fixed", + "fatal_criticals": true, + "stress_cycles": 30, + "gtk_version": "gtk4-4.22.5-2.fc44.x86_64", + "cases": [ + "native Wayland: main surface configured, buffer committed and frame received", + "AT-SPI: named device controls exposed; synthetic device filter responds", + "preferences: native dialog opens and closes without losing the main window", + "background: close hides the window, keeps GUI alive and sends the correct one-time notice", + "single instance: relaunch reopens the original process", + "stress: 30 filter/hide/relaunch cycles retain the original owner", + "Plasma tray: real watcher registration, Activate reopens, Quit menu exits cleanly" + ], + "window": { + "xdg_surface": 42, + "surface": 17, + "toplevel": 43, + "frame_callback": 52 + }, + "settings_backend": "dconf in private XDG directories and session bus", + "display_size": [ + 1280, + 900 + ], + "compositor_version": "kwin 6.7.5", + "selinux": "Enforcing", + "driver_sha256": "1f5939182d91bcaffd066b6e73b32e53163f6b95d96e1ee22f98880e4eaa1d5f", + "wayland_helper_sha256": "61c2d009a182d93fd315b9148863f2f6228b0a6caebb8a9122301c92e2a59562", + "protocol_sha256": "b57116bbef1b786328d4b125e8b2b0988e7049adf2a7b48192261783e3ccccd5", + "executable_kind": "Diagnostic release executable in guest home; not an installed-package receipt", + "package_version_at_build": "0.1.2", + "source_revision": "ddd89772555144d749e52a7d6da33c7b5b7747e9", + "source_sha256": "a2b56e12a89fdf9c64be766113bd9540a592cc4aaeac7da9b547999514c7335f", + "driver_base_revision": "ddd89772555144d749e52a7d6da33c7b5b7747e9", + "driver_modified_worktree": true, + "build_rustc": "rustc 1.99.0 (b940084d7 2026-09-28)" +} diff --git a/docs/verification.md b/docs/verification.md index 0ac1cf0..30f4d21 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -518,6 +518,20 @@ installed executable SHA-256, authorization fixture and each successful case: - [Fedora 44](validation/zbus6-clean-install-2026-10-25/fedora.json) - [Arch rolling](validation/zbus6-clean-install-2026-10-25/arch.json) +The desktop-quality candidate has a separate [reproducible build receipt](validation/desktop-quality-2026-10-25/reproducible.json) +and [Fedora 44 guest receipt](validation/desktop-quality-2026-10-25/fedora.json). +That guest run passed the four daemon/Polkit cases plus accessible-name and +Tab/Shift+Tab focus assertions (5/5), using synthetic USB only. Its installed +executable SHA-256 is `71b56efffc9d97c6ad9228d8ae03356453c24a40f604d7e6977d6e27ca9fbbbd`. + +The same installed executable also passed the separate +[native Wayland smoke check](validation/desktop-quality-2026-10-25/wayland.json) +on headless Weston 15.0.1/Pixman. The check ties the main window's XDG +configuration to a committed buffer and its frame callback, then observes +five seconds of continued liveness. Its startup timeout accounts for TCG; +GNOME/Plasma diagnostic-executable acceptance is recorded below. See the +[guest reproduction procedure](testing.md#native-wayland-guest-smoke-check). + All four pass no-agent denial, real-agent cancellation, successful PAM-authenticated runtime block without persistent-rule changes, and daemon restart/GUI reconnection. The detailed [test scope and reproduction](testing.md#zbus-6-and-real-clean-system-validation-2026-10-2425) @@ -548,3 +562,36 @@ remains the ordinary lint/unit/dependency gate. The GTK tests use a simulated USBGuard bridge, notifications and watcher on private buses. They do not claim real PAM authentication or physical hardware coverage; the clean-install evidence above documents those separate checks. + +## Desktop-quality native follow-up (2026-10-26, unreleased) + +The corrected release-profile diagnostic executable, SHA-256 +`d7d4337c009f06e3799f865a4c74e0f8b8b8bb4e6a51591741a405d2b9ad093a`, +passed seven cases each in private native Wayland sessions on Fedora 44: + +| Desktop | Repeated hide/relaunch cycles | Additional integration | +| :--- | :--- | :--- | +| [GNOME Shell 50.6](validation/desktop-quality-2026-10-26/gnome.json) | 10 | Background without a watcher, one explanatory notification, same-owner relaunch and Quit | +| [KWin/Plasma 6.7.5](validation/desktop-quality-2026-10-26/kde.json) | 30 | Real watcher registration, tray Activate and menu Quit | + +Both also verify a rendered main Wayland frame, named accessible controls, +filtering, the native preferences switch and its persisted value. Tests use +synthetic USB, software rendering, private XDG state/session buses and fatal +criticals; neither final acceptance run uses a debugger. The receipts distinguish +the diagnostic executable in guest home from the earlier installed-package +checks, and record the exact driver/helper/protocol digests. They do not claim +physical hardware or every desktop/renderer combination. + +The application retains transient dialogs through native close callbacks and +releases them on the next idle iteration; GTK contracts also check eventual +destruction. [The investigation](validation/desktop-quality-2026-10-26/investigation.md) +records the original failure, discarded experiment and separate GTK AT-SPI +stale-index issue. The observer uses an atomic application-window snapshot; +it does not suppress toolkit criticals or patch GTK for other clients. + +[Fresh application coverage](validation/desktop-quality-2026-10-26/coverage.json) +is **5500/5607 production lines (98.0917%)**, including GTK and headless builds. +The source and Rust-test digests identify the measured snapshot. All 17 PR +checks passed on `ddd8977`, including Rust stable/beta/1.89, dependency gates and +[independent offline package builds](https://github.com/onyks-os/USBGuardGUI/actions/runs/40328040104). +The final documentation/observer commit and release version must pass CI again. diff --git a/docs/web/how-to/device-actions.md b/docs/web/how-to/device-actions.md index e2215ab..0d7c84b 100644 --- a/docs/web/how-to/device-actions.md +++ b/docs/web/how-to/device-actions.md @@ -27,3 +27,12 @@ agent and a person fetching a password look the same. !!! warning "Cancel stops waiting, not USBGuard" If you cancel after entering the password, USBGuard may already have made the change. The list always shows what USBGuard reports, so check the row after cancelling. + +## Inspect a device + +Click **Details** on its row to see USB interfaces, the physical port path, connection type, +and the state and device rule text reported by USBGuard. Missing attributes are shown explicitly. + +The device rule text describes that device. The `listDevices` response does not identify the +effective policy rule, so the details view states that the matched rule is unavailable rather +than guessing from similar rules. diff --git a/docs/web/how-to/history.md b/docs/web/how-to/history.md new file mode 100644 index 0000000..129a63e --- /dev/null +++ b/docs/web/how-to/history.md @@ -0,0 +1,22 @@ +# Review observed events + +Open **Main menu → Event history** to see device insertions and removals, authorization outcomes, +reported state changes and reconnections observed while USBGuardGUI is running. The newest +events appear first, and retention is limited to the latest 200 entries. + +A marked observation gap means events may have been missed while the connection was unavailable +or a burst required resynchronization. The history describes what this application observed; +it is not a complete daemon audit log. + +## Keep history between runs + +History normally stays in memory for the current run. To retain it, enable +**Main menu → Preferences → Keep event history between runs**. Turning the setting off removes +the previously saved copy. Only event categories and timestamps are retained: no device names, +serial numbers, device IDs, rule text or daemon error details. + +## Export a report + +Click **Export privacy-safe JSON…**, choose a file and save. The export contains a schema version, +`identifiers_included: false`, and event records with timestamps and category names. It excludes +device identifiers whether persistence is enabled or disabled. diff --git a/docs/web/how-to/index.md b/docs/web/how-to/index.md index 047aef4..eab17f5 100644 --- a/docs/web/how-to/index.md +++ b/docs/web/how-to/index.md @@ -11,4 +11,5 @@ installation — if you do not have one, start with the [Quickstart](../tutorial | [Add and remove rules safely](rules.md) | You are editing the policy, possibly while something else edits it too. | | [Change policy with your own password](polkit-rule.md) | Typing the administrator password for every change is too much. | | [Keep announcing devices with the window closed](background.md) | You want notifications without keeping the window open. | +| [Review observed events](history.md) | You want to review recent activity or export event types and times without device identifiers. | | [Report a bug without leaking your hardware](bug-report.md) | You are about to open an issue. | diff --git a/docs/web/how-to/rules.md b/docs/web/how-to/rules.md index e62c18e..2a1be73 100644 --- a/docs/web/how-to/rules.md +++ b/docs/web/how-to/rules.md @@ -21,6 +21,15 @@ Click **Add Rule…**. **Will be sent as** shows the exact text USBGuard will receive. An invalid rule never leaves the program and never raises a password prompt. +Once the rule is valid, click **Preview matching devices** in either editor mode. USBGuard returns +a snapshot of connected devices matching its attributes, or an explicit no-matches result. +The query is read-only and leaves the policy and device states unchanged. **Cancel preview** +stops waiting; editing the rule or closing the dialog invalidates pending results. + +This snapshot does not evaluate rule conditions or earlier-rule precedence. A device shown in +the preview may receive a different final decision when the policy runs. Preview again when +you edit the attributes or the connected devices change. + **Position** decides where the rule goes: at the end, or after a specific rule. **Keep after USBGuard restarts** decides whether it is written to the policy or kept in memory only. diff --git a/docs/web/release-notes/changelog.md b/docs/web/release-notes/changelog.md index a54e1ef..c46fa65 100644 --- a/docs/web/release-notes/changelog.md +++ b/docs/web/release-notes/changelog.md @@ -7,6 +7,109 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Explicit screen-reader names for the device filter/list, device details action, + and icon-only main menu; a repeatable 20-device background memory check. +- A development-only `USBGUARD_GUI_ISOLATED_INSTANCE=1` option for running a + demo/test GUI without forwarding activation to the installed application. +- AT-SPI name assertions in the disposable clean-install UI test for the device + filter/list/details and main menu. +- A local event history for observed device insertions/removals, authorization + outcomes, daemon reconnections and resynchronization gaps. It is capped at 200 + entries, stores only categories and timestamps, persists only by opt-in, and + exports JSON without device identifiers. +- A per-device details popover with USB interfaces, physical port path, + connection type and daemon-reported state. It distinguishes the device rule + text from the effective policy rule, which `listDevices` does not report. +- A read-only preview in both new-rule editor modes showing connected devices + matching the rule's attributes. Conditions and earlier-rule precedence are + called out as factors the preview cannot simulate; edits, cancellation and + closing invalidate pending results. Device names are displayed as plain text. +- French translations for the interface, notifications, desktop entry and + AppStream metadata; gettext/plural/format and package-catalogue tests, plus + the graphical focus regression in both English and French. +- A pinned cargo-deny license/source gate in CI and `make verify`, with rejection + tests for forbidden licenses across dependency kinds, optional/target-specific + dependencies, SPDX AND/OR expressions and unapproved pinned Git sources. + +### Changed + +- Enforce >=98% production line coverage across the complete application, including + GTK and headless builds. Isolated desktop tests cover dialogs, notifications, + device/rule operations, single-instance lifecycle and real 20/180-second notices; + unit-test source no longer inflates the measured application coverage. +- Migrate to zbus 6.1 and Rust 1.89, including the CI minimum and pinned + reproducible builder. Replace ksni with fixed SNI/D-Bus menu interfaces on + zbus; preserve native/Flatpak registration, actions and watcher reconnection. + The deprecated zvariant/zvariant_derive/zbus_names dependency stack is removed. +- Add disposable QEMU clean-install validation with synthetic USB storage, + native packages and real Polkit/PAM. Ubuntu, Debian, Fedora and Arch pass + denial, cancellation, runtime authorization and daemon-restart/reconnection + checks. The verifier validates observed calls, installed hashes and complete + receipts; isolation and failure guards are regression-tested. + +### Fixed + +- Closing native dialogs with animations disabled retains the dialog until the + GTK button callback finishes, avoiding a GObject critical during destruction. +- Coverage targets find checkout-local cargo-llvm-cov without shell PATH changes, + check graphical prerequisites before running tests, and give pinned install + instructions when tools are absent. The diagnostic GUI regression handles + both desktop Polkit agents and agent-less CI runners; tool-discovery fixtures + isolate Cargo's plugin directory from globally installed tools. +- Switching the new-rule form from Guided to Text no longer aborts on a + synchronously re-entered preview borrow. +- Cancellation preserves its outcome and cache invalidation when the UI event + queue is full, without blocking GTK. +- Parameter updates preserve structural access denials and keep unknown daemon + values unselected and insensitive. +- Policy read failures display daemon details as literal text instead of markup. +- A late tray registration cannot resurrect the icon after background mode is + disabled; concurrent requests are coalesced. +- Source crates exclude privileged VM-only tools while retaining required build inputs; a packaging regression enforces this boundary. +- Installed Flatpak headless checks avoid starting the unrelated document portal. +- Reproducible builds compile every language registered in `po/LINGUAS`, and + installed Flatpak validation checks every registered catalogue. + +## [0.1.2] - 2026-10-24 + +### Added + +- `make reproducible`: two clean offline Linux x86_64 GUI builds with a pinned Ubuntu + image/snapshot and Rust 1.88.0. Byte comparison, temporary-path checks, GUI dependency + inspection, source/recipe archives, and an environment report run locally and in CI. +- Reproduction inputs accompany new releases; the published bare binary comes only from the + successful comparison job. Complete RPM, DEB, Arch and Flatpak archives are compared as well. +- Flatpak bundles use a dedicated /app-locale executable and fixed OSTree export clock; + private runtime validation enforces a pinned GNOME commit and checks installed CLI/schema/assets. +- Unit tests for deterministic source archives, excluded credentials, recipe freezing, + checker failure paths, and refusing stale outputs or unacknowledged local changes. +- Mock D-Bus resilience tests for interrupted writes before/after execution (T2), ten-minute + authentication waits with virtual time (T13), and cancellation while authentication is pending. +- Regression tests for log privacy and startup notices when debug/trace is enabled. +- `make coverage-core` and a CI gate requiring >90% line coverage per rule-language, + cancellable-operation, and error-classification file. +- A private-demo-bus filesystem tracing script and scoped measurement notes in `docs/testing.md`. + +### Fixed + +- Dependency-audit CI runs the pinned auditor directly with read-only permissions, + avoiding failed check-run publication and keeping fork pull requests supported. +- Require Tokio 1.53.3 to resolve RUSTSEC-2026-0386 (AsyncFd I/O safety). +- Release builds no longer embed build-machine paths for development-only schemas/catalogues; + installed system assets and debug builds retain their respective behavior. +- Device-table refreshes and reconnection resets clear the old row's keyboard focus before + removing it. This avoids a GTK crash when focus returns from an authentication window after + cancelling Polkit. A graphical regression test reproduces the original crash and runs in CI. +- Reconnection no longer spins when the bridge owns its bus name but cannot serve requests: + retries observe exponential backoff, and reconnection is announced only after subscriptions + and the first device read succeed. Tests now include a real private bus and name replacement. +- Writes whose replies are lost now report an inconclusive outcome and request fresh device/policy + state without retrying automatically. The message is also translated into Italian. +- Connection and malformed-signal errors no longer include raw detail at default log levels; + debug/trace logging prints a privacy notice, including with dependency-specific filters. + ### Changed - Documentation checked against 0.1.1. The security assessment now gives each mitigation the status diff --git a/examples/demo-bridge.rs b/examples/demo-bridge.rs index 4cbcc6b..a4a1eed 100644 --- a/examples/demo-bridge.rs +++ b/examples/demo-bridge.rs @@ -36,7 +36,7 @@ fn device(target: &str, id: &str, name: &str, serial: &str, port: &str, ifaces: #[tokio::main] async fn main() -> zbus::Result<()> { - let devices = vec![ + let mut devices = vec![ ( 1, device( @@ -97,6 +97,33 @@ async fn main() -> zbus::Result<()> { ), ), ]; + // The optional count is useful for memory/large-list checks without + // changing the normal six-device demo. Device details are invented. + let configured_count = std::env::var("USBGUARD_GUI_DEMO_DEVICE_COUNT").ok(); + if let Some(raw_count) = configured_count.as_deref() { + let count = raw_count + .parse::() + .ok() + .filter(|count| (7..=200).contains(count)); + let Some(count) = count else { + eprintln!("USBGUARD_GUI_DEMO_DEVICE_COUNT must be between 7 and 200"); + std::process::exit(2); + }; + for index in 7..=count { + let name = format!("Example USB Device {index}"); + devices.push(( + u32::from(index), + device( + "allow", + &format!("5555:{index:04x}"), + &name, + &format!("DEMO{index:04}"), + &format!("3-{index}"), + "08:06:50", + ), + )); + } + } let rules = vec![ ( 1, @@ -117,6 +144,7 @@ async fn main() -> zbus::Result<()> { .to_owned(), ), ]; + let demo_device_count = devices.len(); let state = Arc::new(Mutex::new(State { devices, rules, @@ -137,23 +165,29 @@ async fn main() -> zbus::Result<()> { .await?; println!("Demo USBGuard bridge running on the session bus. Start the window with:"); println!(" USBGUARD_GUI_BUS=session cargo run"); - println!("A new blocked device will be plugged in 15 seconds from now. Ctrl+C to stop."); + if configured_count.is_some() { + println!("Static demo with {demo_device_count} devices. Ctrl+C to stop."); + } else { + println!("A new blocked device will be plugged in 15 seconds from now. Ctrl+C to stop."); + } - tokio::time::sleep(Duration::from_secs(15)).await; - let phone = device( - "block", - "4444:0001", - "Example Phone", - "EXPHONE01", - "2-2", - "{ 06:01:01 ff:42:01 }", - ); - state.lock().unwrap().devices.push((7, phone.clone())); - let emitter = SignalEmitter::new(&connection, "/org/usbguard1/Devices")?; - let attrs = HashMap::from([("name".to_owned(), "Example Phone".to_owned())]); - Devices::device_presence_changed(&emitter, 7, 1, 1, &phone, attrs.clone()).await?; - Devices::device_policy_changed(&emitter, 7, 1, 1, &phone, 0, attrs).await?; - println!("Plugged in: Example Phone (blocked)."); + if configured_count.is_none() { + tokio::time::sleep(Duration::from_secs(15)).await; + let phone = device( + "block", + "4444:0001", + "Example Phone", + "EXPHONE01", + "2-2", + "{ 06:01:01 ff:42:01 }", + ); + state.lock().unwrap().devices.push((7, phone.clone())); + let emitter = SignalEmitter::new(&connection, "/org/usbguard1/Devices")?; + let attrs = HashMap::from([("name".to_owned(), "Example Phone".to_owned())]); + Devices::device_presence_changed(&emitter, 7, 1, 1, &phone, attrs.clone()).await?; + Devices::device_policy_changed(&emitter, 7, 1, 1, &phone, 0, attrs).await?; + println!("Plugged in: Example Phone (blocked)."); + } std::future::pending::<()>().await; Ok(()) diff --git a/make/project.mk b/make/project.mk index 749187b..766ef25 100644 --- a/make/project.mk +++ b/make/project.mk @@ -84,4 +84,4 @@ test-i18n: ## Test translations, format validation and package catalogues .PHONY: test-clean-install-driver test-clean-install-driver: ## Test disposable VM isolation and input guards (no VM required) - python3 -m unittest discover -s tests -p 'test_clean_install.py' -v + python3 -m unittest discover -s tests -p 'test_clean_install*.py' -v diff --git a/mkdocs.yml b/mkdocs.yml index 50816f1..9f19a87 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -91,6 +91,7 @@ nav: - Add and remove rules: how-to/rules.md - Change policy with your own password: how-to/polkit-rule.md - Background mode and notifications: how-to/background.md + - Review observed events: how-to/history.md - Report a bug: how-to/bug-report.md - Explanation: - Architecture: explanation/architecture.md diff --git a/scripts/README.md b/scripts/README.md index 4a18116..1830911 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -13,17 +13,24 @@ Operational scripts. Shell scripts are linted by `make lint-shell` (ShellCheck) | `trace-filesystem.sh` | Trace background GUI startup and diagnostics on a private demo bus; see [validation notes](../docs/testing.md). | | `verify-flatpak-runtime.py` | Install a bundle in private HOME/XDG/Flatpak directories, enforce the pinned GNOME runtime, and check CLI/schema/assets. | | `reproducible-build.py` | Freeze build inputs, prepare the pinned builder, compare two offline GUI binaries, RPMs, DEBs, Arch packages and Flatpak bundles, and write the measured report. | -| `check-coverage.py` | Check the LLVM JSON report for >90% line coverage in every rule-language and operation-core file; used by `make coverage-core`. | +| `check-coverage.py` | Enforce >=98% production line coverage across the application, including GTK, and >90% per critical core file; reject missing, duplicate and malformed inputs. | +| `test-gui.sh` | Run GTK contracts on an isolated virtual display and private buses/configuration. | +| `verify-clean-install.py` | Manage a disposable rootless QEMU guest with synthetic USB, private disks/SSH credentials and no host passthrough. | +| `clean-install-guest-policy.sh` / `clean-install-guest-ui.py` | Prepare test policy and exercise real Polkit/PAM only inside the marked disposable guest. | +| `clean-install-guest-wayland.py` | Require the installed app's configured Wayland surface, committed buffer and frame callback in a guest Weston session. | +| `clean-install-guest-desktop.py` | Test native GNOME/Plasma rendering, accessibility, background/relaunch and tray in private guest sessions, with fatal criticals and repeated close/reopen cycles. | There is deliberately no `install.sh` or `uninstall.sh`, and there will not be one. USBGuardGUI touches no system configuration: installation is the distribution package's job, and the one action a package performs — recompiling the GSettings schema — is a packaging convention, not a -configuration change. A script here that edited `/etc/polkit-1/rules.d/` or the USBGuard IPC -access-control files would contradict the program's central property; see +configuration change. Production scripts must not edit `/etc/polkit-1/rules.d/` or the USBGuard IPC +access-control files; see [`SECURITY.md`](../SECURITY.md) and [`docs/architecture.md`](../docs/architecture.md) §3.6. +The explicitly marked disposable-guest fixtures are the exception: they install +synthetic test policy inside that VM and refuse to run on an unmarked host. `make reproducible` builds a pinned container and compares two offline GUI -binary, RPM and DEB builds in independent containers. It requires Python 3.11+ and rootless Podman +binary, RPM, DEB, Arch and Flatpak builds in independent containers. It requires Python 3.11+ and rootless Podman (or Docker via `CONTAINER_ENGINE=docker`). See [release verification](../docs/verification.md#5-reproducing-the-build) for inputs, scope, and the explicit `--worktree` mode. `make test-reproducible` runs its unit tests without a container or network. diff --git a/scripts/clean-install-guest-desktop.py b/scripts/clean-install-guest-desktop.py new file mode 100644 index 0000000..5a8d8a6 --- /dev/null +++ b/scripts/clean-install-guest-desktop.py @@ -0,0 +1,664 @@ +#!/usr/bin/env python3 +"""Exercise the installed GUI in a private GNOME/Plasma Wayland guest session. + +Requires the marked disposable Fedora VM and a private dbus-run-session. The +AT-SPI walk is limited to the exact GUI PID created by this test. Both desktop +components and the GUI use a software renderer and a virtual output. +""" +# Copyright (c) 2026 onyks-os +# SPDX-License-Identifier: MIT + +import argparse +import datetime +import hashlib +import importlib.util +import json +import os +import re +import shutil +import subprocess +import tempfile +import time +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any, TextIO, TypeVar + +T = TypeVar("T") + +spec = importlib.util.spec_from_file_location( + "guest_wayland", Path(__file__).with_name("clean-install-guest-wayland.py") +) +helper = importlib.util.module_from_spec(spec) +spec.loader.exec_module(helper) +APP = "io.github.onyks_os.UsbguardGui" +APP_PATH = "/io/github/onyks_os/UsbguardGui" +WATCHER = "org.kde.StatusNotifierWatcher" + + +def require_clean_app_log(protocol: str) -> None: + failure = re.search(r"\b[\w-]+[-:](?:CRITICAL|ERROR)\b", protocol) + if failure: + raise RuntimeError("GUI emitted a toolkit critical or error: " + failure[0]) + + +def main() -> None: + helper.require_guest() + parser = argparse.ArgumentParser() + parser.add_argument("--desktop", required=True, choices=("gnome", "kde")) + parser.add_argument("--binary", type=Path, default=Path("/usr/bin/usbguard-gui")) + parser.add_argument("--cycles", type=int, default=10) + args = parser.parse_args() + receipt = Path("desktop-" + args.desktop + "-report.json") + receipt.unlink(missing_ok=True) + if args.cycles < 1 or args.cycles > 100: + parser.error("--cycles must be between 1 and 100") + binary = args.binary.resolve(strict=True) + if not binary.is_file() or not os.access(binary, os.X_OK): + parser.error("--binary must be an executable file inside the test guest") + runtime = tempfile.TemporaryDirectory( + prefix="usbguard-" + args.desktop + "-", ignore_cleanup_errors=True + ) + env = dict( + os.environ, + XDG_RUNTIME_DIR=runtime.name, + WAYLAND_DISPLAY="usbguard-desktop", + GDK_BACKEND="wayland", + GSK_RENDERER="cairo", + GSETTINGS_BACKEND="dconf", + GTK_A11Y="atspi", + XDG_CONFIG_HOME=runtime.name + "/config", + XDG_CACHE_HOME=runtime.name + "/cache", + XDG_DATA_HOME=runtime.name + "/data", + XDG_SESSION_TYPE="wayland", + XDG_CURRENT_DESKTOP="GNOME" if args.desktop == "gnome" else "KDE", + LIBGL_ALWAYS_SOFTWARE="1", + QT_QUICK_BACKEND="software", + LANG="C.UTF-8", + LANGUAGE="en", + NO_AT_BRIDGE="0", + ) + env.pop("DISPLAY", None) + os.environ.update(env) + os.environ.pop("DISPLAY", None) + processes = [] + required = [] + cases = [] + base = "desktop-" + args.desktop + with ( + Path(base + "-shell.log").open("w") as shell_log, + Path(base + "-app.log").open("w") as app_log, + Path(base + "-notification.log").open("w") as notification_log, + ): + + def spawn( + command: list[str], + log: TextIO = shell_log, + critical: bool = False, + extra_env: dict[str, str] | None = None, + ) -> subprocess.Popen[bytes]: + process = subprocess.Popen( + command, env=extra_env or env, stdout=log, stderr=log + ) + processes.append(process) + if critical: + required.append(process) + return process + + def wait(predicate: Callable[[], T], timeout: float = 120) -> T: + return helper.wait_for(predicate, required, timeout) + + try: + subprocess.run( + [ + "dbus-update-activation-environment", + "WAYLAND_DISPLAY", + "XDG_RUNTIME_DIR", + "GDK_BACKEND", + "GSK_RENDERER", + "GTK_A11Y", + "GSETTINGS_BACKEND", + "XDG_CONFIG_HOME", + "XDG_CACHE_HOME", + "XDG_DATA_HOME", + "LIBGL_ALWAYS_SOFTWARE", + "QT_QUICK_BACKEND", + "XDG_CURRENT_DESKTOP", + "XDG_SESSION_TYPE", + ], + env=env, + check=True, + ) + if args.desktop == "gnome": + for schema, key, value in ( + ("org.gnome.desktop.interface", "enable-animations", "false"), + ("org.gnome.desktop.screensaver", "lock-enabled", "false"), + ("org.gnome.desktop.session", "idle-delay", "0"), + ): + subprocess.run( + ["gsettings", "set", schema, key, value], env=env, check=True + ) + launcher = next( + p + for p in ( + Path("/usr/libexec/at-spi-bus-launcher"), + Path("/usr/lib/at-spi2-core/at-spi-bus-launcher"), + ) + if p.is_file() + ) + spawn([str(launcher), "--launch-immediately"]) + command = ( + [ + "gnome-shell", + "--headless", + "--wayland", + "--no-x11", + "--virtual-monitor=1280x900", + "--wayland-display=usbguard-desktop", + ] + if args.desktop == "gnome" + else [ + "kwin_wayland", + "--virtual", + "--width", + "1280", + "--height", + "900", + "--no-lockscreen", + "--socket", + "usbguard-desktop", + ] + ) + spawn(command, critical=True) + wait(lambda: (Path(runtime.name) / "usbguard-desktop").is_socket(), 180) + registry = next( + p + for p in ( + Path("/usr/libexec/at-spi2-registryd"), + Path("/usr/lib/at-spi2-core/at-spi2-registryd"), + ) + if p.is_file() + ) + spawn([str(registry)]) + import gi + + gi.require_version("Gio", "2.0") + from gi.repository import Gio, GLib + import pyatspi + + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + + def call( + destination: str, + path: str, + interface: str, + method: str, + parameters: Any = None, + timeout_ms: int = 15000, + ) -> tuple[Any, ...]: + return bus.call_sync( + destination, + path, + interface, + method, + parameters, + None, + Gio.DBusCallFlags.NONE, + timeout_ms, + None, + ).unpack() + + def owned(name: str) -> bool: + return call( + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "NameHasOwner", + GLib.Variant("(s)", (name,)), + )[0] + + def prop( + destination: str, path: str, interface: str, name: str, + timeout_ms: int = 15000, + ) -> Any: + return call( + destination, + path, + "org.freedesktop.DBus.Properties", + "Get", + GLib.Variant("(ss)", (interface, name)), + timeout_ms=timeout_ms, + )[0] + + if args.desktop == "kde": + spawn(["kded6"]) + spawn(["plasmashell"], critical=True) + wait( + lambda: ( + owned(WATCHER) + and prop( + WATCHER, + "/StatusNotifierWatcher", + WATCHER, + "IsStatusNotifierHostRegistered", + # Under TCG the watcher can own its bus name before + # Plasma finishes initializing its property handler. + timeout_ms=60000, + ) + ), + 180, + ) + else: + assert not owned(WATCHER), ( + "Stock GNOME fixture unexpectedly has a status notifier watcher" + ) + wait( + lambda: ( + owned("org.freedesktop.Notifications") + or owned("org.gtk.Notifications") + ), + 180, + ) + subprocess.run( + ["gsettings", "set", APP, "run-in-background", "false"], + env=env, + check=True, + ) + app = spawn( + [str(binary)], + log=app_log, + critical=True, + extra_env=dict(env, WAYLAND_DEBUG="client", G_DEBUG="fatal-criticals"), + ) + frame = wait( + lambda: helper.mapped_frame( + Path(base + "-app.log").read_text(errors="replace") + ), + 180, + ) + cases.append( + "native Wayland: main surface configured, buffer committed and frame received" + ) + print("PASS checkpoint:", cases[-1], flush=True) + + def walk(root: Any) -> Iterator[Any]: + yield root + try: + for index in range(min(root.childCount, 4096)): + child = root.getChildAtIndex(index) + if child is not None: + yield from walk(child) + except (RuntimeError, AttributeError): + pass + + def roots() -> Iterator[Any]: + desktop = pyatspi.Registry.getDesktop(0) + for index in range(desktop.childCount): + root = desktop.getChildAtIndex(index) + if root and root.get_process_id() == app.pid: + yield root + + def find( + name: str | None = None, + role: str | tuple[str, ...] | None = None, + root: Any = None, + prefix: bool = False, + ) -> Any: + for application in [root] if root is not None else roots(): + for item in walk(application): + try: + if ( + ( + name is None + or ( + item.name.startswith(name) + if prefix + else item.name == name + ) + ) + and ( + role is None + or item.getRoleName() + in ((role,) if isinstance(role, str) else role) + ) + and item.getState().contains(pyatspi.STATE_SHOWING) + ): + return item + except RuntimeError: + pass + return None + + def click(item: Any) -> None: + # Prefer the actual control to an enclosing accessible row or + # label that may advertise an unrelated activation action. + for candidate in reversed(list(walk(item))): + try: + action = candidate.queryAction() + if action.nActions: + assert action.doAction(0) + return + except NotImplementedError: + pass + raise RuntimeError( + "Accessible widget has no action: " + repr(item.name) + ) + + application = wait(lambda: next(roots(), None)) + accessibility_address = call( + "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus", "GetAddress" + )[0] + accessibility_bus = Gio.DBusConnection.new_for_address_sync( + accessibility_address, + Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT + | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, + None, + None, + ) + + def application_windows() -> list[tuple[str, str]]: + # Query the exact app's children in one request. A cached child + # count followed by GetChildAtIndex races with window hiding; + # GTK 4.22.5 can dereference a null path for that stale index. + return accessibility_bus.call_sync( + application.app.bus_name, + application.path, + "org.a11y.atspi.Accessible", + "GetChildren", + None, + None, + Gio.DBusCallFlags.NONE, + 15000, + None, + ).unpack()[0] + + def visible_frame() -> Any: + return application_windows() and find(role="frame") + + search = wait(lambda: find(name="Filter devices by name, ID, or serial")) + search.queryEditableText().setTextContents("usbguard-clean-test") + wait(lambda: find(name="Allowed")) + for name in ("Connected USB devices", "Show device details", "Main menu"): + wait(lambda name=name: find(name=name)) + cases.append( + "AT-SPI: named device controls exposed; synthetic device filter responds" + ) + print("PASS checkpoint:", cases[-1], flush=True) + # Open the same action offered by the main menu; the dialog is native GTK. + call( + APP, + APP_PATH + "/window/1", + "org.gtk.Actions", + "Activate", + GLib.Variant("(sava{sv})", ("preferences", [], {})), + ) + background = wait( + lambda: find(name="Keep running in the background", role="switch") + ) + + def background_enabled() -> bool: + return any( + item.getState().contains(pyatspi.STATE_CHECKED) + for item in walk(background) + ) + + for widget in walk(background): + if widget.getRoleName() == "switch": + actions = widget.queryAction() + print( + "Background control:", + widget.getRoleName(), + repr(widget.name), + "states", + widget.getState().getStates(), + "actions", + [actions.getName(i) for i in range(actions.nActions)], + flush=True, + ) + if not background_enabled(): + click(background) + wait(background_enabled, 15) + stored = subprocess.check_output( + ["gsettings", "get", APP, "run-in-background"], env=env, text=True + ).strip() + assert stored == "true", "Background preference did not persist: " + stored + print( + "Background preference enabled through the native UI and stored", + flush=True, + ) + dialog = wait(lambda: find(role="dialog")) + close = wait( + lambda: find(name="Close", role=("button", "push button"), root=dialog) + ) + click(close) + wait(lambda: not find(role="dialog")) + cases.append( + "preferences: native dialog opens and closes without losing the main window" + ) + print("PASS checkpoint:", cases[-1], flush=True) + owner = call( + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "GetNameOwner", + GLib.Variant("(s)", (APP,)), + )[0] + matches = [ + f"type='method_call',sender='{owner}',interface='{iface}'" + for iface in ( + "org.gtk.Notifications", + "org.freedesktop.Notifications", + "org.freedesktop.portal.Notification", + ) + ] + spawn( + ["stdbuf", "-oL", "dbus-monitor", "--session", *matches], + log=notification_log, + ) + time.sleep(1) + tray_service = f"org.kde.StatusNotifierItem-{app.pid}-1" + if args.desktop == "kde": + wait( + lambda: ( + tray_service + "/StatusNotifierItem" + in prop( + WATCHER, + "/StatusNotifierWatcher", + WATCHER, + "RegisteredStatusNotifierItems", + ) + ) + ) + assert ( + prop( + tray_service, + "/StatusNotifierItem", + "org.kde.StatusNotifierItem", + "Title", + ) + == "USBGuardGUI" + ) + click(wait(lambda: find(name="Close", role=("button", "push button")))) + wait(lambda: not application_windows()) + expected = ( + "Use the status icon to reopen it" + if args.desktop == "kde" + else "This desktop has no status icon area" + ) + wait( + lambda: ( + expected + in Path(base + "-notification.log").read_text(errors="replace") + ) + ) + assert app.poll() is None + + def notification_count() -> int: + return len( + re.findall( + r"member=(?:AddNotification|Notify)(?:\s|$)", + Path(base + "-notification.log").read_text(errors="replace"), + re.MULTILINE, + ) + ) + + assert notification_count() == 1 + cases.append( + "background: close hides the window, keeps GUI alive and sends the correct one-time notice" + ) + print("PASS checkpoint:", cases[-1], flush=True) + second = spawn([str(binary)], log=app_log) + assert second.wait(timeout=60) == 0 + wait(visible_frame) + assert app.poll() is None + assert ( + owner + == call( + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "GetNameOwner", + GLib.Variant("(s)", (APP,)), + )[0] + ) + cases.append("single instance: relaunch reopens the original process") + print("PASS checkpoint:", cases[-1], flush=True) + for cycle in range(args.cycles): + search = wait(lambda: find(name="Filter devices by name, ID, or serial")) + assert search.queryEditableText().setTextContents("usbguard-clean-test") + wait(lambda: find(name="Allowed")) + click(wait(lambda: find(name="Close", role=("button", "push button")))) + wait(lambda: not application_windows()) + restored = spawn([str(binary)], log=app_log) + assert restored.wait(timeout=60) == 0 + wait(visible_frame) + assert owner == call( + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "GetNameOwner", + GLib.Variant("(s)", (APP,)), + )[0] + print("PASS filter/hide/relaunch cycle", cycle + 1, flush=True) + cases.append(f"stress: {args.cycles} filter/hide/relaunch cycles retain the original owner") + click(wait(lambda: find(name="Close", role=("button", "push button")))) + wait(lambda: not application_windows()) + time.sleep(2) + assert notification_count() == 1, ( + "Background notice repeated on the second close" + ) + if args.desktop == "kde": + call( + tray_service, + "/StatusNotifierItem", + "org.kde.StatusNotifierItem", + "Activate", + GLib.Variant("(ii)", (0, 0)), + ) + wait(visible_frame) + call( + tray_service, + "/MenuBar", + "com.canonical.dbusmenu", + "Event", + GLib.Variant("(isvu)", (3, "clicked", GLib.Variant("s", ""), 0)), + ) + assert app.wait(timeout=60) == 0 + cases.append( + "Plasma tray: real watcher registration, Activate reopens, Quit menu exits cleanly" + ) + else: + call( + APP, + APP_PATH, + "org.gtk.Actions", + "Activate", + GLib.Variant("(sava{sv})", ("quit", [], {})), + ) + assert app.wait(timeout=60) == 0 + assert not owned(WATCHER) + cases.append("GNOME: background without a watcher; Quit exits cleanly") + required.remove(app) + require_clean_app_log(Path(base + "-app.log").read_text(errors="replace")) + print("PASS checkpoint:", cases[-1], flush=True) + report = { + "passed": True, + "desktop": args.desktop, + "validated_at": datetime.datetime.now(datetime.UTC).isoformat(), + "scope": "Private headless native-package desktop session, software rendering, synthetic USB only", + "os_release": Path("/etc/os-release").read_text(), + "kernel": subprocess.check_output(["uname", "-r"], text=True).strip(), + "binary_sha256": hashlib.sha256( + binary.read_bytes() + ).hexdigest(), + "binary_path": str(binary), + "fatal_criticals": True, + "stress_cycles": args.cycles, + "gtk_version": subprocess.check_output( + ["rpm", "-q", "gtk4"], text=True + ).strip(), + "cases": cases, + "window": frame, + "settings_backend": "dconf in private XDG directories and session bus", + "display_size": [1280, 900], + "compositor_version": subprocess.run( + [command[0], "--version"], + env=env, + check=False, + capture_output=True, + text=True, + ).stdout.strip(), + "selinux": subprocess.check_output(["getenforce"], text=True).strip(), + } + except Exception: + for filename in ( + base + "-shell.log", + base + "-app.log", + base + "-notification.log", + ): + print( + filename + + ":\n" + + Path(filename).read_text(errors="replace")[-6000:], + flush=True, + ) + # Only this synthetic app's tree is printed for diagnosis. + if "roots" in locals(): + for application in roots(): + for item in walk(application): + try: + print( + "APP accessible:", + item.getRoleName(), + repr(item.name), + flush=True, + ) + except RuntimeError: + pass + raise + finally: + for process in reversed(processes): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + mount = Path(runtime.name) / "doc" + if os.path.ismount(mount): + unmount = shutil.which("fusermount3") or shutil.which("fusermount") + if unmount: + subprocess.run([unmount, "-uz", str(mount)], check=True) + runtime.cleanup() + report["driver_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + report["wayland_helper_sha256"] = hashlib.sha256( + Path(__file__).with_name("clean-install-guest-wayland.py").read_bytes() + ).hexdigest() + report["protocol_sha256"] = hashlib.sha256( + Path(base + "-app.log").read_bytes() + ).hexdigest() + receipt.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/clean-install-guest-ui.py b/scripts/clean-install-guest-ui.py index 62796f5..15daf97 100755 --- a/scripts/clean-install-guest-ui.py +++ b/scripts/clean-install-guest-ui.py @@ -53,6 +53,27 @@ def find(name=None, role=None): return None +def verify_keyboard_focus(search): + editable = search.queryEditableText() + bounds = search.queryComponent().getExtents(pyatspi.DESKTOP_COORDS) + assert bounds.width > 0 and bounds.height > 0 + print('Keyboard test target:', search.getRoleName(), repr(search.name), + (bounds.x, bounds.y, bounds.width, bounds.height), flush=True) + click(search) + print('Active window:', subprocess.check_output( + ['xdotool', 'getactivewindow', 'getwindowname'], text=True).strip(), flush=True) + subprocess.run(['xdotool', 'key', 'ctrl+a'], check=True) + subprocess.run(['xdotool', 'type', '--clearmodifiers', 'keyboard-before-tab'], check=True) + wait(lambda: editable.getText(0, 128) == 'keyboard-before-tab', timeout=5) + subprocess.run(['xdotool', 'key', 'Tab'], check=True) + subprocess.run(['xdotool', 'type', '--clearmodifiers', 'keyboard-after-tab'], check=True) + assert editable.getText(0, 128) == 'keyboard-before-tab', 'Tab did not move focus out of the filter' + subprocess.run(['xdotool', 'key', 'shift+Tab'], check=True) + subprocess.run(['xdotool', 'key', 'ctrl+a'], check=True) + subprocess.run(['xdotool', 'type', '--clearmodifiers', 'keyboard-returned'], check=True) + wait(lambda: editable.getText(0, 128) == 'keyboard-returned', timeout=5) + + def click(item): actions = item.queryAction() if not actions.nActions: @@ -149,12 +170,19 @@ def wait_denial(offset): processes.append(app) wait(lambda: find(role='entry') or find(role='text')) print('GUI registered on accessibility bus', flush=True) + for name in ('Filter devices by name, ID, or serial', 'Connected USB devices', + 'Show device details', 'Main menu'): + wait(lambda name=name: find(name=name)) + print('Passed checkpoint: screen-reader labels', flush=True) if os.environ.get('USBGUI_DUMP_TREE'): time.sleep(10) for item in tree(): print(item.getRoleName(), repr(item.name), flush=True) else: - search = wait(lambda: find(role='entry') or find(role='text')) + search = wait(lambda: find(name='Filter devices by name, ID, or serial')) + verify_keyboard_focus(search) + report['cases'].append('accessibility and keyboard: labels exposed; Tab/Shift+Tab moves focus') + print('Passed checkpoint: keyboard focus', flush=True) print('Search located', flush=True) search.queryEditableText().setTextContents('usbguard-clean-test') time.sleep(3) diff --git a/scripts/clean-install-guest-wayland.py b/scripts/clean-install-guest-wayland.py new file mode 100644 index 0000000..d267305 --- /dev/null +++ b/scripts/clean-install-guest-wayland.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Verify a rendered native Wayland window only inside a marked disposable VM. + +Run with dbus-run-session after installing Weston in the guest. This is a +Weston/Pixman smoke test; it does not replace GNOME/KDE or accessibility checks. +""" +# Copyright (c) 2026 onyks-os +# SPDX-License-Identifier: MIT +import datetime +import hashlib +import json +import os +import re +import shutil +import subprocess +import tempfile +import time +from collections.abc import Callable +from pathlib import Path +from typing import TypeVar + +T = TypeVar('T') + + +def require_guest(marker: Path = Path('/etc/usbguard-clean-install-vm')) -> None: + if not marker.is_file() or os.getuid() == 0: + raise RuntimeError('Requires the unprivileged user inside the marked disposable VM') + if json.loads(marker.read_text()).get('serial') != 'usbguard-clean-test': + raise RuntimeError('The marked VM must contain the synthetic USB fixture') + + +def mapped_frame(protocol: str) -> dict[str, int] | None: + """Require configuration, a committed buffer and its frame callback together. + + Registry traffic, an empty initial commit, a cursor buffer, and an unrelated + callback must not turn an incomplete launch into a passing window test. + """ + for created in re.finditer( + r'get_xdg_surface\(new id xdg_surface#(\d+), wl_surface#(\d+)\)', protocol): + xdg, surface = created.groups() + events = protocol[created.end():] + toplevel = re.search(rf'xdg_surface#{xdg}\.get_toplevel\(new id xdg_toplevel#(\d+)\)', events) + if not toplevel: + continue + title = re.search(rf'xdg_toplevel#{toplevel[1]}\.set_title\("USBGuardGUI"\)', events) + configured = re.search(rf'xdg_surface#{xdg}\.ack_configure\(\d+\)', events) + if not title or not configured: + continue + configured_end = configured.end() + start = configured_end + for committed in re.finditer(rf'wl_surface#{surface}\.commit\(\)', events[configured_end:]): + end = configured_end + committed.end() + pending = events[start:end] + start = end + attached = re.search(rf'wl_surface#{surface}\.attach\(wl_buffer#\d+,', pending) + frame = re.search(rf'wl_surface#{surface}\.frame\(new id wl_callback#(\d+)\)', pending) + if attached and frame and re.search(rf'wl_callback#{frame[1]}\.done\(\d+\)', events[end:]): + return {'xdg_surface': int(xdg), 'surface': int(surface), + 'toplevel': int(toplevel[1]), 'frame_callback': int(frame[1])} + return None + + +def wait_for(predicate: Callable[[], T], processes: list[subprocess.Popen[bytes]], timeout: float) -> T: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + for process in processes: + if process.poll() is not None: + raise RuntimeError(f'Test process exited prematurely: {process.args[0]} ({process.returncode})') + value = predicate() + if value: + return value + time.sleep(0.25) + raise TimeoutError(f'Wayland checkpoint not reached within {timeout} seconds') + + +def main() -> None: + require_guest() + receipt = Path('wayland-report.json') + receipt.unlink(missing_ok=True) + for executable in ('weston', 'usbguard-gui', 'dbus-update-activation-environment'): + if not shutil.which(executable): + raise RuntimeError(f'Install {executable} inside the disposable guest before this check') + if not os.environ.get('DBUS_SESSION_BUS_ADDRESS'): + raise RuntimeError('Run this guest check with dbus-run-session') + help_text = subprocess.check_output(['weston', '--help'], text=True, stderr=subprocess.STDOUT) + if '--fake-seat' not in help_text: + raise RuntimeError('This headless smoke test requires Weston with --fake-seat support') + + runtime = tempfile.TemporaryDirectory(prefix='usbguard-wayland-', ignore_cleanup_errors=True) + processes = [] + env = dict(os.environ, XDG_RUNTIME_DIR=runtime.name, WAYLAND_DISPLAY='usbguard-wayland', + GDK_BACKEND='wayland', GSK_RENDERER='cairo', GSETTINGS_BACKEND='memory', GTK_A11Y='none', + XDG_CONFIG_HOME=runtime.name + '/config', LANG='C.UTF-8', LANGUAGE='en') + env.pop('DISPLAY', None) + try: + with Path('wayland-compositor.log').open('w') as compositor_log, Path('wayland-app.log').open('w') as app_log: + compositor = subprocess.Popen( + ['weston', '--no-config', '--backend=headless', '--renderer=pixman', '--fake-seat', + '--socket=usbguard-wayland', '--idle-time=0'], env=env, stdout=compositor_log, stderr=compositor_log) + processes.append(compositor) + wait_for(lambda: (Path(runtime.name) / 'usbguard-wayland').is_socket(), processes, 30) + subprocess.run(['dbus-update-activation-environment', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR', + 'GDK_BACKEND', 'GSK_RENDERER', 'GTK_A11Y', 'XDG_CONFIG_HOME'], env=env, check=True) + launched_at = time.monotonic() + app = subprocess.Popen(['usbguard-gui'], env=dict(env, WAYLAND_DEBUG='client'), stdout=app_log, stderr=app_log) + processes.append(app) + evidence = wait_for(lambda: mapped_frame(Path('wayland-app.log').read_text(errors='replace')), processes, 120) + mapped_after = time.monotonic() - launched_at + # Observe five more seconds; a mapped window followed by a crash fails. + observed_at = time.monotonic() + wait_for(lambda: time.monotonic() - observed_at >= 5, processes, 10) + report = { + 'passed': True, 'validated_at': datetime.datetime.now(datetime.UTC).isoformat(), + 'scope': 'Native Wayland window on headless Weston/Pixman with a synthetic seat; no X11 fallback', + 'os_release': Path('/etc/os-release').read_text(), + 'kernel': subprocess.check_output(['uname', '-r'], text=True).strip(), + 'compositor': subprocess.check_output(['weston', '--version'], text=True).strip(), + 'binary_sha256': hashlib.sha256(Path('/usr/bin/usbguard-gui').read_bytes()).hexdigest(), + 'window': evidence, 'mapped_after_seconds': round(mapped_after, 3), 'alive_after_frame_seconds': 5, + 'cases': ['main toplevel configured', 'main surface buffer committed', + 'matching frame callback received', 'GUI alive for five seconds after frame'], + } + except Exception: + for filename in ('wayland-compositor.log', 'wayland-app.log'): + if Path(filename).is_file(): + print(filename + ':\n' + Path(filename).read_text(errors='replace')[-6000:], flush=True) + raise + finally: + for process in reversed(processes): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + mount = Path(runtime.name) / 'doc' + if os.path.ismount(mount): + unmount = shutil.which('fusermount3') or shutil.which('fusermount') + if unmount: + subprocess.run([unmount, '-uz', str(mount)], check=True) + runtime.cleanup() + report['test_driver_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + report['protocol_sha256'] = hashlib.sha256(Path('wayland-app.log').read_bytes()).hexdigest() + receipt.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == '__main__': + main() diff --git a/scripts/measure-memory.sh b/scripts/measure-memory.sh new file mode 100755 index 0000000..28d7db8 --- /dev/null +++ b/scripts/measure-memory.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# Repeatable background memory check against an invented USBGuard daemon. +set -euo pipefail + +repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +duration=${MEMORY_SECONDS:-600} +device_count=${USBGUARD_GUI_DEMO_DEVICE_COUNT:-20} +renderer=${MEMORY_RENDERER:-cairo} +max_pss_kb=${MAX_PSS_KB:-71680} +max_rss_kb=${MAX_CAIRO_RSS_KB:-112640} + +if [[ ! $duration =~ ^[0-9]+$ || $duration -lt 1 ]]; then + printf 'MEMORY_SECONDS must be a positive integer\n' >&2 + exit 2 +fi +if [[ ! $device_count =~ ^[0-9]+$ || $device_count -lt 7 || $device_count -gt 200 ]]; then + printf 'USBGUARD_GUI_DEMO_DEVICE_COUNT must be between 7 and 200\n' >&2 + exit 2 +fi +if [[ -z ${DISPLAY:-} && -z ${WAYLAND_DISPLAY:-} ]]; then + printf 'A graphical session is required (DISPLAY or WAYLAND_DISPLAY)\n' >&2 + exit 2 +fi +for tool in cargo dbus-run-session gdbus; do + if ! command -v "$tool" >/dev/null 2>&1; then + printf 'Required tool not found: %s\n' "$tool" >&2 + exit 2 + fi +done + +cargo build --locked --bin usbguard-gui --example demo-bridge + +export USBGUARD_GUI_BUS=session +export USBGUARD_GUI_ISOLATED_INSTANCE=1 +export USBGUARD_GUI_DEMO_DEVICE_COUNT=$device_count +export REPO_ROOT=$repo_root +export MEMORY_SECONDS=$duration +export MEMORY_RENDERER=$renderer +export MAX_PSS_KB=$max_pss_kb +export MAX_CAIRO_RSS_KB=$max_rss_kb +export GSETTINGS_BACKEND=memory +export GSK_RENDERER=$renderer +export GIO_USE_VFS=local + +test_root=$(mktemp -d "$repo_root/target/memory-check.XXXXXX") +trap 'rm -rf "$test_root"' EXIT +cat >"$test_root/bus.conf" <<'BUS' + + session + unix:tmpdir=/tmp + EXTERNAL + + + + + + + +BUS + +# The inner script intentionally expands variables in the child shell. +# shellcheck disable=SC2016 +dbus-run-session --config-file "$test_root/bus.conf" -- bash -c ' +set -euo pipefail +demo_pid= +gui_pid= +cleanup() { + [[ -z $gui_pid ]] || kill "$gui_pid" 2>/dev/null || true + [[ -z $demo_pid ]] || kill "$demo_pid" 2>/dev/null || true + [[ -z $gui_pid ]] || wait "$gui_pid" 2>/dev/null || true + [[ -z $demo_pid ]] || wait "$demo_pid" 2>/dev/null || true +} +trap cleanup EXIT INT TERM + +"$REPO_ROOT/target/debug/examples/demo-bridge" >/dev/null 2>&1 & +demo_pid=$! +"$REPO_ROOT/target/debug/usbguard-gui" --background >/dev/null 2>&1 & +gui_pid=$! + +# Allow the demo bridge to register and the GUI to complete its initial snapshot. +ready=false +for _ in $(seq 1 30); do + if ! kill -0 "$demo_pid" 2>/dev/null || ! kill -0 "$gui_pid" 2>/dev/null; then + printf "Demo bridge or GUI exited during startup\n" >&2 + exit 1 + fi + if gdbus call --session --dest org.usbguard1 --object-path /org/usbguard1 \ + --method org.freedesktop.DBus.Peer.Ping >/dev/null 2>&1; then + ready=true + break + fi + sleep 1 +done +if [[ $ready != true ]]; then + printf "Demo bridge did not register on the private session bus\n" >&2 + exit 1 +fi +sleep 5 +remaining=$MEMORY_SECONDS +printf "Measuring idle memory for %s seconds with %s demo devices...\n" \ + "$MEMORY_SECONDS" "$USBGUARD_GUI_DEMO_DEVICE_COUNT" +while (( remaining > 0 )); do + interval=60 + (( remaining < interval )) && interval=$remaining + sleep "$interval" + remaining=$((remaining - interval)) + printf "Memory measurement: %s seconds remaining\n" "$remaining" +done + +rollup="/proc/$gui_pid/smaps_rollup" +if [[ ! -r $rollup ]]; then + printf "GUI process exited before the measurement\n" >&2 + exit 1 +fi +read -r rss_kb pss_kb < <(awk "/^(Rss|Pss):/ { if (\$1 == \"Rss:\") rss=\$2; else pss=\$2 } END { print rss, pss }" "$rollup") +printf "renderer=%s devices=%s idle_seconds=%s RSS=%s KiB PSS=%s KiB\n" \ + "$MEMORY_RENDERER" "$USBGUARD_GUI_DEMO_DEVICE_COUNT" "$MEMORY_SECONDS" "$rss_kb" "$pss_kb" + +if (( pss_kb > MAX_PSS_KB )); then + printf "PSS exceeded the %s KiB budget\n" "$MAX_PSS_KB" >&2 + exit 1 +fi +if [[ $MEMORY_RENDERER == cairo ]] && (( rss_kb > MAX_CAIRO_RSS_KB )); then + printf "Cairo RSS exceeded the %s KiB budget\n" "$MAX_CAIRO_RSS_KB" >&2 + exit 1 +fi +' diff --git a/scripts/test-gui.sh b/scripts/test-gui.sh index 4be6437..bd4c28b 100755 --- a/scripts/test-gui.sh +++ b/scripts/test-gui.sh @@ -59,12 +59,19 @@ cleanup() { rm -rf "$test_root" } trap cleanup EXIT -for _ in {1..100}; do +# Hosted CI runners can take several seconds to initialize Xvfb after package +# installation. Allow 20 seconds before treating a still-running server as stuck. +for _ in {1..400}; do if test -s "$test_root/display"; then break; fi if ! kill -0 "$xvfb_pid" 2>/dev/null; then cat "$test_root/display.log" >&2; exit 1; fi sleep 0.05 done -if ! test -s "$test_root/display"; then echo "Xvfb did not start" >&2; exit 1; fi +if ! test -s "$test_root/display"; then + echo "Xvfb did not report a display within 20 seconds" >&2 + cat "$test_root/display.log" >&2 + ps -p "$xvfb_pid" -o pid=,stat=,args= >&2 || true + exit 1 +fi DISPLAY=":$(cat "$test_root/display")" export DISPLAY # The child expands bus variables after dbus-run-session has set them. diff --git a/scripts/verify-clean-install.py b/scripts/verify-clean-install.py index 1c66848..9e5ef91 100755 --- a/scripts/verify-clean-install.py +++ b/scripts/verify-clean-install.py @@ -117,8 +117,11 @@ def validate(args): command([*ssh_args(directory), "bash -c " + shlex.quote(script)], stdout=log, stderr=subprocess.STDOUT) result = subprocess.check_output([*ssh_args(directory), "cat ui-report.json"], text=True) ui = json.loads(result) - if ui.get("passed") is not True or len(ui.get("cases", [])) != 4: - raise ValueError("Guest did not complete all four GUI/PAM cases") + cases = ui.get("cases", []) + if (ui.get("passed") is not True or len(cases) != 5 + or not any(case.startswith("accessibility and keyboard:") for case in cases + if isinstance(case, str))): + raise ValueError("Guest did not complete all five desktop/GUI/PAM checks, including accessibility and keyboard focus") receipt = package.parent.parent / "report.json" if receipt.is_file(): expected = json.loads(receipt.read_text())["binary_sha256"] diff --git a/src/ui/device_view.rs b/src/ui/device_view.rs index 1a79e27..240d8b4 100644 --- a/src/ui/device_view.rs +++ b/src/ui/device_view.rs @@ -111,6 +111,9 @@ impl DeviceView { .placeholder_text(gettext("Filter by name, ID, or serial")) .hexpand(true) .build(); + search.update_property(&[gtk::accessible::Property::Label(&gettext( + "Filter devices by name, ID, or serial", + ))]); search.connect_search_changed({ let (query, filter) = (query, filter.clone()); move |entry| { @@ -128,6 +131,9 @@ impl DeviceView { .show_row_separators(true) .reorderable(false) .build(); + columns.update_property(&[gtk::accessible::Property::Label(&gettext( + "Connected USB devices", + ))]); columns.add_css_class("data-table"); columns.append_column(&state_column()); for (title, expand, text) in text_columns() { @@ -278,6 +284,9 @@ fn details_column() -> gtk::ColumnViewColumn { return; }; let details = gtk::MenuButton::builder().label(gettext("Details")).build(); + details.update_property(&[gtk::accessible::Property::Label(&gettext( + "Show device details", + ))]); let text = gtk::Label::builder() .width_request(320) .max_width_chars(48) diff --git a/src/ui/diagnostic_dialog.rs b/src/ui/diagnostic_dialog.rs index bef6d89..29c074b 100644 --- a/src/ui/diagnostic_dialog.rs +++ b/src/ui/diagnostic_dialog.rs @@ -80,7 +80,7 @@ pub(super) fn present(parent: &impl IsA) { .content_height(480) .child(&toolbar) .build(); - dialog.present(Some(parent)); + super::present_dialog(&dialog, parent); // The probe runs on Tokio; the result comes back over a one-shot channel // and is applied here, on the main thread. diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 70c5d23..9886c2e 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -42,10 +42,29 @@ use window::MainWindow; /// (§1.5). `onyks_os`, not `onyks-os`: GApplication rejects the hyphen. pub const APP_ID: &str = "io.github.onyks_os.UsbguardGui"; +fn application_id(isolated_instance: bool) -> String { + if cfg!(debug_assertions) && isolated_instance { + format!("{APP_ID}.Development") + } else { + APP_ID.to_owned() + } +} + /// The name the user sees: menu, window title, About dialog. Kept in one /// place; translations refer to it as `{app}`. pub(super) const APP_NAME: &str = "USBGuardGUI"; +/// Keep native close-button callbacks alive through their signal emission. +/// With animations disabled, closing can synchronously remove the last dialog +/// owner. Release our temporary reference on the next main-loop iteration. +fn present_dialog(dialog: &impl IsA, parent: &impl IsA) { + dialog.connect_closed(|dialog| { + let dialog = dialog.clone(); + glib::idle_add_local_once(move || drop(dialog)); + }); + dialog.present(Some(parent)); +} + /// Capacity of the event channel. Events are already coalesced (§5.4), so /// this is never reached in practice. const CHANNEL_CAPACITY: usize = 64; @@ -54,7 +73,9 @@ const CHANNEL_CAPACITY: usize = 64; #[must_use] pub fn run(background: bool) -> ExitCode { i18n::init(); - let app = adw::Application::builder().application_id(APP_ID).build(); + let isolated_instance = std::env::var_os("USBGUARD_GUI_ISOLATED_INSTANCE").is_some(); + let app_id = application_id(isolated_instance); + let app = adw::Application::builder().application_id(&app_id).build(); let config = Config::load(); // The flag overrides the setting (docs/interfaces.md §2). let background = background || config.start_in_background(); @@ -88,6 +109,10 @@ pub fn run(background: bool) -> ExitCode { ExitCode::from(status) } +#[cfg(test)] +#[path = "../../tests/unit/ui_application.rs"] +mod application_tests; + /// Application-level actions: the targets of notification buttons and of /// the Quit menu item, which work whether or not the window is visible. fn add_app_actions(app: &adw::Application, window: &Rc>>) { diff --git a/src/ui/preferences.rs b/src/ui/preferences.rs index 4e97f9f..89135c1 100644 --- a/src/ui/preferences.rs +++ b/src/ui/preferences.rs @@ -108,7 +108,7 @@ pub(super) fn present_preferences(parent: &impl IsA, config: &Confi page.add(&history_group); let dialog = adw::PreferencesDialog::new(); dialog.add(&page); - dialog.present(Some(parent)); + super::present_dialog(&dialog, parent); } pub(super) fn present_about(parent: &impl IsA) { @@ -127,7 +127,7 @@ pub(super) fn present_about(parent: &impl IsA) { // Translators: replace with your name(s), one per line, to be credited. .translator_credits(gettext("translator-credits")) .build(); - about.present(Some(parent)); + super::present_dialog(&about, parent); } #[cfg(test)] diff --git a/src/ui/rule_dialog.rs b/src/ui/rule_dialog.rs index 7a47564..41b0807 100644 --- a/src/ui/rule_dialog.rs +++ b/src/ui/rule_dialog.rs @@ -189,7 +189,7 @@ pub(super) fn present( }); recompute(&form); - form.dialog.present(Some(parent)); + super::present_dialog(&form.dialog, parent); } fn build(rules: Vec, default_persistence: Persistence) -> Form { diff --git a/src/ui/window.rs b/src/ui/window.rs index 5bf7c51..6ccd7d7 100644 --- a/src/ui/window.rs +++ b/src/ui/window.rs @@ -195,6 +195,7 @@ impl MainWindow { .tooltip_text(gettext("Main menu")) .primary(true) .build(); + menu_button.update_property(&[gtk::accessible::Property::Label(&gettext("Main menu"))]); let header = adw::HeaderBar::new(); header.set_title_widget(Some( @@ -587,7 +588,7 @@ impl MainWindow { dialog.set_default_response(Some("cancel")); dialog.set_close_response("cancel"); dialog.connect_response(None, move |_, response| on_answer(response == "yes")); - dialog.present(Some(&self.0.window)); + super::present_dialog(&dialog, &self.0.window); } // ----------------------------------------------------------------------- @@ -877,7 +878,7 @@ impl MainWindow { this.start_remove(chosen.clone(), true); } }); - dialog.present(Some(&self.0.window)); + super::present_dialog(&dialog, &self.0.window); } fn finish(&self, op: OperationId, result: Result) { diff --git a/tests/gui/mod.rs b/tests/gui/mod.rs index d8d5428..9d95129 100644 --- a/tests/gui/mod.rs +++ b/tests/gui/mod.rs @@ -64,6 +64,7 @@ fn gui_application_contracts() { .flags(gio::ApplicationFlags::NON_UNIQUE) .build(); app.register(None::<&gio::Cancellable>).unwrap(); + super::preferences::tests::exercise_native_close(&app); let backend = Backend::start(); super::config::tests::exercise(); super::history::tests::exercise(&app); diff --git a/tests/gui/preferences.rs b/tests/gui/preferences.rs index e0a6119..d756669 100644 --- a/tests/gui/preferences.rs +++ b/tests/gui/preferences.rs @@ -1,4 +1,4 @@ -use super::super::tests::{close_dialogs, pump, widgets}; +use super::super::tests::{close_dialogs, pump, pump_for, widgets}; use super::*; #[allow(clippy::unwrap_used)] pub(in crate::ui) fn exercise(app: &adw::Application) { @@ -69,3 +69,46 @@ pub(in crate::ui) fn exercise(app: &adw::Application) { window.close(); pump(); } + +#[allow(clippy::unwrap_used)] +pub(in crate::ui) fn exercise_native_close(app: &adw::Application) { + let window = adw::ApplicationWindow::builder() + .application(app) + .default_width(900) + .default_height(700) + .build(); + window.present(); + let config = Config::load(); + // With animations disabled, the native close button can release the last + // dialog reference synchronously, while GTK is still emitting clicked. + // Drop both test references before dispatching that activation timeout. + let settings = gtk::Settings::default().unwrap(); + let animated = settings.is_gtk_enable_animations(); + settings.set_gtk_enable_animations(false); + window.set_default_size(900, 700); + pump_for(std::time::Duration::from_millis(100)); + for about in [false, true] { + if about { + present_about(&window); + } else { + present_preferences(&window, &config); + } + pump_for(std::time::Duration::from_millis(200)); + let dialog = window.visible_dialog().unwrap(); + let weak = dialog.downgrade(); + let close = widgets::(&dialog) + .into_iter() + .find(|button| button.has_css_class("close")) + .unwrap(); + assert!(close.is_mapped()); + assert!(close.activate()); + drop(close); + drop(dialog); + pump_for(std::time::Duration::from_millis(350)); + assert!(window.visible_dialog().is_none()); + assert!(weak.upgrade().is_none(), "closed dialog must be released"); + } + settings.set_gtk_enable_animations(animated); + window.close(); + pump(); +} diff --git a/tests/test_clean_install.py b/tests/test_clean_install.py index 106bde0..21c9668 100644 --- a/tests/test_clean_install.py +++ b/tests/test_clean_install.py @@ -70,7 +70,7 @@ def validation_fixture(self, root): package = output / "first/candidate.rpm" package.write_bytes(b"test package") (output / "report.json").write_text(json.dumps({"binary_sha256": "a" * 64})) - ui = {"passed": True, "cases": ["no-agent", "cancel", "password", "restart"], "binary_sha256": "a" * 64} + ui = {"passed": True, "cases": ["accessibility and keyboard: focus verified", "no-agent", "cancel", "password", "restart"], "binary_sha256": "a" * 64} return argparse.Namespace(output=directory, package=package), ui def test_successful_validation_checks_installed_bytes_and_records_receipt(self): @@ -87,7 +87,13 @@ def test_successful_validation_checks_installed_bytes_and_records_receipt(self): self.assertIn("rm -f ui-report.json", script) def test_incomplete_failed_or_wrong_binary_validation_cannot_publish_receipt(self): - for changes in ({"passed": False}, {"cases": ["no-agent"]}, {"binary_sha256": "b" * 64}): + for changes in ( + {"passed": False}, + {"cases": ["accessibility and keyboard: focus verified", "no-agent", "cancel", "password"]}, + {"cases": ["a11y", "no-agent", "cancel", "password", "restart"]}, + {"cases": ["no-agent"]}, + {"binary_sha256": "b" * 64}, + ): with self.subTest(changes=changes), tempfile.TemporaryDirectory() as temporary: args, ui = self.validation_fixture(Path(temporary)) old = '{"previous": true}' @@ -114,6 +120,7 @@ def test_crate_omits_privileged_guest_tools_but_keeps_build_inputs(self): self.assertNotIn("SESSION_HANDOFF.md", files) self.assertNotIn("scripts/verify-clean-install.py", files) self.assertFalse(any(name.startswith("scripts/clean-install-") for name in files)) + self.assertFalse(any(name.startswith("tests/test_clean_install") for name in files)) def test_ssh_pins_identity_and_known_hosts_inside_output(self): with tempfile.TemporaryDirectory() as temporary: diff --git a/tests/test_clean_install_desktop.py b/tests/test_clean_install_desktop.py new file mode 100644 index 0000000..d7e20e3 --- /dev/null +++ b/tests/test_clean_install_desktop.py @@ -0,0 +1,67 @@ +"""The desktop fixture must stop before GUI imports or process launch on a host.""" +import contextlib +import importlib.util +import io +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location( + 'guest_desktop', Path(__file__).resolve().parents[1] / 'scripts/clean-install-guest-desktop.py') +desktop = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(desktop) + + +class GuestDesktopGuardTests(unittest.TestCase): + def test_completed_window_traffic_does_not_hide_a_toolkit_critical(self) -> None: + protocol = 'wl_surface#18.commit()\nwl_callback#26.done(42)\n' + desktop.require_clean_app_log(protocol + 'Gtk-WARNING: test environment\n') + for failure in ('GLib-GObject-CRITICAL', 'Gtk-CRITICAL', 'Gdk-ERROR', 'Gtk:ERROR'): + with self.subTest(failure=failure), self.assertRaisesRegex(RuntimeError, failure): + desktop.require_clean_app_log(protocol + failure + ': invalid object') + + def test_unmarked_host_cannot_import_gui_or_launch_a_desktop(self) -> None: + with patch.object(desktop.helper, 'require_guest', side_effect=RuntimeError('unmarked VM')), \ + patch.object(desktop.subprocess, 'Popen') as launch, \ + patch.dict(sys.modules, {'gi': None, 'pyatspi': None}), \ + self.assertRaisesRegex(RuntimeError, 'unmarked VM'): + desktop.main() + launch.assert_not_called() + + def test_invalid_cycle_count_removes_stale_receipt_before_launch(self) -> None: + for cycles in ('0', '-1', '101'): + with self.subTest(cycles=cycles), tempfile.TemporaryDirectory() as temporary, \ + contextlib.chdir(temporary), \ + patch.object(desktop.helper, 'require_guest'), \ + patch.object(sys, 'argv', ['desktop-test', '--desktop', 'gnome', '--cycles', cycles]), \ + patch.object(desktop.subprocess, 'Popen') as launch, \ + patch.dict(sys.modules, {'gi': None, 'pyatspi': None}): + receipt = Path('desktop-gnome-report.json') + receipt.write_text('{"passed": true}') + with contextlib.redirect_stderr(io.StringIO()), \ + self.assertRaises(SystemExit): + desktop.main() + self.assertFalse(receipt.exists()) + launch.assert_not_called() + + def test_nonexecutable_binary_fails_before_gui_import_or_launch(self) -> None: + with tempfile.TemporaryDirectory() as temporary, contextlib.chdir(temporary), \ + patch.object(desktop.helper, 'require_guest'), \ + patch.object(desktop.subprocess, 'Popen') as launch, \ + patch.dict(sys.modules, {'gi': None, 'pyatspi': None}): + binary = Path('candidate') + binary.write_text('not an executable') + binary.chmod(0o600) + receipt = Path('desktop-kde-report.json') + receipt.write_text('{"passed": true}') + with patch.object(sys, 'argv', ['desktop-test', '--desktop', 'kde', '--binary', str(binary)]), \ + contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + desktop.main() + self.assertFalse(receipt.exists()) + launch.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_clean_install_wayland.py b/tests/test_clean_install_wayland.py new file mode 100644 index 0000000..f1f68ea --- /dev/null +++ b/tests/test_clean_install_wayland.py @@ -0,0 +1,100 @@ +"""Reject incomplete Wayland launches without inspecting a live desktop.""" +import contextlib +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +SPEC = importlib.util.spec_from_file_location( + 'guest_wayland', Path(__file__).resolve().parents[1] / 'scripts/clean-install-guest-wayland.py') +wayland = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(wayland) + +# Shape of WAYLAND_DEBUG=client output from the disposable Fedora guest. +FRAME = '''[21:56:56.678179] -> xdg_wm_base#16.get_xdg_surface(new id xdg_surface#20, wl_surface#18) +[21:56:56.681959] -> xdg_surface#20.get_toplevel(new id xdg_toplevel#21) +[21:56:56.683122] -> xdg_toplevel#21.set_title("USBGuardGUI") +[21:56:56.683754] -> wl_surface#18.commit() +[21:56:57.003077] -> xdg_surface#20.ack_configure(2) +[21:56:57.889373] -> wl_surface#18.attach(wl_buffer#23, 0, 0) +[21:56:57.889732] -> wl_surface#18.frame(new id wl_callback#26) +[21:56:57.890019] -> wl_surface#18.commit() +[21:56:57.937215] -> wl_surface#14.attach(wl_buffer#24, 0, 0) +[21:56:57.938357] -> wl_surface#14.commit() +[21:56:57.939195] {Default Queue} wl_callback#26.done(805192) +''' + + +class GuestWaylandTests(unittest.TestCase): + def test_complete_main_window_frame_passes_despite_cursor_traffic(self) -> None: + self.assertEqual(wayland.mapped_frame(FRAME), + {'xdg_surface': 20, 'surface': 18, 'toplevel': 21, 'frame_callback': 26}) + # A frame request may precede the buffer attachment within one commit. + lines = FRAME.splitlines() + lines[5], lines[6] = lines[6], lines[5] + self.assertIsNotNone(wayland.mapped_frame('\n'.join(lines))) + + def test_registry_or_unconfigured_empty_window_cannot_pass(self) -> None: + for protocol in ('', 'wl_registry#2.global(20, "xdg_wm_base", 5)', + '\n'.join(FRAME.splitlines()[:4]), + FRAME.replace('ack_configure(2)', 'configure(2)'), + FRAME.replace('set_title("USBGuardGUI")', 'set_title("other")')): + with self.subTest(protocol=protocol): + self.assertIsNone(wayland.mapped_frame(protocol)) + + def test_wrong_surface_callback_or_missing_commit_cannot_pass(self) -> None: + for protocol in ( + FRAME.replace('wl_surface#18.attach', 'wl_surface#99.attach'), + FRAME.replace('wl_surface#18.frame', 'wl_surface#99.frame'), + FRAME.replace('wl_callback#26.done', 'wl_callback#99.done'), + FRAME.replace('wl_surface#18.commit()', ''), + FRAME.replace('wl_callback#26.done(805192)', ''), + FRAME.replace('attach(wl_buffer#23,', 'attach(nil,'), + ): + with self.subTest(protocol=protocol): + self.assertIsNone(wayland.mapped_frame(protocol)) + + def test_separate_incomplete_commits_cannot_be_combined(self) -> None: + protocol = FRAME.replace('wl_surface#18.frame', 'wl_surface#18.commit()\nwl_surface#18.frame') + self.assertIsNone(wayland.mapped_frame(protocol)) + # A callback delivered before the buffer commit proves no later frame. + protocol = FRAME.replace('wl_callback#26.done(805192)', '') + protocol = protocol.replace('wl_surface#18.frame', 'wl_callback#26.done(805192)\nwl_surface#18.frame') + self.assertIsNone(wayland.mapped_frame(protocol)) + + def test_guest_guard_refuses_missing_marker_root_and_wrong_fixture(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + marker = Path(temporary) / 'marker' + with self.assertRaisesRegex(RuntimeError, 'marked disposable VM'): + wayland.require_guest(marker) + marker.write_text(json.dumps({'serial': 'usbguard-clean-test'})) + with patch.object(wayland.os, 'getuid', return_value=0), \ + self.assertRaisesRegex(RuntimeError, 'unprivileged'): + wayland.require_guest(marker) + marker.write_text(json.dumps({'serial': 'physical-device'})) + with patch.object(wayland.os, 'getuid', return_value=1000), \ + self.assertRaisesRegex(RuntimeError, 'synthetic USB fixture'): + wayland.require_guest(marker) + + def test_exited_process_overrides_apparently_successful_checkpoint(self) -> None: + process = Mock(args=['usbguard-gui'], returncode=-11) + process.poll.return_value = -11 + with self.assertRaisesRegex(RuntimeError, 'prematurely.*-11'): + wayland.wait_for(lambda: True, [process], 1) + with self.assertRaises(TimeoutError): + wayland.wait_for(lambda: False, [], 0) + + def test_failed_preflight_removes_stale_passing_receipt(self) -> None: + with tempfile.TemporaryDirectory() as temporary, contextlib.chdir(temporary): + receipt = Path('wayland-report.json') + receipt.write_text('{"passed": true}') + with patch.object(wayland, 'require_guest'), patch.object(wayland.shutil, 'which', return_value=None), \ + self.assertRaisesRegex(RuntimeError, 'Install weston'): + wayland.main() + self.assertFalse(receipt.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit/ui_application.rs b/tests/unit/ui_application.rs new file mode 100644 index 0000000..ece4a7d --- /dev/null +++ b/tests/unit/ui_application.rs @@ -0,0 +1,12 @@ +#[test] +fn development_instance_can_be_isolated_without_changing_release_identity() { + assert_eq!(super::application_id(false), super::APP_ID); + if cfg!(debug_assertions) { + assert_eq!( + super::application_id(true), + format!("{}.Development", super::APP_ID) + ); + } else { + assert_eq!(super::application_id(true), super::APP_ID); + } +}