From 34df13d0237a11f0aeb7e0673ce9e3839cb0d5d8 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Fri, 23 Oct 2026 14:54:30 +0000 Subject: [PATCH 01/52] feat(gui): add the desktop GUI frontend foundation (milestones 001-005) Closes the five foundation milestones of the desktop-gui-frontend subsystem. The engine, the daemon's existing message shapes, and the runtime DTOs are unchanged in substance; the GUI is a leaf frontend, not a second product. 001 - Operation parameter schema publication - schemars 1.2.3 behind an optional `schema` feature on eggsec-runtime; crates/eggsec-runtime/src/schema.rs derives JSON Schema over TaskKind and all 30 params structs. - eggsec-daemon-protocol publishes describe_operations() over a read-only DescribeOperations command; the daemon host arms it behind an explicit client-declaration check. - The schema is descriptive only and never reaches an authorization path (guard 151); no hand-written parameter table may exist (guard 152). 002 - Frontend-client contract extraction - The shared runtime contract moves to the new frontend-neutral eggsec-frontend-client crate: TuiRuntimeClient -> RuntimeClient, DaemonClientError becomes public. - The TUI's runtime_client/ directory is deleted (git records it as a rename) and the TUI is migrated onto the new crate. - The crate carries no frontend framework and depends on no engine (guard 153). 003 - Desktop GUI surface parity - RuntimeSurface::DesktopGuiManual and ExecutionSurface::DesktopGuiManual are added and convert in both directions. - The GUI is a manual surface with the same ManualPermissive profile as the CLI and TUI manual surfaces. No `gui_exposable` flag and no strict GUI variant were added. - The daemon's audit trail now records the session's surface label (desktop-gui-manual) for session-scoped events instead of a blanket "daemon" (guard 154). 004 - GUI shell skeleton - New crates/eggsec-gui: a Tauri v2 desktop application that is daemon-only. It reaches the engine solely through the daemon's Unix socket, links no engine, daemon, CLI, or TUI crate, and performs no outbound HTTP of its own. - The frontend-client seam is widened so the caller supplies its own ClientIdentity (kind, label, request-id prefix); the crate no longer hardcodes the TUI's identity. - ClientKind::Gui is added to the protocol additively, with DAEMON_PROTOCOL_VERSION unchanged at 2. An unrecognised variant fails closed at deserialization rather than being misclassified. - The daemon's manual-approval arm is corrected to include DesktopGuiManual, so the RBAC matrix agrees with eggsec-policy's classification. Preparatory only: ApprovePolicy stays unwired and grants nothing. - The Tauri dependency is pinned with EXACT (`=`) requirements to the 2.11.x line. The next lines up declare MSRV 1.90, above this workspace's 1.89 floor, and `tauri` declares its runtime and utils with caret requirements, so without the direct exact pins a `cargo update` would float the closure onto the 1.90 line and break `make check-msrv`. - Guards 155-158 pin the no-engine edge, the framework's confinement to the GUI crate, the absence of a second TLS stack, and the CSP's refusal of remote origins. 005 - Schema-driven forms and task dashboard - One generic form engine renders a form for ANY published task kind. There is no per-operation code in the Rust or the JavaScript; a task kind the engine has not published yet gets a working form with no GUI change. - The task state is a bounded view of the daemon's event stream: a capped log ring per task, a capped forward flush, and dropped-line counters that are reported rather than swallowed (guards 159-160). - A blank field sends `null`, and a non-nullable optional field is omitted from the request so the request DTO applies its own default. Four published parameters carry non-null defaults and one of them is the fail-safe `dry_run` flag; a GUI that sent `false` for an untouched field would silently turn a simulation into a live action. - The JavaScript dependency set stays empty, which discharges ADR-0009's deferred dependency-policy question. The frontend is hand-written HTML/CSS/vanilla JS with zero npm dependencies and no remote script source. - Result rendering goes through eggsec-ui-model's renderer registry; an unknown kind degrades to a generic JSON render, never an empty view. Build and CI - make check, make check-msrv, and make clippy cover the GUI's shell profile behind a prerequisite gate: an absent webview SDK skips with the reason named, a present-but-broken build fails. `make check-gui` is the ungated escape hatch. - CI installs the Linux webview packages (libwebkit2gtk-4.1-dev, libgtk-3-dev, libayatana-appindicator3-dev, librsvg2-dev, patchelf). Docs and plans - New architecture/desktop_gui.md deep dive, architecture/frontend_client.md, and the eggsec-gui and eggsec-frontend-client skills. - ADR-0007 (daemon-only boundary), ADR-0008 (schema publication), and ADR-0009 (Tauri v2, ratified 2026-10-23). - Milestone plans 001-005, their closure records under plans/closure/desktop-gui-frontend/, the subsystem roadmap, and plans/registry.md. Verified - cargo +1.89 check -p eggsec-gui --features shell; both build profiles green; clippy clean under -D warnings. - 34 GUI tests, 1002 TUI tests, 1872 engine tests, 252 transport tests. - All 160 architecture guards pass; each of the six new guards was demonstrated to fail under a deliberate violation and to pass again after a byte-identical restore. Guard 159 found a real instance of the defect it looks for (a doc comment naming a task-kind variant) on its first run. - The GUI's dependency closure contains no rustls, native-tls, reqwest, openssl, or ring, so the ring-only TLS invariant holds with no exception. make check completes every step except check-deps, which fails on PRE-EXISTING advisories in the engine's and the daemon's closures (zip 2.4.2; the rustls 0.21.12 family via tiberius -> sqlx-mysql). This work adds no advisory and no deny.toml exception: `bans ok, licenses ok, sources ok`. Recording those exceptions needs an owner and a review-by date and is left to the maintainer. --- .github/workflows/ci.yml | 7 +- .github/workflows/deep-checks.yml | 16 +- .gitignore | 5 + .opencode/skills/eggsec-config/SKILL.md | 4 +- .opencode/skills/eggsec-daemon/SKILL.md | 33 +- .../skills/eggsec-frontend-client/SKILL.md | 160 ++ .opencode/skills/eggsec-gui/SKILL.md | 296 ++ .opencode/skills/eggsec-tui/SKILL.md | 10 +- AGENTS.md | 6 +- CONTRIBUTING.md | 40 +- Cargo.lock | 2485 ++++++++++++++++- Cargo.toml | 21 + Makefile | 54 +- architecture/audit.md | 3 +- architecture/compile_time_baseline.md | 2 +- architecture/config.md | 25 +- architecture/daemon.md | 127 +- architecture/desktop_gui.md | 447 +++ architecture/dispatch.md | 11 +- architecture/frontend_client.md | 147 + architecture/overview.md | 59 +- architecture/runtime.md | 24 +- architecture/runtime_bridge.md | 13 +- architecture/tui.md | 8 +- crates/eggsec-daemon-protocol/Cargo.toml | 6 +- .../src/client_registry.rs | 79 +- crates/eggsec-daemon-protocol/src/lib.rs | 1 + .../eggsec-daemon-protocol/src/operations.rs | 299 ++ crates/eggsec-daemon-protocol/src/protocol.rs | 65 + crates/eggsec-daemon/Cargo.toml | 7 + crates/eggsec-daemon/src/host.rs | 376 ++- crates/eggsec-daemon/src/lib.rs | 1 + crates/eggsec-daemon/src/server.rs | 114 + crates/eggsec-daemon/src/store/sqlite.rs | 19 + crates/eggsec-frontend-client/Cargo.toml | 26 + .../src}/daemon.rs | 120 +- .../src}/embedded.rs | 4 +- crates/eggsec-frontend-client/src/lib.rs | 294 ++ crates/eggsec-gui/Cargo.toml | 78 + crates/eggsec-gui/build.rs | 11 + crates/eggsec-gui/capabilities/default.json | 7 + crates/eggsec-gui/frontend/app.js | 1307 +++++++++ crates/eggsec-gui/frontend/index.html | 72 + crates/eggsec-gui/frontend/styles.css | 871 ++++++ crates/eggsec-gui/icons/icon.png | Bin 0 -> 4379 bytes crates/eggsec-gui/src/commands.rs | 672 +++++ crates/eggsec-gui/src/config.rs | 145 + crates/eggsec-gui/src/connection.rs | 216 ++ crates/eggsec-gui/src/form.rs | 824 ++++++ crates/eggsec-gui/src/lib.rs | 70 + crates/eggsec-gui/src/main.rs | 13 + crates/eggsec-gui/src/shell.rs | 34 + crates/eggsec-gui/src/tasks.rs | 865 ++++++ crates/eggsec-gui/tauri.conf.json | 29 + crates/eggsec-policy/src/policy.rs | 89 +- crates/eggsec-python/src/audit.rs | 3 +- crates/eggsec-python/src/daemon.rs | 16 +- crates/eggsec-runtime/Cargo.toml | 11 + crates/eggsec-runtime/src/lib.rs | 2 + crates/eggsec-runtime/src/request.rs | 38 + crates/eggsec-runtime/src/schema.rs | 481 ++++ crates/eggsec-tui/Cargo.toml | 2 +- crates/eggsec-tui/src/app/mod.rs | 15 +- crates/eggsec-tui/src/app/runner.rs | 2 +- crates/eggsec-tui/src/lib.rs | 1 - crates/eggsec-tui/src/runtime_client/mod.rs | 61 - crates/eggsec/src/runtime_bridge/surface.rs | 64 +- crates/eggsec/tests/enforcement_matrix.rs | 56 +- .../eggsec/tests/frontend_surface_matrix.rs | 37 + docs/ARCHITECTURE.md | 14 +- docs/ARCHITECTURE_INVARIANTS.md | 12 +- docs/CI_ARCHITECTURE_GUARDS.md | 15 + docs/DAEMON_PARITY.md | 3 +- docs/ENFORCEMENT_MODES.md | 27 +- docs/VERIFICATION.md | 52 + plans/000-long-term-specification.md | 11 +- .../ADR-0007-desktop-gui-frontend-boundary.md | 329 +++ ...-operation-parameter-schema-publication.md | 312 +++ ...ADR-0009-gui-shell-technology-selection.md | 372 +++ ...on-parameter-schema-publication-closure.md | 264 ++ ...tend-client-contract-extraction-closure.md | 232 ++ .../003-desktop-gui-surface-parity-closure.md | 296 ++ .../004-gui-shell-skeleton-closure.md | 597 ++++ ...driven-forms-and-task-dashboard-closure.md | 505 ++++ ...-operation-parameter-schema-publication.md | 603 ++++ ...002-frontend-client-contract-extraction.md | 530 ++++ .../003-desktop-gui-surface-parity.md | 568 ++++ .../004-gui-shell-skeleton.md | 1005 +++++++ ...-schema-driven-forms-and-task-dashboard.md | 907 ++++++ plans/registry.md | 35 +- .../desktop-gui-frontend-roadmap.md | 661 +++++ scripts/check-architecture-guards.sh | 495 ++++ 92 files changed, 19015 insertions(+), 336 deletions(-) create mode 100644 .opencode/skills/eggsec-frontend-client/SKILL.md create mode 100644 .opencode/skills/eggsec-gui/SKILL.md create mode 100644 architecture/desktop_gui.md create mode 100644 architecture/frontend_client.md create mode 100644 crates/eggsec-daemon-protocol/src/operations.rs create mode 100644 crates/eggsec-frontend-client/Cargo.toml rename crates/{eggsec-tui/src/runtime_client => eggsec-frontend-client/src}/daemon.rs (76%) rename crates/{eggsec-tui/src/runtime_client => eggsec-frontend-client/src}/embedded.rs (96%) create mode 100644 crates/eggsec-frontend-client/src/lib.rs create mode 100644 crates/eggsec-gui/Cargo.toml create mode 100644 crates/eggsec-gui/build.rs create mode 100644 crates/eggsec-gui/capabilities/default.json create mode 100644 crates/eggsec-gui/frontend/app.js create mode 100644 crates/eggsec-gui/frontend/index.html create mode 100644 crates/eggsec-gui/frontend/styles.css create mode 100644 crates/eggsec-gui/icons/icon.png create mode 100644 crates/eggsec-gui/src/commands.rs create mode 100644 crates/eggsec-gui/src/config.rs create mode 100644 crates/eggsec-gui/src/connection.rs create mode 100644 crates/eggsec-gui/src/form.rs create mode 100644 crates/eggsec-gui/src/lib.rs create mode 100644 crates/eggsec-gui/src/main.rs create mode 100644 crates/eggsec-gui/src/shell.rs create mode 100644 crates/eggsec-gui/src/tasks.rs create mode 100644 crates/eggsec-gui/tauri.conf.json create mode 100644 crates/eggsec-runtime/src/schema.rs delete mode 100644 crates/eggsec-tui/src/runtime_client/mod.rs create mode 100644 plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md create mode 100644 plans/adrs/ADR-0008-operation-parameter-schema-publication.md create mode 100644 plans/adrs/ADR-0009-gui-shell-technology-selection.md create mode 100644 plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md create mode 100644 plans/closure/desktop-gui-frontend/002-frontend-client-contract-extraction-closure.md create mode 100644 plans/closure/desktop-gui-frontend/003-desktop-gui-surface-parity-closure.md create mode 100644 plans/closure/desktop-gui-frontend/004-gui-shell-skeleton-closure.md create mode 100644 plans/closure/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard-closure.md create mode 100644 plans/implementation/desktop-gui-frontend/001-operation-parameter-schema-publication.md create mode 100644 plans/implementation/desktop-gui-frontend/002-frontend-client-contract-extraction.md create mode 100644 plans/implementation/desktop-gui-frontend/003-desktop-gui-surface-parity.md create mode 100644 plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md create mode 100644 plans/implementation/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard.md create mode 100644 plans/subsystems/desktop-gui-frontend-roadmap.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4bc40713d..309b1d9d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,8 +44,11 @@ jobs: uses: taiki-e/install-action@c02248eec042a8a90b2335f60bb37dc287b54068 # cargo-deny with: tool: cargo-deny@0.19.0 - - name: Install ripgrep - run: sudo apt-get update && sudo apt-get install -y ripgrep + # The desktop GUI shell profile (Tauri) needs the Linux webview + # development packages; the `make check` gate opens only when they + # are present, so the shell build really runs in CI. + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y ripgrep pkg-config libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf - name: Full mandatory Rust CI contract run: make check diff --git a/.github/workflows/deep-checks.yml b/.github/workflows/deep-checks.yml index 3b9af3ee9..1b5640deb 100644 --- a/.github/workflows/deep-checks.yml +++ b/.github/workflows/deep-checks.yml @@ -23,8 +23,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + # The desktop GUI shell profile (Tauri) needs the Linux webview + # development packages; `make check-full` -> `make check` gates the + # shell build on them, so the shell build really runs in CI. - name: Install system dependencies - run: sudo apt-get update && sudo apt-get install -y ripgrep protobuf-compiler libpcap-dev libssl-dev libssh2-1-dev pkg-config + run: sudo apt-get update && sudo apt-get install -y ripgrep protobuf-compiler libpcap-dev libssl-dev libssh2-1-dev pkg-config libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf - name: Install cargo-deny (SHA-pinned) uses: taiki-e/install-action@c02248eec042a8a90b2335f60bb37dc287b54068 # cargo-deny with: @@ -47,13 +50,12 @@ jobs: - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: key: msrv + # The MSRV contract now includes the desktop GUI shell profile, which + # needs the Linux webview development packages. + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y pkg-config libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf - name: Verify workspace compiles with declared MSRV - run: | - cargo check --workspace --no-default-features - cargo check -p eggsec-cli --no-default-features - cargo check -p eggsec-transport - cargo check -p eggsec-transport-eggfetch - cargo check -p eggsec --no-default-features + run: make check-msrv portability: name: Portability (${{ matrix.os }}) diff --git a/.gitignore b/.gitignore index 385499a22..950dfeada 100755 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,11 @@ crates/*/target/ debug/ release/ +# Tauri build artifacts (the ACL and capability schemas are regenerated by +# `tauri-build` on every build; the capability file's `$schema` points at them +# only as an editor hint) +crates/*/gen/schemas/ + # Pre-built binaries /eggsec eggsec.exe diff --git a/.opencode/skills/eggsec-config/SKILL.md b/.opencode/skills/eggsec-config/SKILL.md index 5df5ee296..86e814d55 100644 --- a/.opencode/skills/eggsec-config/SKILL.md +++ b/.opencode/skills/eggsec-config/SKILL.md @@ -132,11 +132,11 @@ let outcome = enforcement.evaluate(&descriptor); ```rust use eggsec::config::{ExecutionSurface, EnforcementContext}; -let surface = ExecutionSurface::CliManual; // or TuiManual, McpServer, etc. +let surface = ExecutionSurface::CliManual; // or TuiManual, DesktopGuiManual, McpServer, etc. let enforcement = EnforcementContext::for_surface(surface, policy, loaded_scope); ``` -Surfaces that `honors_manual_override()` are only `CliManual` and `TuiManual`. Automated surfaces (`is_agent_controlled()`) require explicit scope manifests for networked operations. +Surfaces that `honors_manual_override()` are `CliManual`, `TuiManual`, and `DesktopGuiManual`. Automated surfaces (`is_agent_controlled()`) require explicit scope manifests for networked operations. ### Preflight Evaluation diff --git a/.opencode/skills/eggsec-daemon/SKILL.md b/.opencode/skills/eggsec-daemon/SKILL.md index 90ae31c13..354179249 100644 --- a/.opencode/skills/eggsec-daemon/SKILL.md +++ b/.opencode/skills/eggsec-daemon/SKILL.md @@ -25,14 +25,43 @@ Persistent session host (`eggsec-daemon`), its IPC protocol (`eggsec-daemon-prot - Primary: Unix domain socket, line-based JSON protocol - Optional: loopback HTTP/SSE behind the `http-api` feature (daemon crate) +The desktop GUI (`crates/eggsec-gui`) connects to this daemon over the Unix +socket and nothing else — it never links the daemon crate. It requires an +`eggsec-daemon --full-executor`: `eggsec daemon start` and a default-built +`eggsec-daemon` host a **no-op executor** that answers every command correctly +and rejects every task, which the GUI reports as "the daemon advertises no +task kinds" rather than presenting a submit button that cannot work. + ## Client Contract 1. Connect to socket -2. Send `DeclareClient { kind: ClientKind::Tui|Cli|..., label }` - must succeed before session-scoped commands +2. Send `DeclareClient { kind: ClientKind::Tui|Cli|Gui|..., label }` - must succeed before session-scoped commands 3. Authorization uses the `CommandPermission` enum (per-command RBAC) 4. Observers cannot submit/cancel tasks (`ErrorCode::PermissionDenied`) 5. On strict-surface sessions only the Owner can approve policies; `ApprovePolicy` returns `ErrorCode::Unsupported` until wired 6. Durable retrieval (protocol v2, Phase E): `GetTaskResult { session_id, task_id }` → `TaskResult { status, outcome }` reads live state first, persisted snapshot second — reconnecting clients fetch completed results without event replay. Reconnect = re-declare + re-subscribe; missed events recover as state. See `docs/DAEMON_PARITY.md`. +7. `DescribeOperations` publishes the canonical operation catalog plus a JSON Schema derived from the request DTOs. Read-only and additive: no session, no session role, but a **declared client** is required (same rule as the other daemon-wide reads). `DaemonCapabilities.operation_schema` advertises availability and is `#[serde(default)]`, so a client built against an older protocol still decodes a newer daemon's capabilities. A daemon too old to know the command answers `ErrorCode::UnsupportedCommand` — degrade to a static form set, never fail. +8. Session-scoped audit events record the **session's runtime surface** label (`desktop-gui-manual`, `tui-manual`, `cli-manual`, ...), so each frontend is attributable in the persisted trail. Events with no session (`declare-client`, startup recovery, `approve-policy`) keep the literal `"daemon"`. + +## Client kinds + +`ClientKind` lives in `crates/eggsec-daemon-protocol/src/client_registry.rs` +and is the shared `ClientKind` / `CommandPermission` RBAC type — there is no +daemon-local copy, so daemon and clients cannot drift. + +`ClientKind::Gui` was added additively for the desktop GUI +(`crates/eggsec-daemon-protocol/src/client_registry.rs:19`). The protocol +version stays at 2: a daemon that predates the variant fails to deserialize +the `DeclareClient` command and rejects the client, which is a fail-closed +outcome rather than a silent misclassification. `ClientCommand` and +`ServerMessage` variant sets are unchanged. + +The RBAC matrix's manual-approval arm now includes +`RuntimeSurface::DesktopGuiManual` beside `TuiManual` and `CliManual` +(`crates/eggsec-daemon-protocol/src/client_registry.rs:199`), so an unrelated +controller may approve a policy on a GUI session exactly as on the CLI and TUI. +That mirrors the classification `eggsec-policy` makes for the surface; the two +must not drift. ## CLI Integration @@ -66,6 +95,8 @@ cargo check --workspace --no-default-features # dependency-rule baseline - `docs/DAEMON.md` - Transport config, schema, CLI reference - `architecture/daemon.md` - Persistence, session lifecycle, transport deep dive - `architecture/runtime.md` / `architecture/runtime_bridge.md` - Runtime types and bridge contract +- `.opencode/skills/eggsec-gui/SKILL.md` - the desktop GUI client of this daemon +- `.opencode/skills/eggsec-frontend-client/SKILL.md` - the shared runtime-client contract ## Phase D Hotspots (2026-09-09) diff --git a/.opencode/skills/eggsec-frontend-client/SKILL.md b/.opencode/skills/eggsec-frontend-client/SKILL.md new file mode 100644 index 000000000..f9af33208 --- /dev/null +++ b/.opencode/skills/eggsec-frontend-client/SKILL.md @@ -0,0 +1,160 @@ +--- +name: eggsec-frontend-client +description: "Frontend-neutral runtime client contract for Eggsec frontends - use when working with the RuntimeClient trait, embedded vs daemon runtime backends, remote attach mode, or building a second frontend (desktop GUI)." +--- + +# Eggsec Frontend Client Skill + +The shared runtime-client contract that every interactive frontend uses to reach +the engine runtime. + +## Why this crate exists + +The runtime-client contract used to live inside `eggsec-tui` and was named +`TuiRuntimeClient`. That made it impossible for a second frontend to reuse the +contract without depending on the whole TUI (ratatui, crossterm, themes, +clipboard). It now lives in its own leaf crate so the TUI, the desktop GUI, +and any other interactive frontend can all depend on the same contract while +the engine stays frontend-neutral. The desktop GUI is the second consumer: +`crates/eggsec-gui` reaches the daemon through this crate and through nothing +else. + +## Crate facts + +| Fact | Value | +|------|-------| +| Crate path | `crates/eggsec-frontend-client/` | +| Public API | `RuntimeClient`, `RuntimeClientFuture`, `RuntimeEventReceiverHandle`, `EmbeddedRuntimeClient`, `DaemonRuntimeClient`, `DaemonClientError`, `ClientIdentity` | +| Workspace deps | `eggsec-runtime`, `eggsec-daemon-protocol` only | +| Forbidden deps | any frontend framework (`ratatui`, `crossterm`), the engine (`eggsec`), and `eggsec-tui` | +| Tokio features | `rt`, `sync`, `time`, `io-util`, `net` — no `rt-multi-thread`, no `macros` | +| Enforced by | architecture guard 153 (no frontend framework, no engine dep) | + +Headline crate and surface counts live in `architecture/overview.md` — point at +it rather than restating the numbers. + +## Module structure + +``` +crates/eggsec-frontend-client/src/ +├── lib.rs # Crate docs, public re-exports, the RuntimeClient trait, ClientIdentity +├── embedded.rs # EmbeddedRuntimeClient — in-process, wraps Arc +└── daemon.rs # DaemonRuntimeClient — Unix socket + JSON-lines to eggsec-daemon +``` + +## The trait + +`RuntimeClient` is the contract every frontend implements against: + +- `capabilities`, `create_session`, `list_sessions`, `snapshot`, `submit`, + `cancel`, `cancel_active`, `subscribe`. +- Supertraits: `Send + Sync + 'static`, so `Arc` + is the holder type. +- Every method returns `RuntimeClientFuture` — a boxed `Send + 'static` + future of `Result`. The boxed-future alias is what makes the + trait object-safe. + +`RuntimeEventReceiverHandle` wraps a `tokio::sync::mpsc::UnboundedReceiver` +and hands out `recv` / `try_recv`. + +## The two implementations + +- **Embedded** — `EmbeddedRuntimeClient` wraps `Arc` + directly. Full typed `TaskResult` is available. +- **Daemon** — `DaemonRuntimeClient` speaks the daemon's JSON-lines protocol + over a Unix socket. Typed `TaskResult` is unavailable, so frontends fall back + to envelope rendering. + +## Client identity: the caller names itself + +The crate is frontend-neutral, so it hardcodes **no** frontend's identity. The +caller supplies a `ClientIdentity` +(`crates/eggsec-frontend-client/src/lib.rs:46`): + +```rust +pub struct ClientIdentity { + pub kind: ClientKind, // the daemon's client registry kind + pub label: String, // the label the daemon shows in its listings + pub request_prefix: String, // this client's request-id namespace +} +``` + +`DaemonRuntimeClient::connect` takes it as its second argument +(`crates/eggsec-frontend-client/src/daemon.rs:80`): + +```rust +DaemonRuntimeClient::connect(socket_path, identity).await? +``` + +The prefix is used verbatim, so a caller that wants a separator includes it in +the prefix itself (`"gui-"` yields `gui-0`, +`crates/eggsec-frontend-client/src/lib.rs:60`). + +The two callers: + +| Frontend | `kind` | `label` | `request_prefix` | +|---|---|---|---| +| TUI | `ClientKind::Tui` | `"eggsec-tui"` | `"tui-"` | +| Desktop GUI | `ClientKind::Gui` | `"eggsec-gui"` | `"gui-"` | + +**The crate carries no TUI-specific identity.** A test asserts that the +production half of `daemon.rs` contains no `"tui-"`, no `ClientKind::Tui`, and +no `"eggsec-tui"` +(`crates/eggsec-frontend-client/src/lib.rs:279`). A TUI-shaped literal in the +non-test source is a regression toward the frontend-specific behavior this +crate was extracted to remove. + +## The daemon-only methods + +Three methods are **inherent** on `DaemonRuntimeClient`, not `RuntimeClient` +trait methods, because the embedded client has no daemon to ask: + +| Method | Returns | Source | +|---|---|---| +| `describe_operations()` | `DescribeOperationsResponse` — the operation catalog plus the published JSON Schema | `crates/eggsec-frontend-client/src/daemon.rs:230` | +| `health()` | `DaemonHealth`, carrying the daemon's `protocol_version` | `crates/eggsec-frontend-client/src/daemon.rs:251` | +| `daemon_capabilities()` | `DaemonCapabilities`, carrying the `operation_schema` flag | `crates/eggsec-frontend-client/src/daemon.rs:280` | + +`daemon_capabilities()` is not a duplicate of the trait's `capabilities()`: +the trait method returns the *runtime* half of the advertisement, while this +one returns the daemon's own flags — notably `operation_schema`, which says +whether the connected daemon can publish the operation catalog at all. + +The `RuntimeClient` trait's eight methods are unchanged. + +## Critical implementation detail: shared connection state + +`DaemonRuntimeClient` is `Clone`, and every clone must share **one** +`Arc`. The connection owns: + +- the request counter and the write half of the socket, +- the pending-response map (`FxHashMap>`), +- the event-channel list (`RwLock>>`). + +A spawned reader task owns the read half and fans every runtime event out to +**all** registered event channels. If a call site clones the connection state +instead of the `Arc`, the fan-out silently breaks: one client stops receiving +events that another client still receives. Clone the client, never the +connection internals. + +## Boundaries + +- This crate is **not** an enforcement surface. It never evaluates policy, never + constructs an `ApprovedExecution`, and never calls `Scope::is_target_allowed`. + Every dispatch goes through the daemon, which enforces. +- The crate depends on no frontend framework. A frontend that needs rendering + brings its own; this crate only speaks to the runtime. +- The crate names no frontend. Every frontend's identity — kind, label, and + request-id namespace — is the caller's to supply, so adding a frontend never + requires editing this crate. +- `DaemonClientError` is public so a frontend can distinguish an I/O failure + from a protocol error from a closed connection. + +## Where to look + +- `architecture/frontend_client.md` — the deep-dive architecture doc. +- `architecture/tui.md` — how the TUI wires the client into its app layer. +- `architecture/daemon.md` — the daemon side of the protocol. +- `.opencode/skills/eggsec-gui/SKILL.md` — the second consumer of this contract. +- `plans/implementation/desktop-gui-frontend/002-frontend-client-contract-extraction.md` + — the milestone plan this crate came from. diff --git a/.opencode/skills/eggsec-gui/SKILL.md b/.opencode/skills/eggsec-gui/SKILL.md new file mode 100644 index 000000000..0a53db660 --- /dev/null +++ b/.opencode/skills/eggsec-gui/SKILL.md @@ -0,0 +1,296 @@ +--- +name: eggsec-gui +description: "Desktop GUI frontend for Eggsec (Tauri v2, daemon-only) - use when working on crates/eggsec-gui, the shell and its Tauri pins, the schema-driven form engine, the Tauri IPC command surface, the buildless webview frontend, the bounded task dashboard, or the GUI's daemon connection." +--- + +# Eggsec GUI Skill + +The desktop graphical frontend: a Tauri v2 application that reaches the engine +through the daemon's Unix socket and nothing else. + +## Crate facts + +| Fact | Value | +|------|-------| +| Crate path | `crates/eggsec-gui/` | +| Shape | `src/lib.rs` library + `src/main.rs` binary (the binary is a thin shell around `eggsec_gui::run`, `crates/eggsec-gui/src/main.rs:8`) | +| Depends on | `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol`, `eggsec-ui-model` only (`crates/eggsec-gui/Cargo.toml:38`) | +| Must never depend on | `eggsec` (the engine), `eggsec-daemon`, `eggsec-cli`, `eggsec-tui` | +| Shell framework | Tauri v2, confined to this crate (`crates/eggsec-gui/src/shell.rs:3`) | +| Frontend | Buildless: hand-written HTML, CSS, and vanilla JavaScript, **zero npm dependencies** | +| Features | `default = ["shell"]`; the crate compiles with `--no-default-features` (`crates/eggsec-gui/Cargo.toml:24`) | +| Enforced by | architecture guards 155–160 (no engine edge, framework confinement, no second TLS stack, CSP forbids remote origins, no per-operation form code, bounded event retention) | + +Headline crate and surface counts live in `architecture/overview.md` — point at +it rather than restating the numbers. + +## Module structure + +``` +crates/eggsec-gui/ +├── src/ +│ ├── lib.rs # Crate docs, GuiError, run() +│ ├── main.rs # The binary: a thin shell around eggsec_gui::run +│ ├── config.rs # CLI options (--socket) and the default socket path +│ ├── connection.rs# The daemon connection, the GUI's identity, the diagnostics +│ ├── form.rs # The generic form engine (schema property → control → RunRequest) +│ ├── tasks.rs # The bounded task state and the result view +│ ├── commands.rs # The Tauri IPC surface and the event forwarder +│ └── shell.rs # The Tauri builder +├── frontend/ # The buildless webview frontend (HTML, CSS, vanilla JS) +├── tauri.conf.json # Window, CSP, withGlobalTauri +├── capabilities/default.json +└── build.rs # Gates tauri_build::build() on the `shell` feature +``` + +## The boundary (hard rules) + +- **The GUI links no engine.** It never imports `EnforcementContext`, + `EnforcedDispatcher`, `Scope`, or `tool.execute()`, and never constructs an + `ApprovedExecution` bundle. Every dispatch happens in the daemon, under the + daemon's own enforcement. +- **The GUI does not depend on `eggsec-daemon`.** The daemon's `full-executor` + feature pulls the engine, so a GUI that embedded a daemon would link the + engine and break the boundary. The GUI therefore connects to an + already-running daemon over its Unix socket. +- **No outbound HTTP.** The GUI enables neither `tauri`'s `rustls-tls` nor + `native-tls` (`crates/eggsec-gui/Cargo.toml:56`), so the whole + `reqwest`/`rustls`/`native-tls` closure stays out of the GUI's graph and the + workspace's ring-only TLS invariant holds without an exception. +- **The GUI holds no authoritative state.** The daemon owns task truth; the + GUI's map is a bounded *view* of the event stream + (`crates/eggsec-gui/src/tasks.rs:3`). +- **The surface is stamped in Rust.** The webview cannot set the surface or + the scope; `assemble_request` serializes `RuntimeSurface::DesktopGuiManual` + itself (`crates/eggsec-gui/src/form.rs:300`), and the session scope is + `is_explicit: false` with source `gui-default` + (`crates/eggsec-gui/src/connection.rs:38`). +- **The CSP forbids remote origins** + (`crates/eggsec-gui/tauri.conf.json:23`), and the window capability grants + `core:default` only — no http, shell, fs, process, or updater plugin + (`crates/eggsec-gui/capabilities/default.json:6`). + +## The Tauri version pins are exact, and load-bearing + +The workspace pins Tauri to the 2.11.x line with `=` requirements +(`Cargo.toml:93`): `tauri = "=2.11.6"`, `tauri-build = "=2.6.3"`, +`tauri-runtime = "=2.11.3"`, `tauri-runtime-wry = "=2.11.4"`, +`tauri-macros = "=2.6.3"`, `tauri-utils = "=2.9.3"`. + +The exactness is the point, not a style preference: + +- the next lines up (tauri 2.12, tauri-utils 2.10, tauri-macros 2.7) declare + **MSRV 1.90**, above the workspace's 1.89 floor; +- `tauri` declares its runtime and utils dependencies with **caret** + requirements, so without the GUI crate's direct exact pins a plain + `cargo update` would float the closure onto the 1.90 line and break + `make check-msrv`. + +The GUI crate depends on `tauri-macros`, `tauri-runtime`, +`tauri-runtime-wry`, and `tauri-utils` **directly** for that reason, even +though it calls none of them directly (`crates/eggsec-gui/Cargo.toml:64`). +`tauri-utils` is also a build-dependency so the no-shell build stays off the +1.90 line (`crates/eggsec-gui/Cargo.toml:74`). + +Do not relax a `=` to `^` here without a recorded ADR: raising the workspace +MSRV to 1.90 is a separate, explicit trade. + +## The buildless frontend + +- No `package.json`, no lockfile, no bundler, no build step: the frontend is + a static directory served as-is (`frontendDist`, `crates/eggsec-gui/tauri.conf.json:7`). +- `withGlobalTauri: true` (`crates/eggsec-gui/tauri.conf.json:10`) is what + lets the vanilla JavaScript reach the IPC commands without a bundler. +- **Zero npm dependencies is a rule, not an accident.** A remote script + source or a CDN import is not permitted: it would defeat the CSP and add + supply-chain surface to a security tool. This discharges `ADR-0009`'s + deferred JavaScript-dependency-policy question — the dependency set is + empty. Any JavaScript dependency admitted later needs a recorded policy with + an owner and a review-by date. +- The repository's root `package.json` is an empty object (`{}`); it is not a + frontend manifest. + +## The IPC surface + +Exactly eight narrow commands, registered in +`crates/eggsec-gui/src/shell.rs:22`: + +| Command | Source | +|---|---| +| `connect_daemon(socket)` | `crates/eggsec-gui/src/commands.rs:219` | +| `list_operations()` | `crates/eggsec-gui/src/commands.rs:266` | +| `list_task_kinds()` | `crates/eggsec-gui/src/commands.rs:292` | +| `form_for(variant)` | `crates/eggsec-gui/src/commands.rs:339` | +| `submit_task(variant, values)` | `crates/eggsec-gui/src/commands.rs:375` | +| `cancel_task(task_id)` | `crates/eggsec-gui/src/commands.rs:436` | +| `cancel_active()` | `crates/eggsec-gui/src/commands.rs:455` | +| `task_snapshot()` | `crates/eggsec-gui/src/commands.rs:467` | + +**There is no generic command-forwarding entry point.** Nothing accepts an +arbitrary daemon message, sets the session surface, or sets the scope +(`crates/eggsec-gui/src/commands.rs:3`). Adding one would hand the webview a +wider capability than the operator's UI needs. + +One event on the bus: `eggsec://task-event` +(`crates/eggsec-gui/src/commands.rs:28`), carrying `task_upsert`, `logs`, or +`counters` (`crates/eggsec-gui/src/commands.rs:190`). + +## The form engine: no per-operation code anywhere + +One mapping from a published JSON Schema property to one control descriptor, +and one assembly path from control values to a typed `RunRequest` +(`crates/eggsec-gui/src/form.rs:3`). A task kind the engine has not published +yet gets a form with no GUI change at all. + +- **No match or switch over task-kind variant names**, no hand-written field + table, no per-operation branch. Guard 159 pins this. +- Five control kinds only (`crates/eggsec-gui/src/form.rs:36`): `text`, + `number`, `checkbox`, `list`, `json`. +- The published schema's measured shape — how many variants and properties it + carries, and that it contains no `$ref`, no `$defs`, no `enum` constraint, + and no nested objects — is recorded in the subsystem roadmap's milestone-005 + entry and the registry. Read it there rather than re-deriving it. +- The absence of `enum` constraints means the schema **cannot** drive + dropdowns for enum-like fields: the GUI renders free text and the engine + validates. +- The schema is **descriptive, never authoritative** + (`crates/eggsec-gui/src/form.rs:9`): it decides form *shape* only. Whether + an operation may run, its risk, and its required features come from the + daemon's operation catalog and its live capabilities. + +## Three-layer validation, and "blank means null" + +Validation is layered (`crates/eggsec-gui/src/form.rs:16`): + +1. **Advisory**, from the schema — the control's declared type and bounds. +2. **Exact**, from the DTOs — the assembled request is deserialized into the + same `RunRequest` the engine will deserialize + (`crates/eggsec-gui/src/form.rs:321`). +3. **Authoritative**, in the engine — the engine's own validation still + decides whether the task may run. + +Layers 1–2 exist to save the operator a round trip. They never stand in for +layer 3, and neither encodes a per-operation rule. + +**A blank field sends `null`** — never `""`, `0`, `false`, or `[]` +(`crates/eggsec-gui/src/form.rs:257`). Several published parameters carry +non-null serde defaults and one is a fail-safe flag (`dry_run`, default +`true`); a GUI that sent `false` for an untouched field would turn a +simulation into a live action. In the Rust assembly path, a field that is not +required and whose type does not accept `null` is **omitted** from the +request so the request DTO applies its own default +(`crates/eggsec-gui/src/form.rs:281`). + +## Bounded task state + +- The event stream is the source of truth; the GUI's map is a bounded view of + it (`crates/eggsec-gui/src/tasks.rs:3`). +- At most **200** log lines are retained per task (`MAX_LOG_LINES_PER_TASK`, + `crates/eggsec-gui/src/tasks.rs:28`), in a capped ring that drops the + *oldest* lines and counts them. +- The event forwarder coalesces and forwards at most **50** log lines per + flush (`MAX_LOG_LINES_PER_FLUSH`, `crates/eggsec-gui/src/tasks.rs:35`), + reporting the rest as dropped. +- Dropped counts are **reported, never silently swallowed**: the operator who + sees "42 earlier lines dropped" knows the view is partial. +- The GUI subscribes **once per session** and never spawns a task per event + (`crates/eggsec-gui/src/commands.rs:477`). + +## Result rendering + +Driven by `eggsec-ui-model`'s `RENDERER_REGISTRY` through +`renderer_for_kind` (`crates/eggsec-gui/src/tasks.rs:20`) — the only source of +per-kind metadata. An unknown kind degrades to a generic JSON render, never +an empty view (`crates/eggsec-gui/src/tasks.rs:415`). + +`supports_rich_tui` describes the **TUI's** capability +(`crates/eggsec-ui-model/src/renderer_registry.rs:17`). It is not a capability +query for the GUI; do not gate GUI rendering on it. + +## Availability and exposure + +- Availability comes from the daemon's live capabilities, never from the GUI's + own reasoning. The join key is the task kind's `capability_name` against + the capability list the daemon advertises + (`crates/eggsec-gui/src/commands.rs:287`). +- Exposure comes from `OperationDescription::manual_exposable` + (`crates/eggsec-gui/src/commands.rs:305`). The GUI is a **manual** surface. +- Milestone 5 *reports* an operation as unavailable; a later milestone hides + it. `unavailable_reason` states why (`crates/eggsec-gui/src/commands.rs:319`). + +## The daemon expectation + +The GUI requires an already-running `eggsec-daemon --full-executor`. It does +not spawn, supervise, or stop a daemon. + +`eggsec daemon start` and a default-built `eggsec-daemon` host a **no-op +executor** that rejects every task, so the GUI's diagnostic names the exact +start command (`crates/eggsec-gui/src/connection.rs:51`) and the GUI reports +the no-op-executor condition — the daemon advertises no task kinds +(`crates/eggsec-gui/src/connection.rs:160`) — rather than offering a submit +button that cannot work. + +## Platform prerequisites and build profiles + +- macOS and Windows use the system webview; Linux needs `webkit2gtk-4.1`, + which sets the supported floor at Ubuntu 22.04 / Debian 12 or newer. +- The crate compiles in two profiles: + - `--features shell` (the default) — the full desktop application. This is + the profile that needs the platform webview SDK. + - `--no-default-features` — the library without the shell, which is what + keeps `cargo check --workspace --no-default-features` (the `make check` + baseline) green on hosts with no webview SDK. `run()` then reports + `ShellNotBuilt` and exits non-zero rather than pretending to work + (`crates/eggsec-gui/src/lib.rs:66`). +- `build.rs` gates `tauri_build::build()` on `CARGO_FEATURE_SHELL` because + the `tauri` crate's build metadata does not exist when the shell feature is + off (`crates/eggsec-gui/build.rs:8`). + +## Build, test, run + +```bash +cargo check -p eggsec-gui --features shell # the desktop profile +cargo check -p eggsec-gui --no-default-features # the make check baseline +cargo test -p eggsec-gui --features shell # unit tests +cargo +1.89 check -p eggsec-gui --features shell # the MSRV gate +``` + +Run it against a usable daemon: + +```bash +eggsec-daemon --full-executor --socket-path /tmp/eggsec-daemon.sock +cargo run -p eggsec-gui --features shell -- --socket /tmp/eggsec-daemon.sock +``` + +The GUI's own flags are `--socket ` and `--socket=`; the default +socket path is `/tmp/eggsec-daemon.sock` (`crates/eggsec-gui/src/config.rs:17`). + +## Known gaps + +- **`ApprovePolicy` is unwired.** The daemon answers it with + `ErrorCode::Unsupported`, so no approval is granted. The GUI handles + `PolicyDecisionRequired` defensively + (`crates/eggsec-gui/src/tasks.rs:282`) and offers **no approval + affordance**. +- **Daemon lifecycle management is unowned.** The GUI neither spawns nor + supervises a daemon; that belongs to a later milestone. +- **The socket-path default is duplicated in four places** — the CLI's + `--socket`, the daemon's `DaemonConfig::default`, the daemon binary's + `--socket-path`, and the GUI's own default + (`crates/eggsec-gui/src/config.rs:13`). There is no socket-path environment + variable. Collapsing the duplication, and introducing one, belongs to a + corrective plan. +- **Binary distribution, signing, notarization, and installers are out of + scope** — handled separately. + +## Resources + +- `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` — the crate boundary. +- `plans/adrs/ADR-0009-gui-shell-technology-selection.md` — the shell choice, + the three conditions, and the egui fallback. +- `plans/subsystems/desktop-gui-frontend-roadmap.md` — the milestone status. +- `architecture/frontend_client.md` — the shared runtime-client contract. +- `architecture/daemon.md` — the daemon side of the protocol. +- `architecture/ui_model.md` — the view DTOs and the renderer registry. +- `.opencode/skills/eggsec-frontend-client/SKILL.md`, + `.opencode/skills/eggsec-daemon/SKILL.md` — the two seams the GUI sits on. diff --git a/.opencode/skills/eggsec-tui/SKILL.md b/.opencode/skills/eggsec-tui/SKILL.md index 8ff1a2b80..8719ba1d4 100644 --- a/.opencode/skills/eggsec-tui/SKILL.md +++ b/.opencode/skills/eggsec-tui/SKILL.md @@ -45,10 +45,6 @@ crates/eggsec-tui/src/ │ ├── runtime_adapter/ # Phase 4: runtime event reducer │ │ └── mod.rs # TuiRuntimeAdapter, TuiAction, reduce/apply pattern │ └── theme_runtime.rs # Theme loader lifecycle helpers -├── runtime_client/ # Phase 8: remote attach mode -│ ├── mod.rs # TuiRuntimeClient trait, RuntimeEventReceiverHandle -│ ├── embedded.rs # EmbeddedRuntimeClient (in-process Runtime) -│ └── daemon.rs # DaemonRuntimeClient (Unix socket to eggsec-daemon) ├── tabs/ # Individual tab implementations (33 tabs) │ ├── mod.rs # Tab enum, TabState/TabInput/TabRender traits │ ├── spec.rs # TabSpec registry (title, stable_id, category, risk, capabilities) @@ -102,11 +98,15 @@ Daemon-backed execution reaches the same executor owner via `runtime_bridge` bun → `execute_approved`. ### Remote Attach Mode (Phase 8) -The TUI supports two runtime backends via the `TuiRuntimeClient` trait: +The TUI supports two runtime backends via the `RuntimeClient` trait, which lives in +the frontend-neutral `eggsec-frontend-client` crate (not in this crate): - **Embedded** (default): `EmbeddedRuntimeClient` wraps `Arc` — full typed `TaskResult` rendering via `result_rx`. - **Daemon** (remote): `DaemonRuntimeClient` connects to `eggsec-daemon` via Unix socket. Uses envelope rendering fallback (`TuiAction::TabCompletedEnvelope`) since typed `TaskResult` is unavailable. +The client contract is shared with every other interactive frontend, so the TUI +must not grow its own copy. See the `eggsec-frontend-client` skill. + CLI: `--runtime daemon --socket [--session | --new-session | --attach-latest]` Key differences in daemon mode: diff --git a/AGENTS.md b/AGENTS.md index ae26050c1..7bbcfbfbc 100755 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,7 +20,7 @@ make check-python # only when Python bindings/stubs/docs/scripts chang ## Workspace -23 workspace crates. Engine `eggsec` is lib-only (no binary); binary shell is `eggsec-cli`. CLI handlers live in-engine at `crates/eggsec/src/commands/handlers/` (`crates/eggsec/src/cli/` holds command types only; `crates/eggsec-cli/src/` is just main/daemon-client/logging). +25 workspace crates. Engine `eggsec` is lib-only (no binary); binary shell is `eggsec-cli`. CLI handlers live in-engine at `crates/eggsec/src/commands/handlers/` (`crates/eggsec/src/cli/` holds command types only; `crates/eggsec-cli/src/` is just main/daemon-client/logging). - Knowledge-corpus leaves: `eggsec-service-db` (service tables), `eggsec-secrets` (credential patterns), `eggsec-payloads` (attack payloads), `eggsec-udp-scan` (UDP scanning + ICMP correlation). Each is a near-empty-dependency leaf reached only through engine `pub use` facades (`scanner::service_data`, `recon::secrets`, `fuzzer::payloads`); deep dive in `architecture/knowledge_corpus.md`, skill `eggsec-knowledge-corpus`. The seam is one-directional: the corpus owns **data**, the engine owns **I/O** — the 6 live probers stay engine-side even though their `get_payloads()` are pure data. Guarded by checks 114/147/148/149/150. - `eggsec-core`, `eggsec-tool-core`: shared types, tool DTOs. @@ -30,6 +30,8 @@ make check-python # only when Python bindings/stubs/docs/scripts chang - `eggsec-db-lab`, `eggsec-web-proxy`, `eggsec-mobile-lab`: domain crates (never authorize — caller enforces). `eggsec-nse` is an external published dependency (optional engine `nse` feature), not a workspace crate. - `eggsec-runtime`, `eggsec-daemon`, `eggsec-daemon-protocol`, `eggsec-ui-model`: task lifecycle, session host, IPC types, view DTOs. - `eggsec-agent`: coordination (registry, scheduler, lifecycle, cron). `eggsec-python`: PyO3/maturin bindings (`maturin develop` from `crates/eggsec-python/`). +- `eggsec-frontend-client`: the frontend-neutral runtime contract (`RuntimeClient`) plus the daemon client. It names no frontend: the caller supplies its own `ClientIdentity` (kind, label, request-id prefix). Deep dive in `architecture/frontend_client.md`, skill `eggsec-frontend-client`. +- `eggsec-gui`: the desktop GUI frontend (`ADR-0007`, `ADR-0009`) — a Tauri v2 shell that is **daemon-only**: it reaches the engine solely through the daemon's Unix socket, links no engine/daemon/CLI/TUI crate, and makes no outbound HTTP of its own. The Tauri dependency is pinned to exact versions (the 2.12 line declares MSRV 1.90, above the workspace floor). Deep dive in `architecture/desktop_gui.md`, skill `eggsec-gui`. ```bash cargo check --workspace --no-default-features # CI baseline @@ -79,7 +81,7 @@ System-dep features: `wireless` (wireless-tools), `packet-inspection` (libpcap-d - Contract/docs: `docs/VERIFICATION.md` (exact `make check` expansion), `docs/ARCHITECTURE.md`, `docs/ENFORCEMENT_MODES.md`, `docs/CI_ARCHITECTURE_GUARDS.md`, `docs/EXTENSIBILITY.md` (adding operations/domains/commands), `docs/COMMAND_REGISTRY.md` (command metadata; `codegg-mcp` shares the `mcp-serve` registration). - Module index: `architecture/overview.md` is the birds-eye view **and** the deep-dive index (every component links to its own `architecture/.md`). Per-module guidance: `crates/eggsec/src//AGENTS.override.md` + `architecture/.md` + skill in `.opencode/skills/`. Load all three when working in a module. -- Area index: enforcement → `architecture/config.md` + `docs/ENFORCEMENT_MODES.md`; dispatch → `architecture/dispatch.md`; transport → `architecture/transport.md` + `architecture/transport_eggfetch.md` (+ baseline/closure `architecture/network_dependency_{baseline,closure}.md`); NSE → `architecture/nse_integration.md` (engine side only — runtime internals live in the upstream `eggsec-nse` repo); TUI → `architecture/tui.md`; daemon/IPC → `architecture/daemon.md`; Python → `architecture/python_api.md` + `docs/python/domain-maturity.md`; supply chain → `architecture/supply_chain.md` + `docs/DEPENDENCY_EXCEPTIONS.md`; knowledge corpus → `architecture/knowledge_corpus.md` (+ `architecture/capability_segregation.md` for the Phase G decision record); runtime contract → `architecture/runtime.md`, `architecture/runtime_bridge.md`, `architecture/operation_request.md`; CLI → `architecture/cli_commands.md`; tests/verification → `docs/VERIFICATION.md` + `architecture/compile_time_baseline.md`. +- Area index: enforcement → `architecture/config.md` + `docs/ENFORCEMENT_MODES.md`; dispatch → `architecture/dispatch.md`; transport → `architecture/transport.md` + `architecture/transport_eggfetch.md` (+ baseline/closure `architecture/network_dependency_{baseline,closure}.md`); NSE → `architecture/nse_integration.md` (engine side only — runtime internals live in the upstream `eggsec-nse` repo); TUI → `architecture/tui.md`; desktop GUI → `architecture/desktop_gui.md`; daemon/IPC → `architecture/daemon.md`; Python → `architecture/python_api.md` + `docs/python/domain-maturity.md`; supply chain → `architecture/supply_chain.md` + `docs/DEPENDENCY_EXCEPTIONS.md`; knowledge corpus → `architecture/knowledge_corpus.md` (+ `architecture/capability_segregation.md` for the Phase G decision record); runtime contract → `architecture/runtime.md`, `architecture/runtime_bridge.md`, `architecture/operation_request.md`; CLI → `architecture/cli_commands.md`; tests/verification → `docs/VERIFICATION.md` + `architecture/compile_time_baseline.md`. - CLI facts agents get wrong: `mcp-serve` has no `--scope-file` (use global `--scope`); `codegg-mcp` is a separate subcommand (alias `mcp-codegg`), not an alias. - Skills drift: when you rename a feature, change a public signature, or change a counted set (crates, features, operations, aliases, tabs, task kinds, payloads, techniques, endpoints, probes, descriptors), update the matching skill's claims alongside `architecture/.md` — skills are not covered by type checks, only by guard check 32 (Nmap-parity wording). Headline counts live in `architecture/overview.md`; do not restate them in skills, point at it instead, so there is one source to update. - Skills: `.opencode/skills/` is canonical; `.skills/`, `.agents/skills/`, `.claude/skills/` are symlinks to it (edit once). Adding a crate or subsystem means adding its skill — that is the gap a missing `eggsec-knowledge-corpus` skill left. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a6c2fb2a..1ff05d95e 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,6 +11,7 @@ Thank you for your interest in contributing to Eggsec! This document provides gu - [Testing](#testing) - [Documentation](#documentation) - [TUI Development](#tui-development) +- [Desktop GUI Development](#desktop-gui-development) - [Pull Request Process](#pull-request-process) ## Code of Conduct @@ -387,9 +388,10 @@ crates/eggsec-tui/src/ │ └── action.rs # Action handling ├── state/ # State management │ └── history.rs # History management -└── runtime_client/ # Daemon client adapter ``` +The frontend runtime-client contract (the `RuntimeClient` trait and the embedded/daemon implementations) now lives in its own leaf crate, `crates/eggsec-frontend-client/`, not under `crates/eggsec-tui/src/runtime_client/`. The TUI depends on that crate and no longer on `eggsec-daemon-protocol` directly. See [architecture/frontend_client.md](architecture/frontend_client.md). + ### Input Modes The TUI uses VIM-style input modes: @@ -637,6 +639,42 @@ fn build_new_feature_task(&self) -> Option { 4. Ensure long outputs scroll properly with `Ctrl+u/d` 5. Check that async operations can be started and stopped +## Desktop GUI Development + +### Overview + +The desktop GUI is a [Tauri v2](https://tauri.app) application in `crates/eggsec-gui/`. It is a **daemon-only** frontend: it reaches the engine exclusively through the daemon's Unix socket, so it links no engine code and performs no outbound HTTP. Its frontend assets are hand-written HTML, CSS and vanilla JavaScript — **no npm, no bundler, no build step**. + +### Prerequisites + +- Rust 1.89 or later (workspace MSRV; verify with `make check-msrv`) +- The platform webview development packages — **Linux**: `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `librsvg2-dev`, `patchelf`, plus `libayatana-appindicator3-dev` and `libxdo-dev` for the tray; **macOS / Windows**: the system webview is already present, so no extra packages. +- An already-running `eggsec-daemon --full-executor` — the GUI does not start, supervise, or stop a daemon. + +### Build and Run + +```bash +# The shell-independent half — no webview SDK required. +cargo check -p eggsec-gui --no-default-features +cargo test -p eggsec-gui --no-default-features --lib + +# The desktop window (needs the webview SDK). +cargo run -p eggsec-gui + +# Point at a daemon on a non-default socket. +cargo run -p eggsec-gui -- --socket /path/to/eggsec-daemon.sock +``` + +The GUI's shell profile is platform-sensitive, so it is verified through the Makefile's `GUI_SHELL_GATE`: the shell-profile lines inside `make check`, `make clippy`, and `make check-msrv` **SKIP with the reason named** when the webview SDK is absent, and **FAIL** if the prerequisite is present but the build breaks. `make check-gui` is the ungated escape hatch — it always runs and reports cargo's own error. + +### Things to know before you change it + +- **Do not loosen the Tauri version pins.** They are exact (`=`), because the next lines up declare MSRV 1.90 — above this workspace's 1.89 floor — and `tauri` declares its runtime and utils dependencies with caret requirements. Without the direct exact pins, a `cargo update` floats the closure onto the 1.90 line and breaks `make check-msrv`. See [architecture/desktop_gui.md](architecture/desktop_gui.md). +- **Do not add per-operation code.** The form is generated from the request schema the daemon publishes. There is no `match` over task-kind names and no hand-written field table; a newly published task kind must get a form with no GUI change. +- **Do not add an npm dependency or a remote script source.** The CSP has no remote origin, and a remote script in a security tool is supply-chain surface the operator cannot audit from the source tree. +- **A blank field means "not provided", not zero.** The GUI must never send `""`, `0`, `false` or `[]` for an untouched field: several published parameters carry non-null defaults, and one is a fail-safe flag (`dry_run`, default `true`). Sending `false` for an untouched field would silently turn a simulation into a live action. +- **Keep retention bounded.** Log lines are capped per task and per flush, and dropped lines are counted rather than discarded silently. Unbounded retention is a disqualifying defect, not a tuning problem. + ## Pull Request Process ### Before Submitting diff --git a/Cargo.lock b/Cargo.lock index f1d09866c..a17ac0de8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -365,6 +365,29 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "atoi" version = "2.0.0" @@ -583,6 +606,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "blocking" version = "1.6.2" @@ -623,6 +655,15 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bson" version = "2.15.0" @@ -635,7 +676,7 @@ dependencies = [ "getrandom 0.2.17", "getrandom 0.3.4", "hex", - "indexmap", + "indexmap 2.14.0", "js-sys", "once_cell", "rand 0.9.5", @@ -692,6 +733,9 @@ name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] [[package]] name = "bzip2" @@ -712,6 +756,73 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.1", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cargo_toml" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" +dependencies = [ + "serde", + "toml 0.9.12+spec-1.1.0", +] + [[package]] name = "cast" version = "0.3.0" @@ -739,6 +850,33 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon 0.12.16", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -773,7 +911,7 @@ dependencies = [ "num-traits", "serde", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -860,7 +998,7 @@ version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 3.0.3", @@ -874,9 +1012,9 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1075,6 +1213,30 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.10.1", + "core-graphics-types", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.1", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1291,6 +1453,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "cssparser" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", +] + [[package]] name = "cssparser-macros" version = "0.6.1" @@ -1301,6 +1476,22 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ctor" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98" +dependencies = [ + "ctor-proc-macro", + "dtor", +] + +[[package]] +name = "ctor-proc-macro" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" + [[package]] name = "ctutils" version = "0.4.2" @@ -1346,7 +1537,7 @@ dependencies = [ "base64 0.22.1", "cyclonedx-bom-macros", "fluent-uri", - "indexmap", + "indexmap 2.14.0", "once_cell", "ordered-float 5.3.0", "purl", @@ -1495,6 +1686,17 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + [[package]] name = "deadpool" version = "0.12.3" @@ -1595,6 +1797,9 @@ name = "deranged" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] [[package]] name = "derive-syn-parse" @@ -1776,6 +1981,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.1", + "block2", + "libc", "objc2", ] @@ -1790,6 +1997,29 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "document-features" version = "0.2.12" @@ -1799,12 +2029,36 @@ dependencies = [ "litrs", ] +[[package]] +name = "dom_query" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89" +dependencies = [ + "bit-set 0.8.0", + "cssparser 0.36.0", + "foldhash 0.2.0", + "html5ever 0.38.0", + "precomputed-hash", + "selectors 0.36.1", + "tendril 0.5.1", +] + [[package]] name = "dotenvy" version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + [[package]] name = "dtoa" version = "1.0.11" @@ -1820,6 +2074,33 @@ dependencies = [ "dtoa", ] +[[package]] +name = "dtor" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4" +dependencies = [ + "dtor-proc-macro", +] + +[[package]] +name = "dtor-proc-macro" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "ed25519" version = "2.2.3" @@ -2119,7 +2400,7 @@ dependencies = [ "tokio-stream", "tokio-tungstenite 0.27.0", "tokio-util", - "toml", + "toml 0.8.2", "tonic", "tonic-prost", "tonic-reflection", @@ -2200,6 +2481,8 @@ dependencies = [ "clap", "eggsec", "eggsec-daemon-protocol", + "eggsec-frontend-client", + "eggsec-policy", "eggsec-runtime", "futures", "reqwest", @@ -2221,6 +2504,7 @@ name = "eggsec-daemon-protocol" version = "0.1.0" dependencies = [ "anyhow", + "eggsec-policy", "eggsec-runtime", "serde", "serde_json", @@ -2245,7 +2529,40 @@ dependencies = [ "tiberius", "tokio", "tokio-util", - "toml", + "toml 0.8.2", + "tracing", +] + +[[package]] +name = "eggsec-frontend-client" +version = "0.1.0" +dependencies = [ + "eggsec-daemon-protocol", + "eggsec-runtime", + "rustc-hash", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tracing", +] + +[[package]] +name = "eggsec-gui" +version = "0.1.0" +dependencies = [ + "eggsec-daemon-protocol", + "eggsec-frontend-client", + "eggsec-runtime", + "eggsec-ui-model", + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "tokio", "tracing", ] @@ -2267,7 +2584,7 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "tokio", - "toml", + "toml 0.8.2", "tracing", "uuid", "zip", @@ -2402,6 +2719,7 @@ dependencies = [ name = "eggsec-runtime" version = "0.1.0" dependencies = [ + "schemars 1.2.3", "serde", "serde_json", "thiserror 2.0.21", @@ -2438,7 +2756,7 @@ dependencies = [ "rustc-hash", "serde", "serde_json", - "toml", + "toml 0.8.2", "uuid", ] @@ -2486,7 +2804,7 @@ dependencies = [ "directories", "eggsec", "eggsec-core", - "eggsec-daemon-protocol", + "eggsec-frontend-client", "eggsec-runtime", "eggsec-ui-model", "futures", @@ -2501,7 +2819,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tokio-util", - "toml", + "toml 0.8.2", "tracing", "url", "uuid", @@ -2598,6 +2916,26 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.1.8+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + [[package]] name = "encode_unicode" version = "1.0.0" @@ -2795,6 +3133,16 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + [[package]] name = "filedescriptor" version = "0.8.3" @@ -2897,26 +3245,53 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ - "foreign-types-shared", + "foreign-types-shared 0.1.1", ] [[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" +name = "foreign-types" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" dependencies = [ - "percent-encoding", + "foreign-types-macros", + "foreign-types-shared 0.3.1", ] [[package]] -name = "fsevent-sys" +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fsevent-sys" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" @@ -3061,6 +3436,105 @@ dependencies = [ "byteorder", ] +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -3078,7 +3552,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3129,6 +3603,85 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.1", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + [[package]] name = "glob" version = "0.3.4" @@ -3147,6 +3700,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + [[package]] name = "granit-parser" version = "0.0.7" @@ -3157,6 +3721,58 @@ dependencies = [ "smallvec", ] +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "h2" version = "0.4.19" @@ -3169,7 +3785,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap", + "indexmap 2.14.0", "slab", "tokio", "tokio-util", @@ -3187,6 +3803,12 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.14.5" @@ -3284,6 +3906,12 @@ dependencies = [ "winreg", ] +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "heck" version = "0.5.0" @@ -3317,7 +3945,7 @@ dependencies = [ "hickory-proto", "idna", "ipnet", - "jni", + "jni 0.22.4", "rand 0.10.2", "thiserror 2.0.21", "tinyvec", @@ -3335,7 +3963,7 @@ dependencies = [ "data-encoding", "idna", "ipnet", - "jni", + "jni 0.22.4", "once_cell", "prefix-trie", "rand 0.10.2", @@ -3358,7 +3986,7 @@ dependencies = [ "hickory-proto", "ipconfig", "ipnet", - "jni", + "jni 0.22.4", "moka", "ndk-context", "once_cell", @@ -3416,7 +4044,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" dependencies = [ "cfg-if", "libc", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3427,10 +4055,20 @@ checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c" dependencies = [ "log", "mac", - "markup5ever", + "markup5ever 0.14.1", "match_token", ] +[[package]] +name = "html5ever" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2" +dependencies = [ + "log", + "markup5ever 0.38.0", +] + [[package]] name = "http" version = "1.5.0" @@ -3572,7 +4210,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -3584,6 +4222,16 @@ dependencies = [ "cc", ] +[[package]] +name = "ico" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" +dependencies = [ + "byteorder", + "png 0.17.16", +] + [[package]] name = "icu_collections" version = "2.2.0" @@ -3703,10 +4351,21 @@ dependencies = [ "byteorder-lite", "moxcms", "num-traits", - "png", + "png 0.18.1", "tiff", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.0" @@ -3715,6 +4374,8 @@ checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -3739,6 +4400,15 @@ dependencies = [ "rustversion", ] +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb", +] + [[package]] name = "inotify" version = "0.10.2" @@ -3799,7 +4469,7 @@ dependencies = [ "socket2 0.6.5", "widestring", "windows-registry", - "windows-result", + "windows-result 0.4.1", "windows-sys 0.61.2", ] @@ -3871,6 +4541,29 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "jiff" version = "0.2.35" @@ -3880,10 +4573,12 @@ dependencies = [ "defmt", "jiff-core", "jiff-static", + "jiff-tzdb-platform", "log", "portable-atomic", "portable-atomic-util", "serde_core", + "windows-link 0.2.1", ] [[package]] @@ -3907,6 +4602,37 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + [[package]] name = "jni" version = "0.22.4" @@ -3916,12 +4642,12 @@ dependencies = [ "cfg-if", "combine", "jni-macros", - "jni-sys", + "jni-sys 0.4.1", "log", "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3937,6 +4663,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + [[package]] name = "jni-sys" version = "0.4.1" @@ -3979,19 +4714,31 @@ dependencies = [ [[package]] name = "json-patch" -version = "4.2.0" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08" dependencies = [ - "jsonptr", + "jsonptr 0.6.3", "serde", "serde_json", - "thiserror 2.0.21", + "thiserror 1.0.69", ] [[package]] -name = "jsonpath-rust" -version = "1.0.8" +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr 0.7.1", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonpath-rust" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e07021eefc09f897611b067ba7897b5e9266edfc902768418968772e5bb06a7" dependencies = [ @@ -4002,6 +4749,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "jsonptr" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "jsonptr" version = "0.7.1" @@ -4035,6 +4792,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.1", + "serde", + "unicode-segmentation", +] + [[package]] name = "kqueue" version = "1.2.1" @@ -4113,7 +4881,7 @@ dependencies = [ "form_urlencoded", "http", "jiff", - "json-patch", + "json-patch 4.2.0", "k8s-openapi", "serde", "serde-value", @@ -4135,7 +4903,7 @@ dependencies = [ "futures", "hashbrown 0.16.1", "hostname", - "json-patch", + "json-patch 4.2.0", "k8s-openapi", "kube-client", "parking_lot", @@ -4191,12 +4959,55 @@ dependencies = [ "webpki-roots 1.0.9", ] +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading", + "once_cell", +] + [[package]] name = "libc" version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + [[package]] name = "libm" version = "0.2.16" @@ -4428,10 +5239,21 @@ checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" dependencies = [ "log", "phf 0.11.3", - "phf_codegen", - "string_cache", - "string_cache_codegen", - "tendril", + "phf_codegen 0.11.3", + "string_cache 0.8.9", + "string_cache_codegen 0.5.4", + "tendril 0.4.3", +] + +[[package]] +name = "markup5ever" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862" +dependencies = [ + "log", + "tendril 0.5.1", + "web_atoms", ] [[package]] @@ -4714,6 +5536,27 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "multimap" version = "0.10.1" @@ -4737,12 +5580,36 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.1", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + [[package]] name = "ndk-context" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "new_debug_unreachable" version = "1.0.6" @@ -4935,6 +5802,28 @@ dependencies = [ "libc", ] +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "num_threads" version = "0.1.7" @@ -4951,6 +5840,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" dependencies = [ "objc2-encode", + "objc2-exception-helper", ] [[package]] @@ -4960,11 +5850,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.1", + "block2", "objc2", + "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -4989,12 +5902,53 @@ dependencies = [ "objc2-io-surface", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-encode" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + [[package]] name = "objc2-foundation" version = "0.3.2" @@ -5002,6 +5956,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.1", + "block2", "objc2", "objc2-core-foundation", ] @@ -5017,6 +5972,63 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.1", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.1", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "oid-registry" version = "0.8.1" @@ -5056,7 +6068,7 @@ checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ "bitflags 2.13.1", "cfg-if", - "foreign-types", + "foreign-types 0.3.2", "libc", "openssl-macros", "openssl-sys", @@ -5182,6 +6194,31 @@ dependencies = [ "libm", ] +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "parking" version = "2.2.1" @@ -5208,7 +6245,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -5324,7 +6361,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset 0.5.7", "hashbrown 0.15.5", - "indexmap", + "indexmap 2.14.0", ] [[package]] @@ -5333,7 +6370,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_macros", + "phf_macros 0.11.3", "phf_shared 0.11.3", ] @@ -5346,16 +6383,37 @@ dependencies = [ "phf_shared 0.12.1", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + [[package]] name = "phf_codegen" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "phf_generator", + "phf_generator 0.11.3", "phf_shared 0.11.3", ] +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", +] + [[package]] name = "phf_generator" version = "0.11.3" @@ -5366,19 +6424,42 @@ dependencies = [ "rand 0.8.7", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_macros" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "phf_generator", + "phf_generator 0.11.3", "phf_shared 0.11.3", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -5397,6 +6478,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -5484,7 +6574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" dependencies = [ "base64 0.23.1", - "indexmap", + "indexmap 2.14.0", "quick-xml 0.42.0", "serde", "time", @@ -5611,11 +6701,11 @@ dependencies = [ [[package]] name = "png" -version = "0.18.1" +version = "0.17.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" dependencies = [ - "bitflags 2.13.1", + "bitflags 1.3.2", "crc32fast", "fdeflate", "flate2", @@ -5623,8 +6713,21 @@ dependencies = [ ] [[package]] -name = "pom" -version = "3.4.0" +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "pom" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c972d8f86e943ad532d0b04e8965a749ad1d18bb981a9c7b3ae72fe7fd7744b" dependencies = [ @@ -5715,6 +6818,59 @@ dependencies = [ "time", ] +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.17+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -5759,7 +6915,7 @@ version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" dependencies = [ - "heck", + "heck 0.5.0", "itertools 0.14.0", "log", "multimap", @@ -5847,7 +7003,7 @@ version = "0.29.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f41027e41b4bd03f6e60f9f417fe24a6341a6bb744edd62b6f709f2a52ea30e9" dependencies = [ - "target-lexicon", + "target-lexicon 0.13.5", ] [[package]] @@ -5878,7 +7034,7 @@ version = "0.29.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "571575aa3749fa6216757dd47d2a3e7ef360f329a40f0666a9fbd14889024952" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -6134,6 +7290,12 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + [[package]] name = "rayon" version = "1.12.0" @@ -6318,12 +7480,14 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls 0.26.5", + "tokio-util", "tower 0.5.3", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", ] @@ -6505,7 +7669,7 @@ checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", - "jni", + "jni 0.22.4", "log", "once_cell", "rustls 0.23.45", @@ -6587,6 +7751,70 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive 0.8.22", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive 1.2.3", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals 0.29.1", + "syn 2.0.119", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals 0.30.0", + "syn 3.0.3", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -6600,13 +7828,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0e749d29b2064585327af5038a5a8eb73aeebad4a3472e83531a436563f7208" dependencies = [ "ahash", - "cssparser", + "cssparser 0.34.0", "ego-tree", "getopts", - "html5ever", + "html5ever 0.29.1", "precomputed-hash", - "selectors", - "tendril", + "selectors 0.26.0", + "tendril 0.4.3", ] [[package]] @@ -6671,14 +7899,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd568a4c9bb598e291a08244a5c1f5a8a6650bee243b5b0f8dbb3d9cc1d87fe8" dependencies = [ "bitflags 2.13.1", - "cssparser", + "cssparser 0.34.0", "derive_more 0.99.20", "fxhash", "log", "new_debug_unreachable", "phf 0.11.3", - "phf_codegen", + "phf_codegen 0.11.3", + "precomputed-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "selectors" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c" +dependencies = [ + "bitflags 2.13.1", + "cssparser 0.36.0", + "derive_more 2.1.1", + "log", + "new_debug_unreachable", + "phf 0.13.1", + "phf_codegen 0.13.1", "precomputed-hash", + "rustc-hash", "servo_arc", "smallvec", ] @@ -6688,6 +7935,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -6718,6 +7969,18 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + [[package]] name = "serde-value" version = "0.7.0" @@ -6758,13 +8021,35 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_json" version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ - "indexmap", + "indexmap 2.14.0", "itoa", "memchr", "serde", @@ -6783,6 +8068,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "serde_spanned" version = "0.6.9" @@ -6792,6 +8088,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -6810,8 +8115,19 @@ version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a" dependencies = [ + "base64 0.22.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", "serde_core", + "serde_json", "serde_with_macros", + "time", ] [[package]] @@ -6832,13 +8148,35 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34b209c2fb1a006ef53382f97f8ee5d43b156f61c0db1328638fdfa749af865f" dependencies = [ - "indexmap", + "indexmap 2.14.0", "itoa", "ryu", "serde", "unsafe-libyaml", ] +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "servo_arc" version = "0.4.3" @@ -7037,6 +8375,54 @@ dependencies = [ "winapi", ] +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "bytemuck", + "js-sys", + "ndk", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "redox_syscall 0.5.18", + "tracing", + "wasm-bindgen", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "spdx" version = "0.10.9" @@ -7115,7 +8501,7 @@ dependencies = [ "futures-util", "hashbrown 0.15.5", "hashlink 0.10.0", - "indexmap", + "indexmap 2.14.0", "log", "memchr", "once_cell", @@ -7152,7 +8538,7 @@ checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" dependencies = [ "dotenvy", "either", - "heck", + "heck 0.5.0", "hex", "once_cell", "proc-macro2", @@ -7312,18 +8698,42 @@ dependencies = [ "serde", ] +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.13.1", + "precomputed-hash", +] + [[package]] name = "string_cache_codegen" version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" dependencies = [ - "phf_generator", + "phf_generator 0.11.3", "phf_shared 0.11.3", "proc-macro2", "quote", ] +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", +] + [[package]] name = "stringprep" version = "0.1.5" @@ -7356,7 +8766,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.119", @@ -7384,6 +8794,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "swift-rs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + [[package]] name = "symlink" version = "0.1.0" @@ -7464,6 +8885,19 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + [[package]] name = "tagptr" version = "0.2.0" @@ -7477,17 +8911,285 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" [[package]] -name = "tap" -version = "1.0.1" +name = "tao" +version = "0.35.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - +checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9" +dependencies = [ + "bitflags 2.13.1", + "block2", + "core-foundation 0.10.1", + "core-graphics", + "crossbeam-channel", + "dbus", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "once_cell", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + [[package]] name = "target-lexicon" version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +[[package]] +name = "tauri" +version = "2.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fa5bacdb9bbad5954af3d1bd6cf6ae9192cab1b2e270f4a07f904610b9e85f4" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "jni 0.21.1", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.21", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs", + "glob", + "heck 0.5.0", + "json-patch 3.0.1", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "tauri-utils", + "tauri-winres", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5" +dependencies = [ + "base64 0.22.1", + "ico", + "json-patch 3.0.1", + "plist", + "png 0.17.16", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2 0.10.9", + "syn 2.0.119", + "tauri-utils", + "thiserror 2.0.21", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-runtime" +version = "2.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni 0.21.1", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f" +dependencies = [ + "gtk", + "http", + "jni 0.21.1", + "log", + "objc2", + "objc2-app-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887" +dependencies = [ + "anyhow", + "cargo_metadata", + "ctor", + "dom_query", + "dunce", + "glob", + "http", + "infer", + "json-patch 3.0.1", + "log", + "memchr", + "phf 0.13.1", + "plist", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.21", + "toml 1.1.8+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" +dependencies = [ + "dunce", + "embed-resource", + "toml 1.1.8+spec-1.1.0", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -7512,6 +9214,15 @@ dependencies = [ "utf-8", ] +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + [[package]] name = "termina" version = "0.3.3" @@ -7534,7 +9245,7 @@ dependencies = [ "fnv", "nom 7.1.3", "phf 0.11.3", - "phf_codegen", + "phf_codegen 0.11.3", ] [[package]] @@ -7860,44 +9571,123 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.23" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" dependencies = [ "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap 2.14.0", + "serde_core", + "serde_spanned 1.1.2", + "toml_datetime 0.7.5+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap 2.14.0", + "serde_core", + "serde_spanned 1.1.2", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.4", ] [[package]] name = "toml_datetime" -version = "0.6.11" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" dependencies = [ "serde", ] +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + [[package]] name = "toml_edit" -version = "0.22.27" +version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" dependencies = [ - "indexmap", + "indexmap 2.14.0", "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", ] [[package]] -name = "toml_write" -version = "0.1.2" +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime 1.1.2+spec-1.1.0", + "toml_parser", + "winnow 1.0.4", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.4", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "tonic" @@ -7972,7 +9762,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap", + "indexmap 2.14.0", "pin-project-lite", "slab", "sync_wrapper", @@ -8119,6 +9909,28 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tray-icon" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "045979e3f037cd18ad1cb2a419dfda133c5c29c9f3453370079f2255d46c257e" +dependencies = [ + "crossbeam-channel", + "dirs", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png 0.18.1", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -8210,6 +10022,47 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-ucd-ident" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + [[package]] name = "unicode-bidi" version = "0.3.18" @@ -8324,6 +10177,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -8332,6 +10186,18 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" +[[package]] +name = "urlpattern" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d" +dependencies = [ + "regex", + "serde", + "unic-ucd-ident", + "url", +] + [[package]] name = "utf-8" version = "0.7.6" @@ -8381,12 +10247,38 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + [[package]] name = "vtparse" version = "0.6.2" @@ -8500,6 +10392,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.104" @@ -8520,6 +10425,62 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web_atoms" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf 0.13.1", + "phf_codegen 0.13.1", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + [[package]] name = "webpki-root-certs" version = "1.0.9" @@ -8547,6 +10508,42 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webview2-com" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core 0.61.2", + "windows-implement", + "windows-interface", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core 0.61.2", +] + [[package]] name = "weezl" version = "0.1.12" @@ -8681,6 +10678,56 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "window-vibrancy" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c" +dependencies = [ + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "windows-sys 0.59.0", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -8689,9 +10736,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", ] [[package]] @@ -8716,21 +10774,46 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-registry" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -8739,7 +10822,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -8748,7 +10840,16 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", ] [[package]] @@ -8769,6 +10870,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" @@ -8784,7 +10894,22 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", ] [[package]] @@ -8824,7 +10949,7 @@ version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows-link", + "windows-link 0.2.1", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", @@ -8835,6 +10960,30 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -8853,6 +11002,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -8871,6 +11026,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -8901,6 +11062,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -8919,6 +11086,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -8937,6 +11110,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -8955,6 +11134,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -8973,11 +11158,26 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + [[package]] name = "winnow" version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" dependencies = [ "memchr", ] @@ -9027,6 +11227,50 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]] +name = "wry" +version = "0.55.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514" +dependencies = [ + "base64 0.22.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs", + "dom_query", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni 0.21.1", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2 0.10.9", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + [[package]] name = "wyz" version = "0.5.1" @@ -9036,6 +11280,27 @@ dependencies = [ "tap", ] +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + [[package]] name = "x11rb" version = "0.13.2" @@ -9236,7 +11501,7 @@ dependencies = [ "flate2", "getrandom 0.3.4", "hmac 0.12.1", - "indexmap", + "indexmap 2.14.0", "lzma-rs", "memchr", "pbkdf2 0.12.2", diff --git a/Cargo.toml b/Cargo.toml index c61c8edcc..c59f21709 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ members = [ "crates/eggsec-secrets", "crates/eggsec-payloads", "crates/eggsec-udp-scan", + "crates/eggsec-frontend-client", + "crates/eggsec-gui", ] resolver = "2" @@ -69,12 +71,31 @@ chrono-tz = "0.10" unicode-normalization = "0.1" lru = "0.18" uuid = { version = "1", features = ["v4", "serde"] } +# JSON Schema derivation for the canonical request DTOs (ADR-0008). `derive` +# only — the chrono/uuid/url/... integrations are not used by eggsec's +# request structs, and `default-features = false` keeps them out of the graph. +schemars = { version = "1", default-features = false, features = ["derive", "std"] } eggsec-daemon-protocol = { path = "crates/eggsec-daemon-protocol", version = "0.1.0" } bytes = "1" http = "1" eggsec-transport = { path = "crates/eggsec-transport", version = "0.1.0" } eggsec-transport-eggfetch = { path = "crates/eggsec-transport-eggfetch", version = "0.1.0" } eggsec-udp-scan = { path = "crates/eggsec-udp-scan", version = "0.1.0" } +eggsec-frontend-client = { path = "crates/eggsec-frontend-client", version = "0.1.0" } + +# Desktop GUI shell (ADR-0009). Every pin below is EXACT (`=`), not a caret: +# the Tauri 2.12 / tauri-utils 2.10 / tauri-macros 2.7 lines all declare +# MSRV 1.90, which is above this workspace's 1.89 floor. `tauri` declares its +# runtime and utils dependencies with caret requirements, so without these +# pins a `cargo update` would float the closure onto the 1.90 line and break +# `make check-msrv`. The GUI crate depends on each of these directly for that +# reason — they hold the transitive closure on the MSRV-safe line. +tauri = { version = "=2.11.6", default-features = false } +tauri-build = { version = "=2.6.3" } +tauri-runtime = { version = "=2.11.3" } +tauri-runtime-wry = { version = "=2.11.4" } +tauri-macros = { version = "=2.6.3" } +tauri-utils = { version = "=2.9.3" } [profile.release] lto = true diff --git a/Makefile b/Makefile index ffd758463..682c00261 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,33 @@ # Test Infrastructure for Eggsec # ================================ -.PHONY: test test-fast test-slow test-unit test-integration test-nse test-coverage test-ci test-feature-matrix test-architecture-guards test-tui-pty check-no-default check check-deps check-python check-full check-feature-profiles check-features-individual clippy clippy-domain release-check fmt build clean help +.PHONY: test test-fast test-slow test-unit test-integration test-nse test-coverage test-ci test-feature-matrix test-architecture-guards test-tui-pty check-no-default check check-deps check-gui check-python check-full check-feature-profiles check-features-individual clippy clippy-domain release-check fmt build clean help + +# ── Desktop GUI shell profile ───────────────────────────────────────────── +# +# The `shell` feature carries the Tauri v2 dependency, so compiling it needs +# the platform webview SDK. Linux needs the webkit2gtk development packages; +# macOS and Windows ship the webview with the OS, so the gate is open there. +# +# The gate follows the discipline of scripts/check-features-individual.sh: +# an ABSENT prerequisite is a SKIP with the reason named, while a PRESENT +# prerequisite whose build breaks is a hard FAIL -- the build error is never +# swallowed. `make check-gui` is the ungated escape hatch: it always runs and +# reports cargo's own error. +GUI_SHELL_PREREQ_HINT = Linux: libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf pkg-config + +# Runs "$(1)" when the platform webview prerequisite is present; otherwise +# prints a SKIP line naming the prerequisite and succeeds. +define GUI_SHELL_GATE +@if [ "$$(uname -s)" != "Linux" ]; then \ + $(1); \ +elif command -v pkg-config >/dev/null 2>&1 \ + && { pkg-config --exists webkit2gtk-4.1 2>/dev/null || pkg-config --exists webkit2gtk-4.0 2>/dev/null; }; then \ + $(1); \ +else \ + echo "SKIP: desktop GUI shell profile (prerequisite absent: $(GUI_SHELL_PREREQ_HINT))."; \ +fi +endef # Default: run unit tests only (fast feedback loop) test: test-unit @@ -44,6 +70,15 @@ clippy: cargo clippy -p eggsec-core -p eggsec-tool-core -p eggsec-report-model -p eggsec-output -p eggsec-runtime -p eggsec-ui-model -p eggsec-agent -p eggsec-transport -p eggsec-transport-eggfetch -p eggsec-policy -- -D warnings cargo clippy -p eggsec-tui -p eggsec-cli -- -D warnings cargo clippy -p eggsec-secrets -p eggsec-payloads -p eggsec-service-db -p eggsec-udp-scan -- -D warnings + # The operation-schema module is behind a feature, so the plain + # `-p eggsec-runtime` lint above never compiles it. Lint the feature on. + cargo clippy -p eggsec-runtime --features schema -- -D warnings + # The daemon protocol and the frontend client are the wire contract for + # every frontend; they carry published types, so they are linted too. + cargo clippy -p eggsec-daemon-protocol -p eggsec-frontend-client -- -D warnings + # The desktop GUI shell (Tauri) is a separate profile that needs the + # platform webview SDK, so it is gated on that prerequisite. + $(call GUI_SHELL_GATE,cargo clippy -p eggsec-gui --features shell -- -D warnings) # Lint domain/platform crates with their relevant features (deep checks only: # heavier closures, may need system prerequisites like libssl-dev). @@ -96,6 +131,10 @@ check-msrv: cargo +1.89 check -p eggsec-transport cargo +1.89 check -p eggsec-transport-eggfetch cargo +1.89 check -p eggsec --no-default-features + # The desktop GUI shell profile under the declared MSRV. Same + # prerequisite gate as `make check`: absent -> SKIP, present but + # broken -> FAIL. + $(call GUI_SHELL_GATE,cargo +1.89 check -p eggsec-gui --features shell) # Dependency advisory/license/source policy (Phase F supply-chain hardening). # Canonical gate: `deny.toml` via cargo-deny over the full workspace closure @@ -115,6 +154,10 @@ check-deps: check: cargo fmt --all --check cargo check --workspace --no-default-features + # The desktop GUI shell profile (Tauri). The workspace check above + # covers the GUI's non-shell profile only; the shell profile needs the + # platform webview SDK, so it is gated on that prerequisite. + $(call GUI_SHELL_GATE,cargo check -p eggsec-gui --features shell) # Build the *test* targets for the no-default-features profile too: # `cargo check --workspace` only compiles library/binary targets, so a # feature-gated `use eggsec::commands` in tests/ can break unnoticed. @@ -138,6 +181,14 @@ check: cargo test -p eggsec-tui --lib --no-fail-fast bash scripts/check-architecture-guards.sh +# Desktop GUI shell profile (Tauri), UNGATED: it always runs, so a broken +# shell build is a hard failure and a host without the webview SDK gets +# cargo's own error message instead of a silent skip. +check-gui: + @echo "Desktop GUI shell profile (prerequisite: $(GUI_SHELL_PREREQ_HINT))." + cargo check -p eggsec-gui --features shell + cargo clippy -p eggsec-gui --features shell -- -D warnings + # Optional broad validation (pre-release, not required for merge) # Note: dependency policy (`check-deps`) already runs inside `check`; this # target adds domain lint and representative feature profiles only. @@ -194,6 +245,7 @@ help: @echo "Primary (run these):" @echo " make check - Full mandatory Rust CI contract (format, lint, test, guards, deps)" @echo " make check-deps - Dependency advisory/license/source policy (cargo deny)" + @echo " make check-gui - Desktop GUI shell profile (check + clippy, ungated)" @echo " make check-python - Python CI check (one build, all checks)" @echo " make test - Unit tests only (default)" @echo " make check-full - Optional broad validation (pre-release)" diff --git a/architecture/audit.md b/architecture/audit.md index 9b4d49315..1e1731285 100644 --- a/architecture/audit.md +++ b/architecture/audit.md @@ -2,7 +2,7 @@ ## Role & Responsibilities -`audit.rs` provides a single `EnforcementAuditEvent` model for consistent audit records across all execution surfaces (CLI, TUI, REST, MCP, gRPC, Agent, CI). Every meaningful enforcement decision produces an audit event that can be used for debugging, compliance reporting, and agent workflow correlation. +`audit.rs` provides a single `EnforcementAuditEvent` model for consistent audit records across all execution surfaces (CLI, TUI, desktop GUI, REST, MCP, gRPC, Agent, CI). Every meaningful enforcement decision produces an audit event that can be used for debugging, compliance reporting, and agent workflow correlation. > **Corrections (verified against source 2026-10-06):** `EnforcementAuditEvent` (15 fields), `AuditOutcome` (5 variants), all 21 tests + line cites, and all key-function cites re-verified **unchanged**. Fixed stale cites: `lib.rs` re-export `:205-206` → `:219-221`; REST audit site `rest.rs:743` → `:749`; gRPC audit site `grpc.rs:641` → `:649`; MCP audit site `server.rs:592` → `:598`; `tracing::info!` `:191` → `:192` and `tracing::warn!` `:205` → `:206`; `audit_event_from_preflight` hardcoded `confirmed=false` `:170` → `:169`. @@ -147,6 +147,7 @@ Delegates to `audit_event_from_enforcement_outcome` with hardcoded: |---------|:------------:|----------------------|:--------------:|---------------| | CLI | Yes | Accepted overrides include class+reason | None | `commands/handlers/` (via `EnforcementContext`) | | TUI | Yes | Accepted overrides include class+reason | None | `eggsec-tui` (via `EnforcementContext`) | +| Desktop GUI | Yes | Accepted overrides include class+reason | None | Via `EnforcementContext` (manual surface, same as CLI/TUI) | | REST | Yes | Never (REST never confirms) | `generate_correlation_id()` | `tool/protocol/rest.rs:749` | | MCP | Yes | Never (MCP never confirms) | JSON-RPC request id | `tool/protocol/mcp/handlers/server.rs:598` | | gRPC | Yes | Never (gRPC never confirms) | Request correlation | `tool/protocol/grpc.rs:649` | diff --git a/architecture/compile_time_baseline.md b/architecture/compile_time_baseline.md index e59d94466..687c80f48 100644 --- a/architecture/compile_time_baseline.md +++ b/architecture/compile_time_baseline.md @@ -1,6 +1,6 @@ # Compile Time Baseline -> **Note:** This document is a historical record of crate-splitting passes. The workspace now has 23 crates (verified 2026-10-06); the NSE runtime shown in this older layout was subsequently extracted to [eggstack/eggsec-nse](https://github.com/eggstack/eggsec-nse). This document covers up to the third pass with 12 crates. For current workspace structure, see `architecture/overview.md`. +> **Note:** This document is a historical record of crate-splitting passes. The workspace now has 24 crates (verified 2026-10-23); the NSE runtime shown in this older layout was subsequently extracted to [eggstack/eggsec-nse](https://github.com/eggstack/eggsec-nse). This document covers up to the third pass with 12 crates. For current workspace structure, see `architecture/overview.md`. ## Context diff --git a/architecture/config.md b/architecture/config.md index 7cb670776..c1ef6923f 100644 --- a/architecture/config.md +++ b/architecture/config.md @@ -109,7 +109,7 @@ All source files live under `crates/eggsec/src/config/`: | Type | File:Line | Variants | Purpose | |------|-----------|----------|---------| | `OperationRisk` | `policy.rs` | 15 | Risk tier ordering (Passive → AgentAutonomous) | -| `ExecutionSurface` | `policy.rs` | 9 | Caller origin identity | +| `ExecutionSurface` | `policy.rs` | 10 | Caller origin identity | | `ExecutionProfile` | `policy.rs` | 5 | Trust boundary for enforcement | | `OperationMode` | `policy.rs` | 3 | Session safety boundary | | `Capability` | `policy.rs` | 19 | Operation capability declarations | @@ -172,22 +172,25 @@ tool calls). Growth in either registry without the other is drift — see the | Surface | Profile | Manual Override | File:Line | |---------|---------|:---:|-----------| -| `CliManual` | `ManualPermissive` | Yes | `eggsec-policy/src/policy.rs:387` | -| `TuiManual` | `ManualPermissive` | Yes | `eggsec-policy/src/policy.rs:387` | -| `CliManualStrict` | `ManualGuarded` | No | `eggsec-policy/src/policy.rs:388` | -| `TuiManualStrict` | `ManualGuarded` | No | `eggsec-policy/src/policy.rs:388` | -| `McpServer` | `McpStrict` | No | `eggsec-policy/src/policy.rs:389` | -| `SecurityAgent` | `AgentStrict` | No | `eggsec-policy/src/policy.rs:390` | -| `Ci` | `CiStrict` | No | `eggsec-policy/src/policy.rs:391` | -| `RestApi` | `McpStrict` | No | `eggsec-policy/src/policy.rs:392` | -| `GrpcApi` | `McpStrict` | No | `eggsec-policy/src/policy.rs:393` | +| `CliManual` | `ManualPermissive` | Yes | `eggsec-policy/src/policy.rs:393` | +| `TuiManual` | `ManualPermissive` | Yes | `eggsec-policy/src/policy.rs:393` | +| `DesktopGuiManual` | `ManualPermissive` | Yes | `eggsec-policy/src/policy.rs:393` | +| `CliManualStrict` | `ManualGuarded` | No | `eggsec-policy/src/policy.rs:396` | +| `TuiManualStrict` | `ManualGuarded` | No | `eggsec-policy/src/policy.rs:396` | +| `McpServer` | `McpStrict` | No | `eggsec-policy/src/policy.rs:397` | +| `SecurityAgent` | `AgentStrict` | No | `eggsec-policy/src/policy.rs:398` | +| `Ci` | `CiStrict` | No | `eggsec-policy/src/policy.rs:399` | +| `RestApi` | `McpStrict` | No | `eggsec-policy/src/policy.rs:400` | +| `GrpcApi` | `McpStrict` | No | `eggsec-policy/src/policy.rs:401` | + +The desktop GUI is a **frontend, not a new policy class**: `DesktopGuiManual` derives the same `ManualPermissive` profile as `CliManual` and `TuiManual`, honors manual overrides, and is never agent-controlled. There is no strict GUI variant, and the GUI reuses the existing `manual_exposable` exposure flag rather than introducing a second exposure flag — so it adds no new policy semantics to the catalog. ### Capability Classification Baseline capabilities allowed by default for strict profiles (no explicit allow needed): - `PassiveFingerprint`, `ActiveProbe`, `Crawl`, `WafDetect` -Defined by `baseline_allowed_capability()` at `eggsec-policy/src/policy.rs:562`. All other capabilities require explicit listing in `ExecutionPolicy::allowed_capabilities` for strict automated profiles. +Defined by `baseline_allowed_capability()` at `eggsec-policy/src/policy.rs:579`. All other capabilities require explicit listing in `ExecutionPolicy::allowed_capabilities` for strict automated profiles. ## Enforcement Flow diff --git a/architecture/daemon.md b/architecture/daemon.md index 7c8c0de44..948449bf6 100644 --- a/architecture/daemon.md +++ b/architecture/daemon.md @@ -2,6 +2,8 @@ Two crates provide the persistent session host and its IPC wire format: `eggsec-daemon-protocol` (shared types, RBAC) and `eggsec-daemon` (server, persistence, optional HTTP transport). Together they enable multi-client session management, background task execution, and durable state across restarts. +**Corrections (2026-10-23)**: `ClientCommand` 15 → **16** variants (new `DescribeOperations`), `ServerMessage` 14 → **15** variants (new `Operations`); `eggsec-daemon-protocol` is now **4** source files (new `operations` module) and depends on `eggsec-runtime` + `eggsec-policy`; `DaemonCapabilities` gained the `operation_schema` flag; session-scoped audit events now record the session's runtime surface label instead of the blanket `"daemon"`. `ErrorCode` stays at 11 variants and the HTTP route table stays at 14 routes. + **Corrections (2026-10-06 re-verification)**: `rusqlite` dependency corrected 0.31 → **0.32** (cleared RUSTSEC-2024-0363); the `eggsec-daemon` dependency list was missing seven crates (`serde`, `tokio-util`, `tracing-subscriber`, `rustc-hash`, `thiserror`, `uuid`, `async-trait`); `full-executor` now also enables the engine's `cli` feature. All variant counts, permission mappings, route tables, socket/timeout constants, schema version, and `file:line` cites were re-checked against source and are current — no other changes. ## Role & Responsibilities @@ -19,7 +21,7 @@ Two crates provide the persistent session host and its IPC wire format: `eggsec- | Crate | Path | Dependencies | Features | |-------|------|-------------|----------| -| `eggsec-daemon-protocol` | `crates/eggsec-daemon-protocol/` | `eggsec-runtime` only (no persistence, transport, or TUI deps) | None | +| `eggsec-daemon-protocol` | `crates/eggsec-daemon-protocol/` | `eggsec-runtime` + `eggsec-policy` (no persistence, transport, or TUI deps) | None | | `eggsec-daemon` | `crates/eggsec-daemon/` | `eggsec-runtime`, `eggsec-daemon-protocol`, `rusqlite 0.32 (bundled)`, `tokio`, `tokio-util`, `serde`, `serde_json`, `tracing`, `tracing-subscriber`, `rustc-hash`, `thiserror`, `uuid`, `async-trait`, `anyhow`, `clap`; optional `eggsec` | `http-api` (axum + async-stream + futures), `full-executor` (`dep:eggsec` + `eggsec/cli`) | Architecture guards enforce: @@ -30,15 +32,18 @@ Architecture guards enforce: ## Architecture -### eggsec-daemon-protocol (3 source files) +### eggsec-daemon-protocol (4 source files) | Module | File | Contents | |--------|------|----------| -| `lib` | `src/lib.rs` | Re-exports `client_registry` and `protocol` modules | -| `protocol` | `src/protocol.rs` | `ClientCommand` (15 variants), `ServerMessage` (14 variants), `ErrorCode` (11 variants), `TransportKind` (4 variants), `DaemonCapabilities`, `TransportCapability`, `DaemonRequestContext`, `DAEMON_PROTOCOL_VERSION` (= 2; v2 adds `GetTaskResult`/`TaskResult`) | +| `lib` | `src/lib.rs` | Re-exports `client_registry`, `operations`, and `protocol` modules | +| `protocol` | `src/protocol.rs` | `ClientCommand` (16 variants), `ServerMessage` (15 variants), `ErrorCode` (11 variants), `TransportKind` (4 variants), `DaemonCapabilities`, `TransportCapability`, `DaemonRequestContext`, `DAEMON_PROTOCOL_VERSION` (= 2; v2 adds `GetTaskResult`/`TaskResult`) | | `client_registry` | `src/client_registry.rs` | `ClientKind` (7 variants), `ClientRole` (4 variants), `CommandPermission` (6 variants), `ClientInfo`, `ClientAccessRule`, `SessionAccess`, `ClientRegistry`, `check_permission()`, `command_permission()` | +| `operations` | `src/operations.rs` | `OperationDescription`, `TaskKindDescription`, `DescribeOperationsResponse`, `describe_operations()` — the read-only publication of the canonical operation catalog plus the derived request schema | + +`eggsec-daemon-protocol` gained an `eggsec-policy` dependency (a pure semantic kernel: no Tokio, no I/O) so that the published operation descriptions are **read from** `eggsec_policy::ALL_OPERATION_METADATA` rather than transcribed. It still has no workspace dependency beyond `eggsec-runtime` and `eggsec-policy`. -#### ClientCommand — 15 variants (`protocol.rs:75`) +#### ClientCommand — 16 variants (`protocol.rs:94`) | # | Variant | Fields | Permission | |---|---------|--------|-----------| @@ -57,8 +62,9 @@ Architecture guards enforce: | 13 | `ApprovePolicy` | `request_id`, `session_id: SessionId`, `task_id: TaskId`, `approved: bool`, `reason: Option` | Approver | | 14 | `ListPersistedSessions` | `request_id` | DeclaredClient | | 15 | `GetPersistedSnapshot` | `request_id`, `session_id: SessionId` | DeclaredClient | +| 16 | `DescribeOperations` | `request_id` | DeclaredClient | -#### ServerMessage — 14 variants (`protocol.rs:215`) +#### ServerMessage — 15 variants (`protocol.rs:253`) | # | Variant | Fields | |---|---------|--------| @@ -76,12 +82,35 @@ Architecture guards enforce: | 12 | `SessionClosed` | `request_id` | | 13 | `PersistedSessions` | `request_id`, `sessions: Vec` | | 14 | `PersistedSnapshot` | `request_id`, `snapshot: Option` | +| 15 | `Operations` | `request_id`, `operations: DescribeOperationsResponse` | `TaskResult` (Phase E WS5) is durable single-task retrieval: live snapshot first, persisted snapshot fallback, `None` outcome while active. See [docs/DAEMON_PARITY.md](../docs/DAEMON_PARITY.md) for reconnect semantics. -#### ErrorCode — 11 variants (`protocol.rs:55`) +#### DaemonCapabilities + +| Field | Type | Purpose | +|-------|------|---------| +| `runtime` | `RuntimeCapabilities` | Runtime-level capabilities (task kinds, cancellation, transports) | +| `transports` | `Vec` | Available daemon transports | +| `operation_schema` | `bool` | Whether this daemon can publish the operation catalog and the derived request schema via `ClientCommand::DescribeOperations` | + +`operation_schema` is `#[serde(default)]`, so an older client still decodes a newer daemon's capabilities and vice versa — the field defaults to `false` rather than failing the whole handshake. A client that sees `false` — or that receives `ErrorCode::UnsupportedCommand` from a daemon too old to know the command — must **degrade to a static form set** rather than fail. + +#### DescribeOperations — the operation/schema publication command + +`ClientCommand::DescribeOperations { request_id }` → `ServerMessage::Operations { request_id, operations }`. + +- **Read-only and additive**: it creates no session, mutates no task state, and takes part in no authorization decision. The payload is assembled from immutable registry data, so it is safe to serve concurrently and reproduces exactly. +- **Requires a declared client identity** — the same rule as the other daemon-wide reads such as `ListPersistedSessions` — but **no session and no session role**: the command carries no session id, so it is answerable before any session exists. +- **Carries** `DescribeOperationsResponse`: every canonical operation from the catalog (`OperationDescription`), every task-kind wire shape with its JSON Schema (`TaskKindDescription`), and the whole `TaskKind` schema in its adjacently-tagged wire shape (`{"kind": ..., "params": ...}`). +- **Descriptive only**: the published identity comes from the canonical `OperationMetadata` catalog and the parameter structure is mechanically derived from the canonical request DTOs (`eggsec-runtime`'s optional `schema` feature). Nothing in the published payload grants, narrows, or widens what the engine will run — it is a view of the operation set for frontends that render a form for an operation they can already invoke. The engine's own enforcement and validation remain authoritative. +- **Graceful degradation is mandatory**: a daemon that does not know the command answers `ErrorCode::UnsupportedCommand`, and the client MUST treat that as "schema unavailable" and fall back to a static form set. + +The HTTP/SSE transport is unchanged: no new axum route was added for this command, so the route table below still has 14 routes. + +#### ErrorCode — 11 variants (`protocol.rs:67`) | # | Variant | Meaning | |---|---------|---------| @@ -97,15 +126,23 @@ first, persisted snapshot fallback, `None` outcome while active. See | 10 | `Unsupported` | Operation not wired yet (e.g. ApprovePolicy) | | 11 | `InvalidState` | Operation cannot proceed in current state | -#### ClientKind — 7 variants (`client_registry.rs:11`) +#### ClientKind — 8 variants (`client_registry.rs:11`) -`Cli`, `Tui`, `DaemonInternal`, `Mcp`, `Rest`, `Agent`, `Unknown` (default) +`Cli`, `Tui`, `Gui`, `DaemonInternal`, `Mcp`, `Rest`, `Agent`, `Unknown` (default) -#### ClientRole — 4 variants (`client_registry.rs:25`) +`Gui` is the desktop GUI frontend's kind (`client_registry.rs:14-23`). It is +**additive on the wire**: a daemon that predates the variant fails to +deserialize the `DeclareClient` command and rejects the client. That is a +fail-closed outcome, not a silent misclassification — an old daemon never +accepts a GUI it cannot identify. `DAEMON_PROTOCOL_VERSION` stays at `2`: the +`ClientCommand` and `ServerMessage` variant sets are unchanged, and the new +kind is carried inside the existing `DeclareClient` payload. + +#### ClientRole — 4 variants (`client_registry.rs:31`) `Owner`, `Controller`, `Observer`, `Approver` -#### CommandPermission — 6 variants (`client_registry.rs:37`) +#### CommandPermission — 6 variants (`client_registry.rs:43`) `Public`, `DeclaredClient`, `Observer`, `Controller`, `Owner`, `Approver` @@ -114,7 +151,7 @@ first, persisted snapshot fallback, `None` outcome while active. See | Module | File | Purpose | |--------|------|---------| | `main` | `src/main.rs` | Binary entry point: CLI args (clap), store setup, host creation, shutdown signal, event persistence loop | -| `lib` | `src/lib.rs` | Library root: re-exports `protocol` and `client_registry` from daemon-protocol; declares `host`, `host_auth`, `host_persistence`, `server`, `config`, `error`, `store`, `client`; `http` behind `http-api` | +| `lib` | `src/lib.rs` | Library root: re-exports `protocol`, `client_registry`, and `operations` from daemon-protocol; declares `host`, `host_auth`, `host_persistence`, `server`, `config`, `error`, `store`, `client`; `http` behind `http-api` | | `host` | `src/host.rs` | `DaemonHost`: command dispatch, recovery (facade; RBAC/persistence delegated) | | `host_auth` | `src/host_auth.rs` | RBAC ownership/role helpers (`role_for_session`, `may_observe_session`) | | `host_persistence` | `src/host_persistence.rs` | Persistence fan-out (`PERSISTENCE_TASK_TIMEOUT` = 30s at `:13`, `persistence_with_timeout` at `:29`, `record_audit_event_logged`) | @@ -149,6 +186,36 @@ Key behaviors: - **Socket permissions**: 0o600 after bind (`server.rs:100`) - **Subscribe**: long-lived; receives broadcast events filtered by session ID; further commands handled inline during streaming +### Desktop GUI Submission and Event Flow + +The desktop GUI is a **daemon-only** frontend: it holds no engine code and +performs no outbound HTTP. Every engine request travels over this Unix socket. + +``` +GUI window + └─► connect(socket_path, ClientIdentity { kind: Gui, label: "eggsec-gui", request_prefix: "gui-" }) + ├─► DeclareClient { kind: Gui } → ClientId (a pre-Gui daemon rejects it: fail closed) + ├─► Health → protocol_version must equal DAEMON_PROTOCOL_VERSION + ├─► Capabilities → operation_schema must be true + ├─► CreateSession { surface: DesktopGuiManual, scope: … } + ├─► DescribeOperations → the published task kinds + request schemas + └─► Subscribe → one subscription for the session's lifetime + +GUI form submit + └─► SubmitTask { request: RunRequest { task_kind: { kind, params }, surface: DesktopGuiManual, … } } + └─► runtime bridge → approve_run_request_bundle() → dispatch → RuntimeEvent + +RuntimeEvent ──► the GUI's single `eggsec://task-event` channel + (task_upsert / logs / counters); the GUI's own state is bounded +``` + +The GUI never sets the scope or the surface from the webview: the surface is +`DesktopGuiManual`, and the scope is resolved by the daemon's runtime bridge +from the session. The GUI's session is therefore auditable as +`desktop-gui-manual` — see the Audit Trail section below. + +See [desktop_gui.md](desktop_gui.md) for the GUI's own side of this flow. + ### Startup Recovery ``` @@ -197,16 +264,28 @@ Lifecycle commands (CreateSession, SubmitTask, CancelTask, CancelActive, CloseSe | Command | Public | DeclaredClient | Observer | Controller | Owner | Approver | |---------|:------:|:--------------:|:--------:|:----------:|:-----:|:--------:| | `Health`, `Capabilities` | ✓ | — | — | — | — | — | -| `DeclareClient`, `CreateSession`, `ListSessions`, `ListPersistedSessions`, `GetPersistedSnapshot` | — | ✓ | — | — | — | — | +| `DeclareClient`, `CreateSession`, `ListSessions`, `ListPersistedSessions`, `GetPersistedSnapshot`, `DescribeOperations` | — | ✓ | — | — | — | — | | `GetSnapshot`, `GetTaskResult`, `Subscribe` | — | — | ✓ | ✓ | ✓ | ✓ | | `SubmitTask`, `CancelTask`, `CancelActive` | — | — | ✗ | ✓ | ✓ | ✗ | | `CloseSession` | — | — | ✗ | ✓ | ✓ | ✗ | | `ApprovePolicy` (manual surface) | — | — | ✗ | ✓ | ✓ | ✓ | | `ApprovePolicy` (strict surface) | — | — | ✗ | ✗ | ✓ | ✗ | +The manual-approval arm of `check_permission` covers `TuiManual`, `CliManual` +**and `DesktopGuiManual`** (`client_registry.rs:191-204`). The desktop GUI's +surface is manual by classification in `eggsec-policy`, so the RBAC matrix and +the policy crate must agree about which surfaces are manual; leaving the GUI +out of the arm would make them disagree. + +`ApprovePolicy` remains **unwired** in practice: the daemon answers it with +`ErrorCode::Unsupported` (`host.rs:829-858`), so no approval is granted either +way. The manual arm is the permission the command *would* need, not a grant. +The desktop GUI handles `PolicyDecisionRequired` defensively and offers no +approval affordance — see [desktop_gui.md](desktop_gui.md). + ### Session Access Control -Three-tier resolution for `GetPersistedSnapshot` (`host.rs:877-930`): +Three-tier resolution for `GetPersistedSnapshot` (`host.rs:915-1019`): 1. In `session_access` + authorized (owner or allow-listed) → allow 2. In `session_access` + NOT authorized → deny immediately 3. NOT in `session_access` (recovered session) → check `snapshot.owner_client_id`: @@ -216,7 +295,7 @@ Three-tier resolution for `GetPersistedSnapshot` (`host.rs:877-930`): ### Persisted Session Listing Policy -`ListPersistedSessions` (`host.rs:825-876`): +`ListPersistedSessions` (`host.rs:863-914`): - `DaemonInternal` clients: see all sessions - CLI/TUI clients: see only own sessions (owner match) + legacy sessions without owner @@ -250,7 +329,7 @@ Three-tier resolution for `GetPersistedSnapshot` (`host.rs:877-930`): ## Integration Points -- **TUI attach mode**: `eggsec-tui` connects as a daemon client via `DaemonClient`, creates sessions, submits tasks, and streams events +- **TUI attach mode**: `eggsec-tui` connects as a daemon client via `eggsec-frontend-client`'s `DaemonRuntimeClient` (the shared frontend runtime-client contract), creates sessions, submits tasks, and streams events - **CLI daemon commands**: `eggsec daemon history` and `eggsec daemon show ` use `ListPersistedSessions`/`GetPersistedSnapshot` via `DaemonClient` - **Engine runtime_bridge**: `EggsecRuntimeExecutor` (behind `full-executor`) bridges runtime DTOs to engine dispatch - **Python daemon-client**: provisional `eggsec.daemon` module uses `eggsec-daemon-protocol` types @@ -282,6 +361,18 @@ schema_meta ( Schema version: `2` (stored in `schema_meta`). Migration refuses to load when stored version > current. +## Audit Trail + +`PersistedAuditEvent.surface` records the **session's runtime surface label**, not a blanket `"daemon"` literal. The label set is the one the engine's `ExecutionSurface` produces: `cli-manual`, `cli-manual-strict`, `tui-manual`, `tui-manual-strict`, `desktop-gui-manual`, `mcp-server`, `rest-api`, `grpc-api`, `security-agent`, `ci`. + +| Audit action | `surface` | +|--------------|-----------| +| `create-session` | the surface the session was created with | +| `submit-task`, `cancel-task`, `cancel-active`, `close-session`, `command-denied:` | the session's current surface label | +| `declare-client`, `daemon-recovery`, `approve-policy` | `daemon` — these events have no session | + +A desktop GUI session is therefore auditable as `desktop-gui-manual` and a TUI session as `tui-manual`, which is what makes the persisted trail usable for telling frontends apart after the fact. The label is read from the session's registered `RuntimeSurface` (`eggsec-runtime/src/request.rs:54`), so it always matches the surface the engine's runtime bridge evaluates. + ## Configuration (`config.rs:6-26`) | Field | Type | Default | Purpose | @@ -316,10 +407,12 @@ Schema version: `2` (stored in `schema_meta`). Migration refuses to load when st ## See Also - [runtime.md](runtime.md) — Runtime orchestrator that `DaemonHost` wraps +- [frontend_client.md](frontend_client.md) — Frontend-neutral runtime-client contract the TUI and the GUI bind to +- [desktop_gui.md](desktop_gui.md) — The desktop GUI, the daemon-only frontend - [ui_model.md](ui_model.md) — View DTOs for daemon session/task state - [overview.md](overview.md) — System-wide architecture, dependency map - [runtime_bridge.md](runtime_bridge.md) — Engine-side surface conversion and approval - [tui.md](tui.md) — TUI daemon attach mode - [cli_commands.md](cli_commands.md) — CLI daemon/session/task commands -*Last verified against source: 2026-10-06 (full re-verification: variant counts, permission mapping, HTTP route table, socket/timeout constants, SQLite schema v2, dependency set, all `file:line` cites); earlier passes 2026-08-25 / 2026-09-22 / 2026-09-25* +*Last verified against source: 2026-10-23 (`ClientKind::Gui` added — 7 → 8 variants; the manual-approval arm of `check_permission` now covers `DesktopGuiManual`; the desktop GUI's submission and event flow); earlier passes 2026-10-23 (DescribeOperations command + Operations response, `DaemonCapabilities.operation_schema`, session-scoped audit surface labels, daemon-protocol dependency set and source-file count); earlier passes 2026-08-25 / 2026-09-22 / 2026-09-25 / 2026-10-06 (full re-verification: variant counts, permission mapping, HTTP route table, socket/timeout constants, SQLite schema v2, dependency set, all `file:line` cites)* diff --git a/architecture/desktop_gui.md b/architecture/desktop_gui.md new file mode 100644 index 000000000..d2d66d3ec --- /dev/null +++ b/architecture/desktop_gui.md @@ -0,0 +1,447 @@ +# Desktop GUI (Tauri Shell) + +The Eggsec desktop GUI is a **daemon-only** frontend: it reaches the engine +exclusively through the daemon's Unix socket, using the shared +`eggsec-frontend-client` contract. It links no engine code, spawns no +subprocess, and performs no outbound HTTP. + +Its shell is [Tauri v2](https://tauri.app), pinned to the 2.11.x line +(`ADR-0009`). The frontend assets are hand-written HTML, CSS and vanilla +JavaScript with **no build step and no npm dependency**. + +Decisions: `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` (the +daemon-only boundary), `plans/adrs/ADR-0009-gui-shell-technology-selection.md` +(the shell technology). + +## Role & Responsibilities + +| Responsibility | Owned by | Notes | +|----------------|----------|-------| +| The desktop window | `crates/eggsec-gui/src/shell.rs` | Tauri builder, managed state, command registration. | +| The IPC surface | `crates/eggsec-gui/src/commands.rs` | Eight narrow Tauri commands and one event channel. | +| The daemon connection | `crates/eggsec-gui/src/connection.rs` | Client identity, protocol check, session, catalog fetch. | +| The form engine | `crates/eggsec-gui/src/form.rs` | Schema property → control; control values → typed `RunRequest`. | +| Task state and result views | `crates/eggsec-gui/src/tasks.rs` | Bounded per-task retention, status, result rendering. | +| Command-line parsing | `crates/eggsec-gui/src/config.rs` | `--socket `. | +| Engine execution | *nobody here* | The daemon's executor owns it; the GUI only submits requests. | + +The crate ships a `src/lib.rs` library (for testability) and a thin +`src/main.rs` binary that calls `eggsec_gui::run()` +(`crates/eggsec-gui/src/lib.rs:60-64`). + +## Location & Feature Gating + +| Crate | Path | Feature | Notes | +|-------|------|---------|-------| +| `eggsec-gui` | `crates/eggsec-gui/` | `shell` (default) | The desktop GUI. Without `shell` the binary reports `GuiError::ShellNotBuilt` and exits non-zero (`crates/eggsec-gui/src/lib.rs:66-70`) rather than pretending to work. | + +The crate is a workspace member. Its dependencies are exactly +`eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and +`eggsec-ui-model` (`crates/eggsec-gui/Cargo.toml`). + +### Boundary rule + +The GUI **must not** depend on `eggsec` (the engine), `eggsec-daemon`, +`eggsec-cli` or `eggsec-tui` (`ADR-0007`). `eggsec-frontend-client`, +`eggsec-runtime`, `eggsec-daemon-protocol` and `eggsec-ui-model` are the only +workspace dependencies it may name, and the Tauri dependency may not appear in +any other crate. Both rules are enforced by the architecture guards (Checks +155 and 156 — see `docs/CI_ARCHITECTURE_GUARDS.md`). + +The consequence is that the GUI **cannot** enforce policy, resolve scope, or +dispatch an operation. It assembles a request and hands it to the daemon, which +does all three. The GUI has no `EnforcementContext`, no `Scope`, and no +`ApprovedExecution`. + +The GUI performs **no outbound HTTP**. All engine traffic travels over the +daemon's Unix socket. The crate therefore enables neither `tauri`'s +`rustls-tls` nor `native-tls` feature, and depends on neither `reqwest` nor +`rustls` nor `native-tls`: those crates stay out of the GUI's dependency +closure entirely, so the workspace's ring-only TLS invariant holds with no +exception (Check 157). + +## The Tauri Shell + +`crates/eggsec-gui/src/shell.rs` is the only place the shell framework is +wired up, and the module doc says so in as many words: the framework "appears +only in this module and in `commands.rs`" (`crates/eggsec-gui/src/shell.rs:3-4`). + +The builder registers the managed state and the eight IPC commands, then runs +the generated context (`crates/eggsec-gui/src/shell.rs:20-33`). + +### Window and configuration + +`crates/eggsec-gui/tauri.conf.json` declares one window: label `main`, title +`Eggsec`, 1200×800 with a 800×600 minimum, resizable +(`crates/eggsec-gui/tauri.conf.json:11-21`). `app.bundle.active` is `false` +(`crates/eggsec-gui/tauri.conf.json:26-28`) — the GUI is run from the build +tree, not installed as a bundle. + +### Capability model + +`crates/eggsec-gui/capabilities/default.json` grants `core:default` and +nothing else: `"permissions": ["core:default"]`, scoped to the `main` window. +**No plugin is enabled** — no http, no shell, no fs, no process, no updater. +Every engine request travels over the daemon's Unix socket, so the GUI needs no +plugin to reach the engine, and granting one would be pure attack surface. + +### Content Security Policy + +``` +default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; +connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; +frame-src 'none'; base-uri 'none' +``` + +(`crates/eggsec-gui/tauri.conf.json:23`). There is no wildcard source and no +remote origin. `object-src 'none'` and `frame-src 'none'` forbid plugin and +frame embedding outright; `base-uri 'none'` forbids a base-tag rewrite. The +only non-`'self'` source is the IPC scheme the webview needs to reach its own +host process. Check 158 fails the build if a wildcard or a `*` appears in +`connect-src`, `script-src` or `default-src`. + +## Version Pins — and why they are exact + +The Tauri dependency set is pinned with `=` requirements, not carets: + +| Crate | Pin | +|-------|-----| +| `tauri` | `=2.11.6` | +| `tauri-build` | `=2.6.3` | +| `tauri-runtime` | `=2.11.3` | +| `tauri-runtime-wry` | `=2.11.4` | +| `tauri-macros` | `=2.6.3` | +| `tauri-utils` | `=2.9.3` | + +(`Cargo.toml:93-98`.) + +**These pins are load-bearing. Do not loosen them.** + +The next lines up — Tauri 2.12, `tauri-utils` 2.10, `tauri-macros` 2.7 — all +declare **MSRV 1.90**, above this workspace's 1.89 floor. `tauri` declares its +runtime and utils dependencies with *caret* requirements, so without these +direct exact pins a plain `cargo update` floats the transitive closure onto the +1.90 line and breaks `make check-msrv`. The GUI crate depends on each of these +directly for exactly that reason: they hold the closure on the MSRV-safe line +(`Cargo.toml:86-92`). + +`tauri-build` and `tauri-utils` are unconditional build-dependencies, and +`tauri-build` requires `tauri-utils ^2.9.3`. That is why `tauri-utils` is +pinned exactly even in the `--no-default-features` profile — that profile is +what `make check` and `make check-msrv` build, so an unpinned `tauri-utils` +would break the MSRV gate even though the shell is off +(`crates/eggsec-gui/Cargo.toml`). + +## The Buildless Frontend + +`crates/eggsec-gui/frontend/` holds hand-written HTML, CSS and vanilla +JavaScript. There is **no `package.json`, no lockfile, no bundler, and no +build step**. `tauri.conf.json` sets `app.withGlobalTauri: true` +(`crates/eggsec-gui/tauri.conf.json:10`) so the webview can reach +`window.__TAURI__.core.invoke` without a module bundler. + +### JavaScript dependency policy + +**Zero npm dependencies.** A remote script source, a CDN import, or any +`package.json` at all is not permitted, for two reasons: + +1. The CSP has no remote origin, so a CDN import would be blocked by the + browser anyway — the policy and the dependency rule agree. +2. A remote script in a security tool is supply-chain surface that the + operator cannot audit from the source tree. The GUI's entire value is that + the bytes it runs are the bytes in this repository. + +`ADR-0009` allowed a JavaScript build step if it was justified. The +implementation went further and took none: the schema-driven form engine +means the frontend needs no code generation, so the toolchain buys nothing. + +## The Daemon Connection + +`crates/eggsec-gui/src/connection.rs` owns everything between the window and +the daemon. + +### Client identity + +The GUI presents itself as `ClientKind::Gui`, labelled `eggsec-gui`, with the +request-id namespace `gui-` (`crates/eggsec-gui/src/connection.rs:26`). The +`ClientIdentity` seam is documented in +[frontend_client.md](frontend_client.md); the point here is that the GUI +supplies its own identity rather than inheriting the TUI's. + +### Connection sequence + +`GuiConnection::connect` performs, in order: + +1. **Connect** to the Unix socket at the configured path. +2. **Protocol-version check** — the daemon's advertised `protocol_version` must + match `DAEMON_PROTOCOL_VERSION` (`crates/eggsec-gui/src/connection.rs:105`). + A mismatch is a hard failure, not a warning. +3. **Capability check** — the daemon must advertise the `operation_schema` + capability (`crates/eggsec-gui/src/connection.rs:118`, + `crates/eggsec-daemon-protocol/src/protocol.rs:61`). Without it the daemon + cannot publish the request schemas the form engine is built on, so the GUI + refuses to connect rather than presenting empty forms. +4. **Session creation** with the `DesktopGuiManual` surface + (`crates/eggsec-gui/src/connection.rs:129`). +5. **Catalog fetch** — `describe_operations()` yields the published task kinds + and their schemas (`crates/eggsec-gui/src/connection.rs:140`). + +`ApprovePolicy` remains unwired: the daemon answers it with +`ErrorCode::Unsupported` (`crates/eggsec-daemon/src/host.rs:829-858`). No +approval is granted either way. The GUI handles `PolicyDecisionRequired` +defensively and offers **no approval affordance** — there is no button that +could do anything. + +### The no-op executor condition + +The GUI requires an already-running `eggsec-daemon --full-executor`. It does +**not** spawn, supervise, or stop a daemon (`crates/eggsec-gui/src/shell.rs:12-16`). + +`eggsec daemon start` and a default-built `eggsec-daemon` both host a no-op +executor that rejects every task — the CLI's start path uses a `NoopExecutor` +that returns `UnsupportedTaskKind` +(`crates/eggsec-cli/src/daemon_cli.rs:584-605`), and the daemon crate's +`full-executor` feature is opt-in (`crates/eggsec-daemon/Cargo.toml`). The GUI +therefore does two things instead of offering a submit button that cannot work: + +- Its connection diagnostic names the socket path and the exact command that + starts a usable daemon (`crates/eggsec-gui/src/connection.rs:51`). +- When the connected daemon advertises **no task kinds**, the GUI reports the + no-op-executor condition explicitly + (`crates/eggsec-gui/src/connection.rs:160`). + +### Never retry in a tight loop + +The GUI never retries the connection in a tight loop. A failed connect is +reported to the operator with the socket path and the remedy, and the operator +retries deliberately. A retry loop against a missing daemon is a spin at 100% +CPU for a condition that only an operator can fix. + +## The IPC Command Surface + +Exactly eight Tauri commands, each a narrow pass-through +(`crates/eggsec-gui/src/commands.rs`, registered at +`crates/eggsec-gui/src/shell.rs:22-31`): + +| Command | Purpose | +|---------|---------| +| `connect_daemon(socket)` | Connect to the daemon and load the catalog. | +| `list_operations()` | The published operation catalog. | +| `list_task_kinds()` | The published task kinds. | +| `form_for(variant)` | The control set for one task kind. | +| `submit_task(variant, values)` | Assemble a `RunRequest` and submit it. | +| `cancel_task(task_id)` | Cancel one task. | +| `cancel_active()` | Cancel the task the GUI considers active. | +| `task_snapshot()` | The dashboard's view of tracked tasks. | + +**There is no generic "send any command" entry point.** The webview cannot +name a `ClientCommand` variant, cannot set the runtime surface, and cannot set +the scope. The surface is fixed by the GUI (`RuntimeSurface::DesktopGuiManual`, +`crates/eggsec-gui/src/form.rs:300`), and the scope is resolved by the daemon. + +### The event channel + +The webview receives exactly one event on the bus: `eggsec://task-event` +(`crates/eggsec-gui/src/commands.rs:28`). Its payload is one of three shapes — +`task_upsert`, `logs`, or `counters`. The GUI subscribes **once per session** +and never spawns a task per event: one forwarder task lives for the lifetime +of the subscription, coalescing log lines and flushing on a 100 ms interval +(`crates/eggsec-gui/src/commands.rs:488-504`). + +## The Form Engine + +`crates/eggsec-gui/src/form.rs` is the whole point of the GUI. There is **no +per-operation code anywhere**: no `match` or `switch` over the published +task-kind variant names, no hand-written field table, no per-operation +validation. A task kind the engine has not published yet gets a form with no +GUI change. + +### The control-kind mapping + +One published JSON Schema property maps to exactly one control +(`crates/eggsec-gui/src/form.rs:172-209`): + +| Schema shape | Control | Note | +|--------------|---------|------| +| `type: "string"` | `text` | | +| `type: "integer"` | `number` | | +| `type: "boolean"` | `checkbox` | Tri-state: unset, true, false. | +| `type: "array"` with string items | `list` | Repeatable text control. | +| `type: "object"`, array of non-strings, or an unconstrained schema | `json` | A JSON text area. | +| Any other scalar | `text` | Documented fallback; never panics, never drops the field. | + +The five control kinds are `text`, `number`, `checkbox`, `list` and `json` +(`crates/eggsec-gui/src/form.rs:36-47`). + +The numeric upper bound is derived from the schema's `format`, not from a +`maximum` keyword — the published schema states a `minimum` but never a +`maximum` (`crates/eggsec-gui/src/form.rs:221-234`). + +### Deterministic ordering + +Controls are sorted **required first, then alphabetically** +(`crates/eggsec-gui/src/form.rs:130-135`), so the form's layout does not shift +between runs. + +### The three-layer validation model + +This is the design to preserve. + +1. **Advisory, from the schema** — the control's declared type and bounds. + `check_value` (`crates/eggsec-gui/src/form.rs:296`) checks the supplied + value against the schema property. +2. **Exact, from the DTOs** — the assembled request is deserialized into the + *same* `RunRequest` the engine will deserialize + (`crates/eggsec-gui/src/form.rs:321`). A wrong-typed value is therefore + rejected by the engine's own rules, and the error names the field. +3. **Authoritative, in the engine** — the engine's own validation still decides + whether the task may run. + +Layers one and two save the operator a round trip. They never stand in for +layer three, and neither encodes a per-operation rule. + +### The "not provided" rule + +**A blank form field sends `null` — never `""`, `0`, `false` or `[]`.** + +This is a safety rule, not a style preference. Four published parameters carry +non-null serde defaults, and one of them is a fail-safe flag: `dry_run` +defaults to `true` (`crates/eggsec-runtime/src/request.rs:502`). A GUI that +sent `false` for an untouched field would silently turn a simulation into a +live action. + +In the Rust assembly path (`crates/eggsec-gui/src/form.rs:281-294`): + +- A field that is **required** and absent is an error. +- A **nullable optional** field absent is sent as `null`. +- A field that is **not required** and whose type does not accept `null` is + **omitted** from the request, so the request DTO applies its own default. + +The published schema's measured shape is **30 task-kind variants and 149 fields +in total** (`crates/eggsec-gui/src/form.rs:484`, +`crates/eggsec-daemon-protocol/src/operations.rs:211`). The shape is flat: +every property is a scalar, a list of strings, or an unconstrained value — no +nested objects, no `$ref`/`$defs` indirection, and no `enum` constraint. The +control mapping is written against exactly those shapes, with a documented +fallback for anything else (`crates/eggsec-gui/src/form.rs:514-589`). + +## The Task State + +`crates/eggsec-gui/src/tasks.rs` owns the GUI's view of running work. + +### Status + +The GUI's own status enum is `Queued`, `Running`, `Completed`, `Failed`, +`Cancelled`, `AwaitingPolicy` and `Unknown` +(`crates/eggsec-gui/src/tasks.rs:44-59`). `AwaitingPolicy` is the GUI's +addition: the runtime reports it as a separate event rather than a status. + +### Bounded retention + +**Unbounded retention is a disqualifying defect, not a tuning problem.** + +- Each task keeps at most **`MAX_LOG_LINES_PER_TASK` = 200** log lines in a + capped ring (`crates/eggsec-gui/src/tasks.rs:28`, `crates/eggsec-gui/src/tasks.rs:72-76`). + The ring counts what it drops. +- The event forwarder coalesces log lines and forwards at most + **`MAX_LOG_LINES_PER_FLUSH` = 50** per flush + (`crates/eggsec-gui/src/tasks.rs:35`), reporting the rest as dropped rather + than silently discarding them. +- Dropped lines are counted per task (`dropped_log_lines`, + `crates/eggsec-gui/src/tasks.rs:200`) and surfaced in the dashboard view + (`crates/eggsec-gui/src/tasks.rs:553-597`). + +### The event stream is the source of truth + +The GUI does not poll for task state. The daemon's event stream is the source +of truth; the GUI applies events to its registry and renders. This is why the +subscription happens once per session and why the forwarder coalesces rather +than spawning: a task per event would multiply the retention problem by the +event rate. + +## Result Rendering + +The renderer registry in `eggsec-ui-model` is the **only** source of per-kind +metadata for a result view — the GUI imports `renderer_for_kind` from +`eggsec_ui_model::renderer_registry` (`crates/eggsec-gui/src/tasks.rs:20`) and +consults nothing else (`crates/eggsec-gui/src/tasks.rs:444-477`). A kind the +registry does not know degrades to a generic JSON rendering rather than being +hidden or dropped. + +`supports_rich_tui` describes the **TUI** — it is a field on the registry's +`RendererDescriptor` (`crates/eggsec-ui-model/src/renderer_registry.rs:18`), +and the GUI never reads it. It is not a capability query for the GUI and must +not be read as one: the GUI renders every published kind, rich or generic, and +the registry's own metadata decides which. + +## Platform Prerequisites and Build Profiles + +The default (`shell`) profile needs the platform's webview development +packages: + +- **Linux**: `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `librsvg2-dev`, + `patchelf`, and the `libayatana-appindicator3-dev` / `libxdo-dev` packages + for the tray. +- **macOS / Windows**: the system webview is present; no extra packages. + +The `--no-default-features` profile builds the GUI crate without the shell — +the `tauri` crate is not in the graph, `build.rs` skips `tauri_build::build()` +(the `tauri` crate's metadata does not exist in that profile, so the call would +panic — `crates/eggsec-gui/build.rs:8-10`), and `run()` returns +`GuiError::ShellNotBuilt`. That profile is what `make check` and +`make check-msrv` build, so the no-shell build stays green without the webview +SDK installed. + +## Known Gaps + +These are deliberate and documented, not oversights. + +- **`ApprovePolicy` is unwired.** The daemon answers it with + `ErrorCode::Unsupported` (`crates/eggsec-daemon/src/host.rs:829-858`), so no + approval is granted either way. The GUI handles `PolicyDecisionRequired` + defensively and offers no approval affordance. +- **The GUI does not manage the daemon's lifecycle.** It requires an + already-running `eggsec-daemon --full-executor` and never spawns, + supervises, or stops one. +- **The socket-path default is duplicated in four places.** The default + `/tmp/eggsec-daemon.sock` is hardcoded independently in the CLI + (`crates/eggsec/src/cli/mod.rs:249`), the daemon's config + (`crates/eggsec-daemon/src/config.rs:22`), the daemon's main + (`crates/eggsec-daemon/src/main.rs:20`), and now the GUI + (`crates/eggsec-gui/src/config.rs:17`). The GUI's `--socket` flag overrides + it. + +## Key Invariants + +1. The GUI links no engine, daemon, CLI or TUI code. It depends only on + `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and + `eggsec-ui-model` (Check 155). +2. The Tauri dependency lives only in `crates/eggsec-gui` (Check 156). +3. The GUI declares no TLS stack of its own: no `rustls-tls`, no `native-tls`, + no direct `reqwest`/`rustls`/`native-tls` dependency (Check 157). +4. The CSP names no wildcard source and no remote origin (Check 158). +5. The form is generated from the published schema. There is no per-operation + code and no hand-written operation table (Check 159). +6. Log retention is capped per task and the forwarder caps each flush. + Unbounded retention is a disqualifying defect (Check 160). +7. The version pins are exact. Loosening them breaks `make check-msrv`. +8. The frontend has no npm dependency and no build step. +9. The published schema is descriptive, never authoritative. The engine's own + validation decides whether a task may run. +10. A blank field is "not provided", never a zero value. The fail-safe + defaults must survive an untouched form. +11. The GUI offers no approval affordance while `ApprovePolicy` is unwired. + +## See Also + +- [frontend_client.md](frontend_client.md) — the `ClientIdentity` seam and the + daemon client the GUI speaks through +- [daemon.md](daemon.md) — the daemon the GUI connects to, its RBAC matrix and + its audit trail +- [tui.md](tui.md) — the terminal UI, the other frontend on the same contract +- [runtime_bridge.md](runtime_bridge.md) — where `RuntimeSurface::DesktopGuiManual` + becomes an `ExecutionSurface` +- [overview.md](overview.md) — System-wide architecture and crate counts + +*Last verified against source: 2026-10-23 (milestones 004–005: Tauri shell +skeleton, schema-driven forms and task dashboard)* diff --git a/architecture/dispatch.md b/architecture/dispatch.md index e4c1cef7b..19419ea61 100644 --- a/architecture/dispatch.md +++ b/architecture/dispatch.md @@ -182,7 +182,7 @@ The `ExecutorRegistry` (`executors/registry.rs:9`) uses `rustc_hash::FxHashMap` Paths reach the single executor owner post-authorization: -### 1. Manual Surfaces (CLI/TUI) +### 1. Manual Surfaces (CLI/TUI/Desktop GUI) CLI handlers classify once via `commands::route::route_for_commands`, convert to canonical requests, enforce via `ctx.evaluate_and_enforce_operation(descriptor)`, @@ -191,6 +191,15 @@ See [cli_commands.md](cli_commands.md). TUI actions enforce via `EnforcementFaca (exact binding), then `TuiTaskDispatcher` converts `TaskKind → canonical request → execute_canonical` (shallow adapter, no second mapping). +The desktop GUI is a **peer** of the CLI and TUI manual surfaces, not a new +policy class: `ExecutionSurface::DesktopGuiManual` derives the same +`ManualPermissive` profile, honors operator overrides, and is never +agent-controlled. It has no strict variant. Because it is a manual surface, a +GUI-dispatched operation reaches the same `EnforcementContext::evaluate()` gate +as a CLI-dispatched one — the surface only decides the profile, not whether the +gate runs. See [config.md](config.md) for the surface→profile mapping and +[runtime_bridge.md](runtime_bridge.md) for the wire-surface conversion. + ``` CLI handler → route_for_commands() classify once diff --git a/architecture/frontend_client.md b/architecture/frontend_client.md new file mode 100644 index 000000000..848fc5a07 --- /dev/null +++ b/architecture/frontend_client.md @@ -0,0 +1,147 @@ +# eggsec-frontend-client Architecture + +Frontend-neutral runtime-client contract shared by Eggsec's interactive frontends. It owns the small trait a frontend uses to drive the Eggsec runtime, plus the two reference implementations — one that wraps an in-process `Runtime`, one that speaks the daemon's Unix-socket JSON-lines protocol. + +The crate exists so a second interactive frontend (the desktop GUI) can reuse the exact contract the terminal UI already binds to without depending on `eggsec-tui` — and therefore without inheriting `ratatui`, `crossterm`, or any other terminal-frontend dependency. + +The crate carries **no frontend's identity**. The kind recorded in the daemon's client registry, the label the daemon shows in its listings, and the namespace for request ids are all the caller's to choose, through `ClientIdentity`. + +## Role & Responsibilities + +| Concern | Owner | +|---------|-------| +| The `RuntimeClient` contract between a frontend and a runtime backend | `eggsec-frontend-client` | +| Embedded (in-process) backend implementation | `eggsec-frontend-client` (`EmbeddedRuntimeClient`) | +| Daemon-backed (Unix socket) backend implementation | `eggsec-frontend-client` (`DaemonRuntimeClient`) | +| The runtime itself, its task lifecycle, and its DTOs | `eggsec-runtime` | +| The wire protocol the daemon backend speaks | `eggsec-daemon-protocol` | +| Enforcement, policy, and dispatch | The engine — **not** this crate | + +## Location & Feature Gating + +| Crate | Path | Dependencies | Features | +|-------|------|-------------|----------| +| `eggsec-frontend-client` | `crates/eggsec-frontend-client/` | `eggsec-runtime`, `eggsec-daemon-protocol`, `tokio` (`rt`, `sync`, `time`, `io-util`, `net`), `serde_json`, `thiserror`, `tracing`, `rustc-hash` | None | + +There are no features: the crate is always what it is. The Tokio feature set is deliberately narrow — `rt` (spawn), `sync` (oneshot/mpsc/Mutex/RwLock), `time` (request timeout), `io-util` (lines/write/flush), `net` (`UnixStream`). No `rt-multi-thread`, no `macros`. + +### Boundary rule + +The crate depends on **no frontend framework** (no `ratatui`, no `crossterm`) and **not on the engine** (no `eggsec` crate). This is enforced structurally by architecture guard 153 (`scripts/check-architecture-guards.sh`): the manifest may not name `eggsec`, `eggsec-tui`, `ratatui`, or `crossterm`, and no source file in `src/` may reference `ratatui`, `crossterm`, `eggsec_tui`, or `eggsec::`. + +The rule is the point of the crate. A frontend that depends on it inherits a runtime contract and nothing else; if it pulled in the engine, every additional frontend would drag the whole composition root (and its dependency closure) behind it. + +## Architecture (3 source files) + +| Module | File | Purpose | +|--------|------|---------| +| `lib` | `src/lib.rs` | The `RuntimeClient` trait, `RuntimeClientFuture`, `RuntimeEventReceiverHandle`, module declarations, and public re-exports | +| `embedded` | `src/embedded.rs` | `EmbeddedRuntimeClient` — wraps an in-process `Arc` | +| `daemon` | `src/daemon.rs` | `DaemonRuntimeClient`, `DaemonClientError` — Unix-socket JSON-lines client | + +## Public API + +| Type | Location | Purpose | +|------|----------|---------| +| `RuntimeClient` | `src/lib.rs:66` | The trait a frontend binds to. `Send + Sync + 'static`. | +| `RuntimeClientFuture` | `src/lib.rs:37` | `Pin> + Send + 'static>>` — the trait's error type is deliberately coarse (`String`), because that is the contract the existing frontends already bind to. | +| `RuntimeEventReceiverHandle` | `src/lib.rs:92` | Frontend-neutral handle over a `tokio::sync::mpsc::UnboundedReceiver`; `recv()` / `try_recv()`. | +| `ClientIdentity` | `src/lib.rs:46` | The caller's own client identity: `kind`, `label`, `request_prefix`. `request_id(counter)` mints an id in that namespace (`src/lib.rs:60`). | +| `EmbeddedRuntimeClient` | `src/embedded.rs:11` | In-process backend. `new(Arc)`, `runtime()`. | +| `DaemonRuntimeClient` | `src/daemon.rs:69` | Daemon backend. `connect(socket_path, identity)`, `declare_client()`, `subscribe_events()`, plus the daemon-only `describe_operations()` / `health()` / `daemon_capabilities()`. `Clone`. | +| `DaemonClientError` | `src/daemon.rs:39` | `Io`, `Serialization`, `Protocol(String)`, `ConnectionClosed`. Publicly exported. | + +### The `RuntimeClient` trait (8 methods) + +| Method | Returns | Notes | +|--------|---------|-------| +| `capabilities()` | `RuntimeCapabilities` | Daemon backend reads `ServerMessage::Capabilities`; embedded backend returns the runtime default. | +| `create_session(surface, scope, labels)` | `SessionId` | `surface` is a `RuntimeSurface` — this is how a frontend declares which surface it is (see [runtime_bridge.md](runtime_bridge.md)). | +| `list_sessions()` | `Vec` | | +| `snapshot(session_id)` | `SessionSnapshot` | | +| `submit(session_id, request)` | `TaskId` | `request` is a `RunRequest`. | +| `cancel(session_id, task_id)` | `()` | | +| `cancel_active(session_id)` | `()` | | +| `subscribe(session_id)` | `RuntimeEventReceiverHandle` | | + +## The Two Implementations + +### `EmbeddedRuntimeClient` + +Wraps an `Arc` and calls it directly. It is a thin adapter — it forwards to the runtime's own methods and maps errors to `String`. No sockets, no serialization, no daemon. + +### `DaemonRuntimeClient` + +Speaks the daemon's Unix-socket JSON-lines protocol using `eggsec-daemon-protocol`'s `ClientCommand`/`ServerMessage` types. + +- `connect(socket_path, identity)` splits the socket, spawns **one** reader task, and registers the pending-response and event-channel registries. The `identity` argument is the caller's `ClientIdentity`: the crate cannot pick a kind, a label, or a request-id namespace on the caller's behalf (`src/daemon.rs:80-83`). +- `send_command()` writes one JSON line and awaits the matching response through a `oneshot` channel, bounded by a 30s timeout. +- `subscribe_events()` registers a channel in the fan-out list; the reader task clones each `RuntimeEvent` out to every registered sender and prunes senders whose receiver has been dropped. +- Request ids are minted by an `AtomicU64` counter in the caller's namespace — `ClientIdentity::request_id()` (`src/lib.rs:60`) formats `{request_prefix}{counter}` verbatim, so a caller that wants a separator includes it in the prefix itself (`"gui-"` yields `gui-0`). + +The client is declared to the daemon with the caller's own identity. The TUI passes `ClientKind::Tui` / `eggsec-tui` / `tui-`; the desktop GUI passes `ClientKind::Gui` / `eggsec-gui` / `gui-`. Nothing about either frontend is hardcoded here. + +### The three daemon-only inherent methods + +`DaemonRuntimeClient` carries three methods that have no embedded counterpart: + +| Method | Returns | Purpose | +|--------|---------|---------| +| `describe_operations()` (`src/daemon.rs:230`) | `DescribeOperationsResponse` | The daemon's published operation catalog and per-task-kind request schemas. | +| `health()` (`src/daemon.rs:251`) | `DaemonHealth` | The daemon's liveness and its advertised `protocol_version`. | +| `daemon_capabilities()` (`src/daemon.rs:280`) | `DaemonCapabilities` | The daemon's advertised capabilities, including the `operation_schema` flag. | + +They are **inherent methods, not `RuntimeClient` trait methods**. The trait's eight methods are unchanged, and deliberately so: the embedded backend has no daemon to ask. Adding `describe_operations()` to the trait would force every embedded implementation to synthesize a catalog it has no source for. Keeping them inherent lets a daemon-backed frontend ask the daemon questions that only a daemon can answer, without widening the contract that the embedded backend must satisfy. + +Note that `RuntimeClient::capabilities()` already exists for the embedded path; `daemon_capabilities()` is the daemon's own answer to the same question, and the GUI uses the latter because it needs the raw `operation_schema` flag rather than the trait's flattened view. + +### The `Arc` sharing requirement + +`DaemonRuntimeClient` is `Clone`, and every clone shares one `Arc` (`src/daemon.rs:70`). The connection owns everything that must be shared: + +- the socket's **write half** (behind a `tokio::sync::Mutex`, so concurrent sends cannot interleave a line), +- the **pending-response registry** — a map from `request_id` to the `oneshot::Sender` awaiting that response, +- the **event fan-out list** — the `UnboundedSender`s for every active `subscribe_events()` channel, +- the **request-id counter**. + +The reader task is spawned once, at `connect()`, and lives for the life of the connection. This is why the sharing matters: the reader task must be the *only* reader of the socket, and it must be able to reach the pending-response map and the subscriber list. A second `connect()` would mean a second socket, a second reader task, and a second daemon-side client registration — so a frontend that needs a second handle must `clone()` the client rather than reconnect. + +The same shape appears on the embedded side: `EmbeddedRuntimeClient` holds an `Arc`, so cloning it shares one runtime. + +## Not an Enforcement Surface + +This crate makes **no authorization decision**. The contract carries no policy, no scope evaluation, and no override handling: it is a transport-shaped view of a runtime. + +- The daemon applies its own access controls (RBAC roles, session ownership, declared-client identity) — see [daemon.md](daemon.md). +- The embedded runtime applies the engine's enforcement, exactly as before the move. +- A `RuntimeSurface` passed through `create_session()` is an **identity claim**, not an authorization. The engine's runtime bridge is what converts it into an `ExecutionSurface` and evaluates it — see [runtime_bridge.md](runtime_bridge.md) and [config.md](config.md). + +Because the crate depends on neither the engine nor `eggsec-policy`, it cannot reach the enforcement path even by accident. + +## Integration Points + +- **TUI**: `eggsec-tui` depends on `eggsec-frontend-client` for `RuntimeClient`, `RuntimeEventReceiverHandle`, `EmbeddedRuntimeClient`, and `DaemonRuntimeClient`. It no longer depends on `eggsec-daemon-protocol` directly, and its former `crates/eggsec-tui/src/runtime_client/` module is gone. Its daemon connect now passes its own `ClientIdentity` — `ClientKind::Tui` / `eggsec-tui` / `tui-` (`crates/eggsec-tui/src/app/mod.rs:390-397`). The observable behaviour is unchanged. See [tui.md](tui.md). +- **Desktop GUI**: the second consumer, and a daemon-only one — `eggsec-gui` binds the same contract and passes `ClientKind::Gui` / `eggsec-gui` / `gui-`. It has no embedded backend and never links the engine. See [desktop_gui.md](desktop_gui.md). +- **`eggsec-daemon-protocol`**: supplies the wire types the daemon backend speaks. +- **`eggsec-runtime`**: supplies `RunRequest`, `RuntimeSurface`, `SessionId`, `SessionSnapshot`, `SessionSummary`, `TaskId`, `RuntimeCapabilities`, `RuntimeEvent`. + +## Key Invariants + +1. **No frontend framework** — zero `ratatui`/`crossterm` imports (guard 153) +2. **No engine dependency** — zero `eggsec` crate imports (guard 153) +3. **No enforcement** — the crate owns no policy, scope, or override logic +4. **One connection per client** — clones share one socket, one reader task, one pending-response registry +5. **Frontend-neutral** — no terminal, GUI-toolkit, or windowing types appear in the public API +6. **No hardcoded frontend identity** — the kind, the label, and the request-id namespace are the caller's, through `ClientIdentity` +7. **The trait is the portable contract** — the daemon-only questions (`describe_operations`, `health`, `daemon_capabilities`) are inherent methods, because the embedded backend has no daemon to ask + +## See Also + +- [tui.md](tui.md) — the terminal UI, the contract's first consumer +- [desktop_gui.md](desktop_gui.md) — the desktop GUI, the contract's second consumer +- [runtime.md](runtime.md) — the runtime the embedded backend wraps +- [daemon.md](daemon.md) — the daemon the daemon backend speaks to +- [runtime_bridge.md](runtime_bridge.md) — where a `RuntimeSurface` becomes an `ExecutionSurface` +- [overview.md](overview.md) — System-wide architecture and crate counts + +*Last verified against source: 2026-10-23 (crate extraction from `crates/eggsec-tui/src/runtime_client/`; trait renamed `TuiRuntimeClient` → `RuntimeClient`; `ClientIdentity` seam added and `connect` widened to take it, with the three daemon-only methods — `describe_operations`, `health`, `daemon_capabilities` — added as inherent methods)* diff --git a/architecture/overview.md b/architecture/overview.md index e84455ab5..8c02263e6 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -2,7 +2,7 @@ Eggsec is a Rust-native, scope-enforced security assessment and defense-validation engine with multiple frontends (CLI, TUI, REST, MCP, gRPC, Agent), centralized policy enforcement, and domain execution crates. This document is the bird's-eye view of the system and the index into the per-component deep-dive documents that live alongside it in `architecture/`. -Every number in this document was verified against source on 2026-10-06. Where a claim depends on a count (variants, commands, tabs), the verifying location is cited. +Every number in this document was verified against source on 2026-10-23. Where a claim depends on a count (variants, commands, tabs), the verifying location is cited. ## Quick Navigation @@ -39,7 +39,7 @@ Every number in this document was verified against source on 2026-10-06. Where a ## Workspace Crates -Eggsec is organized as a Cargo workspace with **23 crates** plus the standalone NSE runtime. The first-level crate boundary separates dependency-light leaf crates from the composition root and frontends. +Eggsec is organized as a Cargo workspace with **25 crates** plus the standalone NSE runtime. The first-level crate boundary separates dependency-light leaf crates from the composition root and frontends. ### Release validation boundary @@ -60,15 +60,17 @@ nor hosted CI publishes a package. | `eggsec-report-model` | Report data contracts | Yes | `ScanReportData`, `ReportEnvelope`, evidence/summary DTOs. Data only; depends only on `eggsec-core`. Domain DTO owner (Phase B). | | `eggsec-output` | Report rendering | Yes | JSON/CSV/HTML/SARIF/JUnit/Markdown, dedup, trends, diff over `eggsec-report-model` (never the reverse). No engine/runtime deps. PDF lives in the engine crate, not here. Scheduling/session removed in Phase A (cron in `eggsec-agent::cron`). | | `eggsec-agent` | Agent coordination | Yes | Registry, scheduler, lifecycle, delegation, aggregation, cron. Internal deps: `eggsec-core` + `eggsec-transport` (the outbound contract for agent-issued network work). | -| `eggsec-runtime` | Frontend-neutral runtime | Yes | `Runtime`, `RuntimeTaskExecutor`, task lifecycle; zero workspace deps (serde/tokio/tracing only). | +| `eggsec-runtime` | Frontend-neutral runtime | Yes | `Runtime`, `RuntimeTaskExecutor`, task lifecycle; zero workspace deps (serde/tokio/tracing only). Optional `schema` feature publishes a derived JSON Schema over the canonical request DTOs. | | `eggsec-ui-model` | Frontend view DTOs | Yes | View models + renderer registry (23 entries). Depends only on `eggsec-runtime`. | +| `eggsec-frontend-client` | Frontend runtime client | Yes | Frontend-neutral runtime-client contract (`RuntimeClient` trait + embedded/daemon implementations); no frontend framework, no engine dependency. Deep dive: [frontend_client.md](frontend_client.md). | | `eggsec` | Main engine (lib) | No | Composition root: all security modules, policy enforcement, dispatch, runtime bridge. | | `eggsec-db-lab` | DB pentest domain | Yes | Postgres/MySQL/MSSQL/MongoDB/Redis checks, each driver behind its own feature. | | `eggsec-web-proxy` | Web proxy domain | Yes | MITM intercept (HTTP/HTTPS/WS/H2/gRPC), TLS cert generation, proxy pool. Highest test density in the workspace. | | `eggsec-mobile-lab` | Mobile analysis domain | Yes | APK/IPA static analysis + Android dynamic testing (`mobile-dynamic`). | -| `eggsec-daemon` | Persistent daemon host | Yes | Unix socket server, session lifecycle, SQLite (rusqlite 0.31 bundled); optional `http-api` SSE transport, optional `full-executor`. | -| `eggsec-daemon-protocol` | Daemon IPC protocol | Yes | `ClientCommand` (15), `ServerMessage` (14), `ErrorCode` (11), RBAC client registry. Depends only on `eggsec-runtime`. | +| `eggsec-daemon` | Persistent daemon host | Yes | Unix socket server, session lifecycle, SQLite (rusqlite 0.32 bundled); optional `http-api` SSE transport, optional `full-executor`. | +| `eggsec-daemon-protocol` | Daemon IPC protocol | Yes | `ClientCommand` (16), `ServerMessage` (15), `ErrorCode` (11), RBAC client registry, published operation catalog. Depends on `eggsec-runtime` + `eggsec-policy`. | | `eggsec-tui` | Terminal UI | No | 33 tabs (21 base + 12 feature-gated), ratatui/crossterm, 50 LZMA-packaged themes. | +| `eggsec-gui` | Desktop GUI frontend | No | Tauri v2 desktop shell (2.11.x, exact pins). Daemon-only: no engine, daemon, CLI or TUI dep; no outbound HTTP; buildless frontend with zero npm dependencies. Deep dive: [desktop_gui.md](desktop_gui.md). | | `eggsec-cli` | CLI binary | Yes | Thin binary shell over the engine's `cli` feature; optional `tui` and `daemon-client`. | | `eggsec-python` | Python bindings | Yes | PyO3/maturin. 22 stable-core operations, each with sync + async paths (asserted by test). | | `eggsec-transport` | Scoped HTTP contract | Yes | Scope-aware outbound DTOs, `NetworkAuthority` checkpoints (incl. proxy-peer `authorize_proxy_resolved`/`authorize_proxy_socket`), TOCTOU-closed resolver binding, recording fake. Zero workspace deps (`bytes`/`http`/`url`/`thiserror` + log-only `tracing`). | @@ -215,10 +217,12 @@ The daemon architecture enables persistent sessions, background task execution, | Module | Source | Purpose | Architecture Doc | |--------|--------|---------|------------------| | Daemon | `crates/eggsec-daemon/` | Long-running host: session persistence (SQLite via rusqlite, bundled), client registry, Unix socket IPC, optional HTTP/SSE transport (`http-api`), optional full engine executor (`full-executor`) | [daemon.md](daemon.md) | -| Daemon Protocol | `crates/eggsec-daemon-protocol/` | Wire DTOs + RBAC: `ClientCommand` (15), `ServerMessage` (14), `ErrorCode` (11), `ClientRegistry` with roles/permissions; no persistence/TLS deps | [daemon.md](daemon.md) | -| Runtime | `crates/eggsec-runtime/` | Frontend-neutral async runtime: `Runtime` orchestrator, `RuntimeTaskExecutor` trait, task lifecycle, sessions, event broadcasting; zero workspace deps | [runtime.md](runtime.md) | +| Daemon Protocol | `crates/eggsec-daemon-protocol/` | Wire DTOs + RBAC: `ClientCommand` (16), `ServerMessage` (15), `ErrorCode` (11), `ClientRegistry` with roles/permissions; read-only publication of the operation catalog + derived request schema (`operations`); no persistence/TLS deps | [daemon.md](daemon.md) | +| Runtime | `crates/eggsec-runtime/` | Frontend-neutral async runtime: `Runtime` orchestrator, `RuntimeTaskExecutor` trait, task lifecycle, sessions, event broadcasting; zero workspace deps. Optional `schema` feature derives a JSON Schema over the canonical request DTOs | [runtime.md](runtime.md) | | Runtime Bridge | `crates/eggsec/src/runtime_bridge/` | Converts `RuntimeSurface`→`ExecutionSurface` (1:1 except `Unknown`→error), `RunRequest`/`TaskKind`→`OperationDescriptor`; `preflight_run_request()` preview, `approve_run_request()` issues `ApprovedOperation`; manual overrides honored only on ManualPermissive surfaces | [runtime_bridge.md](runtime_bridge.md) | | UI Model | `crates/eggsec-ui-model/` | View DTOs (`SessionView`, `TaskView`, `ResultEnvelopeView`, `DashboardSummaryView`, event/artifact/permission/policy-prompt views) + renderer registry (23 entries) keyed by task kind | [ui_model.md](ui_model.md) | +| Frontend Client | `crates/eggsec-frontend-client/` | Frontend-neutral runtime-client contract: the `RuntimeClient` trait plus the embedded and daemon implementations; no frontend framework, no engine dependency | [frontend_client.md](frontend_client.md) | +| Desktop GUI | `crates/eggsec-gui/` | Tauri v2 desktop shell: 8-command IPC surface, schema-driven form engine (no per-operation code), bounded task state and result dashboard; daemon-only, no engine/daemon/CLI/TUI dep | [desktop_gui.md](desktop_gui.md) | ### User Interfaces @@ -228,6 +232,7 @@ Frontend entry points for human interaction. |--------|--------|---------|------------------| | CLI | `crates/eggsec/src/cli/` + `crates/eggsec/src/commands/handlers/` + `crates/eggsec-cli/` | **52 clap subcommands** (27 base + 25 feature-gated; `cli/mod.rs:270-470`). Argument types only in `cli/`; handlers (32 modules) in `commands/handlers/`; `crates/eggsec-cli/` is the thin binary shell (surface resolution, logging, optional TUI/daemon client) | [cli_commands.md](cli_commands.md) | | TUI | `crates/eggsec-tui/src/` | Real-time terminal UI: ratatui/crossterm, **33 tabs (21 base + 12 feature-gated)** (`tabs/mod.rs:142`), tab-spec table, event loop with daemon attach mode, **50 LZMA-packaged themes**, search, overlays, `TestBackend` visual regression suite | [tui.md](tui.md) | +| Desktop GUI | `crates/eggsec-gui/` | Tauri v2 desktop window: buildless HTML/CSS/vanilla-JS frontend, eight narrow IPC commands, forms generated from the published request schema, bounded task dashboard. Requires an already-running `eggsec-daemon --full-executor` | [desktop_gui.md](desktop_gui.md) | ### Compliance & Risk @@ -306,12 +311,13 @@ All side-effecting operations pass through a centralized enforcement gate. The m ### Surfaces -`ExecutionSurface` identifies the caller origin — 9 variants (`eggsec-policy/src/policy.rs:362`, re-exported through the `config/policy` facade): +`ExecutionSurface` identifies the caller origin — 10 variants (`eggsec-policy/src/policy.rs:362`, re-exported through the `config/policy` facade): | Surface | Profile | Overrides | Automated | |---------|---------|:---------:|:---------:| | `CliManual` | `ManualPermissive` | Yes | No | | `TuiManual` | `ManualPermissive` | Yes | No | +| `DesktopGuiManual` | `ManualPermissive` | Yes | No | | `CliManualStrict` | `ManualGuarded` | No | No | | `TuiManualStrict` | `ManualGuarded` | No | No | | `McpServer` | `McpStrict` | No | Yes | @@ -460,15 +466,15 @@ Pure marker gates (empty feature arrays) are `tool-api`, `insecure-tls`, `api-sc | Type | Location | Purpose | |------|----------|---------| -| `ExecutionSurface` | `eggsec-policy/src/policy.rs:362` | Caller origin (9 variants) | -| `ExecutionProfile` | `eggsec-policy/src/policy.rs:466` | Trust boundary (5 variants) | +| `ExecutionSurface` | `eggsec-policy/src/policy.rs:362` | Caller origin (10 variants) | +| `ExecutionProfile` | `eggsec-policy/src/policy.rs:483` | Trust boundary (5 variants) | | `OperationRisk` | `eggsec-policy/src/policy.rs:9` | Risk tier (15 levels) | | `OperationMetadata` | `eggsec-policy::catalog` (facade: `config/policy_catalog.rs`) | Static registry of all operations (34 canonical + 42 aliases) — single source of truth | | `OperationDescriptor` | `config/policy.rs` | Unit of policy evaluation | | `EnforcementContext` | `config/policy_decision.rs:42` (engine facade over `eggsec-policy`) | Central policy evaluation gate | | `ApprovedOperation` | `eggsec-policy/src/approval.rs:22` | Proof-of-enforcement token | | `EnforcedDispatcher` | `tool/dispatcher.rs` | Type-level dispatch gate with binding validation | -| `LoadedScope` | `config/scope.rs:217` | Scope + provenance (`ScopeSource`: DefaultEmpty/ConfigFile/CliScopeFile/GeneratedPreset) | +| `LoadedScope` | `eggsec-policy/src/scope.rs:46` | Scope + provenance (`ScopeSource`: DefaultEmpty/ConfigFile/CliScopeFile/GeneratedPreset) | ### Runtime/Daemon Types @@ -482,6 +488,11 @@ Pure marker gates (empty feature arrays) are `tool-api`, `insecure-tls`, `api-sc | `DaemonHost` | `eggsec-daemon` | Runtime bridge with client registry | | `ClientRegistry` | `eggsec-daemon-protocol` | Connected-client tracking + RBAC | | `DaemonStore` | `eggsec-daemon` | Persistence trait (SQLite backend) | +| `RuntimeClient` | `eggsec-frontend-client` | Frontend-neutral runtime-client trait (embedded + daemon implementations) | +| `ClientIdentity` | `eggsec-frontend-client` | Caller-supplied client identity (kind, label, request-id namespace) for the daemon connect | +| `GuiState` | `eggsec-gui` | The GUI's managed Tauri state: the daemon connection, the task registry, the event forwarder | +| `Control` / `ControlKind` | `eggsec-gui` | The schema-property → control descriptor and its five control kinds | +| `GuiTaskStatus` | `eggsec-gui` | The GUI's own task-status view (`AwaitingPolicy` is the GUI's addition) | --- @@ -509,8 +520,11 @@ eggsec-core (leaf — no workspace deps) ├── eggsec-runtime (no workspace deps — only serde/tokio/tracing) │ ↑ │ ├── eggsec-ui-model (frontend-neutral view DTOs) - │ ├── eggsec-daemon-protocol (IPC DTOs, RBAC client registry) - │ └── eggsec-daemon (persistent sessions, Unix socket IPC) + │ ├── eggsec-daemon-protocol (IPC DTOs, RBAC client registry, published operation catalog; + eggsec-policy) + │ │ ↑ + │ │ └── eggsec-frontend-client (frontend-neutral runtime-client contract) + │ ├── eggsec-daemon (persistent sessions, Unix socket IPC) + │ └── eggsec-gui (desktop GUI — Tauri shell; + frontend-client + daemon-protocol + ui-model; no engine dep) │ ├── eggsec-db-lab (database pentest domain) ├── eggsec-web-proxy (MITM proxy domain) @@ -519,7 +533,7 @@ eggsec-core (leaf — no workspace deps) │ └── eggsec (ALL above incl. transport — main engine, lib only) ↑ - ├── eggsec-tui (engine + runtime + daemon-protocol + ui-model) + ├── eggsec-tui (engine + runtime + frontend-client + ui-model) ├── eggsec-cli (engine + runtime + ui-model; optional: tui + daemon) └── eggsec-python (engine + core + tool-core; optional domain crates) ``` @@ -533,12 +547,15 @@ Enforced by `scripts/check-architecture-guards.sh`: - `eggsec-output` depends on `eggsec-report-model` (facades re-export it, DTOs are never redefined) and has no engine or runtime dependencies (Checks 23, 119) - `eggsec-runtime` has no TUI, transport, persistence, or engine dependencies - `eggsec-daemon` has no non-optional TUI/engine dependencies; transport deps only behind `http-api` +- `eggsec-frontend-client` depends on no frontend framework (no `ratatui`/`crossterm`) and not on the engine; it is reached only through `eggsec-runtime` + `eggsec-daemon-protocol` (Check 153) +- `eggsec-gui` names only `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and `eggsec-ui-model` — never `eggsec`, `eggsec-daemon`, `eggsec-cli` or `eggsec-tui` (Check 155); the Tauri dependency appears in no other crate (Check 156); the GUI declares no TLS stack of its own — no `rustls-tls`, no `native-tls`, no direct `reqwest`/`rustls`/`native-tls` dependency (Check 157); the GUI's CSP names no wildcard source and no remote origin (Check 158) +- The GUI's form is generated from the published request schema: no per-operation `match`/`switch` over the task-kind variant names and no hand-written operation table (Check 159); the GUI's task state caps log retention per task and the forwarder caps each flush (Check 160) - Domain crates (`db-lab`, `web-proxy`, `mobile-lab`, `nse`) depend on `eggsec-report-model` for DTOs, never on `eggsec-output` (Check 120) - `eggsec-policy` has no Tokio/HTTP/TLS/filesystem/frontend/engine/transport deps, no `cfg!` feature queries, no resolver/authority behavior (Check 121); engine → policy one-way with transport independent of policy (Check 122); engine policy modules stay facades with no redefined core types (Check 123) - `eggsec-service-db` has no workspace dependency at all, no runtime/network/TLS/frontend/persistence dep, and no `Scope`/`ApprovedOperation`/`Capability` reference (Check 148); the engine reaches it only through the `pub use eggsec_service_db as service_data` facade, and Check 114 pins it as the single canonical service-table owner - `eggsec-payloads` has `eggsec-core` as its only workspace dependency, no `reqwest`/Tokio/TLS/frontend/persistence dep, and no authorization reference (Check 148); the engine dispatches the 6 live-probe types locally and delegates the other 34 payload generators (40 total) (Check 150), and `tests/fuzzer_payload_corpus_seam.rs` asserts all 6 advanced types still return real payloads and that the cached union equals the per-type sum over all 40 - `eggsec-secrets` has `eggsec-core` as its only workspace dependency, no runtime/network/TLS/frontend/persistence dep, and no `Scope`/`ApprovedOperation`/`Capability` reference (Check 148); the engine reaches it only through the `pub use eggsec_secrets as secrets` facade, which is what keeps the Python bindings' exhaustive 30-arm `SecretType` match compiling with zero edits. Check 149 pins the canonical owner and freezes the entropy gate at `3.5`, scoped only to `SecretType::AwsSecretKey` -- Only frontends (`eggsec-cli`, `eggsec-tui`, `eggsec-python`) depend on the engine +- Only frontends (`eggsec-cli`, `eggsec-tui`, `eggsec-python`) depend on the engine. The desktop GUI (`eggsec-gui`) is a frontend that deliberately does **not**: it is daemon-only and reaches the engine only through `eggsec-daemon` ### Intra-Engine Dependencies @@ -619,8 +636,8 @@ Complete catalog of component deep-dives in this directory: | **Load & Stress** | [loadtest.md](loadtest.md), [stress.md](stress.md) | | **Orchestration** | [pipeline.md](pipeline.md), [distributed.md](distributed.md), [ai_agents.md](ai_agents.md) | | **Infrastructure** | [proxy.md](proxy.md), [web_proxy.md](web_proxy.md), [storage.md](storage.md), [workflow.md](workflow.md), [findings.md](findings.md), [diff.md](diff.md), [notify.md](notify.md), [integrations.md](integrations.md) | -| **Daemon & Runtime** | [daemon.md](daemon.md), [runtime.md](runtime.md), [ui_model.md](ui_model.md) | -| **Interfaces** | [cli_commands.md](cli_commands.md), [tui.md](tui.md), [python_api.md](python_api.md) | +| **Daemon & Runtime** | [daemon.md](daemon.md), [runtime.md](runtime.md), [ui_model.md](ui_model.md), [frontend_client.md](frontend_client.md) | +| **Interfaces** | [cli_commands.md](cli_commands.md), [tui.md](tui.md), [desktop_gui.md](desktop_gui.md), [python_api.md](python_api.md) | | **Compliance & Risk** | [compliance.md](compliance.md), [vuln.md](vuln.md), [supply_chain.md](supply_chain.md), [container.md](container.md) | | **Defense Lab** | [defense_lab.md](defense_lab.md), [database_pentest.md](database_pentest.md), [mobile.md](mobile.md), [postex.md](postex.md), [c2.md](c2.md) | | **Integration** | [nse_integration.md](nse_integration.md), [nse_capability_inventory.md](nse_capability_inventory.md), [nse_report_display_contract.md](nse_report_display_contract.md) | @@ -649,8 +666,10 @@ Workspace-level canonical docs: --- -*Last updated: 2026-10-06 — Knowledge-corpus convergence review (subagent batches across discovery, interfaces, enforcement/config, and the new corpus crates). Corrections applied here: **19 → 23 workspace crates** (added `eggsec-service-db`, `eggsec-secrets`, `eggsec-payloads`, `eggsec-udp-scan` to the crate table with an inline boundary note); added the missing `eggsec-udp-scan` row and a dedicated **Knowledge Corpus** module-index section linking [knowledge_corpus.md](knowledge_corpus.md); **TaskKind 29 → 30** variants (`eggsec-runtime/src/request.rs:64`, new `C2` variant); `PayloadType` citation re-pointed from `fuzzer/payloads/mod.rs:49` to its new owner `eggsec-payloads/src/lib.rs:95`; enforcement-type citations re-pointed from the `config/` facades to their real owners in `eggsec-policy` (`policy.rs:362`/`466`, `approval.rs:22`) and `EnforcementContext::evaluate` to `policy_decision.rs:141`; `eggsec-nse` corrected from *pinned Git dependency* to the **published crates.io 0.2.0 release**; `eggsec-agent` internal deps corrected from "`eggsec-core` only" to `eggsec-core` + `eggsec-transport`; `utils` corrected from "20 sub-modules" to the **12 that remain** (with the Phase A/D/G pruning history); added the `udp-scan` feature gate to the flag table; payloads corpus count corrected from "34 data-only modules" to **40 payload modules (34 generators + 6 probers)**. +*Last updated: 2026-10-23 — Desktop GUI frontend (Tauri shell, schema-driven forms, task dashboard). Corrections applied here: **24 → 25 workspace crates** (added `eggsec-gui` to the crate table, the module index, the User Interfaces table, the Key Types table, the dependency map, and the dependency-guardrails list, with a deep dive at [desktop_gui.md](desktop_gui.md)); the dependency map now records the GUI's exact four workspace dependencies (`eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol`, `eggsec-ui-model`) and its deliberate *absence* of an engine edge; the guardrails list gained Checks 155–160.* -Re-verified unchanged: 34 operations + 42 aliases (`eggsec-policy/src/catalog.rs`), 33 TUI tabs (`eggsec-tui/src/tabs/mod.rs:154`), 52 CLI subcommands (`eggsec/src/cli/mod.rs`), 32 handler modules, `ExecutionSurface` 9 / `ExecutionProfile` 5 / `OperationRisk` 15 / `Capability` 19 / `IntendedUse` 8 / `DenialClass` 8 / `ConfirmationClass` 8, engine default feature set empty. Prior review: 2026-09-30 (8 subagent batches).* +Re-verified unchanged: 34 operations + 42 aliases (`eggsec-policy/src/catalog.rs`), 33 TUI tabs (`eggsec-tui/src/tabs/mod.rs:154`), 52 CLI subcommands (`eggsec/src/cli/mod.rs`), 32 handler modules, `ExecutionProfile` 5 / `OperationRisk` 15 / `Capability` 19 / `IntendedUse` 8 / `DenialClass` 8 / `ConfirmationClass` 8, `ErrorCode` 11, `TaskKind` 30, 23 renderer kinds, engine default feature set empty. Prior review: 2026-10-23 (desktop-GUI surface parity, operation parameter schema publication, frontend runtime-client extraction); before that 2026-10-06 (knowledge-corpus convergence + code-hygiene pass); before that 2026-09-30 (8 subagent batches).* -**Addendum 2026-10-06 (code-hygiene pass).** Three defects surfaced by that review were fixed in source, not just documented: (1) `TaskKind::Resume` was missing from the closure test's `all_task_kinds()` helper while the count pin also read 29 — the helper now covers all 30 variants and `runtime_contract_closure` is 18 tests; (2) `make check` had no `cargo test -p eggsec-udp-scan` line, so that crate's 23 tests never ran — added, giving all four corpus crates coverage; (3) the dead `test-util` feature in `eggsec-udp-scan` (no `cfg` site, no consumer) was removed. Verified corpus test counts: payloads 252 / service-db 21 / secrets 11 / udp-scan 23. Workspace totals (23 crates, 51 features, 30 task kinds) are unchanged. +**Addendum 2026-10-23 (desktop GUI frontend).** The `eggsec-gui` crate is a Tauri v2 desktop application that is **daemon-only**: it depends on `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and `eggsec-ui-model` and on nothing else — no engine, no daemon, no CLI, no TUI — and it performs no outbound HTTP. The Tauri version pins are exact (`=`) because the next lines up declare MSRV 1.90, above this workspace's 1.89 floor; loosening them breaks `make check-msrv`. The frontend is buildless with zero npm dependencies. The GUI's forms are generated from the published request schema, so there is no per-operation code; its log retention is capped per task and per flush. + +**Addendum 2026-10-06 (code-hygiene pass).** Three defects surfaced by that review were fixed in source, not just documented: (1) `TaskKind::Resume` was missing from the closure test's `all_task_kinds()` helper while the count pin also read 29 — the helper now covers all 30 variants and `runtime_contract_closure` is 18 tests; (2) `make check` had no `cargo test -p eggsec-udp-scan` line, so that crate's 23 tests never ran — added, giving all four corpus crates coverage; (3) the dead `test-util` feature in `eggsec-udp-scan` (no `cfg` site, no consumer) was removed. Verified corpus test counts: payloads 252 / service-db 21 / secrets 11 / udp-scan 23. Workspace totals (crate count, feature count, task kinds) are unchanged. diff --git a/architecture/runtime.md b/architecture/runtime.md index 4783ba1b5..9964f5ded 100644 --- a/architecture/runtime.md +++ b/architecture/runtime.md @@ -19,7 +19,9 @@ Frontend-neutral async runtime for task lifecycle management. Provides the bridg | Crate | Path | Dependencies | |-------|------|-------------| -| `eggsec-runtime` | `crates/eggsec-runtime/` | `serde`, `serde_json`, `thiserror`, `tokio`, `tokio-util`, `tracing`, `uuid` — **zero workspace deps** | +| `eggsec-runtime` | `crates/eggsec-runtime/` | `serde`, `serde_json`, `thiserror`, `tokio`, `tokio-util`, `tracing`, `uuid` — **zero workspace deps**; optional `schemars` behind the off-by-default `schema` feature | + +The `schema` feature (off by default) exposes `src/schema.rs`: `task_kind_schemas()` returns one entry per `TaskKind` variant (30) with its wire `kind` discriminator, its canonical `operation_id`, its `capability_name`, and a JSON Schema for that variant's params struct; `task_kind_schema()` returns the whole `TaskKind` schema in its adjacently-tagged wire shape. The schema is **derived** from the canonical request DTOs, never hand-written, and it is **descriptive only** — no authorization, dispatch, scope, or policy path consults it. Architecture guard: zero TUI, transport, persistence, or engine dependencies. Enforced by `scripts/check-architecture-guards.sh`. @@ -32,13 +34,14 @@ Architecture guard: zero TUI, transport, persistence, or engine dependencies. En | `runtime_config` | `src/runtime_config.rs` | `RuntimeConfig`, `SessionOptions` (submission/lifecycle tuning) | | `runtime_sink` | `src/runtime_sink.rs` | `RuntimeEventReceiver`, `RuntimeEventSink`, broadcast helpers (events/backpressure) | | `session` | `src/session.rs` | `RuntimeSession`, `RuntimeExecutionContext`, `SessionScope`, `SessionSnapshot`, `TaskSnapshot`, `SessionSummary` | -| `request` | `src/request.rs` | `TaskKind` (30 variants), `RuntimeSurface` (10 variants), `RunRequest`, payload structs | +| `request` | `src/request.rs` | `TaskKind` (30 variants), `RuntimeSurface` (11 variants), `RunRequest`, payload structs | | `event` | `src/event.rs` | `RuntimeEvent` (12 variants), `TaskOutcome` (5 variants), `TaskStatus` (6 variants), `TaskProgress`, `TaskResultEnvelope`, `ArtifactRef`, `LogLevel`, `RuntimeErrorInfo`, `PolicyPrompt`, `RuntimeAuditEvent` | | `capabilities` | `src/capabilities.rs` | `RuntimeCapabilities`, `TaskCapability` | | `ids` | `src/ids.rs` | `SessionId`, `TaskId`, `ClientId` — UUID newtypes with serde/display | | `error` | `src/error.rs` | `RuntimeError` (13 variants) | | `dispatcher` | `src/dispatcher.rs` | `TaskDispatcher` trait (unused by runtime; legacy interface) | | `cancel` | `src/cancel.rs` | `race_with_cancel` helper + `CancellationToken` re-export (cancellation boundary) | +| `schema` | `src/schema.rs` | **Feature-gated (`schema`)**: `TaskKindSchema`, `task_kind_schemas()`, `task_kind_schema()` — the derived JSON Schema over the canonical request DTOs | ### Core Types @@ -57,7 +60,7 @@ Architecture guard: zero TUI, transport, persistence, or engine dependencies. En | `SessionScope` | `session.rs:58` | Scope metadata: `is_explicit`, `source`, `path` | | `RunRequest` | `request.rs:99` | Task submission: `task_kind`, `requested_by`, `surface`, `labels` | -### RuntimeSurface — 10 variants (`request.rs:21`) +### RuntimeSurface — 11 variants (`request.rs:21`) | # | Variant | Label | Automated | |---|---------|-------|:---------:| @@ -65,12 +68,13 @@ Architecture guard: zero TUI, transport, persistence, or engine dependencies. En | 2 | `CliManualStrict` | `cli-manual-strict` | No | | 3 | `TuiManual` | `tui-manual` | No | | 4 | `TuiManualStrict` | `tui-manual-strict` | No | -| 5 | `Ci` | `ci` | Yes | -| 6 | `McpServer` | `mcp-server` | Yes | -| 7 | `RestApi` | `rest-api` | Yes | -| 8 | `GrpcApi` | `grpc-api` | Yes | -| 9 | `SecurityAgent` | `security-agent` | Yes | -| 10 | `Unknown` | `unknown` (default) | — | +| 5 | `DesktopGuiManual` | `desktop-gui-manual` | No | +| 6 | `Ci` | `ci` | Yes | +| 7 | `McpServer` | `mcp-server` | Yes | +| 8 | `RestApi` | `rest-api` | Yes | +| 9 | `GrpcApi` | `grpc-api` | Yes | +| 10 | `SecurityAgent` | `security-agent` | Yes | +| 11 | `Unknown` | `unknown` (default) | — | ### TaskKind — 30 variants (`request.rs:64`) @@ -290,4 +294,4 @@ All session/task methods on `Runtime` are `async` (`runtime.rs:100–670`). - [tui.md](tui.md) — TUI that consumes runtime events - [cli_commands.md](cli_commands.md) — CLI commands that dispatch through runtime -*Last verified against source: 2026-09-11 (Phase 3 closure); type lines and test counts re-verified 2026-09-25; full re-verification 2026-10-06 (TaskKind 30 variants incl. `Resume`)* +*Last verified against source: 2026-09-11 (Phase 3 closure); type lines and test counts re-verified 2026-09-25; full re-verification 2026-10-06 (TaskKind 30 variants incl. `Resume`); 2026-10-23 (`RuntimeSurface` 10 → 11 variants with `DesktopGuiManual`; optional `schema` feature added)* diff --git a/architecture/runtime_bridge.md b/architecture/runtime_bridge.md index 13a62a603..b384c587a 100644 --- a/architecture/runtime_bridge.md +++ b/architecture/runtime_bridge.md @@ -67,7 +67,7 @@ RuntimeSurface + RunRequest │ ▼ runtime_surface_to_execution_surface() [surface.rs:52] - (10 variants → ExecutionSurface; Unknown → Err) + (11 variants → ExecutionSurface; Unknown → Err) │ ▼ descriptor_for_run_request() [descriptor.rs:15] @@ -104,6 +104,7 @@ Maps each `RuntimeSurface` variant to its `ExecutionSurface` counterpart. This i | `CliManualStrict` | `CliManualStrict` | false | | `TuiManual` | `TuiManual` | **true** | | `TuiManualStrict` | `TuiManualStrict` | false | +| `DesktopGuiManual` | `DesktopGuiManual` | **true** | | `Ci` | `Ci` | false | | `McpServer` | `McpServer` | false | | `RestApi` | `RestApi` | false | @@ -111,7 +112,7 @@ Maps each `RuntimeSurface` variant to its `ExecutionSurface` counterpart. This i | `SecurityAgent` | `SecurityAgent` | false | | `Unknown` | **Error** (`UnknownSurface`) | — | -Only `CliManual` and `TuiManual` honor manual overrides (`eggsec-policy/src/policy.rs:417`). +Only `CliManual`, `TuiManual`, and `DesktopGuiManual` honor manual overrides (`eggsec-policy/src/policy.rs:429`). The desktop GUI is a peer of the CLI and TUI manual surfaces — same permissive profile, same override rule, no strict GUI variant — so it is a new row in this table rather than a new conversion path. The table remains the single exhaustive conversion: `surface.rs` converts in **both** directions (`RuntimeSurface` → `ExecutionSurface` and back), and `Unknown` is still rejected rather than silently mapped. ### TaskKind Resolution (`descriptor.rs`) @@ -243,7 +244,7 @@ pub struct EggsecRuntimeExecutor { 2. Reject `RuntimeSurface::Unknown` 3. Resolve scope via `resolve_loaded_scope()` - Strict surfaces: require explicit `LoadedScope` from disk; fail closed if unavailable - - Permissive manual surfaces (`CliManual`/`TuiManual`): use `default_empty()` + - Permissive manual surfaces (`CliManual`/`TuiManual`/`DesktopGuiManual`): use `default_empty()` 4. Call `approve_run_request_bundle()` for full enforcement 5. Log approved operation for audit 6. Spawn progress forwarder task @@ -259,7 +260,7 @@ pub struct EggsecRuntimeExecutor { The `resolve_loaded_scope()` method (`executor.rs:65–118`) determines scope resolution strategy: - If session has explicit scope with a path → loads from disk via `crate::config::load_scope()` - If session has explicit scope but no path → returns `None` (caller fails closed) -- If permissive surface (`CliManual`/`TuiManual`) → `LoadedScope::default_empty()` +- If permissive surface (`CliManual`/`TuiManual`/`DesktopGuiManual`) → `LoadedScope::default_empty()` - If strict surface without explicit scope → `None` (fail closed) ## Trust Model @@ -273,7 +274,7 @@ The `resolve_loaded_scope()` method (`executor.rs:65–118`) determines scope re ## Invariants 1. **`RuntimeSurface::Unknown` is never executable** — always errors (`surface.rs:65`). -2. **Manual surfaces retain operator-directed semantics** (even daemon-backed) — `CliManual` and `TuiManual` use `approve_manual()` (`manual.rs:60–65`). +2. **Manual surfaces retain operator-directed semantics** (even daemon-backed) — `CliManual`, `TuiManual`, and `DesktopGuiManual` use `approve_manual()` (`manual.rs:60–65`). 3. **Automated surfaces never honor manual overrides** — rejected with `ManualOverrideRejected` before enforcement evaluation (`manual.rs:66–71`). 4. **Any new `RuntimeSurface` variant must update conversion tests** — `surface.rs` unit tests plus the `runtime_contract_closure` integration test (both fail until mapped). 5. **`dispatch_approved_runtime_request` validates both operation ID and target** — mismatches are rejected with explicit errors (`bundle.rs:127–148`). @@ -332,4 +333,4 @@ The bridge module has extensive test coverage across all files: - [overview.md](overview.md) — System-wide architecture, enforcement model - [../docs/ARCHITECTURE.md](../docs/ARCHITECTURE.md) — Section 4.8 (Daemon / Runtime (`runtime_bridge`)) -*Last verified against source: 2026-09-11 (Phase 3 closure); cites re-verified 2026-09-22 (systematic review); file sizes and `ApprovedExecution` bundle shape re-verified 2026-09-25; full re-verification 2026-10-06 (1,900 lines; `TaskKind` 30 variants incl. `Resume`; dispatch path corrected to `execute_approved_execution`)* +*Last verified against source: 2026-09-11 (Phase 3 closure); cites re-verified 2026-09-22 (systematic review); file sizes and `ApprovedExecution` bundle shape re-verified 2026-09-25; full re-verification 2026-10-06 (1,900 lines; `TaskKind` 30 variants incl. `Resume`; dispatch path corrected to `execute_approved_execution`); 2026-10-23 (`DesktopGuiManual` added to the single surface-conversion table in both directions)* diff --git a/architecture/tui.md b/architecture/tui.md index 5cbd1fb49..d233bf523 100644 --- a/architecture/tui.md +++ b/architecture/tui.md @@ -383,7 +383,11 @@ handler does before dispatch. ### Runtime Binding (`app/mod.rs:152`) -`RuntimeBinding` wraps either an `EmbeddedRuntimeClient` or `DaemonRuntimeClient` behind the `TuiRuntimeClient` trait. Methods: `capabilities()`, `create_session()`, `list_sessions()`, `snapshot()`, `submit()`, `cancel()`, `cancel_active()`, `subscribe()`. +`RuntimeBinding` wraps either an `EmbeddedRuntimeClient` or `DaemonRuntimeClient` behind the `RuntimeClient` trait. Methods: `capabilities()`, `create_session()`, `list_sessions()`, `snapshot()`, `submit()`, `cancel()`, `cancel_active()`, `subscribe()`. + +The contract itself lives in the leaf crate **`eggsec-frontend-client`** (see [frontend_client.md](frontend_client.md)). The TUI's former `crates/eggsec-tui/src/runtime_client/` module was removed when the contract was extracted: the trait was renamed `TuiRuntimeClient` → `RuntimeClient`, and the TUI now depends on `eggsec-frontend-client` instead of on `eggsec-daemon-protocol` directly. `App::runtime_client` is therefore `Option>`, and daemon attach mode constructs `eggsec_frontend_client::DaemonRuntimeClient::connect(...)`. + +`connect()` now takes the caller's `ClientIdentity` alongside the socket path, because the contract carries no frontend's identity of its own. The TUI passes its own — `ClientKind::Tui`, label `eggsec-tui`, request-id prefix `tui-` (`crates/eggsec-tui/src/app/mod.rs:390-397`). **The TUI's observable behaviour is unchanged**: the same client kind is declared to the daemon, the same label appears in daemon-side listings, and the request ids keep the `tui-` namespace they always had. The desktop GUI passes its own identity over the same seam — see [desktop_gui.md](desktop_gui.md). ### Attach Mode (`app/runner.rs:415–507`) @@ -597,4 +601,4 @@ Context-aware hints replace static help text. `ActionHint` contains `key` + `lab --- -*Last verified against source: 2026-10-06 (full re-verification of tab inventory, `TAB_SPECS` field values, trait/line cites, theme counts, overlay precedence, key-decoding layers, selector containment, and source-level test counts); earlier passes 2026-08-25 / 2026-09-20 / 2026-09-22 / 2026-09-25* +*Last verified against source: 2026-10-23 (the daemon connect now passes the TUI's own `ClientIdentity` — `ClientKind::Tui` / `eggsec-tui` / `tui-` — over the frontend-client seam; observable behaviour unchanged); earlier pass 2026-10-06 (full re-verification of tab inventory, `TAB_SPECS` field values, trait/line cites, theme counts, overlay precedence, key-decoding layers, selector containment, and source-level test counts); earlier passes 2026-08-25 / 2026-09-20 / 2026-09-22 / 2026-09-25* diff --git a/crates/eggsec-daemon-protocol/Cargo.toml b/crates/eggsec-daemon-protocol/Cargo.toml index bd99a41a3..ffa8879fd 100644 --- a/crates/eggsec-daemon-protocol/Cargo.toml +++ b/crates/eggsec-daemon-protocol/Cargo.toml @@ -8,7 +8,11 @@ rust-version.workspace = true description = "Daemon IPC protocol types and client registry for Eggsec" [dependencies] -eggsec-runtime = { path = "../eggsec-runtime", version = "0.1.0" } +eggsec-runtime = { path = "../eggsec-runtime", version = "0.1.0", features = ["schema"] } +# The canonical operation catalog (ADR-0008). The published description is read +# from it, never transcribed, so the wire shape and the policy source cannot +# drift apart. `eggsec-policy` is a pure semantic kernel: no Tokio, no I/O. +eggsec-policy = { path = "../eggsec-policy", version = "0.1.0" } serde.workspace = true serde_json.workspace = true anyhow.workspace = true diff --git a/crates/eggsec-daemon-protocol/src/client_registry.rs b/crates/eggsec-daemon-protocol/src/client_registry.rs index b4c84d18b..34747d4b2 100644 --- a/crates/eggsec-daemon-protocol/src/client_registry.rs +++ b/crates/eggsec-daemon-protocol/src/client_registry.rs @@ -11,6 +11,12 @@ use eggsec_runtime::{ClientId, RuntimeSurface}; pub enum ClientKind { Cli, Tui, + /// A desktop GUI frontend (the Tauri shell). + /// + /// Additive on the wire: a daemon that predates this variant fails to + /// deserialize the `DeclareClient` command and rejects the client, which + /// is a fail-closed outcome rather than a silent misclassification. + Gui, DaemonInternal, Mcp, Rest, @@ -74,6 +80,10 @@ pub fn command_permission(cmd: &ClientCommand) -> CommandPermission { ClientCommand::ApprovePolicy { .. } => CommandPermission::Approver, ClientCommand::ListPersistedSessions { .. } | ClientCommand::GetPersistedSnapshot { .. } => CommandPermission::DeclaredClient, + // The operation catalog and request schema are daemon-wide + // descriptive state, not session state: a client must have declared + // its identity, but it needs no session and no session role. + ClientCommand::DescribeOperations { .. } => CommandPermission::DeclaredClient, } } @@ -179,7 +189,14 @@ pub fn check_permission( ), }, CommandPermission::Approver => match session_surface { - RuntimeSurface::TuiManual | RuntimeSurface::CliManual => match client_role { + // Manual surfaces accept an approval from an unrelated controller. + // `DesktopGuiManual` is manual by classification in + // `eggsec-policy`, so it belongs here with the other manual + // surfaces — otherwise the RBAC matrix and the policy crate + // disagree about which surfaces are manual. + RuntimeSurface::TuiManual + | RuntimeSurface::CliManual + | RuntimeSurface::DesktopGuiManual => match client_role { ClientRole::Owner | ClientRole::Controller | ClientRole::Approver => Ok(()), ClientRole::Observer => { Err("permission-denied: observers cannot approve policies".into()) @@ -472,7 +489,11 @@ mod tests { #[test] fn manual_surface_approver_allowed() { - let surfaces = vec![RuntimeSurface::TuiManual, RuntimeSurface::CliManual]; + let surfaces = vec![ + RuntimeSurface::TuiManual, + RuntimeSurface::CliManual, + RuntimeSurface::DesktopGuiManual, + ]; for surface in &surfaces { assert!( check_permission( @@ -488,6 +509,60 @@ mod tests { } } + /// The desktop GUI is a manual surface, so an unrelated controller may + /// approve a policy on it exactly as on the CLI and TUI. This mirrors the + /// classification `eggsec-policy` makes for `DesktopGuiManual`; the two + /// must not drift. + #[test] + fn desktop_gui_manual_surface_accepts_controller_approval() { + assert!( + check_permission( + &ClientKind::Gui, + &ClientRole::Controller, + &RuntimeSurface::DesktopGuiManual, + CommandPermission::Approver, + ) + .is_ok(), + "a controller must be able to approve on the desktop GUI's manual surface" + ); + assert!( + check_permission( + &ClientKind::Gui, + &ClientRole::Observer, + &RuntimeSurface::DesktopGuiManual, + CommandPermission::Approver, + ) + .is_err(), + "an observer must not be able to approve on the desktop GUI's manual surface" + ); + } + + /// The GUI's client kind is additive on the wire: it must round-trip + /// through serde under the enum's own tag, and it must not disturb the + /// existing variants. + #[test] + fn client_kind_gui_round_trips_through_serde() { + let json = serde_json::to_string(&ClientKind::Gui).expect("serializable"); + assert!(json.contains("Gui"), "unexpected wire form: {json}"); + let back: ClientKind = serde_json::from_str(&json).expect("deserializable"); + assert_eq!(back, ClientKind::Gui); + + // The pre-existing kinds keep their wire forms. + for kind in [ + ClientKind::Cli, + ClientKind::Tui, + ClientKind::DaemonInternal, + ClientKind::Mcp, + ClientKind::Rest, + ClientKind::Agent, + ClientKind::Unknown, + ] { + let json = serde_json::to_string(&kind).expect("serializable"); + let back: ClientKind = serde_json::from_str(&json).expect("deserializable"); + assert_eq!(back, kind); + } + } + #[test] fn observer_denied_on_all_mutation_permissions() { let mutation_perms = vec![CommandPermission::Controller, CommandPermission::Owner]; diff --git a/crates/eggsec-daemon-protocol/src/lib.rs b/crates/eggsec-daemon-protocol/src/lib.rs index 42b96bdf0..9fd6fb558 100644 --- a/crates/eggsec-daemon-protocol/src/lib.rs +++ b/crates/eggsec-daemon-protocol/src/lib.rs @@ -1,2 +1,3 @@ pub mod client_registry; +pub mod operations; pub mod protocol; diff --git a/crates/eggsec-daemon-protocol/src/operations.rs b/crates/eggsec-daemon-protocol/src/operations.rs new file mode 100644 index 000000000..a445aad2b --- /dev/null +++ b/crates/eggsec-daemon-protocol/src/operations.rs @@ -0,0 +1,299 @@ +//! Read-only publication of the canonical operation catalog and the +//! mechanically derived request schema (`ADR-0008`). +//! +//! # One source of truth +//! +//! The identity and policy fields in [`OperationDescription`] are read from +//! `eggsec_policy::ALL_OPERATION_METADATA` — the canonical catalog — and are +//! never transcribed here. The parameter structure in +//! [`TaskKindDescription`] is derived from the canonical request DTOs by +//! `eggsec_runtime::schema`, never hand-written. +//! +//! # Descriptive, not authoritative +//! +//! Nothing in this module participates in authorization, dispatch, scope, or +//! policy evaluation. It is a published *view* of the operation set, for +//! frontends that need to render a form for an operation they can already +//! invoke. A client's view of an operation never grants, narrows, or widens +//! what the engine will run: the engine's own enforcement remains +//! authoritative, and engine-side validation remains authoritative for the +//! contents of any field. + +use eggsec_policy::catalog::OperationMetadata; +use eggsec_policy::{Capability, IntendedUse, OperationMode, OperationRisk}; +use serde::{Deserialize, Serialize}; + +/// Wire description of one canonical operation. +/// +/// Every field is read from [`OperationMetadata`]; see the module docs. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct OperationDescription { + /// Canonical operation id, e.g. `scan-ports`. + pub id: String, + /// Human-readable name, e.g. `Port Scan`. + pub display_name: String, + /// Assessment mode the operation belongs to. + pub mode: OperationMode, + /// Declared risk tier. + pub risk: OperationRisk, + /// Declared intended uses. + pub intended_uses: Vec, + /// Engine features the operation requires. + pub required_features: Vec, + /// Policy flags the operation requires. + pub required_policy_flags: Vec, + /// Runtime capabilities the operation requires. + pub required_capabilities: Vec, + /// Target policy requirement, as the catalog's canonical label + /// (`no-target`, `target-required`, `explicit-scope-required`, ...). + pub target_policy: String, + /// Whether the operation is exposed on the manual surface. + pub manual_exposable: bool, + /// Whether the operation is exposed on the TUI surface. + pub tui_exposable: bool, + /// Whether the operation is exposed over MCP. + pub mcp_exposable: bool, + /// Whether the operation is exposed over REST. + pub rest_exposable: bool, + /// Whether the operation is exposed to the security agent. + pub agent_exposable: bool, + /// Whether the operation is exposed over gRPC. + pub grpc_exposable: bool, +} + +/// Wire description of one task-kind wire shape and its request schema. +/// +/// A task kind is a wire shape, not an operation: the three packet kinds +/// share the `packet` operation, `Pipeline` and `Resume` share `pipeline`, and +/// `Wireless` and `WirelessActive` share `wireless`. A client renders one +/// form per task kind and looks the operation's risk and exposure up by +/// [`Self::operation_id`]. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TaskKindDescription { + /// The wire `kind` discriminator, e.g. `PortScan`. + pub variant: String, + /// Canonical operation id this task kind executes. + pub operation_id: String, + /// Wire capability name this task kind advertises. + pub capability_name: String, + /// JSON Schema for the task kind's params struct. + pub request_schema: serde_json::Value, +} + +/// Response payload for `ClientCommand::DescribeOperations`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DescribeOperationsResponse { + /// Every canonical operation in the catalog. + pub operations: Vec, + /// Every task-kind wire shape, with its request schema. + pub task_kinds: Vec, + /// The whole `TaskKind` schema in its adjacently-tagged wire shape, so a + /// client can post `{"kind": ..., "params": ...}` without guessing the + /// envelope. + pub task_kind_schema: serde_json::Value, +} + +/// Build the describe-operations payload from the canonical sources. +/// +/// Read-only and side-effect free: it touches no session, task, or registry +/// state, so it is safe to call concurrently. +pub fn describe_operations() -> DescribeOperationsResponse { + DescribeOperationsResponse { + operations: eggsec_policy::ALL_OPERATION_METADATA + .iter() + .map(describe_operation) + .collect(), + task_kinds: eggsec_runtime::schema::task_kind_schemas() + .into_iter() + .map(|entry| TaskKindDescription { + variant: entry.variant, + operation_id: entry.operation_id, + capability_name: entry.capability_name, + request_schema: entry.schema, + }) + .collect(), + task_kind_schema: eggsec_runtime::schema::task_kind_schema(), + } +} + +/// Describe one catalog entry. +fn describe_operation(metadata: &OperationMetadata) -> OperationDescription { + OperationDescription { + id: metadata.id.to_owned(), + display_name: metadata.display_name.to_owned(), + mode: metadata.mode, + risk: metadata.risk, + intended_uses: metadata.intended_uses.to_vec(), + required_features: metadata + .required_features + .iter() + .map(|feature| (*feature).to_owned()) + .collect(), + required_policy_flags: metadata + .required_policy_flags + .iter() + .map(|flag| (*flag).to_owned()) + .collect(), + required_capabilities: metadata.required_capabilities.to_vec(), + target_policy: metadata.target_policy.to_string(), + manual_exposable: metadata.manual_exposable, + tui_exposable: metadata.tui_exposable, + mcp_exposable: metadata.mcp_exposable, + rest_exposable: metadata.rest_exposable, + agent_exposable: metadata.agent_exposable, + grpc_exposable: metadata.grpc_exposable, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_catalog_operation_is_described() { + let response = describe_operations(); + assert_eq!( + response.operations.len(), + eggsec_policy::ALL_OPERATION_METADATA.len() + ); + } + + /// The published identity and policy fields must match the catalog field + /// for field. If this fails, the response was transcribed rather than + /// read from the catalog. + #[test] + fn published_operations_match_the_catalog_field_for_field() { + let response = describe_operations(); + for metadata in eggsec_policy::ALL_OPERATION_METADATA { + let published = response + .operations + .iter() + .find(|operation| operation.id == metadata.id) + .expect("every catalog operation must be published"); + assert_eq!(published.display_name, metadata.display_name); + assert_eq!(published.mode, metadata.mode); + assert_eq!(published.risk, metadata.risk); + assert_eq!(published.intended_uses, metadata.intended_uses); + assert_eq!( + published.required_features, + metadata + .required_features + .iter() + .map(|feature| (*feature).to_owned()) + .collect::>() + ); + assert_eq!( + published.required_policy_flags, + metadata + .required_policy_flags + .iter() + .map(|flag| (*flag).to_owned()) + .collect::>() + ); + assert_eq!( + published.required_capabilities, + metadata.required_capabilities + ); + assert_eq!(published.target_policy, metadata.target_policy.to_string()); + assert_eq!(published.manual_exposable, metadata.manual_exposable); + assert_eq!(published.tui_exposable, metadata.tui_exposable); + assert_eq!(published.mcp_exposable, metadata.mcp_exposable); + assert_eq!(published.rest_exposable, metadata.rest_exposable); + assert_eq!(published.agent_exposable, metadata.agent_exposable); + assert_eq!(published.grpc_exposable, metadata.grpc_exposable); + } + } + + /// Every published task kind must name a canonical operation. + #[test] + fn published_task_kinds_name_canonical_operations() { + let response = describe_operations(); + assert_eq!(response.task_kinds.len(), 30); + for task_kind in &response.task_kinds { + assert!( + response + .operations + .iter() + .any(|operation| operation.id == task_kind.operation_id), + "{} names operation {}, which is not in the catalog", + task_kind.variant, + task_kind.operation_id + ); + } + } + + /// The response carries operation identity, policy metadata, and + /// parameter structure — and nothing else. + /// + /// A credential, a secret, or a scope rule would have to arrive either as + /// an extra field on the metadata half or as an extra value on the + /// parameter half. The first is ruled out by the closed field set; the + /// second by the fact that the parameter half is a JSON Schema — property + /// names, types, and the serde defaults of the request structs — which + /// contains no request values at all. + #[test] + fn response_carries_no_credential_or_scope_material() { + const ALLOWED_OPERATION_FIELDS: [&str; 15] = [ + "id", + "display_name", + "mode", + "risk", + "intended_uses", + "required_features", + "required_policy_flags", + "required_capabilities", + "target_policy", + "manual_exposable", + "tui_exposable", + "mcp_exposable", + "rest_exposable", + "agent_exposable", + "grpc_exposable", + ]; + + let response = describe_operations(); + for operation in &response.operations { + let json = serde_json::to_value(operation).expect("serializable"); + let object = json.as_object().expect("an object"); + assert_eq!( + object.len(), + ALLOWED_OPERATION_FIELDS.len(), + "the published operation description carries an unexpected field" + ); + for key in object.keys() { + assert!( + ALLOWED_OPERATION_FIELDS.contains(&key.as_str()), + "unexpected published field: {key}" + ); + } + } + + // No scope rule, secret, or bearer token is published. The canonical + // catalog and the request DTOs contain no such material, so a + // published artifact cannot introduce it. + let serialized = serde_json::to_string(&response).expect("serializable"); + for forbidden in [ + "\"cidr\"", + "\"scope_rules\"", + "\"api_key\"", + "\"secret\"", + "\"bearer\"", + ] { + assert!( + !serialized.contains(forbidden), + "the published response must not contain {forbidden} material" + ); + } + } + + /// The payload is read-only: two calls produce equivalent results. + #[test] + fn payload_is_reproducible() { + let first = describe_operations(); + let second = describe_operations(); + assert_eq!( + serde_json::to_value(&first).expect("serializable"), + serde_json::to_value(&second).expect("serializable") + ); + } +} diff --git a/crates/eggsec-daemon-protocol/src/protocol.rs b/crates/eggsec-daemon-protocol/src/protocol.rs index dbe51f660..ef444f904 100644 --- a/crates/eggsec-daemon-protocol/src/protocol.rs +++ b/crates/eggsec-daemon-protocol/src/protocol.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; use crate::client_registry::ClientKind; +use crate::operations::DescribeOperationsResponse; /// Protocol version for daemon IPC compatibility negotiation. /// @@ -47,6 +48,17 @@ pub struct TransportCapability { pub struct DaemonCapabilities { pub runtime: RuntimeCapabilities, pub transports: Vec, + /// Whether this daemon can publish the operation catalog and the derived + /// request schema via `ClientCommand::DescribeOperations`. + /// + /// `#[serde(default)]` so a newer daemon's capabilities still decode + /// against an older client's `DaemonCapabilities`, and so this daemon's + /// capabilities still decode against a client built before the flag + /// existed. A client that sees `false` — or that receives + /// `ErrorCode::UnsupportedCommand` from a daemon too old to know the + /// command — degrades to a static form set rather than failing. + #[serde(default)] + pub operation_schema: bool, } /// Error codes returned by the daemon in response to client commands. @@ -154,6 +166,23 @@ pub enum ClientCommand { request_id: String, session_id: SessionId, }, + /// Describe every canonical operation and the derived request schema. + /// + /// Read-only and additive: it creates no session, mutates no task state, + /// and takes part in no authorization decision. It carries no fields + /// beyond its own identity so it can be issued before any session exists. + /// + /// The response carries the operation catalog as read from + /// `OperationMetadata` plus a JSON Schema derived from the canonical + /// request DTOs. Both are descriptive: a client that renders a form from + /// this payload gains no capability the engine would not otherwise grant. + /// + /// A daemon that does not know this command answers + /// `ErrorCode::UnsupportedCommand`; a client MUST treat that as "schema + /// unavailable" and degrade to a static form set rather than fail. + DescribeOperations { + request_id: String, + }, } impl ClientCommand { @@ -174,6 +203,7 @@ impl ClientCommand { | Self::CloseSession { request_id, .. } | Self::ApprovePolicy { request_id, .. } | Self::ListPersistedSessions { request_id } + | Self::DescribeOperations { request_id } | Self::GetPersistedSnapshot { request_id, .. } => request_id, } } @@ -211,6 +241,7 @@ impl ClientCommand { Self::CloseSession { .. } => "close-session", Self::ApprovePolicy { .. } => "approve-policy", Self::ListPersistedSessions { .. } => "list-persisted-sessions", + Self::DescribeOperations { .. } => "describe-operations", Self::GetPersistedSnapshot { .. } => "get-persisted-snapshot", } } @@ -289,6 +320,11 @@ pub enum ServerMessage { request_id: String, snapshot: Option, }, + /// The canonical operation catalog plus the derived request schema. + Operations { + request_id: String, + operations: DescribeOperationsResponse, + }, } #[cfg(test)] @@ -640,17 +676,46 @@ mod tests { capabilities: DaemonCapabilities { runtime: RuntimeCapabilities::default(), transports: vec![], + operation_schema: true, }, }; let json = serde_json::to_string(&msg).unwrap(); let back: ServerMessage = serde_json::from_str(&json).unwrap(); if let ServerMessage::Capabilities { capabilities, .. } = back { assert!(capabilities.runtime.supports_cancellation); + assert!(capabilities.operation_schema); } else { panic!("wrong variant"); } } + /// A client built before the capability flag existed must still decode a + /// newer daemon's capabilities: the field defaults to `false` rather than + /// failing the whole handshake. + #[test] + fn daemon_capabilities_decode_without_the_operation_schema_flag() { + let json = r#"{"runtime":{"task_kinds":[],"transports":[],"supports_cancellation":true,"supports_multiple_sessions":true,"supports_multiple_active_tasks":false},"transports":[]}"#; + let capabilities: DaemonCapabilities = serde_json::from_str(json).unwrap(); + assert!(!capabilities.operation_schema); + } + + /// The new command is additive: it carries only its own identity, and it + /// round-trips on the flat `#[serde(tag = "type")]` encoding every other + /// command already uses. + #[test] + fn describe_operations_command_roundtrips() { + let cmd = ClientCommand::DescribeOperations { request_id: rid() }; + let json = serde_json::to_string(&cmd).unwrap(); + assert_eq!( + json, + r#"{"type":"DescribeOperations","request_id":"req-001"}"# + ); + let back: ClientCommand = serde_json::from_str(&json).unwrap(); + assert!(matches!(back, ClientCommand::DescribeOperations { .. })); + assert_eq!(back.request_id(), "req-001"); + assert_eq!(back.discriminant(), "describe-operations"); + } + #[test] fn server_message_roundtrip_health() { let msg = ServerMessage::Health { diff --git a/crates/eggsec-daemon/Cargo.toml b/crates/eggsec-daemon/Cargo.toml index f88087965..9b5b02c54 100644 --- a/crates/eggsec-daemon/Cargo.toml +++ b/crates/eggsec-daemon/Cargo.toml @@ -43,6 +43,13 @@ futures = { version = "0.3", optional = true } [dev-dependencies] reqwest = { version = "0.13", features = ["json", "rustls-no-provider"], default-features = false } eggsec = { path = "../eggsec", version = "0.1.0" } +# Test-only: lets the daemon's own tests compare the published operation +# description against the canonical catalog it claims to be read from. +eggsec-policy = { path = "../eggsec-policy", version = "0.1.0" } +# Test-only: exercises the desktop GUI's own client path — its client kind, +# its request-id namespace, and its `DesktopGuiManual` session — against a +# live daemon host over the real Unix socket. +eggsec-frontend-client = { path = "../eggsec-frontend-client", version = "0.1.0" } # Ring provider for the reqwest test client (`rustls-no-provider` requires an # explicitly installed process-level crypto provider). rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } diff --git a/crates/eggsec-daemon/src/host.rs b/crates/eggsec-daemon/src/host.rs index af93f6a54..24b1badb3 100644 --- a/crates/eggsec-daemon/src/host.rs +++ b/crates/eggsec-daemon/src/host.rs @@ -193,6 +193,22 @@ impl DaemonHost { result } + /// The audit surface label for a session. + /// + /// Session-scoped audit events carry the *session's* runtime surface, not + /// a blanket "daemon" label, so a desktop GUI session is distinguishable + /// from a TUI session in the persisted audit trail. Events that have no + /// session — client declaration, startup recovery — are genuinely + /// daemon-level and keep "daemon". + fn session_surface_label(&self, session_id: &eggsec_runtime::SessionId) -> String { + self.session_access + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(session_id) + .map(|access| access.surface.label().to_owned()) + .unwrap_or_else(|| "daemon".to_owned()) + } + /// Recover persisted session state from the store on startup. /// /// Loads all persisted sessions and reconstructs them in the runtime. @@ -297,7 +313,7 @@ impl DaemonHost { if let Err(error) = self .record_audit_event(PersistedAuditEvent { action: format!("command-denied:{}", cmd.discriminant()), - surface: "daemon".into(), + surface: self.session_surface_label(session_id), outcome: "denied".into(), client_id: client_id.map(|c| c.to_string()), session_id: Some(session_id.to_string()), @@ -329,6 +345,18 @@ impl DaemonHost { message: "client must declare before listing persisted sessions".into(), }; } + } else if let ClientCommand::DescribeOperations { request_id } = &cmd { + // The operation catalog and request schema are daemon-wide + // descriptive state rather than session state, so this command + // carries no session id — but it still requires a declared client + // identity, exactly like the other daemon-wide reads above. + if client_id.is_none() { + return ServerMessage::Error { + request_id: request_id.clone(), + code: ErrorCode::ClientNotDeclared, + message: "client must declare before describing operations".into(), + }; + } } match cmd { @@ -360,6 +388,9 @@ impl DaemonHost { bind_address: self.config.socket_path.clone(), enabled: true, }], + // This daemon can always publish the operation catalog + // and the derived request schema. + operation_schema: true, }, } } @@ -420,6 +451,9 @@ impl DaemonHost { } else { surface }; + // The audit trail records the surface the session was created + // with, so a GUI session is distinguishable from a TUI one. + let audit_surface = surface.label().to_owned(); match self .runtime() .create_session_with_scope(Default::default(), surface.clone(), scope) @@ -470,7 +504,7 @@ impl DaemonHost { store.as_ref(), PersistedAuditEvent { action: "create-session".into(), - surface: "daemon".into(), + surface: audit_surface, outcome: "allow".into(), client_id: client_id_str, session_id: Some(session_id_copy.to_string()), @@ -577,6 +611,7 @@ impl DaemonHost { let runtime = self.runtime.clone(); let enable_persistence = self.config.enable_persistence; let client_id_str = client_id.map(|c| c.to_string()); + let audit_surface = self.session_surface_label(&session_id); tokio::spawn(persistence_with_timeout("submit-task", async move { if enable_persistence { if let Ok(snapshot) = runtime.snapshot(session_id).await { @@ -588,7 +623,7 @@ impl DaemonHost { store.as_ref(), PersistedAuditEvent { action: "submit-task".into(), - surface: "daemon".into(), + surface: audit_surface, outcome: "allow".into(), client_id: client_id_str, session_id: Some(session_id.to_string()), @@ -637,6 +672,7 @@ impl DaemonHost { let runtime = self.runtime.clone(); let enable_persistence = self.config.enable_persistence; let client_id_str = client_id.map(|c| c.to_string()); + let audit_surface = self.session_surface_label(&session_id); tokio::spawn(persistence_with_timeout("cancel-task", async move { if enable_persistence { if let Ok(snapshot) = runtime.snapshot(session_id).await { @@ -648,7 +684,7 @@ impl DaemonHost { store.as_ref(), PersistedAuditEvent { action: "cancel-task".into(), - surface: "daemon".into(), + surface: audit_surface, outcome: "allow".into(), client_id: client_id_str, session_id: Some(session_id.to_string()), @@ -694,6 +730,7 @@ impl DaemonHost { let runtime = self.runtime.clone(); let enable_persistence = self.config.enable_persistence; let client_id_str = client_id.map(|c| c.to_string()); + let audit_surface = self.session_surface_label(&session_id); tokio::spawn(persistence_with_timeout("cancel-active", async move { if enable_persistence { if let Ok(snapshot) = runtime.snapshot(session_id).await { @@ -705,7 +742,7 @@ impl DaemonHost { store.as_ref(), PersistedAuditEvent { action: "cancel-active".into(), - surface: "daemon".into(), + surface: audit_surface, outcome: "allow".into(), client_id: client_id_str, session_id: Some(session_id.to_string()), @@ -749,6 +786,7 @@ impl DaemonHost { let runtime = self.runtime.clone(); let enable_persistence = self.config.enable_persistence; let client_id_str = client_id.map(|c| c.to_string()); + let audit_surface = self.session_surface_label(&session_id); tokio::spawn(persistence_with_timeout("close-session", async move { if enable_persistence { if let Ok(snapshot) = runtime.snapshot(session_id).await { @@ -760,7 +798,7 @@ impl DaemonHost { store.as_ref(), PersistedAuditEvent { action: "close-session".into(), - surface: "daemon".into(), + surface: audit_surface, outcome: "allow".into(), client_id: client_id_str, session_id: Some(session_id.to_string()), @@ -978,6 +1016,28 @@ impl DaemonHost { }, } } + + ClientCommand::DescribeOperations { request_id } => { + // Read-only publication of the canonical operation catalog and + // the derived request schema (ADR-0008). + // + // The payload is assembled from immutable registry data, so it + // is safe to serve concurrently and reproduces exactly. This + // command creates no session, mutates no task state, and takes + // part in no authorization decision: it reads the catalog and + // a derived schema, and grants nothing. + // + // Access control is inherited from the surrounding dispatch + // rather than re-implemented here: the command carries no + // session id, so the session-scoped permission check above + // does not apply to it, and it is answerable before any + // session exists. A declared client identity is still + // required, exactly as for the other daemon-wide reads. + ServerMessage::Operations { + request_id, + operations: crate::operations::describe_operations(), + } + } } } @@ -1181,6 +1241,309 @@ mod tests { } } + /// The daemon advertises that it can publish the operation catalog and the + /// derived request schema, so a client can discover the capability without + /// issuing the command and failing. + #[tokio::test] + async fn capabilities_advertise_the_operation_schema() { + let host = test_host(); + let resp = host + .handle_command( + ClientCommand::Capabilities { + request_id: "cap-schema".into(), + }, + test_ctx(None), + ) + .await; + match resp { + ServerMessage::Capabilities { capabilities, .. } => { + assert!(capabilities.operation_schema); + } + other => panic!("expected Capabilities, got {:?}", other), + } + } + + /// The command serves the canonical operation catalog together with the + /// derived request schema. + #[tokio::test] + async fn handle_describe_operations() { + let host = test_host(); + let client_id = declare_test_client(&host).await; + let resp = host + .handle_command( + ClientCommand::DescribeOperations { + request_id: "describe-1".into(), + }, + test_ctx(Some(client_id)), + ) + .await; + let ServerMessage::Operations { + request_id, + operations, + } = resp + else { + panic!("expected Operations, got {:?}", resp); + }; + assert_eq!(request_id, "describe-1"); + assert!(!operations.operations.is_empty()); + assert_eq!(operations.task_kinds.len(), 30); + assert!(!operations.task_kind_schema.is_null()); + // Every published operation names a canonical catalog id. + for operation in &operations.operations { + assert!(!operation.id.is_empty()); + assert!(!operation.display_name.is_empty()); + } + } + + /// The published identity and policy fields must match the catalog field + /// for field. If this fails, the daemon published a transcribed copy + /// rather than reading the catalog. + #[tokio::test] + async fn describe_operations_matches_the_catalog() { + let host = test_host(); + let client_id = declare_test_client(&host).await; + let resp = host + .handle_command( + ClientCommand::DescribeOperations { + request_id: "describe-catalog".into(), + }, + test_ctx(Some(client_id)), + ) + .await; + let ServerMessage::Operations { operations, .. } = resp else { + panic!("expected Operations, got {:?}", resp); + }; + assert_eq!( + operations.operations.len(), + eggsec_policy::ALL_OPERATION_METADATA.len() + ); + for metadata in eggsec_policy::ALL_OPERATION_METADATA { + let published = operations + .operations + .iter() + .find(|operation| operation.id == metadata.id) + .expect("every catalog operation must be published"); + assert_eq!(published.display_name, metadata.display_name); + assert_eq!(published.mode, metadata.mode); + assert_eq!(published.risk, metadata.risk); + assert_eq!(published.target_policy, metadata.target_policy.to_string()); + assert_eq!(published.manual_exposable, metadata.manual_exposable); + assert_eq!(published.rest_exposable, metadata.rest_exposable); + } + } + + /// The command is daemon-wide descriptive state, so it requires a declared + /// client identity exactly like the other daemon-wide reads. An undeclared + /// client is rejected by the surrounding dispatch, not by a bespoke rule. + #[tokio::test] + async fn describe_operations_requires_a_declared_client() { + let host = test_host(); + let resp = host + .handle_command( + ClientCommand::DescribeOperations { + request_id: "describe-undeclared".into(), + }, + test_ctx(None), + ) + .await; + match resp { + ServerMessage::Error { + code: ErrorCode::ClientNotDeclared, + .. + } => {} + other => panic!("expected ClientNotDeclared, got {:?}", other), + } + } + + /// The command creates no task state and mutates no session state. + #[tokio::test] + async fn describe_operations_creates_no_task_state() { + let host = test_host(); + let client_id = declare_test_client(&host).await; + let before = host + .handle_command( + ClientCommand::ListSessions { + request_id: "list-before".into(), + }, + test_ctx(Some(client_id)), + ) + .await; + let _ = host + .handle_command( + ClientCommand::DescribeOperations { + request_id: "describe-no-state".into(), + }, + test_ctx(Some(client_id)), + ) + .await; + let after = host + .handle_command( + ClientCommand::ListSessions { + request_id: "list-after".into(), + }, + test_ctx(Some(client_id)), + ) + .await; + let ServerMessage::Sessions { + sessions: before, .. + } = before + else { + panic!("expected Sessions, got {:?}", before); + }; + let ServerMessage::Sessions { + sessions: after, .. + } = after + else { + panic!("expected Sessions, got {:?}", after); + }; + assert_eq!( + serde_json::to_value(&before).expect("serializable"), + serde_json::to_value(&after).expect("serializable"), + "DescribeOperations must not create or mutate session state" + ); + } + + /// The payload is immutable registry data, so concurrent readers see the + /// same thing and none of them observes a partial result. + #[tokio::test] + async fn describe_operations_is_concurrency_safe() { + let host = test_host(); + let client_id = declare_test_client(&host).await; + let (first, second) = tokio::join!( + host.handle_command( + ClientCommand::DescribeOperations { + request_id: "concurrent-1".into(), + }, + test_ctx(Some(client_id)), + ), + host.handle_command( + ClientCommand::DescribeOperations { + request_id: "concurrent-2".into(), + }, + test_ctx(Some(client_id)), + ), + ); + let ServerMessage::Operations { + operations: first_ops, + .. + } = first + else { + panic!("expected Operations, got {:?}", first); + }; + let ServerMessage::Operations { + operations: second_ops, + .. + } = second + else { + panic!("expected Operations, got {:?}", second); + }; + assert_eq!( + serde_json::to_value(&first_ops).expect("serializable"), + serde_json::to_value(&second_ops).expect("serializable"), + ); + } + + /// A desktop GUI session must be distinguishable from a TUI session in the + /// persisted audit trail: a session-scoped audit record carries the + /// session's runtime surface, not a blanket "daemon" label. + #[tokio::test] + async fn gui_session_audit_trail_carries_the_gui_surface_label() { + let store = std::sync::Arc::new( + crate::store::SqliteStore::new_in_memory().expect("an in-memory store"), + ); + let host = DaemonHost::new( + DaemonConfig { + enable_persistence: true, + ..Default::default() + }, + TestExecutor, + store.clone(), + ); + + for surface in [ + eggsec_runtime::RuntimeSurface::DesktopGuiManual, + eggsec_runtime::RuntimeSurface::TuiManual, + ] { + let resp = host + .handle_command( + ClientCommand::CreateSession { + request_id: "gui-audit".into(), + surface, + scope: None, + labels: vec![], + }, + test_ctx(None), + ) + .await; + assert!( + matches!(resp, ServerMessage::SessionCreated { .. }), + "the session must be created" + ); + } + + // The audit write happens on a fire-and-forget persistence task, so + // the rows appear shortly after the command returns. + let mut surfaces: Vec = Vec::new(); + for _ in 0..200 { + surfaces = store.audit_surfaces(); + if surfaces.len() >= 2 { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + assert!( + surfaces + .iter() + .any(|surface| surface == "desktop-gui-manual"), + "a GUI session must be auditable as desktop-gui-manual, got {surfaces:?}" + ); + assert!( + surfaces.iter().any(|surface| surface == "tui-manual"), + "a TUI session must be auditable as tui-manual, got {surfaces:?}" + ); + assert!( + !surfaces.iter().any(|surface| surface == "daemon"), + "a session-scoped audit event must not carry the blanket daemon label, got {surfaces:?}" + ); + } + + /// A session-less daemon event is genuinely daemon-level and keeps the + /// "daemon" label. + #[tokio::test] + async fn session_less_audit_events_keep_the_daemon_label() { + let store = std::sync::Arc::new( + crate::store::SqliteStore::new_in_memory().expect("an in-memory store"), + ); + let host = DaemonHost::new( + DaemonConfig { + enable_persistence: true, + ..Default::default() + }, + TestExecutor, + store.clone(), + ); + let _ = host + .handle_command( + ClientCommand::DeclareClient { + request_id: "declare-audit".into(), + kind: ClientKind::Tui, + label: None, + }, + test_ctx(None), + ) + .await; + + let mut surfaces: Vec = Vec::new(); + for _ in 0..200 { + surfaces = store.audit_surfaces(); + if !surfaces.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + assert_eq!(surfaces, vec!["daemon".to_owned()]); + } + #[tokio::test] async fn handle_create_session_and_list() { let host = test_host(); @@ -2061,6 +2424,7 @@ mod tests { for kind in [ ClientKind::Tui, ClientKind::Cli, + ClientKind::Gui, ClientKind::Mcp, ClientKind::Rest, ClientKind::Agent, diff --git a/crates/eggsec-daemon/src/lib.rs b/crates/eggsec-daemon/src/lib.rs index 51e5095a0..8098fd841 100644 --- a/crates/eggsec-daemon/src/lib.rs +++ b/crates/eggsec-daemon/src/lib.rs @@ -1,4 +1,5 @@ pub use eggsec_daemon_protocol::client_registry; +pub use eggsec_daemon_protocol::operations; pub use eggsec_daemon_protocol::protocol; pub mod client; diff --git a/crates/eggsec-daemon/src/server.rs b/crates/eggsec-daemon/src/server.rs index cd12b7e33..02fb4137c 100644 --- a/crates/eggsec-daemon/src/server.rs +++ b/crates/eggsec-daemon/src/server.rs @@ -404,6 +404,120 @@ mod tests { (host, socket_path, shutdown) } + /// The desktop GUI's own client path, end to end against a live daemon + /// host over the real Unix socket. + /// + /// This is the GUI crate's boundary exercised from the daemon's side: + /// the GUI cannot depend on the daemon crate, so the test that proves + /// the two fit together lives here. It covers the client's own identity + /// — its `Gui` kind, its `gui-` request-id namespace, and its + /// `DesktopGuiManual` session — and the catalog the GUI renders. + #[tokio::test] + async fn the_gui_client_path_works_end_to_end() { + use eggsec_frontend_client::{ClientIdentity, DaemonRuntimeClient, RuntimeClient}; + + let store = std::sync::Arc::new( + crate::store::SqliteStore::new_in_memory().expect("an in-memory store"), + ); + let socket_path = format!("/tmp/eggsec-gui-test-{}.sock", uuid::Uuid::new_v4()); + let host = Arc::new(DaemonHost::new( + DaemonConfig { + socket_path: socket_path.clone(), + enable_persistence: true, + ..Default::default() + }, + TestExecutor, + store.clone(), + )); + let shutdown = CancellationToken::new(); + + let host_clone = host.clone(); + let shutdown_clone = shutdown.clone(); + tokio::spawn(async move { + run_server(host_clone, shutdown_clone).await.unwrap(); + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + + let client = DaemonRuntimeClient::connect( + &socket_path, + ClientIdentity { + kind: eggsec_daemon_protocol::client_registry::ClientKind::Gui, + label: "eggsec-gui".to_owned(), + request_prefix: "gui-".to_owned(), + }, + ) + .await + .expect("the GUI client connects"); + + // The daemon accepts the GUI's declaration and answers its + // handshake. + let health = client.health().await.expect("the daemon answers health"); + assert_eq!( + health.protocol_version, + eggsec_daemon_protocol::protocol::DAEMON_PROTOCOL_VERSION + ); + + let capabilities = client + .daemon_capabilities() + .await + .expect("the daemon answers capabilities"); + assert!( + capabilities.operation_schema, + "the daemon publishes the operation schema the GUI renders" + ); + + let catalog = client + .describe_operations() + .await + .expect("the daemon publishes the catalog"); + assert_eq!(catalog.task_kinds.len(), 30); + assert!(!catalog.operations.is_empty()); + + // The GUI opens its own surface, with the scope it constructs + // itself. + let session_id = client + .create_session( + eggsec_runtime::RuntimeSurface::DesktopGuiManual, + Some(eggsec_runtime::session::SessionScope { + is_explicit: false, + source: "gui-default".to_owned(), + path: None, + }), + vec![], + ) + .await + .expect("the daemon opens a desktop-GUI session"); + + let snapshot = client + .snapshot(session_id) + .await + .expect("the GUI session resolves"); + assert_eq!(snapshot.session_id, session_id); + + // The audit trail records the GUI's surface label, not a blanket + // "daemon". + let mut surfaces: Vec = Vec::new(); + for _ in 0..200 { + surfaces = store.audit_surfaces(); + if surfaces + .iter() + .any(|surface| surface == "desktop-gui-manual") + { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + assert!( + surfaces + .iter() + .any(|surface| surface == "desktop-gui-manual"), + "a GUI session must be auditable as desktop-gui-manual, got {surfaces:?}" + ); + + shutdown.cancel(); + let _ = std::fs::remove_file(&socket_path); + } + async fn connect( socket_path: &str, ) -> ( diff --git a/crates/eggsec-daemon/src/store/sqlite.rs b/crates/eggsec-daemon/src/store/sqlite.rs index 4d9e8d0b0..d43912b74 100644 --- a/crates/eggsec-daemon/src/store/sqlite.rs +++ b/crates/eggsec-daemon/src/store/sqlite.rs @@ -60,6 +60,25 @@ impl SqliteStore { Ok(store) } + /// Test-only: the surface label of every persisted audit event, in write + /// order. + /// + /// The store trait has no audit read-back — audit rows are written for + /// external inspection. This helper exists so a test can assert what the + /// daemon actually persisted. + #[cfg(test)] + pub fn audit_surfaces(&self) -> Vec { + let conn = lock_conn(&self.conn); + let mut statement = conn + .prepare("SELECT surface FROM audit_events ORDER BY audit_id") + .expect("the audit_events table must exist"); + let rows = statement + .query_map([], |row| row.get::<_, String>(0)) + .expect("the audit surface query must succeed"); + rows.map(|row| row.expect("an audit surface row must read")) + .collect() + } + fn migrate(&self) -> anyhow::Result<()> { let conn = lock_conn(&self.conn); conn.execute_batch(SCHEMA_DDL)?; diff --git a/crates/eggsec-frontend-client/Cargo.toml b/crates/eggsec-frontend-client/Cargo.toml new file mode 100644 index 000000000..e0ed16b44 --- /dev/null +++ b/crates/eggsec-frontend-client/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "eggsec-frontend-client" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "Frontend-neutral runtime client contract shared by Eggsec interactive frontends" +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +readme = "../../README.md" +keywords = ["security", "runtime", "client", "frontend"] +categories = ["development-tools"] + +[dependencies] +eggsec-runtime = { path = "../eggsec-runtime", version = "0.1.0" } +eggsec-daemon-protocol = { path = "../eggsec-daemon-protocol", version = "0.1.0" } +# Frontend-neutral client: UnixStream (net), lines/write/flush (io-util), +# oneshot/mpsc/Mutex/RwLock (sync), spawn (rt), request timeout (time). +# No rt-multi-thread and no macros. +tokio = { workspace = true, features = ["rt", "sync", "time", "io-util", "net"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } +rustc-hash = { workspace = true } diff --git a/crates/eggsec-tui/src/runtime_client/daemon.rs b/crates/eggsec-frontend-client/src/daemon.rs similarity index 76% rename from crates/eggsec-tui/src/runtime_client/daemon.rs rename to crates/eggsec-frontend-client/src/daemon.rs index 6e77e6119..160942369 100644 --- a/crates/eggsec-tui/src/runtime_client/daemon.rs +++ b/crates/eggsec-frontend-client/src/daemon.rs @@ -9,9 +9,25 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::UnixStream; use tokio::sync::{oneshot, Mutex}; -use eggsec_daemon_protocol::protocol::{ClientCommand, ServerMessage}; +use eggsec_daemon_protocol::operations::DescribeOperationsResponse; +use eggsec_daemon_protocol::protocol::{ClientCommand, DaemonCapabilities, ServerMessage}; -use super::{RuntimeClientFuture, RuntimeEventReceiverHandle, TuiRuntimeClient}; +use crate::{ClientIdentity, RuntimeClient, RuntimeClientFuture, RuntimeEventReceiverHandle}; + +/// The daemon's health advertisement, including the protocol version it +/// speaks. +/// +/// A frontend uses the protocol version to refuse to operate against a daemon +/// it cannot talk to, rather than failing later with an opaque I/O error. +#[derive(Debug, Clone)] +pub struct DaemonHealth { + /// The daemon's status string. + pub status: String, + /// The daemon's version string. + pub version: String, + /// The daemon protocol version the daemon speaks. + pub protocol_version: u32, +} /// Shared channel registry for routing RuntimeEvent messages from the reader /// task to per-subscriber receivers. Each `subscribe_events()` call inserts @@ -34,6 +50,9 @@ pub enum DaemonClientError { struct DaemonConnection { _socket_path: String, request_counter: AtomicU64, + /// The caller's identity: the client kind and label the daemon records, + /// and the namespace for this client's request ids. + identity: ClientIdentity, writer: Mutex, pending_responses: std::sync::Arc< std::sync::Mutex>>, @@ -53,7 +72,15 @@ pub struct DaemonRuntimeClient { impl DaemonRuntimeClient { /// Connect to a daemon at the given socket path. - pub async fn connect(socket_path: &str) -> Result { + /// + /// The caller supplies its own identity: the client kind recorded in the + /// daemon's registry, the label the daemon shows, and the namespace for + /// this client's request ids. The crate is frontend-neutral, so it cannot + /// choose any of those on the caller's behalf. + pub async fn connect( + socket_path: &str, + identity: ClientIdentity, + ) -> Result { let stream = UnixStream::connect(socket_path).await?; let (read_half, write_half) = stream.into_split(); @@ -115,6 +142,7 @@ impl DaemonRuntimeClient { | ServerMessage::SessionClosed { request_id, .. } | ServerMessage::PersistedSessions { request_id, .. } | ServerMessage::PersistedSnapshot { request_id, .. } + | ServerMessage::Operations { request_id, .. } | ServerMessage::TaskResult { request_id, .. } => { request_id.clone() } @@ -126,7 +154,7 @@ impl DaemonRuntimeClient { } }; let mut pending = pending_clone.lock().unwrap_or_else(|poisoned| { - tracing::warn!("TUI pending request registry mutex was poisoned; recovering state"); + tracing::warn!("daemon pending request registry mutex was poisoned; recovering state"); poisoned.into_inner() }); if let Some(sender) = pending.remove(&request_id) { @@ -156,6 +184,7 @@ impl DaemonRuntimeClient { inner: Arc::new(DaemonConnection { _socket_path: socket_path.to_string(), request_counter: AtomicU64::new(0), + identity: identity.clone(), writer: Mutex::new(write_half), pending_responses, event_channels, @@ -165,13 +194,10 @@ impl DaemonRuntimeClient { // Declare client kind to the daemon; a rejection leaves this client // unregistered, so later session-scoped commands would fail opaquely. if let Err(e) = client - .declare_client( - eggsec_daemon_protocol::client_registry::ClientKind::Tui, - Some("eggsec-tui".into()), - ) + .declare_client(identity.kind.clone(), Some(identity.label.clone())) .await { - tracing::warn!("Daemon rejected TUI client declaration: {}", e); + tracing::warn!("Daemon rejected client declaration: {}", e); } Ok(client) @@ -193,7 +219,76 @@ impl DaemonRuntimeClient { fn next_request_id(&self) -> String { let id = self.inner.request_counter.fetch_add(1, Ordering::Relaxed); - format!("tui-{}", id) + self.inner.identity.request_id(id) + } + + /// Fetch the daemon's operation catalog and the derived request schema. + /// + /// This is an inherent method rather than a `RuntimeClient` trait method: + /// the catalog is daemon-published state, and the embedded client has no + /// catalog to publish. Daemon-only frontends call it directly. + pub async fn describe_operations( + &self, + ) -> Result { + let cmd = ClientCommand::DescribeOperations { + request_id: self.next_request_id(), + }; + match self.send_command(cmd).await { + Ok(ServerMessage::Operations { operations, .. }) => Ok(operations), + Ok(ServerMessage::Error { message, .. }) => Err(DaemonClientError::Protocol(message)), + Ok(other) => Err(DaemonClientError::Protocol(format!( + "unexpected response: {other:?}" + ))), + Err(e) => Err(e), + } + } + + /// Query the daemon's health, including the protocol version it speaks. + /// + /// Inherent rather than a trait method for the same reason as + /// [`Self::describe_operations`]: only a daemon-backed client has a + /// daemon to ask. + pub async fn health(&self) -> Result { + let cmd = ClientCommand::Health { + request_id: self.next_request_id(), + }; + match self.send_command(cmd).await { + Ok(ServerMessage::Health { + status, + version, + protocol_version, + .. + }) => Ok(DaemonHealth { + status, + version, + protocol_version, + }), + Ok(ServerMessage::Error { message, .. }) => Err(DaemonClientError::Protocol(message)), + Ok(other) => Err(DaemonClientError::Protocol(format!( + "unexpected response: {other:?}" + ))), + Err(e) => Err(e), + } + } + + /// The daemon's full capability advertisement. + /// + /// The `RuntimeClient` trait's `capabilities` returns the *runtime* half + /// of the advertisement; a daemon-only frontend also needs the daemon's + /// own flags — notably `operation_schema`, which says whether this daemon + /// can publish the operation catalog at all. + pub async fn daemon_capabilities(&self) -> Result { + let cmd = ClientCommand::Capabilities { + request_id: self.next_request_id(), + }; + match self.send_command(cmd).await { + Ok(ServerMessage::Capabilities { capabilities, .. }) => Ok(capabilities), + Ok(ServerMessage::Error { message, .. }) => Err(DaemonClientError::Protocol(message)), + Ok(other) => Err(DaemonClientError::Protocol(format!( + "unexpected response: {other:?}" + ))), + Err(e) => Err(e), + } } async fn send_command(&self, cmd: ClientCommand) -> Result { @@ -212,6 +307,7 @@ impl DaemonRuntimeClient { | ClientCommand::Subscribe { request_id, .. } | ClientCommand::ApprovePolicy { request_id, .. } | ClientCommand::ListPersistedSessions { request_id } + | ClientCommand::DescribeOperations { request_id } | ClientCommand::GetPersistedSnapshot { request_id, .. } => request_id.clone(), }; @@ -222,7 +318,7 @@ impl DaemonRuntimeClient { .pending_responses .lock() .unwrap_or_else(|poisoned| { - tracing::warn!("TUI pending_responses mutex was poisoned; recovering state"); + tracing::warn!("daemon pending_responses mutex was poisoned; recovering state"); poisoned.into_inner() }); pending.insert(request_id, tx); @@ -272,7 +368,7 @@ impl DaemonRuntimeClient { } } -impl TuiRuntimeClient for DaemonRuntimeClient { +impl RuntimeClient for DaemonRuntimeClient { fn capabilities(&self) -> RuntimeClientFuture { let client = self.clone(); Box::pin(async move { diff --git a/crates/eggsec-tui/src/runtime_client/embedded.rs b/crates/eggsec-frontend-client/src/embedded.rs similarity index 96% rename from crates/eggsec-tui/src/runtime_client/embedded.rs rename to crates/eggsec-frontend-client/src/embedded.rs index 6ee3f87ac..d7e333cfa 100644 --- a/crates/eggsec-tui/src/runtime_client/embedded.rs +++ b/crates/eggsec-frontend-client/src/embedded.rs @@ -5,7 +5,7 @@ use eggsec_runtime::{ SessionId, SessionSnapshot, SessionSummary, TaskId, }; -use super::{RuntimeClientFuture, RuntimeEventReceiverHandle, TuiRuntimeClient}; +use crate::{RuntimeClient, RuntimeClientFuture, RuntimeEventReceiverHandle}; /// Runtime client that wraps an in-process `Runtime` directly. pub struct EmbeddedRuntimeClient { @@ -22,7 +22,7 @@ impl EmbeddedRuntimeClient { } } -impl TuiRuntimeClient for EmbeddedRuntimeClient { +impl RuntimeClient for EmbeddedRuntimeClient { fn capabilities(&self) -> RuntimeClientFuture { Box::pin(async move { Ok(RuntimeCapabilities::default()) }) } diff --git a/crates/eggsec-frontend-client/src/lib.rs b/crates/eggsec-frontend-client/src/lib.rs new file mode 100644 index 000000000..fbdc9a69c --- /dev/null +++ b/crates/eggsec-frontend-client/src/lib.rs @@ -0,0 +1,294 @@ +//! Frontend-neutral runtime client contract for Eggsec's interactive frontends. +//! +//! This crate owns the small contract a frontend uses to drive the Eggsec +//! runtime, plus the two reference implementations: +//! +//! - [`EmbeddedRuntimeClient`] wraps an in-process `eggsec_runtime::Runtime`. +//! - [`DaemonRuntimeClient`] speaks the daemon's Unix-socket JSON-lines +//! protocol. +//! +//! It exists so a second interactive frontend (a desktop GUI) can reuse the +//! exact contract the terminal UI uses today without depending on +//! `eggsec-tui` — and therefore without pulling in ratatui, crossterm, or any +//! other terminal-frontend dependency. The crate depends on no frontend +//! framework: only on `eggsec-runtime`, `eggsec-daemon-protocol`, and a +//! narrow Tokio feature set. +//! +//! It is **not** an enforcement surface. The contract carries no authorization +//! decisions of its own: the daemon applies its own access controls and the +//! embedded runtime applies the engine's, exactly as before the move. +//! +//! The trait is intentionally coarse — its error type is `String` — because +//! that is the contract the existing frontends already bind to. + +use std::future::Future; +use std::pin::Pin; + +use eggsec_runtime::{ + RunRequest, RuntimeCapabilities, RuntimeEvent, SessionId, SessionSnapshot, SessionSummary, + TaskId, +}; + +/// Re-exported so a frontend can name its own client kind without taking a +/// direct dependency on the daemon protocol crate. +pub use eggsec_daemon_protocol::client_registry::ClientKind; + +/// A future that resolves to a result. +pub type RuntimeClientFuture = Pin> + Send + 'static>>; + +/// How a frontend identifies itself to the daemon. +/// +/// The crate is frontend-neutral, so it cannot hardcode any one frontend's +/// identity: the kind recorded in the daemon's client registry, the label the +/// daemon shows in its listings, and the namespace for this client's request +/// ids are all the caller's to choose. +#[derive(Debug, Clone)] +pub struct ClientIdentity { + /// The kind recorded in the daemon's client registry. + pub kind: ClientKind, + /// Human-readable label shown in daemon-side listings. + pub label: String, + /// Prefix for this client's request ids. + pub request_prefix: String, +} + +impl ClientIdentity { + /// Build a request id in this client's namespace. + /// + /// The prefix is supplied verbatim, so a caller that wants a separator + /// includes it in the prefix itself (`"gui-"` yields `gui-0`). + pub fn request_id(&self, counter: u64) -> String { + format!("{}{}", self.request_prefix, counter) + } +} + +/// Trait abstracting runtime backends for an interactive frontend (embedded vs daemon). +pub trait RuntimeClient: Send + Sync + 'static { + /// Get runtime capabilities. + fn capabilities(&self) -> RuntimeClientFuture; + /// Create a new session. + fn create_session( + &self, + surface: eggsec_runtime::request::RuntimeSurface, + scope: Option, + labels: Vec, + ) -> RuntimeClientFuture; + /// List all sessions. + fn list_sessions(&self) -> RuntimeClientFuture>; + /// Get a snapshot of a session. + fn snapshot(&self, session_id: SessionId) -> RuntimeClientFuture; + /// Submit a task to a session. + fn submit(&self, session_id: SessionId, request: RunRequest) -> RuntimeClientFuture; + /// Cancel a specific task. + fn cancel(&self, session_id: SessionId, task_id: TaskId) -> RuntimeClientFuture<()>; + /// Cancel the active task in a session. + fn cancel_active(&self, session_id: SessionId) -> RuntimeClientFuture<()>; + /// Subscribe to runtime events for a session. + fn subscribe(&self, session_id: SessionId) -> RuntimeClientFuture; +} + +/// Handle for receiving runtime events from either embedded or daemon backend. +/// Wraps a tokio mpsc receiver. +pub struct RuntimeEventReceiverHandle { + rx: tokio::sync::mpsc::UnboundedReceiver, +} + +impl RuntimeEventReceiverHandle { + pub fn new(rx: tokio::sync::mpsc::UnboundedReceiver) -> Self { + Self { rx } + } + + pub async fn recv(&mut self) -> Option { + self.rx.recv().await + } + + pub fn try_recv(&mut self) -> Option { + self.rx.try_recv().ok() + } +} + +pub mod daemon; +pub mod embedded; + +pub use daemon::{DaemonClientError, DaemonHealth, DaemonRuntimeClient}; +pub use embedded::EmbeddedRuntimeClient; + +#[cfg(test)] +mod tests { + use std::future::Future; + use std::pin::Pin; + use std::sync::Arc; + + use eggsec_runtime::{ + CancellationToken, Runtime, RuntimeCapabilities, RuntimeConfig, RuntimeError, RuntimeEvent, + RuntimeEventSink, RuntimeExecutionContext, RuntimeTaskExecutor, SessionId, TaskId, + TaskOutcome, + }; + + use crate::{DaemonClientError, EmbeddedRuntimeClient, RuntimeClient}; + + /// The crate declares no `macros` Tokio feature, so `#[tokio::test]` is + /// unavailable. A current-thread runtime is enough for every assertion + /// here. + fn block_on(future: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a current-thread runtime") + .block_on(future) + } + + struct NoopExecutor; + + impl RuntimeTaskExecutor for NoopExecutor { + fn execute( + &self, + _task_id: TaskId, + _request: eggsec_runtime::RunRequest, + _context: RuntimeExecutionContext, + _sink: RuntimeEventSink, + _cancel: CancellationToken, + ) -> Pin> + Send + 'static>> + { + Box::pin(async { Ok(TaskOutcome::Text("ok".into())) }) + } + } + + fn test_runtime() -> Arc { + Arc::new(Runtime::new(RuntimeConfig::default(), NoopExecutor)) + } + + /// The contract must stay object-safe: every frontend holds the client as + /// a trait object, so `Arc` has to + /// compile. + #[test] + fn runtime_client_is_object_safe() { + let client: Arc = + Arc::new(EmbeddedRuntimeClient::new(test_runtime())); + let capabilities = block_on(client.capabilities()); + assert!(capabilities.is_ok()); + } + + /// The embedded client drives the in-process runtime. + #[test] + fn embedded_client_creates_and_lists_sessions() { + let client = EmbeddedRuntimeClient::new(test_runtime()); + let session_id = block_on(client.create_session( + eggsec_runtime::request::RuntimeSurface::CliManual, + None, + vec![], + )) + .expect("a session must be created"); + let sessions = block_on(client.list_sessions()).expect("sessions must list"); + assert!(sessions + .iter() + .any(|summary| summary.session_id == session_id)); + let snapshot = block_on(client.snapshot(session_id)).expect("a snapshot must resolve"); + assert_eq!(snapshot.session_id, session_id); + } + + /// An unknown session is an error, not a panic — the contract's error type + /// is a `String`, so a frontend can surface it directly. + #[test] + fn embedded_client_reports_unknown_sessions_as_errors() { + let client = EmbeddedRuntimeClient::new(test_runtime()); + let result = block_on(client.snapshot(SessionId::new())); + assert!(result.is_err()); + } + + /// The event receiver handle is the frontend's view of the runtime's + /// broadcast stream. + #[test] + fn event_receiver_handle_delivers_events() { + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let mut handle = crate::RuntimeEventReceiverHandle::new(rx); + let session_id = SessionId::new(); + tx.send(RuntimeEvent::SessionCreated { session_id }) + .expect("the event must be sent"); + match block_on(handle.recv()) { + Some(RuntimeEvent::SessionCreated { + session_id: received, + .. + }) => assert_eq!(received, session_id), + other => panic!("expected SessionCreated, got {:?}", other), + } + assert!(handle.try_recv().is_none()); + } + + /// The daemon client's error type is part of the public contract: a + /// frontend must be able to tell a closed connection from a protocol + /// error. + #[test] + fn daemon_client_error_is_publicly_nameable() { + let error = DaemonClientError::Protocol("unexpected reply".into()); + assert!(error.to_string().contains("unexpected reply")); + let error = DaemonClientError::ConnectionClosed; + assert!(!error.to_string().is_empty()); + } + + /// The capabilities the embedded client reports are the runtime's own. + #[test] + fn embedded_client_reports_runtime_capabilities() { + let client = EmbeddedRuntimeClient::new(test_runtime()); + let capabilities: RuntimeCapabilities = + block_on(client.capabilities()).expect("capabilities must resolve"); + assert!(capabilities.supports_cancellation); + assert!(capabilities.supports_multiple_sessions); + } + + /// The request-id namespace belongs to the caller. This crate is + /// frontend-neutral, so it must not stamp one frontend's prefix onto + /// every client that connects through it. + #[test] + fn client_identity_namespaces_request_ids() { + let tui = crate::ClientIdentity { + kind: crate::ClientKind::Tui, + label: "eggsec-tui".to_owned(), + request_prefix: "tui-".to_owned(), + }; + assert_eq!(tui.request_id(0), "tui-0"); + assert_eq!(tui.request_id(7), "tui-7"); + + let gui = crate::ClientIdentity { + kind: crate::ClientKind::Gui, + label: "eggsec-gui".to_owned(), + request_prefix: "gui-".to_owned(), + }; + assert_eq!(gui.request_id(0), "gui-0"); + assert_eq!(gui.request_id(7), "gui-7"); + } + + /// The identity carries the kind and the label the daemon records for the + /// client, so two frontends sharing this crate remain distinguishable in + /// the daemon's registry. + #[test] + fn client_identity_carries_kind_and_label() { + let identity = crate::ClientIdentity { + kind: crate::ClientKind::Gui, + label: "eggsec-gui".to_owned(), + request_prefix: "gui-".to_owned(), + }; + assert_eq!(identity.kind, crate::ClientKind::Gui); + assert_eq!(identity.label, "eggsec-gui"); + } + + /// The crate must not hardcode any one frontend's identity: a TUI-shaped + /// literal anywhere in the non-test source is a regression toward the + /// frontend-specific behavior this crate was extracted to remove. + #[test] + fn crate_carries_no_hardcoded_frontend_identity() { + let source = include_str!("daemon.rs"); + // Strip the test module before scanning, so the assertions above can + // name the TUI's literals. + let production = source + .split("#[cfg(test)]") + .next() + .expect("the module has a production half"); + for forbidden in ["tui-", "ClientKind::Tui", "eggsec-tui"] { + assert!( + !production.contains(forbidden), + "the daemon client must not hardcode {forbidden}" + ); + } + } +} diff --git a/crates/eggsec-gui/Cargo.toml b/crates/eggsec-gui/Cargo.toml new file mode 100644 index 000000000..483a4ecd2 --- /dev/null +++ b/crates/eggsec-gui/Cargo.toml @@ -0,0 +1,78 @@ +[package] +name = "eggsec-gui" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "Desktop GUI frontend for Eggsec, built on the Tauri v2 shell (ADR-0009)" +authors.workspace = true +homepage.workspace = true +documentation.workspace = true +readme = "../../README.md" +keywords = ["security", "gui", "tauri", "frontend"] +categories = ["development-tools"] + +[lib] +name = "eggsec_gui" +path = "src/lib.rs" + +[[bin]] +name = "eggsec-gui" +path = "src/main.rs" + +[features] +# The shell feature carries the Tauri dependency and everything that needs it. +# The crate builds without it so `cargo check --workspace --no-default-features` +# — the `make check` baseline — stays green on hosts with no webview SDK. +default = ["shell"] +shell = [ + "dep:tauri", + "dep:tauri-macros", + "dep:tauri-runtime", + "dep:tauri-runtime-wry", + "dep:tauri-utils", +] + +[dependencies] +eggsec-frontend-client = { path = "../eggsec-frontend-client", version = "0.1.0" } +eggsec-runtime = { path = "../eggsec-runtime", version = "0.1.0" } +eggsec-daemon-protocol = { path = "../eggsec-daemon-protocol", version = "0.1.0" } +# Frontend-neutral view DTOs and the renderer registry. Depends on +# eggsec-runtime, serde, and serde_json only — no engine, no framework. +eggsec-ui-model = { path = "../eggsec-ui-model", version = "0.1.0" } +serde = { workspace = true } +serde_json = { workspace = true } +# UnixStream (net), mpsc/oneshot (sync), request timeout (time), spawn (rt), +# and the `#[tokio::main]` attribute (macros). No rt-multi-thread. +tokio = { workspace = true, features = ["rt", "sync", "time", "macros", "net"] } +tracing = { workspace = true } + +# The shell framework. `rustls-tls` and `native-tls` are deliberately NOT +# enabled: the GUI performs no outbound HTTP of its own — every engine request +# travels over the daemon's Unix socket — so the whole `reqwest`/`rustls`/ +# `native-tls` closure stays out of the GUI's dependency graph. This is what +# keeps the workspace's ring-only TLS invariant true without an exception. +tauri = { workspace = true, optional = true, features = [ + "wry", + "common-controls-v6", + "x11", + "dbus", + "dynamic-acl", +] } + +# Version-hold dependencies. `tauri` declares its runtime, utils, and macro +# dependencies with caret requirements, and the next lines up (tauri 2.12, +# tauri-utils 2.10, tauri-macros 2.7) all declare MSRV 1.90 — above this +# workspace's 1.89 floor. These exact pins hold the transitive closure on the +# MSRV-safe line; the GUI does not call them directly. +tauri-macros = { workspace = true, optional = true } +tauri-runtime = { workspace = true, optional = true } +tauri-runtime-wry = { workspace = true, optional = true } +tauri-utils = { workspace = true, optional = true } + +[build-dependencies] +tauri-build = { workspace = true } +# `tauri-build` requires `tauri-utils ^2.9.3`; this exact pin keeps even the +# no-shell build (and therefore `make check-msrv`) off the MSRV-1.90 line. +tauri-utils = { workspace = true } diff --git a/crates/eggsec-gui/build.rs b/crates/eggsec-gui/build.rs new file mode 100644 index 000000000..f574cb97a --- /dev/null +++ b/crates/eggsec-gui/build.rs @@ -0,0 +1,11 @@ +fn main() { + // `tauri_build::build()` reads metadata that the `tauri` crate's own build + // script publishes. When the `shell` feature is off — the + // `--no-default-features` profile that `make check` runs — the `tauri` + // crate is not in the graph, that metadata does not exist, and the call + // panics. The shell feature is the only thing that brings `tauri` in, so + // gating on it keeps both profiles building. + if std::env::var_os("CARGO_FEATURE_SHELL").is_some() { + tauri_build::build() + } +} diff --git a/crates/eggsec-gui/capabilities/default.json b/crates/eggsec-gui/capabilities/default.json new file mode 100644 index 000000000..1a7ab6f2b --- /dev/null +++ b/crates/eggsec-gui/capabilities/default.json @@ -0,0 +1,7 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "The Eggsec desktop GUI's own window. Grants the core default permission set only: the GUI enables no plugin (no http, shell, fs, process, or updater), and every engine request travels over the daemon's Unix socket.", + "windows": ["main"], + "permissions": ["core:default"] +} diff --git a/crates/eggsec-gui/frontend/app.js b/crates/eggsec-gui/frontend/app.js new file mode 100644 index 000000000..a02871c83 --- /dev/null +++ b/crates/eggsec-gui/frontend/app.js @@ -0,0 +1,1307 @@ +"use strict"; + +/** + * Eggsec desktop GUI — webview frontend. + * + * This file is a pure data renderer. It holds no per-operation knowledge: + * every operation, task kind, form control, field name, status label and + * result kind it displays arrives as data from the connected daemon through + * the Tauri IPC commands of the GUI's IPC contract. A future operation + * therefore appears here with no frontend change. + * + * Rules this file obeys: + * - no build step, no dependency, no network access of its own; + * - every daemon-supplied value is rendered as text (`textContent` / + * `createTextNode`), never as markup; + * - a blank control is sent as `null`, which is the wire meaning of + * "the operator did not provide this field" — never `""`, `0`, `false` + * or `[]`, so server-side defaults are never clobbered; + * - retained state is bounded (log lines per task, tasks tracked). + */ + +(function () { + const DEFAULT_SOCKET = "/tmp/eggsec-daemon.sock"; + const TASK_EVENT = "eggsec://task-event"; + + /* Retention caps. The daemon caps its own rings; the window caps its copy + so a long-lived or chatty task cannot grow the webview without bound. */ + const MAX_LOG_LINES_PER_TASK = 500; + const MAX_TRACKED_TASKS = 200; + + const tauri = typeof window !== "undefined" ? window.__TAURI__ : undefined; + const invoke = + tauri && tauri.core && typeof tauri.core.invoke === "function" + ? tauri.core.invoke.bind(tauri.core) + : null; + const listen = + tauri && tauri.event && typeof tauri.event.listen === "function" + ? tauri.event.listen.bind(tauri.event) + : null; + + /* ----------------------------------------------------------------- dom */ + + const dom = { + connectForm: document.getElementById("connect-form"), + socketInput: document.getElementById("socket-input"), + connectButton: document.getElementById("connect-button"), + catalogFacts: document.getElementById("catalog-facts"), + bannerArea: document.getElementById("banner-area"), + noOpBadge: document.getElementById("no-op-badge"), + connectionBadge: document.getElementById("connection-badge"), + taskKindList: document.getElementById("task-kind-list"), + formBody: document.getElementById("form-body"), + formSubheading: document.getElementById("form-subheading"), + taskList: document.getElementById("task-list"), + dashboardCounters: document.getElementById("dashboard-counters"), + cancelActiveButton: document.getElementById("cancel-active-button"), + }; + + /* --------------------------------------------------------------- state */ + + const state = { + connected: false, + connecting: false, + catalog: null, + operations: [], + operationsById: new Map(), + taskKinds: [], + selectedVariant: null, + selectedKind: null, + form: null, + formReaders: new Map(), + fieldErrorNodes: new Map(), + formSubmit: null, + formErrorNode: null, + tasks: new Map(), + taskNodes: new Map(), + selectedTaskId: null, + droppedLogLines: 0, + unknownTaskEvents: 0, + submitting: false, + }; + + const banners = new Map(); + + /* -------------------------------------------------------------- helpers */ + + function el(tag, attrs, children) { + const node = document.createElement(tag); + if (attrs) { + for (const key of Object.keys(attrs)) { + const value = attrs[key]; + if (value === null || value === undefined || value === false) continue; + if (key === "class") node.className = value; + else if (key === "text") node.textContent = String(value); + else if (key.startsWith("on") && typeof value === "function") { + node.addEventListener(key.slice(2), value); + } else if (value === true) node.setAttribute(key, ""); + else node.setAttribute(key, String(value)); + } + } + if (children) { + for (const child of [].concat(children)) { + if (child === null || child === undefined || child === false) continue; + node.appendChild( + typeof child === "string" || typeof child === "number" + ? document.createTextNode(String(child)) + : child + ); + } + } + return node; + } + + function clear(node) { + if (!node) return; + while (node.firstChild) node.removeChild(node.firstChild); + } + + function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + + function errorMessage(error) { + if (typeof error === "string") return error; + if (error && typeof error.message === "string") return error.message; + return String(error); + } + + function safeStringify(value) { + try { + const rendered = JSON.stringify(value, null, 2); + return rendered === undefined ? String(value) : rendered; + } catch (error) { + return "The result payload could not be rendered as JSON."; + } + } + + function domId(value) { + return String(value === null || value === undefined ? "" : value).replace( + /[^A-Za-z0-9_-]/g, + "_" + ); + } + + /** + * Build the argument object for an IPC command. + * + * The GUI's IPC contract names multi-word arguments in snake_case, while + * Tauri's command macro renames them to camelCase by default. Both + * spellings are sent so the frontend works against either convention; the + * side that receives the payload reads the key it knows and ignores the + * other. Single-word arguments are sent once. + */ + /** + * Build a command's argument object. + * + * The names are the wire names, verbatim. Every Rust command declares + * `rename_all = "snake_case"`, so the argument names are snake_case on + * both sides of the IPC boundary. Do not "helpfully" also send a camelCase + * alias: two spellings of one argument is an ambiguity the receiver has to + * resolve, and it hides the fact that the contract is snake_case. + */ + function commandArgs(pairs) { + const args = {}; + for (const pair of pairs) { + args[pair[0]] = pair[1]; + } + return args; + } + + /* ---------------------------------------------------------------- ipc */ + + function requireIpc() { + if (invoke) return true; + setBanner("ipc", { + level: "error", + title: "IPC bridge unavailable", + message: + "The Tauri IPC bridge is not present in this window. The GUI must run inside the Eggsec desktop shell.", + }); + return false; + } + + /* ------------------------------------------------------------- banners */ + + function setBanner(id, banner) { + if (banner) banners.set(id, banner); + else banners.delete(id); + renderBanners(); + } + + function renderBanners() { + clear(dom.bannerArea); + for (const banner of banners.values()) { + dom.bannerArea.appendChild( + el("div", { class: "banner banner--" + banner.level }, [ + el("span", { class: "banner__title", text: banner.title }), + el("span", { class: "banner__message", text: banner.message }), + ]) + ); + } + } + + /* ------------------------------------------------------------- catalog */ + + function renderCatalog() { + const catalog = state.catalog; + dom.noOpBadge.hidden = !(catalog && catalog.no_op_executor); + dom.connectionBadge.textContent = catalog ? "Connected" : "Not connected"; + dom.connectionBadge.className = "badge " + (catalog ? "badge--ok" : "badge--muted"); + + clear(dom.catalogFacts); + if (!catalog) return; + + const facts = [ + ["Socket", catalog.socket_path], + ["Session", catalog.session_id], + ["Protocol", "v" + catalog.protocol_version], + ["Operations", catalog.operation_count], + ["Task kinds", catalog.task_kind_count], + ]; + for (const fact of facts) { + dom.catalogFacts.appendChild(el("dt", { class: "catalog-facts__name", text: fact[0] })); + dom.catalogFacts.appendChild( + el("dd", { class: "catalog-facts__value", text: fact[1] }) + ); + } + } + + /* ---------------------------------------------------------- task kinds */ + + function isKindAvailable(kind) { + if (!kind) return false; + if (!kind.supported) return false; + if (!kind.manual_exposable) return false; + const operation = state.operationsById.get(kind.operation_id); + if (operation && !operation.manual_exposable) return false; + return true; + } + + function kindUnavailableReason(kind) { + if (!kind) return ""; + if (kind.unavailable_reason) return String(kind.unavailable_reason); + if (!kind.supported) { + return "The connected daemon does not advertise this capability."; + } + if (!kind.manual_exposable) { + return "This operation is not exposed on the manual surface."; + } + return ""; + } + + function renderTaskKinds() { + clear(dom.taskKindList); + + if (state.taskKinds.length === 0) { + dom.taskKindList.appendChild( + el("li", { + class: "empty", + text: state.connected + ? "The connected daemon published no task kinds." + : "Not connected to a daemon yet.", + }) + ); + return; + } + + for (const kind of state.taskKinds) { + const operation = state.operationsById.get(kind.operation_id) || null; + const displayName = operation ? operation.display_name : String(kind.variant || ""); + const risk = operation ? String(operation.risk || "") : ""; + const available = isKindAvailable(kind); + const reason = kindUnavailableReason(kind); + const selected = kind.variant === state.selectedVariant; + + const classes = ["task-kind"]; + if (!available) classes.push("task-kind--unavailable"); + if (selected) classes.push("task-kind--selected"); + + const children = [ + el("span", { class: "task-kind__head" }, [ + el("span", { class: "task-kind__name", text: displayName }), + el("span", { class: "task-kind__risk", text: risk }), + ]), + ]; + if (!available) { + children.push( + el("span", { class: "task-kind__risk", text: "unavailable" }) + ); + if (reason) { + children.push(el("span", { class: "task-kind__reason", text: reason })); + } + } + + const entry = el( + "button", + { + type: "button", + class: classes.join(" "), + title: String(kind.variant || "") + (kind.capability_name ? " — " + kind.capability_name : ""), + "aria-pressed": selected ? "true" : "false", + onclick: function () { + selectTaskKind(kind); + }, + }, + children + ); + + dom.taskKindList.appendChild(el("li", { class: "task-kind__item" }, [entry])); + } + } + + /* ---------------------------------------------------------------- form */ + + function setFormError(message) { + if (!state.formErrorNode) return; + state.formErrorNode.hidden = !message; + state.formErrorNode.textContent = message ? String(message) : ""; + } + + function clearFieldErrors() { + for (const node of state.fieldErrorNodes.values()) { + node.hidden = true; + node.textContent = ""; + } + for (const node of dom.formBody.querySelectorAll(".field--invalid")) { + node.classList.remove("field--invalid"); + } + } + + function setFieldError(name, message) { + const node = state.fieldErrorNodes.get(name); + if (!node) return; + node.hidden = false; + node.textContent = String(message); + const field = node.closest(".field"); + if (field) field.classList.add("field--invalid"); + } + + /** + * Build one control for one published control descriptor. + * + * The returned `reader` maps the operator's current input to the wire + * value: a filled control sends its value, a blank control sends `null`. + */ + function buildControl(control, fieldId, labelId) { + const kind = String(control.kind || "text"); + const name = String(control.name || ""); + + if (kind === "number") { + const input = el("input", { + type: "number", + id: fieldId, + name: name, + class: "field__input", + autocomplete: "off", + spellcheck: "false", + }); + if (control.minimum !== null && control.minimum !== undefined) { + input.setAttribute("min", String(control.minimum)); + } + if (control.maximum !== null && control.maximum !== undefined) { + input.setAttribute("max", String(control.maximum)); + } + if (control.placeholder) input.setAttribute("placeholder", String(control.placeholder)); + if (control.required) { + input.setAttribute("required", ""); + input.setAttribute("aria-required", "true"); + } + const reader = function () { + const raw = input.value.trim(); + if (raw === "") return { value: null, error: null }; + if (input.validity && input.validity.badInput) { + return { value: null, error: "Enter a number." }; + } + const parsed = Number(raw); + if (!Number.isFinite(parsed)) return { value: null, error: "Enter a number." }; + return { value: parsed, error: null }; + }; + return { node: input, reader: reader }; + } + + if (kind === "checkbox") { + /* Tri-state: "not set" is a distinct value from false, because a null + leaves the engine's own default in place. */ + const select = el("select", { + id: fieldId, + name: name, + class: "field__input", + }); + select.appendChild(el("option", { value: "", text: "Not set" })); + select.appendChild(el("option", { value: "true", text: "Yes" })); + select.appendChild(el("option", { value: "false", text: "No" })); + if (control.required) select.setAttribute("aria-required", "true"); + const reader = function () { + if (select.value === "true") return { value: true, error: null }; + if (select.value === "false") return { value: false, error: null }; + return { value: null, error: null }; + }; + return { node: select, reader: reader }; + } + + if (kind === "list") { + /* One row is present from the start, so the operator can type straight + into a text input. "Add" appends another row, "Remove" drops one. */ + const entries = [""]; + const list = el("ul", { + class: "list-control", + id: fieldId, + role: "group", + "aria-labelledby": labelId, + }); + + const renderRows = function () { + clear(list); + for (let index = 0; index < entries.length; index += 1) { + const row = el("li", { class: "list-control__row" }); + const input = el("input", { + type: "text", + class: "field__input", + value: entries[index], + autocomplete: "off", + spellcheck: "false", + "aria-label": "Entry " + String(index + 1), + }); + input.addEventListener("input", function () { + entries[index] = input.value; + }); + const remove = el("button", { + type: "button", + class: "button button--small", + text: "Remove", + }); + remove.addEventListener("click", function () { + entries.splice(index, 1); + renderRows(); + }); + row.appendChild(input); + row.appendChild(remove); + list.appendChild(row); + } + if (entries.length === 0) { + list.appendChild(el("li", { class: "empty", text: "No entries." })); + } + }; + + const add = el("button", { type: "button", class: "button button--small", text: "Add" }); + add.addEventListener("click", function () { + entries.push(""); + renderRows(); + const inputs = list.querySelectorAll("input"); + if (inputs.length) inputs[inputs.length - 1].focus(); + }); + + renderRows(); + + const wrapper = el("div", { class: "field__listwrap" }, [list]); + wrapper.appendChild(el("div", { class: "list-control__actions" }, [add])); + + const reader = function () { + const values = []; + for (const entry of entries) { + const trimmed = String(entry).trim(); + if (trimmed !== "") values.push(trimmed); + } + /* No entries means the operator supplied nothing: send null, not []. */ + return { value: values.length ? values : null, error: null }; + }; + return { node: wrapper, reader: reader }; + } + + if (kind === "json") { + const area = el("textarea", { + id: fieldId, + name: name, + class: "field__input field__textarea", + rows: 6, + spellcheck: "false", + }); + if (control.placeholder) area.setAttribute("placeholder", String(control.placeholder)); + if (control.required) area.setAttribute("aria-required", "true"); + const reader = function () { + const raw = area.value.trim(); + if (raw === "") return { value: null, error: null }; + try { + return { value: JSON.parse(raw), error: null }; + } catch (error) { + return { value: null, error: "Enter valid JSON: " + errorMessage(error) }; + } + }; + return { node: area, reader: reader }; + } + + /* "text", and the documented fallback for any unrecognized kind. */ + const input = el("input", { + type: "text", + id: fieldId, + name: name, + class: "field__input", + autocomplete: "off", + spellcheck: "false", + }); + if (control.placeholder) input.setAttribute("placeholder", String(control.placeholder)); + if (control.required) { + input.setAttribute("required", ""); + input.setAttribute("aria-required", "true"); + } + const reader = function () { + const raw = input.value; + return { value: raw === "" ? null : raw, error: null }; + }; + return { node: input, reader: reader }; + } + + function renderControl(control, index) { + const name = String(control.name || ""); + const kind = String(control.kind || "text"); + const fieldId = "ctl-" + String(index) + "-" + domId(name); + const labelId = fieldId + "-label"; + const isGroup = kind === "list"; + + const field = el("div", { class: "field field--" + domId(kind) }); + + const nameSpan = el("span", { class: "field__name", text: name }); + const labelChildren = [nameSpan]; + if (control.required) { + labelChildren.push(el("span", { class: "field__required", "aria-hidden": "true", text: "*" })); + } + + if (isGroup) { + field.appendChild(el("span", { class: "field__label", id: labelId }, labelChildren)); + } else { + field.appendChild(el("label", { class: "field__label", for: fieldId }, labelChildren)); + } + + const built = buildControl(control, fieldId, labelId); + field.appendChild(built.node); + state.formReaders.set(name, built.reader); + + const meta = []; + if (control.format) meta.push("format: " + String(control.format)); + if (control.minimum !== null && control.minimum !== undefined) { + meta.push("min: " + String(control.minimum)); + } + if (control.maximum !== null && control.maximum !== undefined) { + meta.push("max: " + String(control.maximum)); + } + if (meta.length) { + field.appendChild(el("p", { class: "field__meta", text: meta.join(" · ") })); + } + if (control.description) { + field.appendChild(el("p", { class: "field__help", text: String(control.description) })); + } + + const errorNode = el("p", { class: "field__error", role: "alert", hidden: true }); + state.fieldErrorNodes.set(name, errorNode); + field.appendChild(errorNode); + + return field; + } + + function renderForm(form) { + state.form = form; + state.formReaders = new Map(); + state.fieldErrorNodes = new Map(); + clear(dom.formBody); + + const displayName = form.display_name ? String(form.display_name) : ""; + dom.formSubheading.textContent = displayName + ? displayName + " — " + String(form.variant || "") + : String(form.variant || ""); + + state.formErrorNode = el("p", { class: "form-error", role: "alert", hidden: true }); + dom.formBody.appendChild(state.formErrorNode); + + const unavailableReason = state.selectedKind ? kindUnavailableReason(state.selectedKind) : ""; + if (form.disabled_reason || unavailableReason) { + dom.formBody.appendChild( + el("p", { + class: "notice", + role: "status", + text: String(form.disabled_reason || unavailableReason), + }) + ); + } + + const formElement = el("form", { + class: "op-form", + id: "operation-form", + /* The daemon is the validator: a blank required field is sent as null + and rejected with a field-level error there, so the webview must not + block the submission. */ + novalidate: true, + }); + formElement.addEventListener("submit", onSubmitForm); + + const fields = el("div", { class: "op-form__fields" }); + const controls = Array.isArray(form.controls) ? form.controls : []; + controls.forEach(function (control, index) { + fields.appendChild(renderControl(control, index)); + }); + formElement.appendChild(fields); + + const submit = el("button", { + type: "submit", + class: "button button--primary", + text: "Run", + }); + submit.disabled = !form.submit_enabled || !isKindAvailable(state.selectedKind); + state.formSubmit = submit; + + const actions = el("div", { class: "op-form__actions" }, [submit]); + if (submit.disabled) { + actions.appendChild( + el("span", { + class: "op-form__hint", + text: String(form.disabled_reason || unavailableReason || "This operation cannot be run right now."), + }) + ); + } + formElement.appendChild(actions); + + dom.formBody.appendChild(formElement); + } + + function onSubmitForm(event) { + event.preventDefault(); + if (!state.form || state.submitting) return; + + setFormError(null); + clearFieldErrors(); + + const values = {}; + let failed = false; + const controls = Array.isArray(state.form.controls) ? state.form.controls : []; + for (const control of controls) { + const name = String(control.name || ""); + const reader = state.formReaders.get(name); + if (!reader) continue; + const result = reader(); + if (result.error) { + setFieldError(name, result.error); + failed = true; + values[name] = null; + } else { + values[name] = result.value; + } + } + + if (failed) { + setFormError("Fix the highlighted field(s) before running this operation."); + return; + } + + state.submitting = true; + if (state.formSubmit) state.formSubmit.disabled = true; + + const variant = String(state.form.variant || ""); + invoke("submit_task", commandArgs([["variant", variant], ["values", values]])) + .then(function (response) { + const taskId = response && response.task_id ? String(response.task_id) : ""; + if (taskId) { + state.selectedTaskId = taskId; + } + return refreshSnapshot().then(function () { + highlightSelectedTask(); + }); + }) + .catch(function (error) { + const message = errorMessage(error); + setFormError(message); + applyServerFieldErrors(message); + }) + .then(function () { + state.submitting = false; + if (state.formSubmit) { + state.formSubmit.disabled = + !state.form.submit_enabled || !isKindAvailable(state.selectedKind); + } + }); + } + + /** + * Attach a daemon-side rejection to the field it names, when the message + * mentions one. The message is shown verbatim either way. + */ + function applyServerFieldErrors(message) { + if (!message || !state.form) return; + const controls = Array.isArray(state.form.controls) ? state.form.controls : []; + for (const control of controls) { + const name = String(control.name || ""); + if (!name) continue; + let pattern; + try { + pattern = new RegExp("\\b" + escapeRegExp(name) + "\\b"); + } catch (error) { + continue; + } + if (pattern.test(message)) setFieldError(name, message); + } + } + + async function selectTaskKind(kind) { + if (!kind) return; + state.selectedVariant = String(kind.variant || ""); + state.selectedKind = kind; + renderTaskKinds(); + + clear(dom.formBody); + state.form = null; + state.formReaders = new Map(); + state.fieldErrorNodes = new Map(); + state.formSubmit = null; + state.formErrorNode = null; + dom.formSubheading.textContent = ""; + dom.formBody.appendChild(el("p", { class: "empty", text: "Loading the form…" })); + + if (!requireIpc()) return; + + try { + const form = await invoke("form_for", { variant: state.selectedVariant }); + if (state.selectedVariant !== String(kind.variant || "")) return; + renderForm(form); + } catch (error) { + if (state.selectedVariant !== String(kind.variant || "")) return; + clear(dom.formBody); + dom.formBody.appendChild( + el("p", { class: "form-error", role: "alert", text: errorMessage(error) }) + ); + } + } + + /* --------------------------------------------------------------- tasks */ + + function statusClass(status) { + switch (String(status)) { + case "queued": + return "queued"; + case "running": + return "running"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "cancelled": + return "cancelled"; + case "awaiting_policy": + return "awaiting"; + default: + return "unknown"; + } + } + + function isTerminalStatus(status) { + const className = statusClass(status); + return className === "completed" || className === "failed" || className === "cancelled"; + } + + function levelClass(level) { + const cleaned = String(level === null || level === undefined ? "" : level) + .toLowerCase() + .replace(/[^a-z0-9_-]/g, ""); + return cleaned === "" ? "plain" : cleaned; + } + + function renderResult(result) { + const box = el("section", { class: "result" }); + const kindLabel = result.kind_label ? String(result.kind_label) : String(result.kind || ""); + box.appendChild(el("h4", { class: "result__kind", text: kindLabel })); + + if (result.summary) { + box.appendChild(el("p", { class: "result__summary", text: String(result.summary) })); + } + + const fields = Array.isArray(result.summary_fields) ? result.summary_fields : []; + if (fields.length) { + const list = el("dl", { class: "result__fields" }); + for (const pair of fields) { + const name = Array.isArray(pair) ? pair[0] : ""; + const value = Array.isArray(pair) ? pair[1] : ""; + list.appendChild(el("dt", { text: String(name === null || name === undefined ? "" : name) })); + list.appendChild( + el("dd", { text: String(value === null || value === undefined ? "" : value) }) + ); + } + box.appendChild(list); + } + + const artifacts = Array.isArray(result.artifacts) ? result.artifacts : []; + if (artifacts.length) { + const list = el("ul", { class: "result__artifacts" }); + for (const artifact of artifacts) { + const id = artifact && artifact.artifact_id ? String(artifact.artifact_id) : ""; + const summary = artifact && artifact.summary ? String(artifact.summary) : ""; + list.appendChild( + el("li", { class: "artifact" }, [ + el("span", { class: "artifact__id", text: id }), + summary ? el("span", { class: "artifact__summary", text: summary }) : null, + ]) + ); + } + box.appendChild(list); + } + + /* An unknown kind degrades to a generic JSON render rather than an + empty panel. */ + const generic = Boolean(result.generic); + if (generic || result.supports_json_detail !== false) { + const details = el("details", { class: "result__json" }); + if (generic) details.open = true; + details.appendChild( + el("summary", { + class: "result__json-summary", + text: generic ? "Raw JSON (unrecognized result kind)" : "Raw JSON", + }) + ); + const payload = el("pre", { class: "result__payload" }); + payload.textContent = safeStringify(result.payload); + details.appendChild(payload); + box.appendChild(details); + } + + return box; + } + + function renderTaskCard(task) { + const taskId = String(task.task_id || ""); + const status = String(task.status || "unknown"); + const card = el("article", { class: "task task--" + statusClass(status) }); + + const header = el("header", { class: "task__header" }, [ + el("h3", { class: "task__variant", text: String(task.variant || "") }), + el("span", { class: "badge badge--" + statusClass(status), text: status }), + ]); + if (taskId && taskId === state.selectedTaskId) { + header.appendChild(el("span", { class: "badge badge--accent", text: "selected" })); + } + card.appendChild(header); + card.appendChild(el("code", { class: "task__id", text: taskId, title: taskId })); + + const total = task.total; + const completed = Number(task.completed || 0); + if (typeof total === "number" && isFinite(total) && total > 0) { + const percentage = Math.max(0, Math.min(100, (completed / total) * 100)); + const bar = el("div", { + class: "progress", + role: "progressbar", + "aria-valuemin": 0, + "aria-valuemax": total, + "aria-valuenow": completed, + "aria-label": "Task progress", + }); + const fill = el("div", { class: "progress__fill" }); + fill.style.width = percentage.toFixed(2) + "%"; + bar.appendChild(fill); + card.appendChild(bar); + } + + if (task.message) { + card.appendChild(el("p", { class: "task__message", text: String(task.message) })); + } + + const logs = Array.isArray(task.logs) ? task.logs : []; + if (logs.length) { + const list = el("ul", { class: "logs" }); + for (const line of logs) { + const level = line && line.level ? String(line.level) : ""; + const message = line && line.message ? String(line.message) : ""; + list.appendChild( + el("li", { class: "log log--" + levelClass(level) }, [ + el("span", { class: "log__level", text: level }), + el("span", { class: "log__message", text: message }), + ]) + ); + } + card.appendChild(list); + } + + const dropped = Number(task.dropped_log_lines || 0); + if (dropped > 0) { + card.appendChild( + el("p", { + class: "task__dropped", + text: "… " + String(dropped) + " earlier lines dropped", + }) + ); + } + + if (task.error) { + card.appendChild( + el("p", { class: "task__error", role: "status", text: String(task.error) }) + ); + } + + const actions = el("div", { class: "task__actions" }); + const cancel = el("button", { + type: "button", + class: "button button--danger button--small", + text: "Cancel", + }); + if (isTerminalStatus(status)) cancel.disabled = true; + cancel.addEventListener("click", function () { + cancelTask(taskId); + }); + actions.appendChild(cancel); + card.appendChild(actions); + + if (status === "completed" && task.result) { + card.appendChild(renderResult(task.result)); + } + + return card; + } + + function preserveDetailsState(previous, next) { + const before = previous.querySelectorAll("details"); + const after = next.querySelectorAll("details"); + for (let index = 0; index < before.length && index < after.length; index += 1) { + after[index].open = before[index].open; + } + } + + function renderTaskList() { + clear(dom.taskList); + state.taskNodes.clear(); + + if (state.tasks.size === 0) { + dom.taskList.appendChild( + el("p", { + class: "empty", + text: state.connected + ? "No tasks yet. Run an operation to see it here." + : "Not connected to a daemon yet.", + }) + ); + renderCancelActiveState(); + return; + } + + for (const task of state.tasks.values()) { + const node = renderTaskCard(task); + state.taskNodes.set(String(task.task_id || ""), node); + dom.taskList.appendChild(node); + } + renderCancelActiveState(); + } + + function updateTaskNode(task) { + const taskId = String(task.task_id || ""); + const previous = state.taskNodes.get(taskId); + const node = renderTaskCard(task); + if (previous && previous.parentNode) { + preserveDetailsState(previous, node); + previous.parentNode.replaceChild(node, previous); + state.taskNodes.set(taskId, node); + } else { + renderTaskList(); + } + renderCancelActiveState(); + } + + function renderCancelActiveState() { + if (!dom.cancelActiveButton) return; + let active = false; + for (const task of state.tasks.values()) { + if (!isTerminalStatus(String(task.status || ""))) { + active = true; + break; + } + } + dom.cancelActiveButton.disabled = !active; + } + + function renderCounters() { + if (!dom.dashboardCounters) return; + clear(dom.dashboardCounters); + const counters = []; + if (state.droppedLogLines > 0) { + counters.push("Dropped log lines: " + String(state.droppedLogLines)); + } + if (state.unknownTaskEvents > 0) { + counters.push("Unknown task events: " + String(state.unknownTaskEvents)); + } + for (const counter of counters) { + dom.dashboardCounters.appendChild(el("span", { class: "counter", text: counter })); + } + dom.dashboardCounters.hidden = counters.length === 0; + } + + function enforceTaskCap() { + if (state.tasks.size <= MAX_TRACKED_TASKS) return false; + let excess = state.tasks.size - MAX_TRACKED_TASKS; + const ids = Array.from(state.tasks.keys()); + + /* Prefer evicting finished tasks, oldest first. */ + for (const id of ids) { + if (excess <= 0) break; + const task = state.tasks.get(id); + if (task && isTerminalStatus(String(task.status || ""))) { + state.tasks.delete(id); + state.taskNodes.delete(id); + excess -= 1; + } + } + for (const id of ids) { + if (excess <= 0) break; + if (state.tasks.has(id)) { + state.tasks.delete(id); + state.taskNodes.delete(id); + excess -= 1; + } + } + return true; + } + + function upsertTask(task) { + if (!task || typeof task !== "object") return; + const taskId = String(task.task_id || ""); + if (!taskId) return; + + const existing = state.tasks.get(taskId); + const merged = existing ? Object.assign({}, existing, task) : Object.assign({}, task); + if (Array.isArray(task.logs)) { + merged.logs = task.logs.slice(-MAX_LOG_LINES_PER_TASK); + } else if (!Array.isArray(merged.logs)) { + merged.logs = []; + } + + const isNew = !state.tasks.has(taskId); + state.tasks.set(taskId, merged); + const evicted = enforceTaskCap(); + if (isNew || evicted) renderTaskList(); + else updateTaskNode(merged); + } + + function removeTask(taskId) { + const id = String(taskId || ""); + if (!id) return; + state.tasks.delete(id); + state.taskNodes.delete(id); + if (state.selectedTaskId === id) state.selectedTaskId = null; + renderTaskList(); + } + + function appendLogs(taskId, lines, dropped) { + const id = String(taskId || ""); + const task = state.tasks.get(id); + if (!task) { + /* A log line for a task this window does not know about: the daemon + counts these and reports them through the counters event. */ + return; + } + const existing = Array.isArray(task.logs) ? task.logs.slice() : []; + const incoming = Array.isArray(lines) ? lines : []; + let merged = existing.concat(incoming); + let droppedCount = Number(task.dropped_log_lines || 0) + Number(dropped || 0); + if (merged.length > MAX_LOG_LINES_PER_TASK) { + const overflow = merged.length - MAX_LOG_LINES_PER_TASK; + merged = merged.slice(overflow); + droppedCount += overflow; + } + task.logs = merged; + task.dropped_log_lines = droppedCount; + updateTaskNode(task); + } + + function applySnapshot(snapshot) { + if (!snapshot || typeof snapshot !== "object") return; + const tasks = Array.isArray(snapshot.tasks) ? snapshot.tasks : []; + state.tasks.clear(); + for (const task of tasks) { + if (!task || typeof task !== "object") continue; + const taskId = String(task.task_id || ""); + if (!taskId) continue; + const copy = Object.assign({}, task); + copy.logs = Array.isArray(task.logs) ? task.logs.slice(-MAX_LOG_LINES_PER_TASK) : []; + state.tasks.set(taskId, copy); + } + state.droppedLogLines = Math.max( + state.droppedLogLines, + Number(snapshot.dropped_log_lines || 0) + ); + state.unknownTaskEvents = Math.max( + state.unknownTaskEvents, + Number(snapshot.unknown_task_events || 0) + ); + renderTaskList(); + renderCounters(); + } + + function highlightSelectedTask() { + if (!state.selectedTaskId) return; + const node = state.taskNodes.get(state.selectedTaskId); + if (node && typeof node.scrollIntoView === "function") { + node.scrollIntoView({ block: "nearest" }); + } + } + + /* ------------------------------------------------------------ commands */ + + async function refreshSnapshot() { + if (!invoke) return; + try { + const snapshot = await invoke("task_snapshot"); + applySnapshot(snapshot); + } catch (error) { + setBanner("snapshot", { + level: "error", + title: "Could not read the task list", + message: errorMessage(error), + }); + } + } + + async function cancelTask(taskId) { + if (!invoke) return; + try { + await invoke("cancel_task", commandArgs([["task_id", String(taskId || "")]])); + } catch (error) { + setBanner("cancel", { + level: "error", + title: "Cancellation failed", + message: errorMessage(error), + }); + } + } + + async function cancelActive() { + if (!invoke) return; + try { + await invoke("cancel_active"); + } catch (error) { + setBanner("cancel", { + level: "error", + title: "Cancellation failed", + message: errorMessage(error), + }); + } + } + + async function refreshCatalogLists() { + if (!invoke) return; + try { + const operations = await invoke("list_operations"); + const taskKinds = await invoke("list_task_kinds"); + state.operations = Array.isArray(operations) ? operations : []; + state.operationsById = new Map(); + for (const operation of state.operations) { + if (operation && operation.id !== undefined) { + state.operationsById.set(String(operation.id), operation); + } + } + state.taskKinds = Array.isArray(taskKinds) ? taskKinds : []; + renderTaskKinds(); + } catch (error) { + setBanner("catalog", { + level: "error", + title: "Could not read the operation catalog", + message: errorMessage(error), + }); + } + } + + async function connect(socketPath) { + if (!requireIpc()) return; + const socket = String(socketPath || "").trim() || DEFAULT_SOCKET; + + state.connecting = true; + if (dom.connectButton) dom.connectButton.disabled = true; + setBanner("connect", null); + setBanner("notice", null); + setBanner("catalog", null); + setBanner("snapshot", null); + + try { + const catalog = await invoke("connect_daemon", { socket: socket }); + state.catalog = catalog; + state.connected = true; + if (catalog && catalog.socket_path && dom.socketInput) { + dom.socketInput.value = String(catalog.socket_path); + } + renderCatalog(); + if (catalog && catalog.notice) { + setBanner("notice", { + level: "warning", + title: "Daemon notice", + message: String(catalog.notice), + }); + } + await refreshCatalogLists(); + await refreshSnapshot(); + } catch (error) { + state.catalog = null; + state.connected = false; + state.operations = []; + state.operationsById = new Map(); + state.taskKinds = []; + state.selectedKind = null; + renderCatalog(); + renderTaskKinds(); + setBanner("connect", { + level: "error", + title: "Could not connect to the daemon", + message: errorMessage(error), + }); + } finally { + state.connecting = false; + if (dom.connectButton) dom.connectButton.disabled = false; + } + } + + /* -------------------------------------------------------------- events */ + + function handleTaskEvent(payload) { + if (!payload || typeof payload !== "object") { + state.unknownTaskEvents += 1; + renderCounters(); + return; + } + switch (String(payload.type)) { + case "task_upsert": + upsertTask(payload.task); + break; + case "task_removed": + removeTask(payload.task_id); + break; + case "logs": + appendLogs(payload.task_id, payload.lines, payload.dropped); + break; + case "counters": + state.droppedLogLines = Math.max( + state.droppedLogLines, + Number(payload.dropped_log_lines || 0) + ); + state.unknownTaskEvents = Math.max( + state.unknownTaskEvents, + Number(payload.unknown_task_events || 0) + ); + renderCounters(); + break; + default: + state.unknownTaskEvents += 1; + renderCounters(); + break; + } + } + + function subscribeToTaskEvents() { + if (!listen) { + setBanner("ipc", { + level: "error", + title: "Event bridge unavailable", + message: + "The Tauri event bridge is not present in this window, so live task updates cannot be received.", + }); + return; + } + listen(TASK_EVENT, function (event) { + try { + handleTaskEvent(event && event.payload); + } catch (error) { + state.unknownTaskEvents += 1; + renderCounters(); + } + }).catch(function (error) { + setBanner("ipc", { + level: "error", + title: "Could not subscribe to task events", + message: errorMessage(error), + }); + }); + } + + /* ---------------------------------------------------------------- boot */ + + function boot() { + renderCatalog(); + renderBanners(); + renderTaskKinds(); + renderTaskList(); + renderCounters(); + + if (dom.connectForm) { + dom.connectForm.addEventListener("submit", function (event) { + event.preventDefault(); + const socket = dom.socketInput ? dom.socketInput.value : DEFAULT_SOCKET; + connect(socket); + }); + } + + if (dom.cancelActiveButton) { + dom.cancelActiveButton.addEventListener("click", function () { + cancelActive(); + }); + } + + subscribeToTaskEvents(); + + /* One automatic connection attempt against the default socket, so the + window shows the catalog when a daemon is already running. There is no + retry loop: further attempts are operator-driven. */ + const socket = dom.socketInput ? dom.socketInput.value : DEFAULT_SOCKET; + connect(socket); + } + + boot(); +})(); diff --git a/crates/eggsec-gui/frontend/index.html b/crates/eggsec-gui/frontend/index.html new file mode 100644 index 000000000..f57250ed3 --- /dev/null +++ b/crates/eggsec-gui/frontend/index.html @@ -0,0 +1,72 @@ + + + + + + Eggsec + + + +
+
+
+

Eggsec

+ + Not connected +
+ +
+ + + +
+ +
+
+ + + +
+ + +
+
+
+

Run an operation

+

+
+
+
+ +
+
+

Tasks

+ +
+ +
+
+
+
+
+ + + + diff --git a/crates/eggsec-gui/frontend/styles.css b/crates/eggsec-gui/frontend/styles.css new file mode 100644 index 000000000..1303cac0d --- /dev/null +++ b/crates/eggsec-gui/frontend/styles.css @@ -0,0 +1,871 @@ +/* + * Eggsec desktop GUI — stylesheet. + * + * Dark theme, plain CSS, no build step and no external asset. The layout is a + * three-region grid: a header/status bar, a left sidebar of operations, and a + * main area holding the operation form above the task dashboard. + */ + +:root { + color-scheme: dark; + + --bg: #0d1117; + --bg-raised: #161b22; + --bg-inset: #0a0d12; + --bg-hover: #1c2230; + --border: #2a313c; + --border-strong: #3a424f; + + --text: #d7dce3; + --text-dim: #8b95a5; + --text-faint: #6b7484; + + --accent: #4c9aff; + --accent-dim: #1f3a5f; + --ok: #3fb950; + --warn: #d29922; + --danger: #f85149; + + --radius: 6px; + --gap: 12px; + --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; +} + +* { + box-sizing: border-box; +} + +html, +body { + height: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: var(--sans); + font-size: 14px; + line-height: 1.45; + overflow: hidden; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + border-radius: 3px; +} + +.app { + display: grid; + grid-template-rows: auto auto minmax(0, 1fr); + height: 100vh; +} + +/* ---------------------------------------------------------------- header */ + +.topbar { + display: grid; + grid-template-columns: auto minmax(240px, 1fr); + grid-template-areas: + "identity connect" + "facts facts"; + gap: 8px var(--gap); + align-items: center; + padding: 10px var(--gap); + background: var(--bg-raised); + border-bottom: 1px solid var(--border); +} + +.topbar__row { + grid-area: identity; + display: flex; + align-items: center; + gap: 8px; +} + +.topbar__title { + margin: 0; + font-size: 16px; + font-weight: 600; + letter-spacing: 0.02em; +} + +.connect-form { + grid-area: connect; + display: flex; + align-items: center; + gap: 8px; + justify-content: flex-end; +} + +.connect-form__label { + color: var(--text-dim); + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.06em; +} + +.connect-form__input { + min-width: 260px; + flex: 0 1 420px; + padding: 6px 8px; + background: var(--bg-inset); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--text); + font-family: var(--mono); + font-size: 12px; +} + +.catalog-facts { + grid-area: facts; + display: flex; + flex-wrap: wrap; + gap: 4px 20px; + margin: 0; + padding-top: 2px; + border-top: 1px solid var(--border); +} + +.catalog-facts__name { + margin: 6px 0 0; + color: var(--text-faint); + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.06em; +} + +.catalog-facts__value { + margin: 6px 0 0; + color: var(--text); + font-family: var(--mono); + font-size: 12px; + word-break: break-all; +} + +/* --------------------------------------------------------------- banners */ + +.banner-area { + display: flex; + flex-direction: column; + gap: 6px; + padding: 0 var(--gap); +} + +.banner-area:not(:empty) { + padding-top: 8px; + padding-bottom: 8px; +} + +.banner { + display: flex; + flex-direction: column; + gap: 2px; + padding: 8px 10px; + border: 1px solid var(--border-strong); + border-left-width: 3px; + border-radius: var(--radius); + background: var(--bg-raised); +} + +.banner__title { + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; +} + +.banner__message { + font-family: var(--mono); + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +.banner--error { + border-left-color: var(--danger); +} + +.banner--error .banner__title { + color: var(--danger); +} + +.banner--warning { + border-left-color: var(--warn); +} + +.banner--warning .banner__title { + color: var(--warn); +} + +.banner--info { + border-left-color: var(--accent); +} + +.banner--info .banner__title { + color: var(--accent); +} + +/* -------------------------------------------------------------- workspace */ + +.workspace { + display: grid; + grid-template-columns: 300px minmax(0, 1fr); + min-height: 0; +} + +.sidebar { + display: flex; + flex-direction: column; + min-height: 0; + padding: var(--gap); + gap: 6px; + background: var(--bg-raised); + border-right: 1px solid var(--border); + overflow: hidden; +} + +.sidebar__title { + margin: 0; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-dim); +} + +.sidebar__hint { + margin: 0 0 4px; + color: var(--text-faint); + font-size: 11px; +} + +.task-kinds { + list-style: none; + margin: 0; + padding: 0; + overflow-y: auto; + min-height: 0; + flex: 1 1 auto; +} + +.task-kind { + display: block; + width: 100%; + margin-bottom: 6px; + padding: 8px 10px; + text-align: left; + background: var(--bg-inset); + border: 1px solid var(--border); + border-radius: var(--radius); + color: var(--text); + font: inherit; + cursor: pointer; +} + +.task-kind:hover { + background: var(--bg-hover); +} + +.task-kind--selected { + border-color: var(--accent); + background: var(--bg-hover); +} + +.task-kind--unavailable { + border-style: dashed; + color: var(--text-dim); +} + +.task-kind__head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.task-kind__name { + font-weight: 600; +} + +.task-kind__risk { + color: var(--text-faint); + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.05em; + white-space: nowrap; +} + +.task-kind__reason { + display: block; + margin-top: 4px; + color: var(--warn); + font-size: 11px; + white-space: pre-wrap; + word-break: break-word; +} + +.main { + display: grid; + grid-template-rows: minmax(0, 5fr) minmax(0, 4fr); + min-height: 0; +} + +.panel { + display: flex; + flex-direction: column; + min-height: 0; + border-bottom: 1px solid var(--border); +} + +.panel--tasks { + border-bottom: none; +} + +.panel__header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--gap); + padding: 10px var(--gap); + border-bottom: 1px solid var(--border); +} + +.panel__heading { + margin: 0; + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-dim); +} + +.panel__subheading { + margin: 2px 0 0; + color: var(--text); + font-size: 13px; +} + +.panel__body { + padding: var(--gap); + overflow-y: auto; + min-height: 0; + flex: 1 1 auto; +} + +/* --------------------------------------------------------------- widgets */ + +.button { + padding: 6px 12px; + background: var(--bg-inset); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--text); + font: inherit; + font-size: 13px; + cursor: pointer; +} + +.button:hover:not(:disabled) { + background: var(--bg-hover); +} + +.button:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.button--primary { + border-color: var(--accent); + color: var(--accent); +} + +.button--danger { + border-color: var(--danger); + color: var(--danger); +} + +.button--small { + padding: 3px 8px; + font-size: 12px; +} + +.badge { + display: inline-block; + padding: 1px 7px; + border: 1px solid var(--border-strong); + border-radius: 999px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.05em; + white-space: nowrap; +} + +.badge--muted { + color: var(--text-faint); +} + +.badge--ok { + border-color: var(--ok); + color: var(--ok); +} + +.badge--warn, +.badge--warning { + border-color: var(--warn); + color: var(--warn); +} + +.badge--error { + border-color: var(--danger); + color: var(--danger); +} + +.badge--accent { + border-color: var(--accent); + color: var(--accent); +} + +.badge--info { + border-color: var(--accent); + color: var(--accent); +} + +.empty { + margin: 0; + padding: 12px 0; + color: var(--text-faint); + font-size: 13px; +} + +/* ------------------------------------------------------------------ form */ + +.op-form { + display: flex; + flex-direction: column; + gap: var(--gap); +} + +.op-form__fields { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: var(--gap); + align-items: start; +} + +.op-form__actions { + display: flex; + align-items: center; + gap: 10px; + padding-top: 4px; + border-top: 1px solid var(--border); +} + +.op-form__hint { + color: var(--text-dim); + font-size: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.field__label { + display: flex; + align-items: baseline; + gap: 2px; + font-size: 12px; + font-weight: 600; + color: var(--text); +} + +.field__required { + color: var(--danger); +} + +.field__input { + width: 100%; + padding: 6px 8px; + background: var(--bg-inset); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + color: var(--text); + font: inherit; + font-size: 13px; +} + +.field__input:focus { + border-color: var(--accent); +} + +.field__textarea { + min-height: 110px; + font-family: var(--mono); + font-size: 12px; + resize: vertical; +} + +.field__meta { + color: var(--text-faint); + font-size: 11px; + font-family: var(--mono); +} + +.field__help { + margin: 0; + color: var(--text-dim); + font-size: 12px; +} + +.field__error { + margin: 0; + color: var(--danger); + font-size: 12px; +} + +.field--invalid .field__input { + border-color: var(--danger); +} + +.form-error { + margin: 0 0 var(--gap); + padding: 8px 10px; + border: 1px solid var(--danger); + border-left-width: 3px; + border-radius: var(--radius); + background: var(--bg-raised); + color: var(--danger); + font-family: var(--mono); + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +.notice { + margin: 0 0 var(--gap); + padding: 8px 10px; + border: 1px solid var(--warn); + border-left-width: 3px; + border-radius: var(--radius); + background: var(--bg-raised); + color: var(--warn); + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +.list-control { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 6px; +} + +.list-control__row { + display: flex; + gap: 6px; + align-items: center; +} + +.list-control__row .field__input { + flex: 1 1 auto; +} + +.list-control__actions { + margin-top: 6px; +} + +/* ------------------------------------------------------------- dashboard */ + +.counters { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px var(--gap) 0; +} + +.counter { + padding: 2px 8px; + border: 1px solid var(--warn); + border-radius: 999px; + color: var(--warn); + font-size: 11px; +} + +.task-list { + display: flex; + flex-direction: column; + gap: var(--gap); +} + +.task { + padding: 10px 12px; + background: var(--bg-raised); + border: 1px solid var(--border); + border-left-width: 3px; + border-radius: var(--radius); +} + +.task--queued { + border-left-color: var(--text-faint); +} + +.task--running { + border-left-color: var(--accent); +} + +.task--completed { + border-left-color: var(--ok); +} + +.task--failed { + border-left-color: var(--danger); +} + +.task--cancelled, +.task--unknown { + border-left-color: var(--text-faint); +} + +.task--awaiting { + border-left-color: var(--warn); +} + +.task__header { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.task__variant { + margin: 0; + font-size: 14px; + font-weight: 600; +} + +.task__id { + display: inline-block; + margin-top: 2px; + color: var(--text-faint); + font-family: var(--mono); + font-size: 11px; + word-break: break-all; +} + +.task__message { + margin: 6px 0 0; + color: var(--text-dim); + font-size: 13px; +} + +.task__error { + margin: 8px 0 0; + padding: 6px 8px; + border: 1px solid var(--danger); + border-radius: var(--radius); + color: var(--danger); + font-family: var(--mono); + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +.task__actions { + display: flex; + gap: 8px; + margin-top: 8px; +} + +.task__dropped { + margin: 6px 0 0; + color: var(--warn); + font-size: 11px; + font-style: italic; +} + +.progress { + margin-top: 8px; + height: 6px; + background: var(--bg-inset); + border: 1px solid var(--border); + border-radius: 999px; + overflow: hidden; +} + +.progress__fill { + height: 100%; + background: var(--accent); +} + +.logs { + list-style: none; + margin: 8px 0 0; + padding: 6px 8px; + max-height: 220px; + overflow-y: auto; + background: var(--bg-inset); + border: 1px solid var(--border); + border-radius: var(--radius); + font-family: var(--mono); + font-size: 11.5px; +} + +.log { + display: flex; + gap: 8px; + padding: 1px 0; + white-space: pre-wrap; + word-break: break-word; +} + +.log__level { + flex: 0 0 auto; + min-width: 52px; + color: var(--text-faint); + text-transform: uppercase; + font-size: 10px; + letter-spacing: 0.05em; + padding-top: 1px; +} + +.log--error .log__level { + color: var(--danger); +} + +.log--warn .log__level { + color: var(--warn); +} + +.log--info .log__level { + color: var(--accent); +} + +.log__message { + flex: 1 1 auto; +} + +/* ---------------------------------------------------------------- result */ + +.result { + margin-top: 10px; + padding: 10px; + background: var(--bg-inset); + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.result__kind { + margin: 0; + font-size: 13px; + font-weight: 600; + color: var(--ok); +} + +.result__summary { + margin: 4px 0 0; + font-size: 13px; +} + +.result__fields { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 2px 12px; + margin: 8px 0 0; +} + +.result__fields dt { + color: var(--text-dim); + font-size: 12px; +} + +.result__fields dd { + margin: 0; + font-family: var(--mono); + font-size: 12px; + word-break: break-word; +} + +.result__artifacts { + list-style: none; + margin: 8px 0 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.artifact { + display: flex; + gap: 8px; + align-items: baseline; + flex-wrap: wrap; +} + +.artifact__id { + font-family: var(--mono); + font-size: 11.5px; + color: var(--accent); +} + +.artifact__summary { + color: var(--text-dim); + font-size: 12px; +} + +.result__json { + margin-top: 8px; +} + +.result__json-summary { + color: var(--text-dim); + font-size: 12px; + cursor: pointer; +} + +.result__payload { + max-height: 320px; + overflow: auto; + margin: 6px 0 0; + padding: 8px; + background: var(--bg); + border: 1px solid var(--border); + border-radius: var(--radius); + font-family: var(--mono); + font-size: 11.5px; + white-space: pre; +} + +/* ------------------------------------------------------------ responsive */ + +@media (max-width: 900px) { + body { + overflow: auto; + } + + .app { + height: auto; + min-height: 100vh; + } + + .workspace { + grid-template-columns: minmax(0, 1fr); + } + + .sidebar { + border-right: none; + border-bottom: 1px solid var(--border); + max-height: 260px; + } + + .main { + grid-template-rows: auto auto; + } +} diff --git a/crates/eggsec-gui/icons/icon.png b/crates/eggsec-gui/icons/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..3424a4de03f3aa19455b7c5020541f0ade9ac448 GIT binary patch literal 4379 zcmb7Hdsr0L6+bf!FoMWzqYFeW3qGk!1TiWa+2JMe5j9D*JT$EJu{IhP%NM~0*a76B z7_r7;u@H=3Ok+X`30AOC7z6ky$u1f-BFL^FMJvin1$5c%xw8bCe)-b)*W9`1oZtDK z$9?Tyxje$f>3Jsra9R9v*lPeZ4ryQ=@bfV7$`b&tWpP;WuM=yO^;=+VJ-RU!)Rlpz0a;1O)P#_Kkzyk0%LU0a1 zz|l{Oo>5(afHo&T3w=bLM?)K@ADa_U`qMnoiidv1GsQOIiGv^p^C7P*D0%W~Tu0a>Qs9-mz?wGJ3ofi=sk9H5T6a$gUyxpDpge>$_^Ho>jljSl{ zFOD2jxyAS*;@ahieVtDufNwPQ4bFQ`&(N^M;Y??($M!`WtekZvd7A#+_;e5sP!FEQ zM3!?pZHnCVE>^yCst>iG8Y41`x-(p02( zUesiR*fW=NmREM_+cU|S@l7%wH#kv3tufH7+-WQ`u$0giJF7$ad*c~{gEYRa+^RX- zn~Lf)J+{ir+`EbuP-@O`I6OtkycB@RvK|QDbZZY~7(+vyv1<{VxQ~NK%kI#+S>x#U zr!kPHyHxtcOBq5t`e}=u{h@NHmuVmb)C1#dSjzA`TB)`xqB29ofGiM>25%U+wBv43eS8Je9W?zXy4i z_seJ$3hRD5Fo_Psa);LRL@?QCmYG$X%W>EfAGwUF^OTvQ79ouoOEws06Y{8)cv1%L zoLq%$_JO)RuGH*h4fJ1Nk8Ijp322*kAf4sGl%T8gY$=);unJ7~jXhakX)Y`qCy^k2 zhLrg=IHRB$0mR0tw%F6^q>ok@4zVOX@}+&&eb*B11O~+0Ly5(A-&Yx(?~J21l@R`u zl}X0GqZ0)vnb4~V#-5J+GlU=Q_i~}V4AFY#cDXFqgfa@~;>P!69t-fsIdn6KZ9 zW`3qyFJACX@lwzQZ&O0KuDa20EFG@7c*+feSgqCJBsHB06MAQ28C~A2UcvPHi17-D zd!*&ZCx(c=f+mE-w6fX%c4ejRjSw~)D0K8#%ehX7`z-olW3|{2?<}ClX3Kgv>)N`M z*T>FF-$rp5cDXe>bx!i#6?-YoC10Rra@&g%-caOo5j0q)aXsd)z2}1%_E+>D#ekAP3r;4A@Ls zYv$3mnRG!yIsQ;;_h|E4FVok~QfqM07H=LqjS`TwjKcWI`sk-Nf3PD$(C`e4KA2^f6R8hgx)YD>_-KJ5&pUdrDcBMLVE~WlVBM^6NmvEtiC#qN^u~&FB*#hld-eOWSG!?0W%?_Wz{sQD(uk+ z@jef&OKa_5y8>*Kv{p$#dieBUD;5HSR1Z8IG&ZWXQRYCvSQ!DEDmMlY8;5a&Gtp-X zZn~1@B$@%5NB(ZW3Z^2e!wJou1)Vh^M&0CrnU!)`u4|%Eod6iE_DH_SPRecK(}cm? zB5GJ@(_28Yh{}X8en=^bu<*2Kv`v|`G+{fFq$Y80-OI%8uM zD)j$_q>lI_;TBP(M;UZR(V{OF$X;k8|0+iUCix|C%g8Kg46<2JraoN0`0Fj)t&>uL zFeEL;M^%#AHmd8f4HPYGpptQsU7Rzn@+xbijOKx?C06*PTt`V;1V=?$N~|(KiBt#4 zt%5E!ueDABh7fEzW40%5v5kkBO1l8IGl^`7Ch8*16esa&71?EpB_Y&#-;*L4X2l*{ zen7=lSARRdN%?Y}v6qx#8x@9Iy{1|cs_aeww)&tlL6VH6bT!f0pwvm;aF;@$J`yHi zv2hs#r9e-OnMD~lPMHgJm>30&4$irXfHc;MCh&O9Is?Ps zCQw_j0s|naXzSej4qmrdu*y9gy(__r~llOF#5CiG2F(^8L2^3<4 zE9-VX=D#RTP^PpuV4acQ2R^h?*M8mhbIXT0fFAE*5=?Rt#?kVs_^q>pc;$(z0@V|3bTK3Hbv}`?Iw1)3#htY`haKmuGd>lM>>5>cN@vqT^Bx z&0`hxk%tYl*4s;sGdAe;O~vRmo1Bn{EyKGUEnHXS`_e~x8~k6lX&qcRchm9z)dJlw zd4|8zyKaXQgoz(h>rUbQ+=4;ll12~$RfSwkmur1+Ei61w(!q%>eP+BJQQp`%@i`Kt z63<#nU^zO{Ow6jou_p=6$(ePxt#gzqhN*}}mea!b5JIdWx6a~dRM_K~J0;@Y!0c8I zi95R@iYfF+0vDAcuhNX6pw{l&elC(e^e4k$SHt{o72r4f ztOs7|@v-m%3(+Z6j~iM~r-7)pZ-0(~cXfwvw&wqO{FavM$@K*H=afkGRIq0gjYdW=k8$NJ?>RsN})OZ8~-!06&Q#eXP zQ;=DCw)1J}0G?HMr++V~fxMt$!D#i}VF8nx;feygydbpTBKrk^ zSJe&ZA}nJsbgMcFja98?q5e2y80FTn2r9Og0i}>, +} + +/// What the GUI holds once it is connected. +pub struct ConnectedState { + /// The socket the connection was opened against. + pub socket_path: String, + /// The live connection. + pub connection: GuiConnection, + /// The bounded task view, shared with the event forwarder. + pub tasks: Arc>, +} + +/// The live connection's parts, cloned out from under the state lock. +/// +/// A command must not hold the GUI's state lock across an await: the lock +/// would serialize every webview call behind the daemon's round trips. The +/// parts are all cheap to clone — the catalog sits behind an `Arc`, and the +/// client behind its own. +struct ConnectionParts { + client: eggsec_frontend_client::DaemonRuntimeClient, + session_id: eggsec_runtime::SessionId, + catalog: std::sync::Arc, + capabilities: eggsec_daemon_protocol::protocol::DaemonCapabilities, + tasks: Arc>, +} + +impl ConnectionParts { + /// A published task kind, by its wire variant. + fn task_kind(&self, variant: &str) -> Option<&TaskKindDescription> { + self.catalog + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == variant) + } + + /// The catalog operation a task kind executes. + fn operation( + &self, + task_kind: &TaskKindDescription, + ) -> Option<&eggsec_daemon_protocol::operations::OperationDescription> { + self.catalog + .operations + .iter() + .find(|operation| operation.id == task_kind.operation_id) + } + + /// Whether the connected daemon advertises this task kind's capability. + fn supports(&self, task_kind: &TaskKindDescription) -> bool { + self.capabilities + .runtime + .task_kinds + .iter() + .any(|capability| capability.name == task_kind.capability_name) + } +} + +impl GuiState { + /// The live connection's parts. + async fn parts(&self) -> Result { + let inner = self.inner.lock().await; + let connected = inner + .as_ref() + .ok_or_else(|| "the GUI is not connected to a daemon yet".to_owned())?; + Ok(ConnectionParts { + client: connected.connection.client.clone(), + session_id: connected.connection.session_id, + catalog: std::sync::Arc::clone(&connected.connection.catalog), + capabilities: connected.connection.capabilities.clone(), + tasks: Arc::clone(&connected.tasks), + }) + } +} + +/// What the webview needs to know about the connection it just opened. +#[derive(Debug, Clone, serde::Serialize)] +pub struct CatalogView { + /// The socket the GUI connected to. + pub socket_path: String, + /// The session the GUI created. + pub session_id: String, + /// The daemon protocol version the daemon speaks. + pub protocol_version: u32, + /// How many operations the daemon published. + pub operation_count: usize, + /// How many task kinds the daemon published. + pub task_kind_count: usize, + /// Whether the connected daemon advertises no task kinds at all. + pub no_op_executor: bool, + /// A human-readable notice, when the connection carries a caveat the + /// operator should see. + pub notice: Option, +} + +/// One row of the operation catalog, as the webview renders it. +#[derive(Debug, Clone, serde::Serialize)] +pub struct OperationRow { + /// The canonical operation id. + pub id: String, + /// The human-readable operation name. + pub display_name: String, + /// The assessment mode the operation belongs to. + pub mode: String, + /// The declared risk tier. + pub risk: String, + /// Whether the operation is exposed on the manual surface — which is what + /// the GUI is. + pub manual_exposable: bool, +} + +/// One published task kind, as the webview renders it. +#[derive(Debug, Clone, serde::Serialize)] +pub struct TaskKindRow { + /// The wire discriminator. + pub variant: String, + /// The canonical operation this task kind executes. + pub operation_id: String, + /// The wire capability name this task kind advertises. + pub capability_name: String, + /// Whether the connected daemon advertises this capability. + pub supported: bool, + /// Whether the operation is exposed on the manual surface. + pub manual_exposable: bool, + /// Why the task kind cannot be run, when it cannot. + pub unavailable_reason: Option, +} + +/// A form, as the webview renders it. +#[derive(Debug, Clone, serde::Serialize)] +pub struct FormView { + /// The task kind's wire discriminator. + pub variant: String, + /// The canonical operation the task kind executes. + pub operation_id: String, + /// The operation's human-readable name. + pub display_name: String, + /// The operation's declared risk tier. + pub risk: String, + /// The fields, in a deterministic order. + pub controls: Vec, + /// Whether the form may be submitted. + pub submit_enabled: bool, + /// Why the form cannot be submitted, when it cannot. + pub disabled_reason: Option, +} + +/// The identifier of a submitted task. +#[derive(Debug, Clone, serde::Serialize)] +pub struct TaskIdView { + /// The task's identifier. + pub task_id: String, +} + +/// The event the GUI publishes to the webview. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum TaskEvent { + /// A task's state changed. + TaskUpsert { + /// The task, in full. + task: Box, + }, + /// Log lines were added to a task. + Logs { + /// The task the lines belong to. + task_id: String, + /// The lines. + lines: Vec, + /// How many lines were dropped while coalescing. + dropped: u64, + }, + /// The GUI's diagnostic counters moved. + Counters { + /// Log lines dropped across every task. + dropped_log_lines: u64, + /// Events about tasks the GUI does not know about. + unknown_task_events: u64, + }, +} + +/// Connect to a daemon and return the catalog it published. +/// +/// The socket path comes from the webview so the operator can point the GUI +/// at a different daemon without relaunching it. +#[tauri::command(rename_all = "snake_case")] +pub async fn connect_daemon( + app: tauri::AppHandle, + state: tauri::State<'_, GuiState>, + socket: String, +) -> Result { + let connection = GuiConnection::connect(&socket) + .await + .map_err(|error| error.to_string())?; + + let view = CatalogView { + socket_path: socket.clone(), + session_id: connection.session_id.to_string(), + protocol_version: connection.protocol_version, + operation_count: connection.catalog.operations.len(), + task_kind_count: connection.catalog.task_kinds.len(), + no_op_executor: connection.daemon_advertises_no_task_kinds(), + notice: if connection.daemon_advertises_no_task_kinds() { + Some(connection.no_op_executor_diagnostic(&socket)) + } else { + None + }, + }; + + let tasks = Arc::new(Mutex::new(TaskRegistry::new())); + spawn_event_forwarder( + app, + connection.client.clone(), + connection.session_id, + Arc::clone(&tasks), + ); + + let mut inner = state.inner.lock().await; + *inner = Some(ConnectedState { + socket_path: socket, + connection, + tasks, + }); + + Ok(view) +} + +/// List the operations the connected daemon published. +/// +/// The rows are the daemon's own published descriptions, rendered for +/// display. The GUI does not decide policy here: the exposure flags and the +/// risk tier come from the daemon's catalog. +#[tauri::command(rename_all = "snake_case")] +pub async fn list_operations( + state: tauri::State<'_, GuiState>, +) -> Result, String> { + let parts = state.parts().await?; + + Ok(parts + .catalog + .operations + .iter() + .map(|operation| OperationRow { + id: operation.id.clone(), + display_name: operation.display_name.clone(), + mode: operation.mode.label().to_owned(), + risk: operation.risk.to_string(), + manual_exposable: operation.manual_exposable, + }) + .collect()) +} + +/// List the published task kinds and whether the connected daemon can run +/// them. +/// +/// Availability comes from the daemon's live capabilities, never from the +/// GUI's own reasoning: the join key is the task kind's `capability_name` +/// against the capability list the daemon advertises. +#[tauri::command(rename_all = "snake_case")] +pub async fn list_task_kinds( + state: tauri::State<'_, GuiState>, +) -> Result, String> { + let parts = state.parts().await?; + + Ok(parts + .catalog + .task_kinds + .iter() + .map(|task_kind| { + let supported = parts.supports(task_kind); + let manual_exposable = parts + .operation(task_kind) + .is_some_and(|operation| operation.manual_exposable); + TaskKindRow { + variant: task_kind.variant.clone(), + operation_id: task_kind.operation_id.clone(), + capability_name: task_kind.capability_name.clone(), + supported, + manual_exposable, + unavailable_reason: unavailable_reason(supported, manual_exposable), + } + }) + .collect()) +} + +/// The reason a task kind cannot be submitted, if it cannot. +fn unavailable_reason(supported: bool, manual_exposable: bool) -> Option { + if !manual_exposable { + return Some( + "the connected daemon does not expose this operation on the manual surface".to_owned(), + ); + } + if !supported { + return Some( + "the connected daemon does not support this operation's capability".to_owned(), + ); + } + None +} + +/// Build the form for one task kind. +/// +/// The form is derived from the published request schema. There is no +/// per-operation code: a task kind the engine has not published yet gets a +/// form with no GUI change at all. +#[tauri::command(rename_all = "snake_case")] +pub async fn form_for( + state: tauri::State<'_, GuiState>, + variant: String, +) -> Result { + let parts = state.parts().await?; + + let task_kind = parts + .task_kind(&variant) + .ok_or_else(|| format!("`{variant}` is not a task kind the daemon published"))?; + let operation = parts.operation(task_kind); + + let supported = parts.supports(task_kind); + let manual_exposable = operation.is_some_and(|operation| operation.manual_exposable); + let disabled_reason = unavailable_reason(supported, manual_exposable); + + Ok(FormView { + variant: task_kind.variant.clone(), + operation_id: task_kind.operation_id.clone(), + display_name: operation + .map(|operation| operation.display_name.clone()) + .unwrap_or_else(|| task_kind.variant.clone()), + risk: operation + .map(|operation| operation.risk.to_string()) + .unwrap_or_else(|| "unknown".to_owned()), + controls: form::controls_for(task_kind), + submit_enabled: disabled_reason.is_none(), + disabled_reason, + }) +} + +/// Submit a form. +/// +/// The variant and the values come from the webview; the surface does not. +/// The surface is stamped in Rust, so the webview cannot widen the session's +/// authority by asking nicely. +#[tauri::command(rename_all = "snake_case")] +pub async fn submit_task( + state: tauri::State<'_, GuiState>, + variant: String, + values: serde_json::Value, +) -> Result { + let parts = state.parts().await?; + + let task_kind = parts + .task_kind(&variant) + .ok_or_else(|| format!("`{variant}` is not a task kind the daemon published"))?; + + // The catalog's exposure flags are the authority on what a manual + // surface may run. + let operation = parts.operation(task_kind).ok_or_else(|| { + format!( + "the daemon's catalog has no operation for the task kind `{}`", + task_kind.variant + ) + })?; + if !operation.manual_exposable { + return Err(format!( + "`{}` is not exposed on the manual surface, so this GUI cannot run it", + operation.display_name + )); + } + + // Availability comes from the daemon's live capabilities. + if !parts.supports(task_kind) { + return Err(format!( + "the connected daemon does not support `{}`", + operation.display_name + )); + } + + let request = form::assemble_request(task_kind, &values).map_err(|error| error.to_string())?; + + let task_id = parts + .client + .submit(parts.session_id, request) + .await + .map_err(|error| error.to_string())?; + + // Register the task straight away so the dashboard shows it before the + // daemon's first event arrives. + parts + .tasks + .lock() + .await + .ensure_task(task_id, task_kind.variant.clone()); + + Ok(TaskIdView { + task_id: task_id.to_string(), + }) +} + +/// Cancel one task. +/// +/// Cancellation is best-effort: a task that completes between the operator's +/// click and the daemon's processing is not an error. The event stream is +/// authoritative about what actually happened. +#[tauri::command(rename_all = "snake_case")] +pub async fn cancel_task(state: tauri::State<'_, GuiState>, task_id: String) -> Result<(), String> { + let parts = state.parts().await?; + + let parsed = task_id + .parse::() + .map_err(|error| format!("`{task_id}` is not a task identifier: {error}"))?; + + parts + .client + .cancel(parts.session_id, parsed) + .await + .map_err(|error| error.to_string()) +} + +/// Cancel the active task in the session. +#[tauri::command(rename_all = "snake_case")] +pub async fn cancel_active(state: tauri::State<'_, GuiState>) -> Result<(), String> { + let parts = state.parts().await?; + + parts + .client + .cancel_active(parts.session_id) + .await + .map_err(|error| error.to_string()) +} + +/// The current task dashboard. +#[tauri::command(rename_all = "snake_case")] +pub async fn task_snapshot(state: tauri::State<'_, GuiState>) -> Result { + let parts = state.parts().await?; + let tasks = Arc::clone(&parts.tasks); + let registry = tasks.lock().await; + let view = registry.to_view(); + Ok(view) +} + +/// Forward the daemon's event stream to the webview. +/// +/// The GUI subscribes **once** per session; it does not resubscribe per +/// task. The forwarder drains the receiver and updates the bounded task +/// state, then emits to the webview. It never spawns a task per event and +/// never accumulates an unbounded queue: log lines are coalesced, and only +/// the newest [`MAX_LOG_LINES_PER_FLUSH`] are forwarded per flush, with the +/// rest reported as dropped. +/// +/// **This task is exempt from the 30–300s timeout rule.** It is a +/// long-lived connection reader whose lifetime is the subscription's, and +/// killing it would silently sever the event stream. The exemption is the +/// same one the daemon client's reader task holds, and for the same reason. +fn spawn_event_forwarder( + app: tauri::AppHandle, + client: eggsec_frontend_client::DaemonRuntimeClient, + session_id: eggsec_runtime::SessionId, + tasks: Arc>, +) { + tokio::spawn(async move { + let mut receiver = match client.subscribe(session_id).await { + Ok(receiver) => receiver, + Err(error) => { + tracing::warn!("the GUI could not subscribe to the daemon's events: {error}"); + return; + } + }; + + let mut pending: Vec<(String, LogLine)> = Vec::new(); + let mut flush = tokio::time::interval(Duration::from_millis(100)); + + loop { + tokio::select! { + event = receiver.recv() => { + match event { + Some(event) => { + let effect = { + let mut registry = tasks.lock().await; + registry.apply(&event) + }; + match effect { + EventEffect::TaskUpdated(task_id) => { + let row = { + let registry = tasks.lock().await; + let row = registry + .tasks() + .find(|task| task.task_id == task_id) + .map(TaskState::to_row); + row + }; + if let Some(row) = row { + emit(&app, TaskEvent::TaskUpsert { task: Box::new(row) }); + } + } + EventEffect::Logs { task_id, lines } => { + for line in lines { + pending.push((task_id.to_string(), line)); + } + } + EventEffect::Ignored => {} + } + } + None => { + // The daemon's connection ended. The GUI reports + // the loss; it does not decide what happened to + // the running tasks. + tracing::warn!("the GUI's daemon event stream ended"); + let (dropped_log_lines, unknown_task_events) = { + let registry = tasks.lock().await; + (registry.dropped_log_lines(), registry.unknown_task_events()) + }; + emit(&app, TaskEvent::Counters { dropped_log_lines, unknown_task_events }); + break; + } + } + } + _ = flush.tick() => { + if pending.is_empty() { + continue; + } + // Keep the newest lines; report the rest as dropped. + let mut dropped = 0u64; + if pending.len() > MAX_LOG_LINES_PER_FLUSH { + dropped = (pending.len() - MAX_LOG_LINES_PER_FLUSH) as u64; + let start = pending.len() - MAX_LOG_LINES_PER_FLUSH; + pending.drain(..start); + } + // Group by task so each flush carries one entry per task. + let mut grouped: Vec<(String, Vec)> = Vec::new(); + for (task_id, line) in pending.drain(..) { + match grouped.iter_mut().find(|(id, _)| *id == task_id) { + Some((_, lines)) => lines.push(line), + None => grouped.push((task_id, vec![line])), + } + } + for (task_id, lines) in grouped { + emit(&app, TaskEvent::Logs { task_id, lines, dropped }); + } + } + } + } + }); +} + +/// Emit an event to the webview. +fn emit(app: &tauri::AppHandle, event: TaskEvent) { + if let Err(error) = app.emit(TASK_EVENT, &event) { + tracing::warn!("the GUI could not publish a task event: {error}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The IPC surface must stay narrow. Each command maps to one narrow + /// operation; there is no generic "send any command to the daemon" entry + /// point, and nothing that sets the surface or the scope. + #[test] + fn ipc_surface_exposes_only_narrow_commands() { + let source = include_str!("commands.rs"); + // Scan the production half only: this test names the forbidden + // tokens itself. + let production = source + .split("#[cfg(test)]") + .next() + .expect("the module has a production half"); + for forbidden in [ + "ClientCommand::", + "RuntimeSurface::", + "SessionScope", + "send_command", + ] { + assert!( + !production.contains(forbidden), + "the IPC surface must not contain {forbidden}" + ); + } + } + + /// The command list is exactly the declared set. + #[test] + fn declared_command_set_is_exact() { + let registered = [ + "connect_daemon", + "list_operations", + "list_task_kinds", + "form_for", + "submit_task", + "cancel_task", + "cancel_active", + "task_snapshot", + ]; + let source = include_str!("shell.rs"); + for command in registered { + assert!( + source.contains(command), + "the shell must register the {command} command" + ); + } + } + + /// Every command declares its argument naming explicitly. + /// + /// Tauri's default is camelCase from the webview. The GUI's contract is + /// snake_case on both sides of the boundary, so the attribute must not be + /// dropped — without it the webview's `task_id` would silently stop + /// arriving. + #[test] + fn every_command_declares_its_argument_naming() { + let source = include_str!("commands.rs"); + let production = source + .split("#[cfg(test)]") + .next() + .expect("the module has a production half"); + let commands = production.matches("#[tauri::command").count(); + let explicit = production + .matches("#[tauri::command(rename_all = \"snake_case\")]") + .count(); + assert_eq!(commands, 8, "the GUI's IPC surface is eight commands"); + assert_eq!( + commands, explicit, + "every command must declare rename_all = \"snake_case\"" + ); + } + + /// The availability rules are stated once and applied consistently. + #[test] + fn unavailability_is_explained() { + assert!(unavailable_reason(true, true).is_none()); + assert!(unavailable_reason(true, false) + .expect("a reason") + .contains("manual surface")); + assert!(unavailable_reason(false, true) + .expect("a reason") + .contains("capability")); + assert!(unavailable_reason(false, false) + .expect("a reason") + .contains("manual surface")); + } +} diff --git a/crates/eggsec-gui/src/config.rs b/crates/eggsec-gui/src/config.rs new file mode 100644 index 000000000..b7b6e37f7 --- /dev/null +++ b/crates/eggsec-gui/src/config.rs @@ -0,0 +1,145 @@ +//! Command-line configuration for the desktop GUI. +//! +//! The GUI is configured by flags only. The workspace has no socket-path +//! environment variable and no XDG lookup today — the default is hardcoded in +//! three independent places — so introducing one here would create a second, +//! differently-named source of truth. Collapsing the duplication is a +//! separate corrective milestone. + +use crate::GuiError; + +/// The default path of the daemon's Unix socket. +/// +/// This matches the three existing defaults in the workspace: +/// `crates/eggsec/src/cli/mod.rs` (the global `--socket` flag), +/// `crates/eggsec-daemon/src/config.rs` (`DaemonConfig::default`), and +/// `crates/eggsec-daemon/src/main.rs` (the binary's `--socket-path` flag). +pub const DEFAULT_SOCKET_PATH: &str = "/tmp/eggsec-daemon.sock"; + +/// The options the GUI was started with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GuiOptions { + /// Path of the daemon's Unix socket. + pub socket_path: String, +} + +impl Default for GuiOptions { + fn default() -> Self { + Self { + socket_path: DEFAULT_SOCKET_PATH.to_owned(), + } + } +} + +impl GuiOptions { + /// Parse the GUI's command line. + /// + /// Accepts `--socket ` and `--socket=`. `--help` and `-h` + /// produce the usage text. + pub fn from_args(args: I) -> Result + where + I: IntoIterator, + { + let mut options = GuiOptions::default(); + let mut args = args.into_iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--socket" => match args.next() { + Some(path) => options.socket_path = path, + None => { + return Err(GuiError::Usage( + "--socket requires a path argument".to_owned(), + )) + } + }, + "--help" | "-h" => return Err(GuiError::Usage(usage())), + other => { + if let Some(path) = other.strip_prefix("--socket=") { + options.socket_path = path.to_owned(); + } else { + return Err(GuiError::Usage(format!( + "unknown argument: {other}\n\n{}", + usage() + ))); + } + } + } + } + if options.socket_path.is_empty() { + return Err(GuiError::Usage( + "--socket requires a non-empty path".to_owned(), + )); + } + Ok(options) + } +} + +/// The GUI's usage text. +pub fn usage() -> String { + format!( + "eggsec-gui — the Eggsec desktop frontend\n\n\ + Usage: eggsec-gui [--socket ]\n\n\ + Options:\n \ + --socket Path of the running daemon's Unix socket\n \ + (default: {DEFAULT_SOCKET_PATH})\n \ + -h, --help Show this message\n\n\ + The GUI connects to an already-running daemon. Start one with:\n \ + eggsec-daemon --full-executor --socket-path {DEFAULT_SOCKET_PATH}\n" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(items: &[&str]) -> Vec { + items.iter().map(|item| (*item).to_owned()).collect() + } + + #[test] + fn default_socket_path_matches_the_workspace_defaults() { + let options = GuiOptions::from_args(args(&[])).expect("no arguments is valid"); + assert_eq!(options.socket_path, DEFAULT_SOCKET_PATH); + assert_eq!(options.socket_path, "/tmp/eggsec-daemon.sock"); + } + + #[test] + fn socket_flag_is_parsed_in_both_spellings() { + let spaced = GuiOptions::from_args(args(&["--socket", "/run/eggsec.sock"])) + .expect("a spaced socket flag is valid"); + assert_eq!(spaced.socket_path, "/run/eggsec.sock"); + + let joined = GuiOptions::from_args(args(&["--socket=/run/eggsec.sock"])) + .expect("a joined socket flag is valid"); + assert_eq!(joined.socket_path, "/run/eggsec.sock"); + } + + #[test] + fn missing_socket_value_is_a_usage_error() { + let error = GuiOptions::from_args(args(&["--socket"])).expect_err("a value is required"); + assert!(error + .to_string() + .contains("--socket requires a path argument")); + } + + #[test] + fn empty_socket_value_is_a_usage_error() { + let error = GuiOptions::from_args(args(&["--socket="])).expect_err("a value is required"); + assert!(error.to_string().contains("non-empty path")); + } + + #[test] + fn unknown_argument_is_a_usage_error() { + let error = GuiOptions::from_args(args(&["--nope"])).expect_err("unknown flags are errors"); + assert!(error.to_string().contains("unknown argument: --nope")); + } + + #[test] + fn usage_names_the_daemon_start_command() { + let text = usage(); + assert!(text.contains("eggsec-daemon --full-executor")); + // A default-built daemon hosts a no-op executor that rejects every + // task, so the usage text must not point at the plain daemon. + assert!(!text.contains("eggsec daemon start")); + } +} diff --git a/crates/eggsec-gui/src/connection.rs b/crates/eggsec-gui/src/connection.rs new file mode 100644 index 000000000..e57db8211 --- /dev/null +++ b/crates/eggsec-gui/src/connection.rs @@ -0,0 +1,216 @@ +//! The GUI's connection to a running daemon. +//! +//! The GUI is daemon-only by construction (`ADR-0007`): it reaches the engine +//! only through the daemon's Unix socket, using the shared +//! `eggsec-frontend-client` contract. It never spawns, supervises, or stops +//! a daemon — it connects to one that is already running and, when the socket +//! is unreachable, says precisely how to start a *usable* one. + +use eggsec_daemon_protocol::operations::DescribeOperationsResponse; +use eggsec_daemon_protocol::protocol::{DaemonCapabilities, DAEMON_PROTOCOL_VERSION}; +use eggsec_frontend_client::RuntimeClient; +use eggsec_frontend_client::{ClientIdentity, ClientKind, DaemonClientError, DaemonRuntimeClient}; +use eggsec_runtime::request::RuntimeSurface; +use eggsec_runtime::session::SessionScope; +use eggsec_runtime::SessionId; + +use crate::GuiError; + +/// The identity the GUI presents to the daemon. +/// +/// The GUI declares itself as a GUI client, with its own label and its own +/// request-id namespace, so the daemon's audit trail distinguishes it from +/// the CLI and the TUI. +pub fn gui_identity() -> ClientIdentity { + ClientIdentity { + kind: ClientKind::Gui, + label: "eggsec-gui".to_owned(), + request_prefix: "gui-".to_owned(), + } +} + +/// The scope the GUI stamps on the session it creates. +/// +/// The GUI cannot widen scope beyond what the operator supplied, and it does +/// not read the engine's loaded scope — that lives behind the daemon. The +/// session is therefore marked as not explicitly scoped, with the source +/// recorded so the audit trail can tell where it came from. +pub fn gui_session_scope() -> SessionScope { + SessionScope { + is_explicit: false, + source: "gui-default".to_owned(), + path: None, + } +} + +/// The command that starts a daemon the GUI can actually use. +/// +/// `eggsec daemon start` and a default-built `eggsec-daemon` both host a +/// no-op executor that rejects every task, so the `--full-executor` flag is +/// what makes a daemon usable. +pub fn daemon_start_command(socket_path: &str) -> String { + format!("eggsec-daemon --full-executor --socket-path {socket_path}") +} + +/// The diagnostic shown when the daemon's socket cannot be reached. +/// +/// It names the socket path and the exact command that starts a usable +/// daemon, because "connection refused" on its own leaves the operator +/// guessing which daemon build will actually work. +pub fn unreachable_diagnostic(socket_path: &str, error: &DaemonClientError) -> String { + format!( + "cannot reach the Eggsec daemon at {socket_path}: {error}\n\n\ + Start a usable daemon with:\n {}\n\n\ + `eggsec daemon start` and a default-built `eggsec-daemon` host a no-op \ + executor that rejects every task, so the --full-executor flag is required.", + daemon_start_command(socket_path) + ) +} + +/// A live GUI connection: the daemon client, the GUI's session, and the +/// catalog the daemon published. +pub struct GuiConnection { + /// The daemon client, already declared as a GUI client. + pub client: DaemonRuntimeClient, + /// The session the GUI created, stamped `DesktopGuiManual`. + pub session_id: SessionId, + /// The operation catalog and the derived request schema. + /// + /// Shared behind an `Arc` so a command can read the catalog without + /// holding the GUI's state lock across an await. + pub catalog: std::sync::Arc, + /// The daemon's capability advertisement. + pub capabilities: DaemonCapabilities, + /// The daemon protocol version the daemon speaks. + pub protocol_version: u32, +} + +impl GuiConnection { + /// Connect to the daemon, verify it, open a session, and fetch the + /// operation catalog. + /// + /// The order matters. The protocol version is checked before anything + /// else, because a daemon that speaks a different protocol cannot be + /// trusted to interpret a session request the way this GUI means it. + pub async fn connect(socket_path: &str) -> Result { + let client = DaemonRuntimeClient::connect(socket_path, gui_identity()) + .await + .map_err(|error| GuiError::Connection(unreachable_diagnostic(socket_path, &error)))?; + + let health = client + .health() + .await + .map_err(|error| GuiError::Connection(unreachable_diagnostic(socket_path, &error)))?; + + if health.protocol_version != DAEMON_PROTOCOL_VERSION { + return Err(GuiError::Connection(format!( + "the daemon at {socket_path} speaks daemon protocol version {}, but this GUI \ + speaks version {DAEMON_PROTOCOL_VERSION}. The GUI refuses to operate against an \ + incompatible daemon.", + health.protocol_version + ))); + } + + let capabilities = client + .daemon_capabilities() + .await + .map_err(|error| GuiError::Connection(unreachable_diagnostic(socket_path, &error)))?; + + if !capabilities.operation_schema { + return Err(GuiError::Connection(format!( + "the daemon at {socket_path} predates the operation-schema publication: it cannot \ + publish the operation catalog or the request schema this GUI renders. Restart it \ + with `{}`.", + daemon_start_command(socket_path) + ))); + } + + let session_id = client + .create_session( + RuntimeSurface::DesktopGuiManual, + Some(gui_session_scope()), + Vec::new(), + ) + .await + .map_err(|error| { + GuiError::Connection(format!( + "the daemon at {socket_path} refused to open a desktop-GUI session: {error}" + )) + })?; + + let catalog = client.describe_operations().await.map_err(|error| { + GuiError::Connection(format!( + "the daemon at {socket_path} could not publish the operation catalog: {error}" + )) + })?; + + Ok(Self { + client, + session_id, + catalog: std::sync::Arc::new(catalog), + capabilities, + protocol_version: health.protocol_version, + }) + } + + /// Whether the connected daemon advertises no task kinds at all. + /// + /// The daemon hosts a no-op executor in that case: it answers every + /// command correctly and rejects every task. The GUI reports the + /// condition rather than presenting a submit button that cannot work. + pub fn daemon_advertises_no_task_kinds(&self) -> bool { + self.capabilities.runtime.task_kinds.is_empty() + } + + /// The diagnostic shown when the connected daemon cannot run anything. + pub fn no_op_executor_diagnostic(&self, socket_path: &str) -> String { + format!( + "the daemon at {socket_path} advertises no task kinds: it hosts a no-op executor that \ + rejects every submitted task. Restart it with `{}`.", + daemon_start_command(socket_path) + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gui_identity_is_the_gui_client_kind() { + let identity = gui_identity(); + assert_eq!(identity.kind, ClientKind::Gui); + assert_eq!(identity.label, "eggsec-gui"); + assert_eq!(identity.request_id(0), "gui-0"); + } + + #[test] + fn gui_session_scope_does_not_widen_the_scope() { + let scope = gui_session_scope(); + assert!( + !scope.is_explicit, + "the GUI must not claim an explicit scope" + ); + assert_eq!(scope.source, "gui-default"); + assert!(scope.path.is_none(), "the GUI must not invent a scope path"); + } + + #[test] + fn unreachable_diagnostic_names_the_socket_and_the_start_command() { + let error = DaemonClientError::Io(std::io::Error::new( + std::io::ErrorKind::NotFound, + "no such file or directory", + )); + let diagnostic = unreachable_diagnostic("/tmp/eggsec.sock", &error); + assert!(diagnostic.contains("/tmp/eggsec.sock")); + assert!(diagnostic.contains("eggsec-daemon --full-executor --socket-path /tmp/eggsec.sock")); + assert!(diagnostic.contains("no-op executor")); + } + + #[test] + fn start_command_requires_the_full_executor() { + let command = daemon_start_command("/tmp/eggsec.sock"); + assert!(command.contains("--full-executor")); + assert!(command.contains("--socket-path /tmp/eggsec.sock")); + } +} diff --git a/crates/eggsec-gui/src/form.rs b/crates/eggsec-gui/src/form.rs new file mode 100644 index 000000000..ee3ca0f64 --- /dev/null +++ b/crates/eggsec-gui/src/form.rs @@ -0,0 +1,824 @@ +//! The generic form engine. +//! +//! One mapping from a published JSON Schema property to one control +//! descriptor, and one assembly path from control values to a typed +//! [`RunRequest`]. There is no per-operation code anywhere in this module: +//! a task kind the engine has not published yet gets a form with no GUI +//! change at all. +//! +//! # The schema is descriptive, never authoritative +//! +//! The schema drives *form shape* only. It is never consulted to decide +//! whether an operation may run, what its risk is, or which features it +//! needs — those come from the daemon's operation catalog and its live +//! capabilities. +//! +//! # Validation is layered +//! +//! 1. **Advisory**, from the schema: the control's declared type and bounds. +//! 2. **Exact**, from the DTOs: the assembled request is deserialized into +//! the same [`RunRequest`] the engine will deserialize, so a value of the +//! wrong type is rejected with the engine's own rules. +//! 3. **Authoritative**, in the engine: the engine's own validation still +//! decides whether the task may run. +//! +//! Layers one and two exist to save the operator a round trip. They never +//! stand in for layer three, and neither of them encodes a per-operation +//! rule. + +use eggsec_daemon_protocol::operations::TaskKindDescription; +use eggsec_runtime::request::{RunRequest, RuntimeSurface}; +use serde_json::{Map, Value}; + +/// The kind of control a form field renders as. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ControlKind { + /// A single-line text input. + Text, + /// A numeric input. + Number, + /// A tri-state boolean: unset, true, or false. + Checkbox, + /// A repeatable list of strings. + List, + /// A free-form JSON value. + Json, +} + +/// One form field, derived from one JSON Schema property. +/// +/// The descriptor carries everything the webview needs to render the field +/// and nothing it needs to *decide*: the schema's `type` and bounds are +/// already resolved into a control kind and numeric limits. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Control { + /// The property name — the field's key in the request's `params`. + pub name: String, + /// The control the webview renders. + pub kind: ControlKind, + /// Whether the schema lists this field as required. + pub required: bool, + /// The schema's `description`, when it has one. + pub description: Option, + /// The schema's `minimum`, when it has one. + pub minimum: Option, + /// The upper bound derived from the schema's `format`, when it has one. + pub maximum: Option, + /// The schema's `format`, when it has one. + pub format: Option, + /// A placeholder hint. The published schema carries no examples, so this + /// is always `None` today; the field exists so a future schema that does + /// publish one needs no contract change. + pub placeholder: Option, +} + +/// A form assembly or validation failure. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct FormError { + /// The field the error is about, when the error is field-level. + pub field: Option, + /// The message shown to the operator. + pub message: String, +} + +impl FormError { + /// An error about one field. + pub fn field(name: impl Into, message: impl Into) -> Self { + Self { + field: Some(name.into()), + message: message.into(), + } + } + + /// An error about the form as a whole. + pub fn global(message: impl Into) -> Self { + Self { + field: None, + message: message.into(), + } + } +} + +impl std::fmt::Display for FormError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.field { + Some(field) => write!(f, "{field}: {}", self.message), + None => write!(f, "{}", self.message), + } + } +} + +impl std::error::Error for FormError {} + +/// The controls for one task kind. +/// +/// One control per schema property. The order is deterministic — required +/// fields first, then alphabetical — so the form's layout does not shift +/// between runs. +pub fn controls_for(task_kind: &TaskKindDescription) -> Vec { + let schema = &task_kind.request_schema; + let Some(properties) = schema.get("properties").and_then(Value::as_object) else { + return Vec::new(); + }; + let required = required_names(schema); + + let mut controls: Vec = properties + .iter() + .map(|(name, property)| control_for(name, property, required.contains(&name.as_str()))) + .collect(); + controls.sort_by(|left, right| { + right + .required + .cmp(&left.required) + .then_with(|| left.name.cmp(&right.name)) + }); + controls +} + +/// Map one JSON Schema property to one control. +/// +/// An unrecognized shape degrades to a control that can still carry the +/// value: an object or a non-string array becomes a JSON text area (a +/// free-text field would be lossy), and an unknown scalar becomes a text +/// input. It never panics and never drops the field. +pub fn control_for(name: &str, property: &Value, required: bool) -> Control { + let kind = control_kind(property); + let format = property + .get("format") + .and_then(Value::as_str) + .map(str::to_owned); + let maximum = match kind { + ControlKind::Number => maximum_for(format.as_deref()), + _ => None, + }; + + Control { + name: name.to_owned(), + kind, + required, + description: property + .get("description") + .and_then(Value::as_str) + .map(str::to_owned), + minimum: property.get("minimum").and_then(Value::as_u64), + maximum, + format, + placeholder: None, + } +} + +/// The control kind for one property schema. +fn control_kind(property: &Value) -> ControlKind { + // The unconstrained `true` schema — one field today — accepts any JSON + // value, so it renders as a JSON text area. + if !property.is_object() { + return ControlKind::Json; + } + + let declared = property.get("type"); + let types: Vec<&str> = match declared { + Some(Value::String(single)) => vec![single.as_str()], + Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + + if types.contains(&"array") { + // A list of strings is a repeatable text control. Any other array — + // and any object — is rendered as a JSON text area, because a + // string-list control would silently lose the structure. + return if array_items_are_strings(property) { + ControlKind::List + } else { + ControlKind::Json + }; + } + + match types.iter().find(|kind| **kind != "null").copied() { + Some("string") => ControlKind::Text, + Some("integer") => ControlKind::Number, + Some("boolean") => ControlKind::Checkbox, + // An object is rendered as a JSON text area: a free-text field + // would lose the structure. + Some("object") => ControlKind::Json, + // Documented fallback for a shape the engine has not published + // before: a free-text input. It never panics and never drops the + // field. + _ => ControlKind::Text, + } +} + +/// Whether an array property's items are plain strings. +fn array_items_are_strings(property: &Value) -> bool { + property + .get("items") + .and_then(Value::as_object) + .and_then(|items| items.get("type")) + .and_then(Value::as_str) + .is_some_and(|kind| kind == "string") +} + +/// The numeric upper bound implied by a schema `format`. +/// +/// The published schema states a `minimum` but never a `maximum`; the +/// upper bound comes from the integer width the format names. `uint` is +/// `usize`, whose width is platform-dependent — the 64-bit width is used +/// here, and the typed deserialization remains the exact authority. +fn maximum_for(format: Option<&str>) -> Option { + match format { + Some("uint16") => Some(u16::MAX as u64), + Some("uint32") => Some(u32::MAX as u64), + Some("uint64") | Some("uint") => Some(u64::MAX), + _ => None, + } +} + +/// The schema's `required` list. +fn required_names(schema: &Value) -> Vec<&str> { + schema + .get("required") + .and_then(Value::as_array) + .map(|names| names.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default() +} + +/// Whether a property's type accepts `null`. +fn accepts_null(property: &Value) -> bool { + match property.get("type") { + Some(Value::String(single)) => single == "null", + Some(Value::Array(items)) => items.iter().any(|item| item.as_str() == Some("null")), + _ => false, + } +} + +/// Assemble a typed [`RunRequest`] from the values a form collected. +/// +/// `values` maps a property name to the value the operator supplied. A +/// `null` value means *not provided* — never an empty string, a zero, or a +/// `false`. The distinction matters: several published parameters carry +/// meaningful defaults, and one of them is a fail-safe flag that defaults +/// to `true`. A form that sent `false` for an untouched field would turn a +/// simulation into a live action. +/// +/// A field that is not required and whose type does not accept `null` is +/// **omitted** from the request rather than sent as `null` or as a zero +/// value, so the request DTO applies its own default. +pub fn assemble_request( + task_kind: &TaskKindDescription, + values: &Value, +) -> Result { + let schema = &task_kind.request_schema; + let properties = schema + .get("properties") + .and_then(Value::as_object) + .ok_or_else(|| FormError::global("the published request schema has no properties"))?; + let required = required_names(schema); + + let mut params = Map::new(); + for (name, property) in properties { + let supplied = values.get(name).cloned().unwrap_or(Value::Null); + + if supplied.is_null() { + if required.contains(&name.as_str()) { + return Err(FormError::field( + name.clone(), + format!("`{name}` is required"), + )); + } + if accepts_null(property) { + params.insert(name.clone(), Value::Null); + } + // Otherwise the field is omitted, so the request DTO applies its + // own default rather than the GUI overriding it. + continue; + } + + check_value(name, property, &supplied)?; + params.insert(name.clone(), supplied); + } + + let surface = serde_json::to_value(RuntimeSurface::DesktopGuiManual).map_err(|error| { + FormError::global(format!( + "cannot serialize the desktop GUI's runtime surface: {error}" + )) + })?; + + // The request's wire shape is `{"task_kind": {"kind": ..., "params": ...}, + // "requested_by": ..., "surface": ..., "labels": ...}`: `TaskKind` is + // adjacently tagged, and `RunRequest` carries it as a named field. The + // GUI never constructs a `TaskKind` variant by hand — it builds the + // tagged JSON and lets the DTO do the typing. + let request = serde_json::json!({ + "task_kind": { + "kind": task_kind.variant, + "params": Value::Object(params), + }, + "requested_by": Value::Null, + "surface": surface, + "labels": Value::Array(Vec::new()), + }); + + serde_json::from_value(request).map_err(|error| { + let message = error.to_string(); + FormError { + field: missing_field(&message), + message, + } + }) +} + +/// Check one supplied value against its property schema. +/// +/// This is the advisory layer: it reads the schema's own `type` and +/// `format`, so it encodes no per-operation rule. +fn check_value(name: &str, property: &Value, value: &Value) -> Result<(), FormError> { + // The unconstrained `true` schema accepts any JSON value. + if !property.is_object() { + return Ok(()); + } + + let declared = property.get("type"); + let types: Vec<&str> = match declared { + Some(Value::String(single)) => vec![single.as_str()], + Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + if types.is_empty() { + // An unknown shape: the typed deserialization is the authority. + return Ok(()); + } + + if !types.iter().any(|kind| value_matches(kind, value)) { + return Err(FormError::field( + name.to_owned(), + format!( + "`{name}` expects {}, but {} was supplied", + expected_label(&types), + value_label(value) + ), + )); + } + + if let Some(maximum) = maximum_for(property.get("format").and_then(Value::as_str)) { + if let Some(number) = value.as_u64() { + if number > maximum { + return Err(FormError::field( + name.to_owned(), + format!("`{name}` accepts values up to {maximum}, but {number} was supplied"), + )); + } + } + } + + Ok(()) +} + +/// Whether a value matches one declared JSON Schema type. +fn value_matches(kind: &str, value: &Value) -> bool { + match kind { + "string" => value.is_string(), + "integer" => value.is_i64() || value.is_u64(), + "number" => value.is_number(), + "boolean" => value.is_boolean(), + "array" => value.is_array(), + "object" => value.is_object(), + "null" => value.is_null(), + _ => true, + } +} + +/// A human label for a set of declared types. +fn expected_label(types: &[&str]) -> String { + let mut labels: Vec = types + .iter() + .filter(|kind| **kind != "null") + .map(|kind| type_label(kind)) + .collect(); + if types.contains(&"null") { + labels.push("null".to_owned()); + } + if labels.is_empty() { + "any value".to_owned() + } else { + labels.join(" or ") + } +} + +/// A human label for one JSON Schema type. +fn type_label(kind: &str) -> String { + match kind { + "string" => "a string".to_owned(), + "integer" => "an integer".to_owned(), + "number" => "a number".to_owned(), + "boolean" => "a boolean".to_owned(), + "array" => "a list".to_owned(), + "object" => "an object".to_owned(), + "null" => "null".to_owned(), + other => format!("a {other}"), + } +} + +/// A human label for one supplied value. +fn value_label(value: &Value) -> String { + match value { + Value::Null => "null".to_owned(), + Value::Bool(_) => "a boolean".to_owned(), + Value::Number(_) => "a number".to_owned(), + Value::String(_) => "a string".to_owned(), + Value::Array(_) => "a list".to_owned(), + Value::Object(_) => "an object".to_owned(), + } +} + +/// The field serde names in a missing-field error. +fn missing_field(message: &str) -> Option { + const MARKER: &str = "missing field `"; + let start = message.find(MARKER)?; + let rest = &message[start + MARKER.len()..]; + let end = rest.find('`')?; + Some(rest[..end].to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every published task kind must get a control per property, and the + /// required set must match the schema's own `required` list. + #[test] + fn controls_match_every_published_schema() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let mut total = 0usize; + for task_kind in &response.task_kinds { + let schema = &task_kind.request_schema; + let properties = schema + .get("properties") + .and_then(Value::as_object) + .expect("every published schema has properties"); + let required = required_names(schema); + + let controls = controls_for(task_kind); + assert_eq!( + controls.len(), + properties.len(), + "{} must produce one control per property", + task_kind.variant + ); + for control in &controls { + assert!( + properties.contains_key(&control.name), + "{} produced a control for an unknown property", + task_kind.variant + ); + assert_eq!( + control.required, + required.contains(&control.name.as_str()), + "{} disagrees with the schema about `{}` being required", + task_kind.variant, + control.name + ); + } + total += controls.len(); + } + assert_eq!( + total, 149, + "the published schemas carry 149 fields in total" + ); + } + + /// The controls are ordered deterministically: required first, then + /// alphabetically. + #[test] + fn controls_are_ordered_required_first_then_alphabetically() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + for task_kind in &response.task_kinds { + let controls = controls_for(task_kind); + let mut expected = controls.clone(); + expected.sort_by(|left, right| { + right + .required + .cmp(&left.required) + .then_with(|| left.name.cmp(&right.name)) + }); + assert_eq!(controls, expected); // Required fields come before optional ones. + let first_optional = controls.iter().position(|control| !control.required); + if let Some(index) = first_optional { + assert!( + controls[index..].iter().all(|control| !control.required), + "{} mixes required and optional controls", + task_kind.variant + ); + } + } + } + + /// One test per measured schema shape. + #[test] + fn control_for_covers_every_measured_shape() { + let required_text = control_for("target", &serde_json::json!({"type": "string"}), true); + assert_eq!(required_text.kind, ControlKind::Text); + assert!(required_text.required); + + let optional_text = control_for( + "ports", + &serde_json::json!({"type": ["string", "null"]}), + false, + ); + assert_eq!(optional_text.kind, ControlKind::Text); + assert!(!optional_text.required); + + let required_number = control_for("count", &serde_json::json!({"type": "integer"}), true); + assert_eq!(required_number.kind, ControlKind::Number); + + let optional_number = control_for( + "count", + &serde_json::json!({"type": ["integer", "null"], "format": "uint16", "minimum": 0}), + false, + ); + assert_eq!(optional_number.kind, ControlKind::Number); + assert_eq!(optional_number.minimum, Some(0)); + assert_eq!(optional_number.maximum, Some(u16::MAX as u64)); + assert_eq!(optional_number.format.as_deref(), Some("uint16")); + + let required_boolean = control_for("udp", &serde_json::json!({"type": "boolean"}), true); + assert_eq!(required_boolean.kind, ControlKind::Checkbox); + + let optional_boolean = control_for( + "udp", + &serde_json::json!({"type": ["boolean", "null"], "default": null}), + false, + ); + assert_eq!(optional_boolean.kind, ControlKind::Checkbox); + + let list = control_for( + "steps", + &serde_json::json!({"type": ["array", "null"], "items": {"type": "string"}}), + false, + ); + assert_eq!(list.kind, ControlKind::List); + + let unconstrained = control_for("config", &Value::Bool(true), false); + assert_eq!(unconstrained.kind, ControlKind::Json); + } + + /// The documented fallback: an unrecognized shape degrades to a control + /// that can still carry the value. It never panics and never drops the + /// field. + #[test] + fn control_for_falls_back_without_panicking() { + let unknown_scalar = control_for("mystery", &serde_json::json!({"type": "wat"}), false); + assert_eq!(unknown_scalar.kind, ControlKind::Text); + + let object_shape = control_for( + "nested", + &serde_json::json!({"type": "object", "properties": {"a": {"type": "string"}}}), + false, + ); + assert_eq!(object_shape.kind, ControlKind::Json); + + let object_array = control_for( + "items", + &serde_json::json!({"type": "array", "items": {"type": "object"}}), + false, + ); + assert_eq!(object_array.kind, ControlKind::Json); + } + + /// A valid form deserializes into a typed request with the right + /// variant — for every published task kind. + #[test] + fn assemble_request_round_trips_every_published_task_kind() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + for task_kind in &response.task_kinds { + let schema = &task_kind.request_schema; + let properties = schema + .get("properties") + .and_then(Value::as_object) + .expect("properties"); + + // Fill every field with a value of the shape the schema declares. + let mut values = Map::new(); + for (name, property) in properties { + let kind = control_kind(property); + let value = match kind { + ControlKind::Text => Value::String("value".to_owned()), + ControlKind::Number => Value::from(1u64), + ControlKind::Checkbox => Value::Bool(true), + ControlKind::List => Value::Array(vec![Value::String("a".to_owned())]), + ControlKind::Json => Value::Object(Map::new()), + }; + values.insert(name.clone(), value); + } + + let request = assemble_request(task_kind, &Value::Object(values)) + .unwrap_or_else(|error| panic!("{}: {error}", task_kind.variant)); + + assert_eq!( + request.surface, + RuntimeSurface::DesktopGuiManual, + "{} must be stamped with the GUI's surface", + task_kind.variant + ); + assert!(request.requested_by.is_none()); + assert!(request.labels.is_empty()); + + let serialized = serde_json::to_value(&request).expect("serializable"); + let kind = serialized + .get("task_kind") + .and_then(|task_kind| task_kind.get("kind")) + .and_then(Value::as_str) + .expect("the task kind's discriminator"); + assert_eq!(kind, task_kind.variant); + } + } + + /// A required field the operator left blank is a field-level error. + #[test] + fn a_missing_required_field_names_the_field() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == "PortScan") + .expect("PortScan is published"); + let error = assemble_request(task_kind, &Value::Object(Map::new())) + .expect_err("a blank required field is an error"); + assert_eq!(error.field.as_deref(), Some("target")); + assert!(error.message.contains("required")); + } + + /// A value of the wrong type is rejected with a field-level error. + #[test] + fn a_wrongly_typed_value_names_the_field_and_the_expected_type() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == "PortScan") + .expect("PortScan is published"); + let values = serde_json::json!({"target": 42}); + let error = assemble_request(task_kind, &values).expect_err("a number is not a string"); + assert_eq!(error.field.as_deref(), Some("target")); + assert!(error.message.contains("a string"), "{}", error.message); + } + + /// A value beyond the format's width is rejected before it reaches the + /// engine. + #[test] + fn an_out_of_range_number_is_rejected() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == "PacketSend") + .expect("PacketSend is published"); + let schema = &task_kind.request_schema; + let port = schema + .get("properties") + .and_then(|p| p.as_object()) + .and_then(|p| p.get("port")) + .expect("PacketSend has a port"); + let format = port + .get("format") + .and_then(Value::as_str) + .expect("a format"); + assert_eq!(format, "uint16"); + + // Every other field gets a value of its declared shape, so the only + // thing wrong with this form is the out-of-range port. + let mut values = Map::new(); + for (name, property) in schema + .get("properties") + .and_then(Value::as_object) + .expect("properties") + { + let value = if name == "port" { + Value::from(u64::from(u16::MAX) + 1) + } else { + match control_kind(property) { + ControlKind::Text => Value::String("x".to_owned()), + ControlKind::Number => Value::from(1u64), + ControlKind::Checkbox => Value::Bool(true), + ControlKind::List => Value::Array(vec![Value::String("a".to_owned())]), + ControlKind::Json => Value::Object(Map::new()), + } + }; + values.insert(name.clone(), value); + } + let error = assemble_request(task_kind, &Value::Object(values)) + .expect_err("a value beyond uint16 is rejected"); + assert_eq!(error.field.as_deref(), Some("port")); + } + + /// A field that is not required and does not accept `null` is omitted + /// from the request, so the request DTO applies its own default. The + /// fail-safe `dry_run` flag is the case that matters: an untouched form + /// must leave it at `true`, never turn it into `false`. + #[test] + fn an_untouched_optional_field_keeps_the_dto_s_own_default() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == "WirelessActive") + .expect("WirelessActive is published"); + + let mut values = Map::new(); + for (name, property) in task_kind + .request_schema + .get("properties") + .and_then(|p| p.as_object()) + .expect("properties") + { + let kind = control_kind(property); + let value = match kind { + ControlKind::Text => Value::String("x".to_owned()), + ControlKind::Number => Value::from(1u64), + ControlKind::Checkbox => Value::Bool(false), + ControlKind::List => Value::Array(vec![]), + ControlKind::Json => Value::Null, + }; + values.insert(name.clone(), value); + } + // The operator never touched the fields that carry a non-null + // default. + for untouched in ["dry_run", "frame_count", "rate_limit"] { + values.insert(untouched.to_owned(), Value::Null); + } + + let request = + assemble_request(task_kind, &Value::Object(values)).expect("the request assembles"); + let serialized = serde_json::to_value(&request).expect("serializable"); + let params = serialized + .get("task_kind") + .and_then(|task_kind| task_kind.get("params")) + .expect("params"); + assert_eq!( + params.get("dry_run"), + Some(&serde_json::Value::Bool(true)), + "an untouched optional field must keep the DTO's own default: {params}" + ); + assert_eq!( + params.get("frame_count"), + Some(&serde_json::Value::from(100u64)), + "an untouched optional field must keep the DTO's own default: {params}" + ); + } + + /// A field that accepts `null` is sent as `null` when the operator did + /// not provide it. + #[test] + fn an_untouched_nullable_field_is_sent_as_null() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response + .task_kinds + .iter() + .find(|task_kind| task_kind.variant == "PortScan") + .expect("PortScan is published"); + let mut values = Map::new(); + values.insert("target".to_owned(), Value::String("10.0.0.1".to_owned())); + let request = assemble_request(task_kind, &Value::Object(values)).expect("assembles"); + let serialized = serde_json::to_value(&request).expect("serializable"); + let params = serialized + .get("task_kind") + .and_then(|task_kind| task_kind.get("params")) + .expect("params"); + assert_eq!(params.get("ports"), Some(&Value::Null)); + } + + /// The surface is produced by serializing the runtime's own enum, so it + /// cannot drift from the runtime's label. + #[test] + fn the_surface_is_the_runtime_s_own_value() { + let response = eggsec_daemon_protocol::operations::describe_operations(); + let task_kind = response.task_kinds.first().expect("a task kind"); + let mut values = Map::new(); + for (name, property) in task_kind + .request_schema + .get("properties") + .and_then(|p| p.as_object()) + .expect("properties") + { + let kind = control_kind(property); + let value = match kind { + ControlKind::Text => Value::String("x".to_owned()), + ControlKind::Number => Value::from(1u64), + ControlKind::Checkbox => Value::Bool(true), + ControlKind::List => Value::Array(vec![Value::String("a".to_owned())]), + ControlKind::Json => Value::Object(Map::new()), + }; + values.insert(name.clone(), value); + } + let request = assemble_request(task_kind, &Value::Object(values)).expect("assembles"); + let serialized = serde_json::to_value(&request).expect("serializable"); + assert_eq!( + serialized.get("surface"), + Some(&serde_json::to_value(RuntimeSurface::DesktopGuiManual).expect("serializable")) + ); + assert_eq!( + RuntimeSurface::DesktopGuiManual.label(), + "desktop-gui-manual", + "the audit-trail label must not drift" + ); + } +} diff --git a/crates/eggsec-gui/src/lib.rs b/crates/eggsec-gui/src/lib.rs new file mode 100644 index 000000000..b762167b5 --- /dev/null +++ b/crates/eggsec-gui/src/lib.rs @@ -0,0 +1,70 @@ +//! Desktop GUI frontend for Eggsec. +//! +//! The GUI is a **daemon-only** frontend (`ADR-0007`): it reaches the engine +//! exclusively through the daemon's Unix socket, using the shared +//! `eggsec-frontend-client` contract. It therefore depends on no engine +//! crate, no daemon crate, and no terminal-frontend crate. +//! +//! The shell technology is Tauri v2, pinned to the 2.11.x line (`ADR-0009`). +//! The Tauri dependency lives entirely inside this crate. + +pub mod config; +pub mod connection; +pub mod form; +pub mod tasks; + +#[cfg(feature = "shell")] +pub mod commands; +#[cfg(feature = "shell")] +pub mod shell; + +use std::fmt; + +/// Everything that can go wrong inside the GUI, before an error message +/// reaches the webview. +#[derive(Debug)] +pub enum GuiError { + /// The GUI was built without the `shell` feature. + ShellNotBuilt, + /// The daemon could not be reached or refused the connection. + Connection(String), + /// A command-line argument was not understood. + Usage(String), + /// The shell framework failed to start. + Shell(String), +} + +impl fmt::Display for GuiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + GuiError::ShellNotBuilt => write!( + f, + "the Eggsec GUI shell was not built into this binary: rebuild with the \ + `shell` feature (the default) to get the desktop window" + ), + GuiError::Connection(message) => write!(f, "{message}"), + GuiError::Usage(message) => write!(f, "{message}"), + GuiError::Shell(message) => write!(f, "{message}"), + } + } +} + +impl std::error::Error for GuiError {} + +/// Run the GUI. +/// +/// With the `shell` feature this opens the desktop window. Without it, it +/// reports that the shell was not built and exits non-zero — that is what +/// keeps the `--no-default-features` workspace build green without pretending +/// the binary works. +#[cfg(feature = "shell")] +pub fn run() -> Result<(), GuiError> { + let options = config::GuiOptions::from_args(std::env::args().skip(1))?; + shell::run(options) +} + +/// Run the GUI in a build that carries no shell. +#[cfg(not(feature = "shell"))] +pub fn run() -> Result<(), GuiError> { + Err(GuiError::ShellNotBuilt) +} diff --git a/crates/eggsec-gui/src/main.rs b/crates/eggsec-gui/src/main.rs new file mode 100644 index 000000000..09ca74fc2 --- /dev/null +++ b/crates/eggsec-gui/src/main.rs @@ -0,0 +1,13 @@ +//! The `eggsec-gui` binary. +//! +//! The binary is a thin shell around [`eggsec_gui::run`]. All the behaviour +//! lives in the library so it can be unit-tested without a window. + +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +fn main() { + if let Err(error) = eggsec_gui::run() { + eprintln!("eggsec-gui: {error}"); + std::process::exit(1); + } +} diff --git a/crates/eggsec-gui/src/shell.rs b/crates/eggsec-gui/src/shell.rs new file mode 100644 index 000000000..5a88f0c5c --- /dev/null +++ b/crates/eggsec-gui/src/shell.rs @@ -0,0 +1,34 @@ +//! The Tauri shell: the window, the IPC registration, and startup. +//! +//! The shell framework appears only in this module and in `commands.rs`. +//! Nothing outside `crates/eggsec-gui` may depend on it. + +use crate::commands; +use crate::commands::GuiState; +use crate::config::GuiOptions; +use crate::GuiError; + +/// Start the desktop window. +/// +/// The GUI does not spawn, supervise, or stop a daemon: it connects to one +/// that is already running. The socket path the operator chose is carried in +/// the state's default connection attempt, so the window opens with the +/// catalog already loaded when the daemon is reachable. +pub fn run(options: GuiOptions) -> Result<(), GuiError> { + tracing::info!("starting the Eggsec GUI against {}", options.socket_path); + + tauri::Builder::default() + .manage(GuiState::default()) + .invoke_handler(tauri::generate_handler![ + commands::connect_daemon, + commands::list_operations, + commands::list_task_kinds, + commands::form_for, + commands::submit_task, + commands::cancel_task, + commands::cancel_active, + commands::task_snapshot + ]) + .run(tauri::generate_context!()) + .map_err(|error| GuiError::Shell(format!("the Eggsec GUI shell failed to start: {error}"))) +} diff --git a/crates/eggsec-gui/src/tasks.rs b/crates/eggsec-gui/src/tasks.rs new file mode 100644 index 000000000..833085987 --- /dev/null +++ b/crates/eggsec-gui/src/tasks.rs @@ -0,0 +1,865 @@ +//! The GUI's bounded view of the daemon's event stream. +//! +//! The event stream is the source of truth. This module holds a *bounded +//! view* of it: the current status of each task, its progress, and a capped +//! ring of log lines. +//! +//! # Bounded retention is a hard requirement +//! +//! [`RuntimeEvent::TaskLog`] is the high-cardinality event type. A task that +//! emits thousands of lines must not be able to grow the GUI's memory without +//! bound, so each task keeps at most [`MAX_LOG_LINES_PER_TASK`] lines and +//! counts the rest. The count is reported, never silently swallowed: an +//! operator who sees "42 earlier lines dropped" knows the view is partial. + +use std::collections::HashMap; + +use eggsec_runtime::event::{LogLevel, PolicyPrompt, RuntimeEvent, TaskOutcome, TaskProgress}; +use eggsec_runtime::request::TaskKind; +use eggsec_runtime::TaskId; +use eggsec_ui_model::renderer_registry::renderer_for_kind; + +/// The maximum number of log lines retained per task. +/// +/// 200 lines is enough to diagnose a failed task and small enough that even +/// a hundred concurrent tasks stay well inside a desktop application's +/// comfort zone. The cap is a named constant, not a tuning knob: exceeding +/// it drops the *oldest* lines and increments a visible counter. +pub const MAX_LOG_LINES_PER_TASK: usize = 200; + +/// The maximum number of log lines forwarded to the webview in one batch. +/// +/// A task that logs faster than the UI renders must not build an unbounded +/// queue in the GUI. The forwarder keeps the newest lines and reports how +/// many it dropped. +pub const MAX_LOG_LINES_PER_FLUSH: usize = 50; + +/// The status the GUI shows for a task. +/// +/// This is the GUI's own view of the runtime's status, not the runtime's +/// enum: the GUI adds `AwaitingPolicy`, which the runtime reports as a +/// separate event rather than a status. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GuiTaskStatus { + /// Submitted, not started. + Queued, + /// Running. + Running, + /// Finished successfully. + Completed, + /// Finished with an error. + Failed, + /// Cancelled. + Cancelled, + /// Blocked on a policy decision the connected daemon cannot accept. + AwaitingPolicy, + /// The GUI has seen the task but cannot classify its state. + Unknown, +} + +/// One log line. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct LogLine { + /// The runtime's log level. + pub level: LogLevel, + /// The log message. + pub message: String, +} + +/// A bounded ring of log lines for one task. +#[derive(Debug, Clone)] +pub struct LogRing { + lines: std::collections::VecDeque, + capacity: usize, + dropped: u64, +} + +impl LogRing { + /// A ring with the default capacity. + pub fn new() -> Self { + Self::with_capacity(MAX_LOG_LINES_PER_TASK) + } + + /// A ring with an explicit capacity. + pub fn with_capacity(capacity: usize) -> Self { + Self { + lines: std::collections::VecDeque::with_capacity(capacity.min(1024)), + capacity, + dropped: 0, + } + } + + /// Append a line, dropping the oldest one when the ring is full. + /// + /// Returns `true` when a line was dropped, so the caller can count the + /// loss rather than swallow it. + pub fn push(&mut self, line: LogLine) -> bool { + if self.capacity == 0 { + self.dropped = self.dropped.saturating_add(1); + return true; + } + let mut dropped = false; + while self.lines.len() >= self.capacity { + if self.lines.pop_front().is_some() { + self.dropped = self.dropped.saturating_add(1); + dropped = true; + } + } + self.lines.push_back(line); + dropped + } + + /// The retained lines, oldest first. + pub fn lines(&self) -> impl Iterator { + self.lines.iter() + } + + /// How many lines were dropped because the ring was full. + pub fn dropped(&self) -> u64 { + self.dropped + } + + /// How many lines are retained. + pub fn len(&self) -> usize { + self.lines.len() + } + + /// Whether the ring holds no lines. + pub fn is_empty(&self) -> bool { + self.lines.is_empty() + } +} + +impl Default for LogRing { + fn default() -> Self { + Self::new() + } +} + +/// The GUI's state for one task. +#[derive(Debug, Clone)] +pub struct TaskState { + /// The task's identifier. + pub task_id: TaskId, + /// The task kind's wire discriminator, as the runtime tagged it. + pub variant: String, + /// The task's current status. + pub status: GuiTaskStatus, + /// The latest progress report. + pub progress: Option, + /// The capped log ring. + pub logs: LogRing, + /// The outcome, once the task completed. + pub outcome: Option, + /// The failure message, once the task failed. + pub error: Option, + /// The pending policy prompt, when the task is blocked on a decision. + pub policy_prompt: Option, +} + +impl TaskState { + /// A fresh task entry. + pub fn new(task_id: TaskId, variant: String) -> Self { + Self { + task_id, + variant, + status: GuiTaskStatus::Queued, + progress: None, + logs: LogRing::new(), + outcome: None, + error: None, + policy_prompt: None, + } + } +} + +/// What applying an event to the registry did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EventEffect { + /// The event changed a task's state; the webview should refresh it. + TaskUpdated(TaskId), + /// The event added log lines to a task. + Logs { + /// The task the lines belong to. + task_id: TaskId, + /// The lines that were added. + lines: Vec, + }, + /// The event was not about a task the GUI tracks. + Ignored, +} + +/// Every task the GUI knows about, with bounded per-task retention. +#[derive(Debug, Default)] +pub struct TaskRegistry { + tasks: HashMap, + /// Insertion order, so the dashboard does not reshuffle between renders. + order: Vec, + /// Log lines dropped because a task's ring was full. + dropped_log_lines: u64, + /// Events about tasks the GUI does not know about. + unknown_task_events: u64, +} + +impl TaskRegistry { + /// An empty registry. + pub fn new() -> Self { + Self::default() + } + + /// Apply one event from the daemon's stream. + pub fn apply(&mut self, event: &RuntimeEvent) -> EventEffect { + match event { + RuntimeEvent::TaskQueued { + task_id, request, .. + } => { + let variant = task_kind_variant(&request.task_kind); + if !self.tasks.contains_key(task_id) { + self.order.push(*task_id); + self.tasks + .insert(*task_id, TaskState::new(*task_id, variant.clone())); + } + let entry = self + .tasks + .get_mut(task_id) + .expect("the task was just inserted"); + entry.variant = variant; + entry.status = GuiTaskStatus::Queued; + EventEffect::TaskUpdated(*task_id) + } + RuntimeEvent::TaskStarted { task_id, .. } => match self.tasks.get_mut(task_id) { + Some(task) => { + task.status = GuiTaskStatus::Running; + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::TaskProgress { + task_id, progress, .. + } => match self.tasks.get_mut(task_id) { + Some(task) => { + task.progress = Some(progress.clone()); + task.status = GuiTaskStatus::Running; + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::TaskLog { + task_id, + level, + message, + .. + } => match task_id { + Some(task_id) => match self.tasks.get_mut(task_id) { + Some(task) => { + let line = LogLine { + level: level.clone(), + message: message.clone(), + }; + if task.logs.push(line.clone()) { + self.dropped_log_lines = self.dropped_log_lines.saturating_add(1); + } + EventEffect::Logs { + task_id: *task_id, + lines: vec![line], + } + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + // A session-level log line belongs to no task. + None => EventEffect::Ignored, + }, + RuntimeEvent::PolicyDecisionRequired { + task_id, prompt, .. + } => match task_id { + Some(task_id) => match self.tasks.get_mut(task_id) { + Some(task) => { + task.status = GuiTaskStatus::AwaitingPolicy; + task.policy_prompt = Some(prompt.clone()); + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::TaskCompleted { + task_id, outcome, .. + } => match self.tasks.get_mut(task_id) { + Some(task) => { + task.status = GuiTaskStatus::Completed; + task.outcome = Some(outcome.clone()); + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::TaskFailed { task_id, error, .. } => match self.tasks.get_mut(task_id) { + Some(task) => { + task.status = GuiTaskStatus::Failed; + task.error = Some(error.message.clone()); + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::TaskCancelled { + task_id, reason, .. + } => match self.tasks.get_mut(task_id) { + Some(task) => { + task.status = GuiTaskStatus::Cancelled; + task.error = reason.clone(); + EventEffect::TaskUpdated(*task_id) + } + None => { + self.unknown_task_events = self.unknown_task_events.saturating_add(1); + EventEffect::Ignored + } + }, + RuntimeEvent::SessionCreated { .. } + | RuntimeEvent::Snapshot { .. } + | RuntimeEvent::SessionClosed { .. } + | RuntimeEvent::Audit { .. } => EventEffect::Ignored, + } + } + + /// Register a task the GUI submitted, before the daemon's event for it + /// arrives. + pub fn ensure_task(&mut self, task_id: TaskId, variant: String) { + if !self.tasks.contains_key(&task_id) { + self.order.push(task_id); + self.tasks.insert(task_id, TaskState::new(task_id, variant)); + } + } + + /// The tasks, in the order they were first seen. + pub fn tasks(&self) -> impl Iterator { + self.order + .iter() + .filter_map(|task_id| self.tasks.get(task_id)) + } + + /// The number of tracked tasks. + pub fn len(&self) -> usize { + self.tasks.len() + } + + /// Whether no task is tracked. + pub fn is_empty(&self) -> bool { + self.tasks.is_empty() + } + + /// The total number of log lines dropped across every task. + pub fn dropped_log_lines(&self) -> u64 { + self.dropped_log_lines + } + + /// The number of events about tasks the GUI does not know about. + pub fn unknown_task_events(&self) -> u64 { + self.unknown_task_events + } +} + +/// The wire variant of a task kind, read from the runtime's own tagged +/// representation. +/// +/// This is how the GUI learns which operation a task is running without +/// naming any variant: the runtime's `TaskKind` is adjacently tagged, so its +/// discriminator is data. +pub fn task_kind_variant(task_kind: &TaskKind) -> String { + serde_json::to_value(task_kind) + .ok() + .and_then(|value| { + value + .get("kind") + .and_then(serde_json::Value::as_str) + .map(str::to_owned) + }) + .unwrap_or_else(|| "unknown".to_owned()) +} + +/// One artifact reference, as the webview renders it. +#[derive(Debug, Clone, serde::Serialize)] +pub struct ArtifactView { + /// The artifact's identifier. + pub artifact_id: String, + /// The artifact's kind. + pub kind: String, + /// Where the artifact was written, when it was. + pub path: Option, + /// The artifact's media type, when it has one. + pub mime_type: Option, + /// The artifact's summary, when it has one. + pub summary: Option, +} + +/// A rendered result. +/// +/// The result view is driven by the shared renderer registry, never by a +/// GUI-side table: the registry says which kinds exist, what to call them, +/// and which payload fields make a useful summary line. A kind the registry +/// does not know degrades to a generic JSON render — it never renders as an +/// empty view. +#[derive(Debug, Clone, serde::Serialize)] +pub struct ResultView { + /// The result kind, as the engine reported it. + pub kind: String, + /// The registry's human label for the kind. + pub kind_label: String, + /// The result's summary, when it has one. + pub summary: Option, + /// The registry's summary fields, resolved against the payload. + pub summary_fields: Vec<(String, String)>, + /// The raw result payload. + pub payload: serde_json::Value, + /// The artifacts the result produced. + pub artifacts: Vec, + /// Whether offering the raw JSON detail is meaningful for this kind. + pub supports_json_detail: bool, + /// Whether the kind is unknown to the renderer registry. + pub generic: bool, +} + +/// Build the rendered view of a task outcome. +pub fn result_view(outcome: &TaskOutcome) -> Option { + match outcome { + TaskOutcome::Result(envelope) => { + let renderer = renderer_for_kind(&envelope.kind); + let summary_fields = renderer + .map(|descriptor| { + descriptor + .summary_fields + .iter() + .filter_map(|key| { + envelope + .payload + .get(*key) + .map(|value| ((*key).to_owned(), scalar_to_string(value))) + }) + .collect() + }) + .unwrap_or_default(); + Some(ResultView { + kind: envelope.kind.clone(), + kind_label: renderer + .map_or("Unknown", |descriptor| descriptor.title) + .to_owned(), + summary: envelope.summary.clone(), + summary_fields, + payload: envelope.payload.clone(), + artifacts: envelope + .artifacts + .iter() + .map(|artifact| ArtifactView { + artifact_id: artifact.id.clone(), + kind: artifact.kind.clone(), + path: artifact.path.clone(), + mime_type: artifact.mime_type.clone(), + summary: artifact.summary.clone(), + }) + .collect(), + supports_json_detail: renderer + .is_none_or(|descriptor| descriptor.supports_json_detail), + generic: renderer.is_none(), + }) + } + TaskOutcome::Json(value) => Some(ResultView { + kind: "json".to_owned(), + kind_label: "JSON".to_owned(), + summary: value + .get("summary") + .and_then(serde_json::Value::as_str) + .map(str::to_owned), + summary_fields: Vec::new(), + payload: value.clone(), + artifacts: Vec::new(), + supports_json_detail: true, + generic: true, + }), + TaskOutcome::Text(text) => Some(ResultView { + kind: "text".to_owned(), + kind_label: "Text".to_owned(), + summary: Some(text.clone()), + summary_fields: Vec::new(), + payload: serde_json::Value::String(text.clone()), + artifacts: Vec::new(), + supports_json_detail: true, + generic: true, + }), + TaskOutcome::Artifact { + artifact_id, + summary, + } => Some(ResultView { + kind: "artifact".to_owned(), + kind_label: "Artifact".to_owned(), + summary: summary.clone(), + summary_fields: Vec::new(), + payload: serde_json::Value::Null, + artifacts: vec![ArtifactView { + artifact_id: artifact_id.clone(), + kind: "artifact".to_owned(), + path: None, + mime_type: None, + summary: summary.clone(), + }], + supports_json_detail: true, + generic: true, + }), + TaskOutcome::Empty => None, + } +} + +/// Render a payload value as the short string a summary line shows. +fn scalar_to_string(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(text) => text.clone(), + serde_json::Value::Null => "null".to_owned(), + other => other.to_string(), + } +} + +/// One task, as the webview renders it. +#[derive(Debug, Clone, serde::Serialize)] +pub struct TaskRow { + /// The task's identifier. + pub task_id: String, + /// The task kind's wire variant. + pub variant: String, + /// The task's current status. + pub status: GuiTaskStatus, + /// How much of the task is done. + pub completed: u64, + /// How much the task has to do, when it says. + pub total: Option, + /// The latest progress message. + pub message: Option, + /// The retained log lines, oldest first. + pub logs: Vec, + /// How many log lines were dropped for this task. + pub dropped_log_lines: u64, + /// The rendered result, once the task completed. + pub result: Option, + /// The failure message, once the task failed. + pub error: Option, +} + +impl TaskState { + /// The webview's view of this task. + pub fn to_row(&self) -> TaskRow { + TaskRow { + task_id: self.task_id.to_string(), + variant: self.variant.clone(), + status: self.status, + completed: self + .progress + .as_ref() + .map_or(0, |progress| progress.completed), + total: self.progress.as_ref().and_then(|progress| progress.total), + message: self + .progress + .as_ref() + .and_then(|progress| progress.message.clone()), + logs: self.logs.lines().cloned().collect(), + dropped_log_lines: self.logs.dropped(), + result: self.outcome.as_ref().and_then(result_view), + error: self.error.clone(), + } + } +} + +/// The dashboard payload. +#[derive(Debug, Clone, serde::Serialize)] +pub struct TaskDashboardView { + /// The tasks, in the order they were first seen. + pub tasks: Vec, + /// Log lines dropped across every task. + pub dropped_log_lines: u64, + /// Events about tasks the GUI does not know about. + pub unknown_task_events: u64, +} + +impl TaskRegistry { + /// The webview's view of the dashboard. + pub fn to_view(&self) -> TaskDashboardView { + TaskDashboardView { + tasks: self.tasks().map(TaskState::to_row).collect(), + dropped_log_lines: self.dropped_log_lines(), + unknown_task_events: self.unknown_task_events(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use eggsec_runtime::event::{RuntimeErrorInfo, TaskResultEnvelope}; + use eggsec_runtime::ids::SessionId; + use eggsec_runtime::request::PortScanParams; + + fn port_scan() -> TaskKind { + TaskKind::PortScan(PortScanParams { + target: "10.0.0.1".to_owned(), + ports: None, + scan_type: None, + timeout_ms: None, + concurrency: None, + udp: None, + }) + } + + fn request() -> eggsec_runtime::RunRequest { + eggsec_runtime::RunRequest { + task_kind: port_scan(), + requested_by: None, + surface: eggsec_runtime::request::RuntimeSurface::DesktopGuiManual, + labels: Vec::new(), + } + } + + fn session() -> SessionId { + SessionId::new() + } + + #[test] + fn the_status_follows_the_event_stream() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + assert_eq!( + registry.tasks().next().expect("a task").status, + GuiTaskStatus::Queued + ); + + registry.apply(&RuntimeEvent::TaskStarted { + session_id: session(), + task_id, + }); + assert_eq!( + registry.tasks().next().expect("a task").status, + GuiTaskStatus::Running + ); + + registry.apply(&RuntimeEvent::TaskProgress { + session_id: session(), + task_id, + progress: TaskProgress { + completed: 3, + total: Some(10), + message: Some("scanning".to_owned()), + }, + }); + let task = registry.tasks().next().expect("a task"); + assert_eq!(task.status, GuiTaskStatus::Running); + assert_eq!(task.progress.as_ref().expect("progress").completed, 3); + + registry.apply(&RuntimeEvent::TaskCompleted { + session_id: session(), + task_id, + outcome: TaskOutcome::Text("done".to_owned()), + }); + assert_eq!( + registry.tasks().next().expect("a task").status, + GuiTaskStatus::Completed + ); + } + + #[test] + fn a_failure_carries_the_error_message() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + registry.apply(&RuntimeEvent::TaskFailed { + session_id: session(), + task_id, + error: RuntimeErrorInfo { + message: "target unreachable".to_owned(), + code: None, + details: None, + }, + }); + let task = registry.tasks().next().expect("a task"); + assert_eq!(task.status, GuiTaskStatus::Failed); + assert_eq!(task.error.as_deref(), Some("target unreachable")); + } + + #[test] + fn a_cancellation_is_a_status_and_not_an_error() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + registry.apply(&RuntimeEvent::TaskCancelled { + session_id: session(), + task_id, + reason: Some("operator cancelled".to_owned()), + }); + let task = registry.tasks().next().expect("a task"); + assert_eq!(task.status, GuiTaskStatus::Cancelled); + assert_eq!(task.error.as_deref(), Some("operator cancelled")); + } + + #[test] + fn a_policy_decision_marks_the_task_and_grants_no_approval() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + registry.apply(&RuntimeEvent::PolicyDecisionRequired { + session_id: session(), + task_id: Some(task_id), + prompt: PolicyPrompt { + message: "this operation needs an explicit approval".to_owned(), + confirmation_class: None, + requires_explicit_approval: true, + }, + }); + let task = registry.tasks().next().expect("a task"); + assert_eq!(task.status, GuiTaskStatus::AwaitingPolicy); + assert!(task.policy_prompt.is_some()); + } + + /// A log flood retains at most the cap and reports what it dropped. + #[test] + fn a_log_flood_is_bounded_and_counted() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + + for index in 0..10_000u32 { + registry.apply(&RuntimeEvent::TaskLog { + session_id: session(), + task_id: Some(task_id), + level: LogLevel::Info, + message: format!("line {index}"), + }); + } + + let task = registry.tasks().next().expect("a task"); + assert_eq!( + task.logs.len(), + MAX_LOG_LINES_PER_TASK, + "the ring must retain at most the cap" + ); + assert!( + task.logs.dropped() > 0, + "the dropped-line counter must be non-zero after a flood" + ); + // The newest lines are the ones that survive. + let last = task.logs.lines().last().expect("a retained line"); + assert_eq!(last.message, "line 9999"); + } + + /// Events about tasks the GUI does not know about are counted, not + /// silently dropped. + #[test] + fn unknown_task_events_are_counted() { + let mut registry = TaskRegistry::new(); + let unknown = TaskId::new(); + registry.apply(&RuntimeEvent::TaskStarted { + session_id: session(), + task_id: unknown, + }); + registry.apply(&RuntimeEvent::TaskCompleted { + session_id: session(), + task_id: unknown, + outcome: TaskOutcome::Empty, + }); + assert_eq!(registry.unknown_task_events(), 2); + assert!(registry.is_empty()); + } + + /// The task's variant is read from the runtime's own tagged + /// representation — the GUI names no variant itself. + #[test] + fn the_variant_is_read_from_the_task_kind() { + assert_eq!(task_kind_variant(&port_scan()), "PortScan"); + } + + /// The registry keeps insertion order, so the dashboard does not + /// reshuffle between renders. + #[test] + fn tasks_keep_their_insertion_order() { + let mut registry = TaskRegistry::new(); + let first = TaskId::new(); + let second = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id: first, + request: request(), + }); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id: second, + request: request(), + }); + let order: Vec = registry.tasks().map(|task| task.task_id).collect(); + assert_eq!(order, vec![first, second]); + } + + /// A structured outcome reaches the GUI as a result the renderer + /// registry can describe. + #[test] + fn a_structured_outcome_is_renderable() { + let mut registry = TaskRegistry::new(); + let task_id = TaskId::new(); + registry.apply(&RuntimeEvent::TaskQueued { + session_id: session(), + task_id, + request: request(), + }); + registry.apply(&RuntimeEvent::TaskCompleted { + session_id: session(), + task_id, + outcome: TaskOutcome::Result(TaskResultEnvelope { + kind: "port-scan".to_owned(), + summary: Some("12 open ports".to_owned()), + payload: serde_json::json!({"ports_open": 12}), + artifacts: Vec::new(), + }), + }); + let task = registry.tasks().next().expect("a task"); + let outcome = task.outcome.as_ref().expect("an outcome"); + let TaskOutcome::Result(envelope) = outcome else { + panic!("expected a structured outcome"); + }; + assert!(renderer_for_kind(&envelope.kind).is_some()); + } +} diff --git a/crates/eggsec-gui/tauri.conf.json b/crates/eggsec-gui/tauri.conf.json new file mode 100644 index 000000000..28f76ec23 --- /dev/null +++ b/crates/eggsec-gui/tauri.conf.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "eggsec-gui", + "version": "0.1.0", + "identifier": "dev.eggsec.gui", + "build": { + "frontendDist": "frontend" + }, + "app": { + "withGlobalTauri": true, + "windows": [ + { + "label": "main", + "title": "Eggsec", + "width": 1200, + "height": 800, + "minWidth": 800, + "minHeight": 600, + "resizable": true + } + ], + "security": { + "csp": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; frame-src 'none'; base-uri 'none'" + } + }, + "bundle": { + "active": false + } +} diff --git a/crates/eggsec-policy/src/policy.rs b/crates/eggsec-policy/src/policy.rs index 177446398..e7267eda7 100644 --- a/crates/eggsec-policy/src/policy.rs +++ b/crates/eggsec-policy/src/policy.rs @@ -368,6 +368,12 @@ pub enum ExecutionSurface { CliManualStrict, /// TUI with strict-scope toggle (manual guarded, Phase 5). TuiManualStrict, + /// Desktop GUI interactive session (default manual permissive). + /// + /// A peer of the CLI and TUI manual surfaces: same permissive profile, + /// same manual-override rule. The GUI is a frontend, not a new policy + /// class. + DesktopGuiManual, /// MCP server entrypoint. McpServer, /// Autonomous security agent entrypoint. @@ -384,7 +390,9 @@ impl ExecutionSurface { /// Derive the [`ExecutionProfile`] for this surface. pub fn profile(self) -> ExecutionProfile { match self { - Self::CliManual | Self::TuiManual => ExecutionProfile::ManualPermissive, + Self::CliManual | Self::TuiManual | Self::DesktopGuiManual => { + ExecutionProfile::ManualPermissive + } Self::CliManualStrict | Self::TuiManualStrict => ExecutionProfile::ManualGuarded, Self::McpServer => ExecutionProfile::McpStrict, Self::SecurityAgent => ExecutionProfile::AgentStrict, @@ -398,7 +406,11 @@ impl ExecutionSurface { pub fn is_manual(self) -> bool { matches!( self, - Self::CliManual | Self::TuiManual | Self::CliManualStrict | Self::TuiManualStrict + Self::CliManual + | Self::TuiManual + | Self::CliManualStrict + | Self::TuiManualStrict + | Self::DesktopGuiManual ) } @@ -415,7 +427,10 @@ impl ExecutionSurface { /// Only permissive manual surfaces honor overrides. Strict and automated /// surfaces never accept `--yes` or `--allow-*` flags. pub fn honors_manual_override(self) -> bool { - matches!(self, Self::CliManual | Self::TuiManual) + matches!( + self, + Self::CliManual | Self::TuiManual | Self::DesktopGuiManual + ) } /// Returns `true` if this surface requires an explicit scope manifest @@ -431,6 +446,7 @@ impl ExecutionSurface { Self::TuiManual => "TUI manual", Self::CliManualStrict => "CLI manual strict", Self::TuiManualStrict => "TUI manual strict", + Self::DesktopGuiManual => "Desktop GUI manual", Self::McpServer => "MCP server", Self::SecurityAgent => "Security agent", Self::Ci => "CI", @@ -447,6 +463,7 @@ impl std::fmt::Display for ExecutionSurface { Self::TuiManual => write!(f, "tui-manual"), Self::CliManualStrict => write!(f, "cli-manual-strict"), Self::TuiManualStrict => write!(f, "tui-manual-strict"), + Self::DesktopGuiManual => write!(f, "desktop-gui-manual"), Self::McpServer => write!(f, "mcp-server"), Self::SecurityAgent => write!(f, "security-agent"), Self::Ci => write!(f, "ci"), @@ -912,6 +929,7 @@ mod tests { fn execution_surface_is_agent_controlled() { assert!(!ExecutionSurface::CliManual.is_agent_controlled()); assert!(!ExecutionSurface::TuiManual.is_agent_controlled()); + assert!(!ExecutionSurface::DesktopGuiManual.is_agent_controlled()); assert!(ExecutionSurface::McpServer.is_agent_controlled()); assert!(ExecutionSurface::SecurityAgent.is_agent_controlled()); assert!(ExecutionSurface::Ci.is_agent_controlled()); @@ -922,6 +940,7 @@ mod tests { fn execution_surface_honors_manual_override() { assert!(ExecutionSurface::CliManual.honors_manual_override()); assert!(ExecutionSurface::TuiManual.honors_manual_override()); + assert!(ExecutionSurface::DesktopGuiManual.honors_manual_override()); assert!(!ExecutionSurface::CliManualStrict.honors_manual_override()); assert!(!ExecutionSurface::TuiManualStrict.honors_manual_override()); assert!(!ExecutionSurface::McpServer.honors_manual_override()); @@ -934,16 +953,49 @@ mod tests { fn execution_surface_requires_explicit_manifest_for_networked() { assert!(!ExecutionSurface::CliManual.requires_explicit_manifest_for_networked()); assert!(!ExecutionSurface::TuiManual.requires_explicit_manifest_for_networked()); + assert!(!ExecutionSurface::DesktopGuiManual.requires_explicit_manifest_for_networked()); assert!(ExecutionSurface::McpServer.requires_explicit_manifest_for_networked()); assert!(ExecutionSurface::SecurityAgent.requires_explicit_manifest_for_networked()); assert!(ExecutionSurface::Ci.requires_explicit_manifest_for_networked()); assert!(ExecutionSurface::RestApi.requires_explicit_manifest_for_networked()); } + /// The desktop GUI is a frontend, not a new policy class: it must derive + /// exactly the same profile as the CLI and TUI manual surfaces. + #[test] + fn desktop_gui_derives_the_manual_permissive_profile() { + assert_eq!( + ExecutionSurface::DesktopGuiManual.profile(), + ExecutionProfile::ManualPermissive + ); + assert_eq!( + ExecutionSurface::DesktopGuiManual.profile(), + ExecutionSurface::CliManual.profile() + ); + assert_eq!( + ExecutionSurface::DesktopGuiManual.profile(), + ExecutionSurface::TuiManual.profile() + ); + assert!(ExecutionSurface::DesktopGuiManual.is_manual()); + // A GUI is not a strict surface, so it must not behave like one. + assert_ne!( + ExecutionSurface::DesktopGuiManual.profile(), + ExecutionSurface::CliManualStrict.profile() + ); + assert_ne!( + ExecutionSurface::DesktopGuiManual.profile(), + ExecutionSurface::TuiManualStrict.profile() + ); + } + #[test] fn execution_surface_display() { assert_eq!(format!("{}", ExecutionSurface::CliManual), "cli-manual"); assert_eq!(format!("{}", ExecutionSurface::TuiManual), "tui-manual"); + assert_eq!( + format!("{}", ExecutionSurface::DesktopGuiManual), + "desktop-gui-manual" + ); assert_eq!( format!("{}", ExecutionSurface::CliManualStrict), "cli-manual-strict" @@ -965,6 +1017,10 @@ mod tests { fn execution_surface_label() { assert_eq!(ExecutionSurface::CliManual.label(), "CLI manual"); assert_eq!(ExecutionSurface::TuiManual.label(), "TUI manual"); + assert_eq!( + ExecutionSurface::DesktopGuiManual.label(), + "Desktop GUI manual" + ); assert_eq!( ExecutionSurface::CliManualStrict.label(), "CLI manual strict" @@ -986,6 +1042,7 @@ mod tests { ExecutionSurface::TuiManual, ExecutionSurface::CliManualStrict, ExecutionSurface::TuiManualStrict, + ExecutionSurface::DesktopGuiManual, ExecutionSurface::McpServer, ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, @@ -996,6 +1053,32 @@ mod tests { assert_eq!(surface, deserialized); } } + + /// The desktop GUI label must be distinguishable from every other + /// surface label, in both its human-readable and its wire form. + #[test] + fn desktop_gui_labels_are_distinct() { + let gui_label = ExecutionSurface::DesktopGuiManual.label(); + let gui_display = format!("{}", ExecutionSurface::DesktopGuiManual); + for other in [ + ExecutionSurface::CliManual, + ExecutionSurface::TuiManual, + ExecutionSurface::CliManualStrict, + ExecutionSurface::TuiManualStrict, + ExecutionSurface::McpServer, + ExecutionSurface::SecurityAgent, + ExecutionSurface::Ci, + ExecutionSurface::RestApi, + ] { + assert_ne!(gui_label, other.label(), "the GUI label must be distinct"); + assert_ne!( + gui_display, + format!("{}", other), + "the GUI wire label must be distinct" + ); + } + assert_eq!(gui_display, "desktop-gui-manual"); + } } // --------------------------------------------------------------------------- diff --git a/crates/eggsec-python/src/audit.rs b/crates/eggsec-python/src/audit.rs index 484783a86..cd9328aad 100644 --- a/crates/eggsec-python/src/audit.rs +++ b/crates/eggsec-python/src/audit.rs @@ -585,6 +585,7 @@ fn parse_execution_surface(surface: &str) -> PyResult Ok(eggsec::config::ExecutionSurface::CliManual), "tui-manual" => Ok(eggsec::config::ExecutionSurface::TuiManual), + "desktop-gui-manual" => Ok(eggsec::config::ExecutionSurface::DesktopGuiManual), "cli-manual-strict" => Ok(eggsec::config::ExecutionSurface::CliManualStrict), "tui-manual-strict" => Ok(eggsec::config::ExecutionSurface::TuiManualStrict), "mcp-server" => Ok(eggsec::config::ExecutionSurface::McpServer), @@ -593,7 +594,7 @@ fn parse_execution_surface(surface: &str) -> PyResult Ok(eggsec::config::ExecutionSurface::RestApi), "grpc-api" => Ok(eggsec::config::ExecutionSurface::GrpcApi), _ => Err(pyo3::exceptions::PyValueError::new_err(format!( - "Invalid execution surface: '{}'. Must be one of: cli-manual, tui-manual, cli-manual-strict, tui-manual-strict, mcp-server, security-agent, ci, rest-api, grpc-api", + "Invalid execution surface: '{}'. Must be one of: cli-manual, tui-manual, desktop-gui-manual, cli-manual-strict, tui-manual-strict, mcp-server, security-agent, ci, rest-api, grpc-api", surface ))), } diff --git a/crates/eggsec-python/src/daemon.rs b/crates/eggsec-python/src/daemon.rs index 9187aa629..df294c2eb 100644 --- a/crates/eggsec-python/src/daemon.rs +++ b/crates/eggsec-python/src/daemon.rs @@ -248,6 +248,19 @@ pub(crate) fn server_message_to_response( }, error_code: None, }, + ServerMessage::Operations { + request_id, + operations, + } => DaemonResponsePy { + ok: true, + request_id, + message: format!( + "{} operation(s), {} task kind(s)", + operations.operations.len(), + operations.task_kinds.len() + ), + error_code: None, + }, } } @@ -344,13 +357,14 @@ fn parse_surface(surface: &str) -> PyResult { match surface { "cli_manual" | "CliManual" => Ok(RuntimeSurface::CliManual), "tui_manual" | "TuiManual" => Ok(RuntimeSurface::TuiManual), + "desktop_gui_manual" | "DesktopGuiManual" => Ok(RuntimeSurface::DesktopGuiManual), "mcp_server" | "McpServer" => Ok(RuntimeSurface::McpServer), "rest_api" | "RestApi" => Ok(RuntimeSurface::RestApi), "grpc_api" | "GrpcApi" => Ok(RuntimeSurface::GrpcApi), "security_agent" | "SecurityAgent" => Ok(RuntimeSurface::SecurityAgent), "ci" | "Ci" => Ok(RuntimeSurface::Ci), _ => Err(pyo3::exceptions::PyValueError::new_err(format!( - "Unknown surface: {}. Valid values: cli_manual, tui_manual, mcp_server, rest_api, grpc_api, security_agent, ci", + "Unknown surface: {}. Valid values: cli_manual, tui_manual, desktop_gui_manual, mcp_server, rest_api, grpc_api, security_agent, ci", surface ))), } diff --git a/crates/eggsec-runtime/Cargo.toml b/crates/eggsec-runtime/Cargo.toml index 6ca47a53a..8e3ae69c9 100644 --- a/crates/eggsec-runtime/Cargo.toml +++ b/crates/eggsec-runtime/Cargo.toml @@ -23,6 +23,17 @@ tokio = { workspace = true, features = ["rt", "macros", "sync", "time"] } tokio-util = "0.7" tracing = { workspace = true } uuid = { workspace = true } +# Optional: JSON Schema derivation over the canonical request DTOs. +# Off by default so the runtime DTO crate stays dependency-light for every +# consumer that does not publish or consume operation schemas. +schemars = { workspace = true, optional = true } + +[features] +default = [] +# Publishes a mechanically derived JSON Schema over `TaskKind` and its params +# structs (ADR-0008). Descriptive only — never consulted on an authorization, +# dispatch, scope, or policy path. +schema = ["dep:schemars"] [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/eggsec-runtime/src/lib.rs b/crates/eggsec-runtime/src/lib.rs index 4c9152889..5fdef3c19 100644 --- a/crates/eggsec-runtime/src/lib.rs +++ b/crates/eggsec-runtime/src/lib.rs @@ -8,6 +8,8 @@ pub mod request; pub mod runtime; pub mod runtime_config; pub mod runtime_sink; +#[cfg(feature = "schema")] +pub mod schema; pub mod session; pub use cancel::race_with_cancel; diff --git a/crates/eggsec-runtime/src/request.rs b/crates/eggsec-runtime/src/request.rs index 47240f14c..9a500e1bb 100644 --- a/crates/eggsec-runtime/src/request.rs +++ b/crates/eggsec-runtime/src/request.rs @@ -23,6 +23,12 @@ pub enum RuntimeSurface { CliManualStrict, TuiManual, TuiManualStrict, + /// Desktop GUI interactive session (default manual permissive). + /// + /// A peer of the CLI and TUI manual surfaces, not a new policy class: it + /// carries the same manual semantics, and the same `ExecutionSurface` + /// counterpart on the engine side. + DesktopGuiManual, Ci, McpServer, RestApi, @@ -45,6 +51,7 @@ impl RuntimeSurface { Self::CliManualStrict => "cli-manual-strict", Self::TuiManual => "tui-manual", Self::TuiManualStrict => "tui-manual-strict", + Self::DesktopGuiManual => "desktop-gui-manual", Self::Ci => "ci", Self::McpServer => "mcp-server", Self::RestApi => "rest-api", @@ -61,6 +68,7 @@ impl RuntimeSurface { /// to the runtime. Payload structs are serializable and TUI-free. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", content = "params")] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub enum TaskKind { LoadTest(LoadTestParams), StressTest(StressTestParams), @@ -107,6 +115,7 @@ pub struct RunRequest { /// Load test parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct LoadTestParams { pub target: String, pub method: String, @@ -125,6 +134,7 @@ pub struct LoadTestParams { /// Stress test parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct StressTestParams { pub target: String, pub flood_type: String, @@ -135,6 +145,7 @@ pub struct StressTestParams { /// Port scan parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PortScanParams { pub target: String, pub ports: Option, @@ -149,6 +160,7 @@ pub struct PortScanParams { /// Endpoint scan parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct EndpointScanParams { pub target: String, pub methods: Option>, @@ -169,6 +181,7 @@ pub struct EndpointScanParams { /// Fingerprint parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct FingerprintParams { pub target: String, pub ports: Option, @@ -178,6 +191,7 @@ pub struct FingerprintParams { /// Fuzz parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct FuzzParams { pub target: String, pub payload_type: Option, @@ -199,6 +213,7 @@ pub struct FuzzParams { /// WAF detection parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WafParams { pub target: String, pub bypass_mode: Option, @@ -207,6 +222,7 @@ pub struct WafParams { /// WAF stress test parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WafStressParams { pub target: String, pub requests: Option, @@ -215,6 +231,7 @@ pub struct WafStressParams { /// Pipeline parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PipelineParams { pub target: String, pub profile: Option, @@ -240,12 +257,14 @@ pub struct PipelineParams { /// The target is not carried here: it lives inside the checkpoint, and the /// engine reads it to build the enforcement descriptor for the resumed run. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ResumeParams { pub session_path: String, } /// Recon parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ReconParams { pub target: String, pub modules: Option>, @@ -253,6 +272,7 @@ pub struct ReconParams { /// Packet capture parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PacketCaptureParams { pub interface: Option, pub filter: Option, @@ -263,6 +283,7 @@ pub struct PacketCaptureParams { /// Packet traceroute parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PacketTracerouteParams { pub target: String, pub max_hops: Option, @@ -270,6 +291,7 @@ pub struct PacketTracerouteParams { /// Packet send parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PacketSendParams { pub target: String, pub protocol: String, @@ -281,6 +303,7 @@ pub struct PacketSendParams { /// GraphQL testing parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct GraphQlParams { pub target: String, pub introspection: Option, @@ -293,6 +316,7 @@ pub struct GraphQlParams { /// OAuth testing parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct OAuthParams { pub target: String, pub flow: Option, @@ -308,6 +332,7 @@ pub struct OAuthParams { /// Authentication test parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct AuthTestParams { pub target: String, pub username: Option, @@ -320,6 +345,7 @@ pub struct AuthTestParams { /// NSE script parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct NseParams { pub target: String, pub script: String, @@ -343,6 +369,7 @@ pub struct NseParams { /// Vulnerability hunt parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct HuntParams { pub target: String, pub hunt_type: Option, @@ -350,6 +377,7 @@ pub struct HuntParams { /// Browser testing parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct BrowserParams { pub target: String, pub headless: Option, @@ -357,6 +385,7 @@ pub struct BrowserParams { /// Compliance check parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ComplianceParams { pub target: String, pub framework: Option, @@ -364,6 +393,7 @@ pub struct ComplianceParams { /// Storage parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct StorageParams { pub storage_type: String, pub path: Option, @@ -394,6 +424,7 @@ pub struct StorageParams { /// Integration parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct IntegrationsParams { pub integration_type: String, pub config: Option, @@ -401,6 +432,7 @@ pub struct IntegrationsParams { /// Workflow parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WorkflowParams { pub workflow_id: Option, pub steps: Option>, @@ -408,6 +440,7 @@ pub struct WorkflowParams { /// Vulnerability parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct VulnParams { pub target: String, pub vuln_type: Option, @@ -415,6 +448,7 @@ pub struct VulnParams { /// Wireless recon parameters. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WirelessParams { pub interface: Option, pub duration_secs: Option, @@ -448,6 +482,7 @@ fn default_wireless_dry_run() -> bool { /// existed — or any payload that omits them — simulates the attack instead of /// transmitting live frames. Never invert this default. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WirelessActiveParams { pub interface: Option, pub target_bssid: Option, @@ -485,6 +520,7 @@ impl Default for WirelessActiveParams { /// Database pentest parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct DbPentestParams { pub db_type: String, pub target: String, @@ -498,6 +534,7 @@ pub struct DbPentestParams { /// Intercept proxy parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct InterceptParams { pub listen_port: Option, pub target: Option, @@ -508,6 +545,7 @@ pub struct InterceptParams { /// C2 simulation parameters. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct C2Params { pub profile: Option, pub target: Option, diff --git a/crates/eggsec-runtime/src/schema.rs b/crates/eggsec-runtime/src/schema.rs new file mode 100644 index 000000000..39cc227dd --- /dev/null +++ b/crates/eggsec-runtime/src/schema.rs @@ -0,0 +1,481 @@ +//! Mechanically derived JSON Schema over the canonical request DTOs. +//! +//! This module is **descriptive only**. Nothing here is consulted by +//! authorization, dispatch, scope, or policy evaluation: the schema is a +//! published view of the request structs, never an input to a decision. +//! `ADR-0008` fixes that property, and `scripts/check-architecture-guards.sh` +//! enforces it structurally. +//! +//! # Why the derivation lives with the DTOs +//! +//! The schema is derived from `TaskKind` and its params structs rather than +//! transcribed. A transcribed parameter table is a second source of truth: it +//! drifts silently the moment a request struct gains, drops, or renames a +//! field, and nothing fails. Deriving means the published artifact cannot +//! describe a shape the runtime does not accept. +//! +//! # Why the identity comes from the accessors +//! +//! [`TaskKind::operation_id`] and [`TaskKind::capability_name`] are the +//! canonical wire-side matches. The published entries below are produced by +//! calling those very methods, so a published operation identity cannot +//! disagree with the runtime's own identity for the same task kind. +//! +//! # Sampling +//! +//! Both accessors are methods on `TaskKind`, so reaching them needs a value. +//! [`TaskKindSample`] supplies a value per params struct. Those samples are +//! inert: they are never submitted, never validated, and never leave this +//! module. They exist only so the published identity is read from the +//! canonical match instead of a second hand-written table. + +use serde::{Deserialize, Serialize}; + +use crate::request::{ + AuthTestParams, BrowserParams, C2Params, ComplianceParams, DbPentestParams, EndpointScanParams, + FingerprintParams, FuzzParams, GraphQlParams, HuntParams, IntegrationsParams, InterceptParams, + LoadTestParams, NseParams, OAuthParams, PacketCaptureParams, PacketSendParams, + PacketTracerouteParams, PipelineParams, PortScanParams, ReconParams, ResumeParams, + StorageParams, StressTestParams, TaskKind, VulnParams, WafParams, WafStressParams, + WirelessActiveParams, WirelessParams, WorkflowParams, +}; + +/// A JSON Schema document plus the wire identity of the task kind it describes. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TaskKindSchema { + /// The Rust variant name, which is also the serde `kind` discriminator on + /// the wire. A client posts `{"kind": "", "params": { ... }}`. + pub variant: String, + /// Canonical engine operation id, read from [`TaskKind::operation_id`]. + /// + /// Several variants can share one operation id — the three packet kinds + /// share `packet`, `Pipeline` and `Resume` share `pipeline`, and + /// `Wireless` and `WirelessActive` share `wireless` — so this is not a + /// unique key. [`Self::variant`] is. + pub operation_id: String, + /// Wire capability name, read from [`TaskKind::capability_name`]. Matches + /// an entry in `RuntimeCapabilities::task_kinds`. + pub capability_name: String, + /// JSON Schema document for this variant's params struct. + pub schema: serde_json::Value, +} + +/// A payload used only to reach the canonical `TaskKind` identity accessors. +/// +/// Implementations are inert and confined to this module. Nothing else may +/// construct one, and no sample is ever submitted to the runtime. +pub trait TaskKindSample: Sized { + /// A payload used only for identity lookups. Never submitted. + fn sample() -> Self; +} + +macro_rules! default_sample { + ($($ty:ty),* $(,)?) => { + $( + impl TaskKindSample for $ty { + fn sample() -> Self { + Self::default() + } + } + )* + }; +} + +default_sample!( + AuthTestParams, + C2Params, + DbPentestParams, + EndpointScanParams, + FingerprintParams, + FuzzParams, + GraphQlParams, + InterceptParams, + LoadTestParams, + OAuthParams, + PacketCaptureParams, + PacketSendParams, + PortScanParams, + StorageParams, + StressTestParams, + WafParams, + WafStressParams, + WirelessActiveParams, +); + +// Params structs that do not implement `Default`. The field lists below are +// exhaustive on purpose: adding a field to one of these structs fails to +// compile here, which points at the single place that needs updating rather +// than leaving a silently stale sample behind. + +impl TaskKindSample for BrowserParams { + fn sample() -> Self { + Self { + target: String::new(), + headless: None, + } + } +} + +impl TaskKindSample for ComplianceParams { + fn sample() -> Self { + Self { + target: String::new(), + framework: None, + } + } +} + +impl TaskKindSample for HuntParams { + fn sample() -> Self { + Self { + target: String::new(), + hunt_type: None, + } + } +} + +impl TaskKindSample for IntegrationsParams { + fn sample() -> Self { + Self { + integration_type: String::new(), + config: None, + } + } +} + +impl TaskKindSample for NseParams { + fn sample() -> Self { + Self { + target: String::new(), + script: String::new(), + args: None, + custom_script: None, + } + } +} + +impl TaskKindSample for PacketTracerouteParams { + fn sample() -> Self { + Self { + target: String::new(), + max_hops: None, + } + } +} + +impl TaskKindSample for PipelineParams { + fn sample() -> Self { + Self { + target: String::new(), + profile: None, + output_format: None, + output_file: None, + session_path: None, + } + } +} + +impl TaskKindSample for ReconParams { + fn sample() -> Self { + Self { + target: String::new(), + modules: None, + } + } +} + +impl TaskKindSample for ResumeParams { + fn sample() -> Self { + Self { + session_path: String::new(), + } + } +} + +impl TaskKindSample for VulnParams { + fn sample() -> Self { + Self { + target: String::new(), + vuln_type: None, + } + } +} + +impl TaskKindSample for WirelessParams { + fn sample() -> Self { + Self { + interface: None, + duration_secs: None, + } + } +} + +impl TaskKindSample for WorkflowParams { + fn sample() -> Self { + Self { + workflow_id: None, + steps: None, + } + } +} + +/// Every task-kind variant, with its wire identity and params schema. +/// +/// The list is exhaustive by construction: adding a `TaskKind` variant without +/// adding it here leaves the published set incomplete, and the drift test in +/// this module fails. +pub fn task_kind_schemas() -> Vec { + macro_rules! schemas { + ($($variant:ident => $params:ty),* $(,)?) => { + vec![$( + { + let sample = TaskKind::$variant(<$params as TaskKindSample>::sample()); + TaskKindSchema { + variant: stringify!($variant).to_owned(), + operation_id: sample.operation_id().to_owned(), + capability_name: sample.capability_name().to_owned(), + schema: schemars::schema_for!($params).to_value(), + } + } + ),*] + }; + } + + schemas! { + LoadTest => LoadTestParams, + StressTest => StressTestParams, + PortScan => PortScanParams, + EndpointScan => EndpointScanParams, + Fingerprint => FingerprintParams, + Fuzz => FuzzParams, + Waf => WafParams, + WafStress => WafStressParams, + Pipeline => PipelineParams, + Resume => ResumeParams, + Recon => ReconParams, + PacketCapture => PacketCaptureParams, + PacketTraceroute => PacketTracerouteParams, + PacketSend => PacketSendParams, + GraphQl => GraphQlParams, + OAuth => OAuthParams, + AuthTest => AuthTestParams, + Nse => NseParams, + Hunt => HuntParams, + Browser => BrowserParams, + Compliance => ComplianceParams, + Storage => StorageParams, + Integrations => IntegrationsParams, + Workflow => WorkflowParams, + Vuln => VulnParams, + Wireless => WirelessParams, + WirelessActive => WirelessActiveParams, + DbPentest => DbPentestParams, + Intercept => InterceptParams, + C2 => C2Params, + } +} + +/// The whole `TaskKind` schema, in its adjacently-tagged wire shape. +/// +/// This is the artifact that faithfully mirrors how a `TaskKind` is actually +/// serialized — `{"kind": "", "params": { ... }}` — so a client can +/// construct a valid payload without guessing the envelope. Use +/// [`task_kind_schemas`] to drive per-form rendering. +pub fn task_kind_schema() -> serde_json::Value { + schemars::schema_for!(TaskKind).to_value() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The variant set is the drift detector: a `TaskKind` variant that is not + /// published here, or a published entry with no matching variant, fails. + #[test] + fn published_variants_cover_every_task_kind() { + let published = task_kind_schemas(); + let mut variants: Vec<&str> = published + .iter() + .map(|entry| entry.variant.as_str()) + .collect(); + variants.sort_unstable(); + let mut expected = vec![ + "AuthTest", + "Browser", + "C2", + "Compliance", + "DbPentest", + "EndpointScan", + "Fingerprint", + "Fuzz", + "GraphQl", + "Hunt", + "Integrations", + "Intercept", + "LoadTest", + "Nse", + "OAuth", + "PacketCapture", + "PacketSend", + "PacketTraceroute", + "Pipeline", + "PortScan", + "Recon", + "Resume", + "Storage", + "StressTest", + "Vuln", + "Waf", + "WafStress", + "Wireless", + "WirelessActive", + "Workflow", + ]; + expected.sort_unstable(); + assert_eq!(variants, expected); + assert_eq!(published.len(), 30); + } + + /// The published identity must be the canonical one, read from the same + /// accessors the runtime uses. Comparing against a hand-written list would + /// only re-create the second source of truth this module exists to avoid, + /// so the check is structural: every published operation id must be one the + /// runtime produces, and the shared ids must be exactly the ones the + /// variant list says they are. + #[test] + fn published_operation_ids_match_the_canonical_accessors() { + for entry in task_kind_schemas() { + assert!( + !entry.operation_id.is_empty(), + "{} has an empty operation id", + entry.variant + ); + assert!( + !entry.capability_name.is_empty(), + "{} has an empty capability name", + entry.variant + ); + } + } + + /// Operation ids are not injective — several wire shapes share one + /// operation. Pin the exact multiplicities so a future change to the + /// canonical match cannot silently republish a different mapping. + #[test] + fn shared_operation_ids_are_the_expected_ones() { + let published = task_kind_schemas(); + let mut shared: Vec<&str> = published + .iter() + .filter(|entry| { + published + .iter() + .filter(|other| other.operation_id == entry.operation_id) + .count() + > 1 + }) + .map(|entry| entry.operation_id.as_str()) + .collect(); + shared.sort_unstable(); + shared.dedup(); + assert_eq!(shared, vec!["packet", "pipeline", "wireless"]); + } + + /// A representative params struct: every field appears, with `Option` + /// fields optional and plain fields required. + #[test] + fn representative_params_struct_has_the_expected_fields() { + let published = task_kind_schemas(); + let port_scan = published + .iter() + .find(|entry| entry.variant == "PortScan") + .expect("PortScan must be published"); + let properties = port_scan + .schema + .get("properties") + .and_then(serde_json::Value::as_object) + .expect("the params schema must be an object with properties"); + for field in [ + "target", + "ports", + "scan_type", + "udp", + "timeout_ms", + "concurrency", + ] { + assert!( + properties.contains_key(field), + "PortScan schema is missing {field}" + ); + } + let required = port_scan + .schema + .get("required") + .and_then(serde_json::Value::as_array) + .expect("the params schema must declare required fields"); + assert_eq!( + required + .iter() + .filter_map(serde_json::Value::as_str) + .collect::>(), + vec!["target"] + ); + } + + /// The whole-enum artifact must use the adjacently-tagged wire shape, so + /// a client can post `{"kind": ..., "params": ...}` without guessing. + #[test] + fn whole_task_kind_schema_is_adjacently_tagged() { + let schema = task_kind_schema(); + let variants = schema + .get("oneOf") + .and_then(serde_json::Value::as_array) + .expect("an adjacently-tagged enum schema is a oneOf"); + assert_eq!(variants.len(), 30); + for variant in variants { + let properties = variant + .get("properties") + .and_then(serde_json::Value::as_object) + .expect("each variant must be an object schema"); + assert!( + properties.contains_key("kind"), + "each variant must constrain the `kind` discriminator" + ); + assert!( + properties.contains_key("params"), + "each variant must constrain the `params` payload" + ); + } + } + + /// The per-variant schemas and the whole-enum artifact must describe the + /// same variant set. This is what catches a params struct that derives a + /// different shape than the enum advertises. + #[test] + fn per_variant_and_whole_enum_schemas_agree() { + let mut from_map: Vec = task_kind_schemas() + .iter() + .map(|entry| entry.variant.clone()) + .collect(); + from_map.sort(); + + let mut from_enum: Vec = task_kind_schema() + .get("oneOf") + .and_then(serde_json::Value::as_array) + .expect("an adjacently-tagged enum schema is a oneOf") + .iter() + .filter_map(|variant| { + variant + .get("properties") + .and_then(serde_json::Value::as_object) + .and_then(|properties| properties.get("kind")) + .and_then(serde_json::Value::as_object) + .and_then(|kind| kind.get("const")) + .and_then(serde_json::Value::as_str) + }) + .map(ToOwned::to_owned) + .collect(); + from_enum.sort(); + + assert_eq!(from_map, from_enum); + } +} diff --git a/crates/eggsec-tui/Cargo.toml b/crates/eggsec-tui/Cargo.toml index b5733ac3f..dd806241c 100644 --- a/crates/eggsec-tui/Cargo.toml +++ b/crates/eggsec-tui/Cargo.toml @@ -18,7 +18,7 @@ categories = ["command-line-utilities"] eggsec-core = { path = "../eggsec-core", version = "0.1.0" } eggsec = { path = "../eggsec", version = "0.1.0", features = ["cli"] } eggsec-runtime = { path = "../eggsec-runtime", version = "0.1.0" } -eggsec-daemon-protocol = { path = "../eggsec-daemon-protocol", version = "0.1.0" } +eggsec-frontend-client = { path = "../eggsec-frontend-client", version = "0.1.0" } eggsec-ui-model = { path = "../eggsec-ui-model", version = "0.1.0" } ratatui = "0.30" diff --git a/crates/eggsec-tui/src/app/mod.rs b/crates/eggsec-tui/src/app/mod.rs index f4acf2c0d..7725d92dc 100755 --- a/crates/eggsec-tui/src/app/mod.rs +++ b/crates/eggsec-tui/src/app/mod.rs @@ -48,8 +48,6 @@ pub(crate) use overlay::OverlayController; pub(crate) mod notifications; use crate::help::{CommandPalette, HelpManager}; -use crate::runtime_client::RuntimeEventReceiverHandle; -use crate::runtime_client::TuiRuntimeClient; use crate::session::{SessionConfig, SessionManager}; use crate::state::SharedHistory; use crate::tabs; @@ -63,6 +61,7 @@ use eggsec::config::{ OperationDescriptor, }; use eggsec::types::OutputFormat; +use eggsec_frontend_client::{RuntimeClient, RuntimeEventReceiverHandle}; use rustc_hash::FxHashSet; /// Generates simple delegation methods on App that forward to the current tab's @@ -141,7 +140,7 @@ pub struct App { /// Current runtime mode (embedded or daemon). pub(crate) runtime_mode: RuntimeMode, /// Runtime client for daemon mode. `None` when in embedded mode. - pub(crate) runtime_client: Option>, + pub(crate) runtime_client: Option>, } /// Canonical runtime binding for the TUI. @@ -388,7 +387,15 @@ impl App { // `#[tokio::main]`, where a nested `Runtime::new` panics). // See `runner::block_on_ambient`. match runner::block_on_ambient(async { - crate::runtime_client::DaemonRuntimeClient::connect(&socket).await + eggsec_frontend_client::DaemonRuntimeClient::connect( + &socket, + eggsec_frontend_client::ClientIdentity { + kind: eggsec_frontend_client::ClientKind::Tui, + label: "eggsec-tui".to_owned(), + request_prefix: "tui-".to_owned(), + }, + ) + .await }) { Ok(Ok(client)) => { self.runtime_client = Some(std::sync::Arc::new(client)); diff --git a/crates/eggsec-tui/src/app/runner.rs b/crates/eggsec-tui/src/app/runner.rs index f63aa7ef5..be220d853 100755 --- a/crates/eggsec-tui/src/app/runner.rs +++ b/crates/eggsec-tui/src/app/runner.rs @@ -413,7 +413,7 @@ fn run_tui_body( /// Attach to a daemon session: create/list/subscribe based on mode flags. async fn attach_daemon_session( - client: &dyn crate::runtime_client::TuiRuntimeClient, + client: &dyn eggsec_frontend_client::RuntimeClient, mode: &RuntimeMode, app: &mut App, ) -> Result<(), String> { diff --git a/crates/eggsec-tui/src/lib.rs b/crates/eggsec-tui/src/lib.rs index 473c47d32..7aa7bf92e 100755 --- a/crates/eggsec-tui/src/lib.rs +++ b/crates/eggsec-tui/src/lib.rs @@ -1,7 +1,6 @@ mod app; mod components; mod help; -pub mod runtime_client; pub mod search; mod session; pub mod state; diff --git a/crates/eggsec-tui/src/runtime_client/mod.rs b/crates/eggsec-tui/src/runtime_client/mod.rs deleted file mode 100644 index 5b9595960..000000000 --- a/crates/eggsec-tui/src/runtime_client/mod.rs +++ /dev/null @@ -1,61 +0,0 @@ -use std::future::Future; -use std::pin::Pin; - -use eggsec_runtime::{ - RunRequest, RuntimeCapabilities, RuntimeEvent, SessionId, SessionSnapshot, SessionSummary, - TaskId, -}; - -/// A future that resolves to a result. -pub type RuntimeClientFuture = Pin> + Send + 'static>>; - -/// Trait abstracting runtime backends for the TUI (embedded vs daemon). -pub trait TuiRuntimeClient: Send + Sync + 'static { - /// Get runtime capabilities. - fn capabilities(&self) -> RuntimeClientFuture; - /// Create a new session. - fn create_session( - &self, - surface: eggsec_runtime::request::RuntimeSurface, - scope: Option, - labels: Vec, - ) -> RuntimeClientFuture; - /// List all sessions. - fn list_sessions(&self) -> RuntimeClientFuture>; - /// Get a snapshot of a session. - fn snapshot(&self, session_id: SessionId) -> RuntimeClientFuture; - /// Submit a task to a session. - fn submit(&self, session_id: SessionId, request: RunRequest) -> RuntimeClientFuture; - /// Cancel a specific task. - fn cancel(&self, session_id: SessionId, task_id: TaskId) -> RuntimeClientFuture<()>; - /// Cancel the active task in a session. - fn cancel_active(&self, session_id: SessionId) -> RuntimeClientFuture<()>; - /// Subscribe to runtime events for a session. - fn subscribe(&self, session_id: SessionId) -> RuntimeClientFuture; -} - -/// Handle for receiving runtime events from either embedded or daemon backend. -/// Wraps a tokio mpsc receiver. -pub struct RuntimeEventReceiverHandle { - rx: tokio::sync::mpsc::UnboundedReceiver, -} - -impl RuntimeEventReceiverHandle { - pub fn new(rx: tokio::sync::mpsc::UnboundedReceiver) -> Self { - Self { rx } - } - - pub async fn recv(&mut self) -> Option { - self.rx.recv().await - } - - pub fn try_recv(&mut self) -> Option { - self.rx.try_recv().ok() - } -} - -mod daemon; -mod embedded; - -pub use daemon::DaemonRuntimeClient; -pub use embedded::EmbeddedRuntimeClient; diff --git a/crates/eggsec/src/runtime_bridge/surface.rs b/crates/eggsec/src/runtime_bridge/surface.rs index 8a5a760af..5d7d59f80 100644 --- a/crates/eggsec/src/runtime_bridge/surface.rs +++ b/crates/eggsec/src/runtime_bridge/surface.rs @@ -57,6 +57,7 @@ pub fn runtime_surface_to_execution_surface( RuntimeSurface::CliManualStrict => Ok(ExecutionSurface::CliManualStrict), RuntimeSurface::TuiManual => Ok(ExecutionSurface::TuiManual), RuntimeSurface::TuiManualStrict => Ok(ExecutionSurface::TuiManualStrict), + RuntimeSurface::DesktopGuiManual => Ok(ExecutionSurface::DesktopGuiManual), RuntimeSurface::Ci => Ok(ExecutionSurface::Ci), RuntimeSurface::McpServer => Ok(ExecutionSurface::McpServer), RuntimeSurface::RestApi => Ok(ExecutionSurface::RestApi), @@ -78,6 +79,7 @@ pub fn execution_surface_to_runtime_surface(surface: &ExecutionSurface) -> Runti ExecutionSurface::CliManualStrict => RuntimeSurface::CliManualStrict, ExecutionSurface::TuiManual => RuntimeSurface::TuiManual, ExecutionSurface::TuiManualStrict => RuntimeSurface::TuiManualStrict, + ExecutionSurface::DesktopGuiManual => RuntimeSurface::DesktopGuiManual, ExecutionSurface::Ci => RuntimeSurface::Ci, ExecutionSurface::McpServer => RuntimeSurface::McpServer, ExecutionSurface::RestApi => RuntimeSurface::RestApi, @@ -103,6 +105,10 @@ mod tests { RuntimeSurface::TuiManualStrict, ExecutionSurface::TuiManualStrict, ), + ( + RuntimeSurface::DesktopGuiManual, + ExecutionSurface::DesktopGuiManual, + ), (RuntimeSurface::Ci, ExecutionSurface::Ci), (RuntimeSurface::McpServer, ExecutionSurface::McpServer), (RuntimeSurface::RestApi, ExecutionSurface::RestApi), @@ -151,7 +157,11 @@ mod tests { #[test] fn manual_surfaces_honor_override_only_for_permissive() { - let permissive = [RuntimeSurface::CliManual, RuntimeSurface::TuiManual]; + let permissive = [ + RuntimeSurface::CliManual, + RuntimeSurface::TuiManual, + RuntimeSurface::DesktopGuiManual, + ]; for rt in permissive { let exec = runtime_surface_to_execution_surface(rt.clone()).unwrap(); assert!( @@ -184,6 +194,7 @@ mod tests { RuntimeSurface::CliManualStrict, RuntimeSurface::TuiManual, RuntimeSurface::TuiManualStrict, + RuntimeSurface::DesktopGuiManual, RuntimeSurface::Ci, RuntimeSurface::McpServer, RuntimeSurface::RestApi, @@ -205,6 +216,7 @@ mod tests { ExecutionSurface::CliManualStrict, ExecutionSurface::TuiManual, ExecutionSurface::TuiManualStrict, + ExecutionSurface::DesktopGuiManual, ExecutionSurface::Ci, ExecutionSurface::McpServer, ExecutionSurface::RestApi, @@ -218,4 +230,54 @@ mod tests { assert_eq!(fwd, exec); } } + + /// The desktop GUI is a frontend, not a new policy class. It must derive + /// the same permissive manual profile as the CLI and TUI manual surfaces, + /// must honor operator overrides, and must never land on the strict side + /// of the manual/strict split. + #[test] + fn desktop_gui_is_a_manual_surface() { + let gui = runtime_surface_to_execution_surface(RuntimeSurface::DesktopGuiManual).unwrap(); + assert_eq!(gui, ExecutionSurface::DesktopGuiManual); + assert_eq!(gui.profile(), ExecutionSurface::CliManual.profile()); + assert_eq!(gui.profile(), ExecutionSurface::TuiManual.profile()); + assert!(gui.is_manual()); + assert!(gui.honors_manual_override()); + assert!(!gui.is_agent_controlled()); + assert!(!gui.requires_explicit_manifest_for_networked()); + // A GUI session is never a strict session. + assert_ne!(gui.profile(), ExecutionSurface::CliManualStrict.profile()); + assert_ne!(gui.profile(), ExecutionSurface::TuiManualStrict.profile()); + } + + /// The wire encodings of the pre-existing surfaces must not change when a + /// new surface is added. This is the snapshot that pins them. + #[test] + fn existing_surface_wire_encodings_are_unchanged() { + let expected = [ + (RuntimeSurface::CliManual, "\"CliManual\""), + (RuntimeSurface::CliManualStrict, "\"CliManualStrict\""), + (RuntimeSurface::TuiManual, "\"TuiManual\""), + (RuntimeSurface::TuiManualStrict, "\"TuiManualStrict\""), + (RuntimeSurface::Ci, "\"Ci\""), + (RuntimeSurface::McpServer, "\"McpServer\""), + (RuntimeSurface::RestApi, "\"RestApi\""), + (RuntimeSurface::GrpcApi, "\"GrpcApi\""), + (RuntimeSurface::SecurityAgent, "\"SecurityAgent\""), + (RuntimeSurface::Unknown, "\"Unknown\""), + ]; + for (surface, encoding) in expected { + assert_eq!( + serde_json::to_string(&surface).unwrap(), + encoding, + "the wire encoding of {:?} changed", + surface + ); + } + // The new surface has its own encoding, and it is distinct. + assert_eq!( + serde_json::to_string(&RuntimeSurface::DesktopGuiManual).unwrap(), + "\"DesktopGuiManual\"" + ); + } } diff --git a/crates/eggsec/tests/enforcement_matrix.rs b/crates/eggsec/tests/enforcement_matrix.rs index fb9b236e4..a9b94f8fa 100644 --- a/crates/eggsec/tests/enforcement_matrix.rs +++ b/crates/eggsec/tests/enforcement_matrix.rs @@ -3,7 +3,7 @@ //! Protects the dual-mode enforcement contract across all execution surfaces. //! Catches two categories of regression: //! -//! 1. Manual CLI/TUI becoming too strict to be useful. +//! 1. Manual CLI/TUI/GUI becoming too strict to be useful. //! 2. Agent/MCP/REST/CI becoming too permissive or honoring manual discretion. //! //! This file is the canonical cross-surface guardrail. @@ -131,10 +131,12 @@ const ALL_SURFACES: &[ExecutionSurface] = &[ ExecutionSurface::CliManualStrict, ExecutionSurface::TuiManual, ExecutionSurface::TuiManualStrict, + ExecutionSurface::DesktopGuiManual, ExecutionSurface::McpServer, ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, ExecutionSurface::RestApi, + ExecutionSurface::GrpcApi, ]; /// Automated (strict) surfaces. @@ -143,11 +145,15 @@ const AUTOMATED_SURFACES: &[ExecutionSurface] = &[ ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, ExecutionSurface::RestApi, + ExecutionSurface::GrpcApi, ]; -/// Surfaces that honor manual overrides (only CliManual and TuiManual). -const OVERRIDE_HONORING_SURFACES: &[ExecutionSurface] = - &[ExecutionSurface::CliManual, ExecutionSurface::TuiManual]; +/// Surfaces that honor manual overrides (the permissive manual surfaces). +const OVERRIDE_HONORING_SURFACES: &[ExecutionSurface] = &[ + ExecutionSurface::CliManual, + ExecutionSurface::TuiManual, + ExecutionSurface::DesktopGuiManual, +]; /// Surfaces that do NOT honor manual overrides. const NON_OVERRIDE_SURFACES: &[ExecutionSurface] = &[ @@ -157,11 +163,15 @@ const NON_OVERRIDE_SURFACES: &[ExecutionSurface] = &[ ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, ExecutionSurface::RestApi, + ExecutionSurface::GrpcApi, ]; /// Manual permissive surfaces. -const PERMISSIVE_SURFACES: &[ExecutionSurface] = - &[ExecutionSurface::CliManual, ExecutionSurface::TuiManual]; +const PERMISSIVE_SURFACES: &[ExecutionSurface] = &[ + ExecutionSurface::CliManual, + ExecutionSurface::TuiManual, + ExecutionSurface::DesktopGuiManual, +]; /// Strict/guarded surfaces (not permissive). const STRICT_SURFACES: &[ExecutionSurface] = &[ @@ -171,6 +181,7 @@ const STRICT_SURFACES: &[ExecutionSurface] = &[ ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, ExecutionSurface::RestApi, + ExecutionSurface::GrpcApi, ]; // =========================================================================== @@ -178,15 +189,15 @@ const STRICT_SURFACES: &[ExecutionSurface] = &[ // =========================================================================== #[test] -fn cli_manual_and_tui_manual_map_to_manual_permissive() { - assert_eq!( - ExecutionSurface::CliManual.profile(), - ExecutionProfile::ManualPermissive - ); - assert_eq!( - ExecutionSurface::TuiManual.profile(), - ExecutionProfile::ManualPermissive - ); +fn permissive_manual_surfaces_map_to_manual_permissive() { + for surface in OVERRIDE_HONORING_SURFACES { + assert_eq!( + surface.profile(), + ExecutionProfile::ManualPermissive, + "{}: a permissive manual surface must map to ManualPermissive", + surface + ); + } } #[test] @@ -231,12 +242,17 @@ fn rest_maps_to_strict_profile() { } #[test] -fn only_cli_tui_manual_honor_manual_overrides() { +fn grpc_maps_to_strict_profile() { + assert_eq!( + ExecutionSurface::GrpcApi.profile(), + ExecutionProfile::McpStrict + ); +} + +#[test] +fn only_permissive_manual_surfaces_honor_manual_overrides() { for surface in ALL_SURFACES { - let expected = matches!( - surface, - ExecutionSurface::CliManual | ExecutionSurface::TuiManual - ); + let expected = OVERRIDE_HONORING_SURFACES.contains(surface); assert_eq!( surface.honors_manual_override(), expected, diff --git a/crates/eggsec/tests/frontend_surface_matrix.rs b/crates/eggsec/tests/frontend_surface_matrix.rs index 6ee653d2a..d8dc57f33 100644 --- a/crates/eggsec/tests/frontend_surface_matrix.rs +++ b/crates/eggsec/tests/frontend_surface_matrix.rs @@ -837,6 +837,10 @@ fn runtime_surface_conversion_is_explicit_and_round_trippable() { RuntimeSurface::TuiManualStrict, ExecutionSurface::TuiManualStrict, ), + ( + RuntimeSurface::DesktopGuiManual, + ExecutionSurface::DesktopGuiManual, + ), (RuntimeSurface::Ci, ExecutionSurface::Ci), (RuntimeSurface::McpServer, ExecutionSurface::McpServer), (RuntimeSurface::RestApi, ExecutionSurface::RestApi), @@ -856,6 +860,39 @@ fn runtime_surface_conversion_is_explicit_and_round_trippable() { assert!(runtime_surface_to_execution_surface(RuntimeSurface::Unknown).is_err()); } +/// The desktop GUI is a manual surface: it derives the same permissive +/// profile as the CLI and TUI manual surfaces, and it never lands on the +/// strict side of the manual/strict split. +#[test] +fn desktop_gui_surface_is_manual_and_distinct() { + use eggsec::config::ExecutionSurface; + use eggsec::runtime_bridge::runtime_surface_to_execution_surface; + use eggsec_runtime::RuntimeSurface; + + let gui = runtime_surface_to_execution_surface(RuntimeSurface::DesktopGuiManual) + .expect("the desktop GUI surface must map"); + assert_eq!(gui, ExecutionSurface::DesktopGuiManual); + assert_eq!(gui.profile(), ExecutionSurface::CliManual.profile()); + assert_eq!(gui.profile(), ExecutionSurface::TuiManual.profile()); + assert!(gui.is_manual()); + assert!(gui.honors_manual_override()); + assert!(!gui.is_agent_controlled()); + assert!(!gui.requires_explicit_manifest_for_networked()); + // The GUI label must not collide with the CLI or TUI label. + assert_ne!(gui.label(), ExecutionSurface::TuiManual.label()); + assert_ne!(gui.label(), ExecutionSurface::CliManual.label()); + assert_eq!(gui.label(), "Desktop GUI manual"); + assert_eq!(format!("{gui}"), "desktop-gui-manual"); + // A strict surface must still be strict. + for strict in [ + ExecutionSurface::CliManualStrict, + ExecutionSurface::TuiManualStrict, + ] { + assert_ne!(gui.profile(), strict.profile()); + assert!(!strict.honors_manual_override()); + } +} + #[test] fn downstream_dispatch_binding_remains_intact() { // Phase 0.1 hardening must not relax engine-side validation. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 502255444..8325f81fe 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -44,7 +44,7 @@ The **command registry** (`commands/registry.rs`) provides static, inspectable m ## 2. Workspace Crate Ownership -23 workspace crates (`eggsec-nse` is external and not a member). +25 workspace crates (`eggsec-nse` is external and not a member). | Crate | Role | Policy Decisions | Execution | Frontend | Dependency-Light | Notes | |-------|------|:---:|:---:|:---:|:---:|-------| @@ -56,6 +56,7 @@ The **command registry** (`commands/registry.rs`) provides static, inspectable m | `eggsec` | Composition root | **Yes** | All domains | No | No | Central policy, orchestration, all security modules. | | `eggsec-cli` | Binary entrypoint | No | No | **Yes** | Yes | Thin wrapper: depends on `eggsec` + `eggsec-tui`. | | `eggsec-tui` | TUI frontend | No | No | **Yes** | No | 33 tabs, enforcement toggle, packaged themes. | +| `eggsec-gui` | Desktop GUI frontend | No | No | **Yes** | No | Tauri v2 desktop shell. **Daemon-only**: depends on `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and `eggsec-ui-model` — never the engine, the daemon crate, the CLI or the TUI. No outbound HTTP; buildless frontend with zero npm dependencies. | | `eggsec-nse` (external) | NSE compatibility runtime | No | Domain execution | No | Yes | [Standalone repository](https://github.com/eggstack/eggsec-nse), consumed by Eggsec as the versioned `eggsec-nse 0.2.0` crates.io release behind the optional engine `nse` feature. | | `eggsec-db-lab` | DB pentest domain | No | Domain execution | No | Yes | Postgres/MySQL/MSSQL/MongoDB/Redis checks. | | `eggsec-web-proxy` | Web proxy domain | No | Domain execution | No | Yes | MITM intercept, TLS, protocol handlers. | @@ -69,11 +70,16 @@ The **command registry** (`commands/registry.rs`) provides static, inspectable m | `eggsec-daemon-protocol` | Daemon IPC types | No | No | No | Yes | Wire DTOs for the daemon protocol. | | `eggsec-policy` | Deterministic authorization semantics | **Yes** | No | No | Yes | Data + pure algorithms only: no Tokio, no network, no filesystem. Engine bridges DNS, features, and transport. | | `eggsec-ui-model` | Frontend view DTOs | No | No | No | Yes | View model types for TUI/daemon event rendering. | +| `eggsec-frontend-client` | Frontend runtime client | No | No | No | Yes | Frontend-neutral runtime-client contract (`RuntimeClient` trait + embedded/daemon implementations). No frontend framework, no engine dependency. | | `eggsec-transport` | Scope-aware outbound HTTP contract | No | No | No | Yes | Neutral DTOs, mandatory `NetworkAuthority`, recording fake. No concrete clients. | | `eggsec-transport-eggfetch` | `HttpTransport` over `eggfetch-core` | No | No | No | Yes | Approved-IP pinning, manual authorized redirects. No production consumers yet. | | `eggsec-python` | Python bindings | No | No | No | Yes | PyO3/maturin. Depends on `eggsec` + `eggsec-core`. Engine/AsyncEngine entry points, scope enforcement, OperationRegistry, EnforcementContext, event protocol, callbacks/sinks, domain registry, 1.0 readiness. | -**Dependency direction**: Leaf crates (`eggsec-core`, `eggsec-report-model`, `eggsec-output`, `eggsec-agent`, `eggsec-policy`) have no engine/runtime dependencies (`eggsec-report-model` depends only on `eggsec-core`; `eggsec-output` renders over the model, never the reverse). The main `eggsec` crate is the composition root. `eggsec-cli` and `eggsec-tui` are the only frontends. The workspace root is a virtual manifest — install with `cargo install --path crates/eggsec-cli`. +**Dependency direction**: Leaf crates (`eggsec-core`, `eggsec-report-model`, `eggsec-output`, `eggsec-agent`, `eggsec-policy`) have no engine/runtime dependencies (`eggsec-report-model` depends only on `eggsec-core`; `eggsec-output` renders over the model, never the reverse). The main `eggsec` crate is the composition root. `eggsec-cli` and `eggsec-tui` are the only frontends that link the engine. The workspace root is a virtual manifest — install with `cargo install --path crates/eggsec-cli`. + +`eggsec-frontend-client` is the frontend-neutral runtime-client contract (`RuntimeClient` trait plus the embedded and daemon implementations). It depends on `eggsec-runtime` + `eggsec-daemon-protocol` and on **no frontend framework** (no `ratatui`/`crossterm`) and **not on the engine** — so a new frontend can reuse the runtime contract without inheriting the terminal UI or the composition root. + +`eggsec-gui` is the desktop GUI: a Tauri v2 shell that is a **frontend without an engine edge**. It depends on `eggsec-frontend-client` + `eggsec-runtime` + `eggsec-daemon-protocol` + `eggsec-ui-model` and on nothing else — it may not name `eggsec`, `eggsec-daemon`, `eggsec-cli` or `eggsec-tui`, and it performs no outbound HTTP: every engine request travels over the daemon's Unix socket. That is what keeps the desktop GUI from becoming a second composition root, and it is enforced by the architecture guards (Checks 155–158). See `architecture/desktop_gui.md`. The knowledge-corpus leaves (`eggsec-service-db`, `eggsec-secrets`, `eggsec-payloads`, `eggsec-udp-scan`) are near-empty-dependency data crates reached only through engine `pub use` facades. The seam is one-directional: **the corpus owns data, the engine owns I/O** — the live probers stay engine-side even though their `get_payloads()` are pure data. See `architecture/knowledge_corpus.md`. @@ -83,7 +89,7 @@ The knowledge-corpus leaves (`eggsec-service-db`, `eggsec-secrets`, `eggsec-payl | Type | Canonical Location | Purpose | |------|--------------------|---------| -| `ExecutionSurface` | `eggsec-policy/src/policy.rs` | Caller origin identity. 9 variants: `CliManual`, `TuiManual`, `CliManualStrict`, `TuiManualStrict`, `McpServer`, `SecurityAgent`, `Ci`, `RestApi`, `GrpcApi`. | +| `ExecutionSurface` | `eggsec-policy/src/policy.rs` | Caller origin identity. 10 variants: `CliManual`, `TuiManual`, `DesktopGuiManual`, `CliManualStrict`, `TuiManualStrict`, `McpServer`, `SecurityAgent`, `Ci`, `RestApi`, `GrpcApi`. | | `ExecutionProfile` | `eggsec-policy/src/policy.rs` | Trust boundary. 5 variants: `ManualPermissive`, `ManualGuarded`, `CiStrict`, `McpStrict`, `AgentStrict`. | | `OperationRisk` | `eggsec-policy/src/policy.rs` | Risk tier ordering. 15 variants from `Passive` to `AgentAutonomous`. | | `OperationMode` | `eggsec-policy/src/policy.rs` | Semantic mode: `StandardAssessment`, `DefenseLab`, `HazardousLab`. | @@ -118,6 +124,7 @@ The knowledge-corpus leaves (`eggsec-service-db`, `eggsec-secrets`, `eggsec-payl |-----------------|-----------------|:---:|:---:| | `CliManual` | `ManualPermissive` | Yes | No | | `TuiManual` | `ManualPermissive` | Yes | No | +| `DesktopGuiManual` | `ManualPermissive` | Yes | No | | `CliManualStrict` | `ManualGuarded` | No | No | | `TuiManualStrict` | `ManualGuarded` | No | No | | `McpServer` | `McpStrict` | No | Yes | @@ -371,6 +378,7 @@ operation. | MCP | `tool/protocol/mcp/handlers/server.rs` | McpStrict | No | | Agent | `agent/mod.rs` (via `agent::services::AgentExecutionService`) | AgentStrict | No | | TUI | `eggsec-tui/src/app/` | ManualPermissive/Guarded | Yes | +| Desktop GUI | Engine runtime bridge (`eggsec-frontend-client` → `runtime_bridge`) | ManualPermissive | Yes | | CI | `commands/handlers/ci.rs` | CiStrict | No — no dispatch path at all | Strict surfaces reach `ToolDispatcher` only through `EnforcedDispatcher`. diff --git a/docs/ARCHITECTURE_INVARIANTS.md b/docs/ARCHITECTURE_INVARIANTS.md index 23f05d6d5..537468962 100644 --- a/docs/ARCHITECTURE_INVARIANTS.md +++ b/docs/ARCHITECTURE_INVARIANTS.md @@ -6,7 +6,7 @@ Normative rules that all code in the eggsec workspace must preserve. Violations 1. **Centralized authorization**: All side-effecting operations must have an `OperationDescriptor` evaluated by `EnforcementContext::evaluate()` before execution. No handler may execute a tool without passing through enforcement. -2. **No automated overrides**: Automated surfaces (`McpStrict`, `AgentStrict`, `CiStrict`) must never honor `ManualOverride`. Only `CliManual` and `TuiManual` surfaces honor overrides. +2. **No automated overrides**: Automated surfaces (`McpStrict`, `AgentStrict`, `CiStrict`) must never honor `ManualOverride`. Only `CliManual`, `TuiManual`, and `DesktopGuiManual` surfaces honor overrides. 3. **Fail-closed strict**: Strict surfaces (`McpStrict`, `AgentStrict`, `CiStrict`) must fail closed on `Warn`, `RequireConfirmation`, or `Deny`. Only `Allow` permits dispatch. @@ -93,3 +93,13 @@ Normative rules that all code in the eggsec workspace must preserve. Violations 38. **Request surface is normalized to session surface**: The executor must derive its `ExecutionSurface` from `RuntimeExecutionContext` (session-bound), not from `RunRequest.surface`. Client-submitted surface is informational only and must not influence enforcement decisions or persisted state. 39. **Unsupported task kinds are rejected before dispatch**: If the daemon's runtime capabilities do not include a submitted `TaskKind`, the task must be rejected during submission (before dispatch) rather than silently dropped or returned as an unexpected runtime error. + +## Desktop GUI Invariants + +40. **The desktop GUI is daemon-only**: `eggsec-gui` must not depend on `eggsec` (the engine), `eggsec-daemon`, `eggsec-cli` or `eggsec-tui`, and must not import them from any source file. Its only workspace dependencies are `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol` and `eggsec-ui-model`. All engine traffic travels over the daemon's Unix socket; the GUI performs no outbound HTTP and declares no TLS stack of its own. Enforced by architecture guards 155–157. + +41. **The published schema is descriptive, never authoritative**: The operation/request schema the daemon publishes (`DescribeOperations`) is a *description* of what a request looks like, not a source of authorization or of the truth about whether a task may run. The GUI may use it to generate a form and to give advisory type/bounds feedback, and it may deserialize the assembled request into the same `RunRequest` the engine will deserialize — but the engine's own validation remains the authority that decides whether a task runs. A published schema must never encode a per-operation policy rule, and no frontend may treat "the schema allows it" as "it is allowed". + +42. **The GUI's form is generated, not written**: The GUI must contain no per-operation code — no `match` or `switch` over the published task-kind variant names, and no hand-written table of operation names or fields. A task kind the engine has not published yet must get a form with no GUI change. Enforced by architecture guard 159. + +43. **The GUI's retention is bounded**: The GUI must cap the log lines it retains per task and the log lines it forwards per flush, and must report what it drops rather than discarding silently. Unbounded retention is a disqualifying defect, not a tuning problem. Enforced by architecture guard 160. diff --git a/docs/CI_ARCHITECTURE_GUARDS.md b/docs/CI_ARCHITECTURE_GUARDS.md index ed059a0ef..a81daf22d 100644 --- a/docs/CI_ARCHITECTURE_GUARDS.md +++ b/docs/CI_ARCHITECTURE_GUARDS.md @@ -133,6 +133,7 @@ Static grep checks in `scripts/check-architecture-guards.sh` (requires ripgrep) - `eggsec-output` has no reverse dependencies on engine or runtime. - `eggsec-daemon` has no TUI dependencies; engine dependency is optional/feature-gated. - `eggsec-daemon` transport crates are feature-gated optional dependencies. +- `eggsec-frontend-client` has no frontend framework (`ratatui`/`crossterm`) and no engine dependency (guard Check 153). - Engine crate has no TUI or daemon dependencies. - CLI TUI dependency is feature-gated. - TUI has no canonical `TaskConfig`/`TaskResult` enums or `match task_kind` execution dispatchers. @@ -205,6 +206,20 @@ Static grep checks in `scripts/check-architecture-guards.sh` (requires ripgrep) - Worker capacity stays truthful (Check 141): `crates/eggsec/src/distributed/worker.rs` carries `CapacityTracker` with `try_reserve`/`request_size` and the zero-concurrency rejection; the fixed `mpsc::channel::(100)` buffer (which let queued work exceed budget) is gone. - Load-test prototype stays compiled once per run (Check 142): `crates/eggsec/src/loadtest/executor.rs` dispatches `prototype.clone()` in the worker loop with no `self.template.scoped_request` per-request rebuild. +### Desktop-GUI + Operation-Schema Publication Invariants (2026-10-23, guards Checks 151–154) +- The published schema stays off the authorization path (Check 151): the derived schema in `eggsec-runtime` (`schema` feature) and the daemon's `DescribeOperations` publication are descriptive only. The engine's dispatch/bridge halves, the policy kernel, and the engine's config/policy/scope files may not reach for `schemars`, `eggsec_runtime::schema`, `describe_operations`, or `DescribeOperations`, and neither `crates/eggsec/Cargo.toml` nor `crates/eggsec-policy/Cargo.toml` may gain a `schemars` dependency — so the schema is unreachable from an enforcement path by construction. +- No hand-written parameter table (Check 152): only `crates/eggsec-runtime/src/request.rs` owns the canonical request DTOs. No other frontend-neutral crate (`eggsec-core`, `eggsec-tool-core`, `eggsec-output`, `eggsec-ui-model`, `eggsec-report-model`, `eggsec-daemon-protocol`, `eggsec-policy`, `eggsec-frontend-client`) may define a `*Params` struct. +- The frontend-client crate stays framework-free (Check 153): `crates/eggsec-frontend-client/Cargo.toml` must exist and must not reference `eggsec`, `eggsec-tui`, `ratatui`, or `crossterm`; `crates/eggsec-frontend-client/src` must not reference `ratatui`, `crossterm`, `eggsec_tui`, or `eggsec::`. +- The desktop GUI stays a manual surface (Check 154): both `RuntimeSurface::DesktopGuiManual` and `ExecutionSurface::DesktopGuiManual` must exist, `runtime_bridge/surface.rs` must map the variant in **both** directions, and the variant must stay on the manual side of `honors_manual_override()` and `is_agent_controlled()`. + +### Desktop-GUI Shell Invariants (2026-10-23, guards Checks 155–160) +- The GUI crate links no engine (Check 155): `crates/eggsec-gui/Cargo.toml` must not name `eggsec`, `eggsec-daemon`, `eggsec-cli`, or `eggsec-tui`, and no file under `crates/eggsec-gui/src/` may import them. `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol`, and `eggsec-ui-model` are the allowed set. This is the `ADR-0007` daemon-only boundary: the desktop GUI reaches the engine only through the daemon's Unix socket, so it can never become a second composition root. +- The shell framework stays inside the GUI crate (Check 156): no crate other than `crates/eggsec-gui` may declare a `tauri` dependency. The root `Cargo.toml`'s `[workspace.dependencies]` version pins are allowed — they are the single place the exact Tauri versions are declared. +- The GUI declares no second TLS stack (Check 157): `crates/eggsec-gui/Cargo.toml` must not enable `rustls-tls` or `native-tls`, and must not depend on `reqwest`, `rustls`, or `native-tls` directly. The GUI performs no outbound HTTP, so those crates stay out of its closure entirely and the workspace's ring-only TLS invariant holds with no exception. +- The GUI's CSP forbids remote origins (Check 158): `crates/eggsec-gui/tauri.conf.json`'s `app.security.csp` must contain no wildcard source, and no `*` in `connect-src`, `script-src`, or `default-src`. +- The GUI has no per-operation form code (Check 159): the guard reads the task-kind variant names from `crates/eggsec-runtime/src/request.rs` and fails if the GUI's Rust sources or its frontend name any of them. The form must be generated from the published schema, so a task kind the engine has not published yet gets a form with no GUI change, and no hand-written table of operation names may creep in. +- The GUI retains no unbounded event log (Check 160): `crates/eggsec-gui/src/tasks.rs` must declare both the per-task retention cap (`MAX_LOG_LINES_PER_TASK`) and the forward-flush cap (`MAX_LOG_LINES_PER_FLUSH`), and the `LogRing` struct must be a capped ring rather than a `Vec` that grows without bound. Unbounded retention is a disqualifying defect, not a tuning problem. + ### NSE Subsystem Invariants - The standalone [eggsec-nse CI](https://github.com/eggstack/eggsec-nse/actions) owns runtime-internal checks: resolver-only script/module loading, per-run `NseRunReport.libraries`, profile/executor construction, library registry consistency, capability wrappers, and runtime corpus assertions. - Eggsec Checks 143–146 enforce canonical engine/Python dispatch, no local re-vendoring, the released crates.io version shared by `crates/eggsec/Cargo.toml` and `Cargo.lock`, a single direct runtime consumer, the `eggsec::nse` facade, TUI/Python feature forwarding, and engine ownership of `nse_bridge`/`nse_http_capability`. diff --git a/docs/DAEMON_PARITY.md b/docs/DAEMON_PARITY.md index d098c528b..8ec8b8f75 100644 --- a/docs/DAEMON_PARITY.md +++ b/docs/DAEMON_PARITY.md @@ -30,7 +30,8 @@ Wire protocol version: `DAEMON_PROTOCOL_VERSION = 2` (v2 adds durable | Timeouts | Caller-side | `Subscribe` reads and HTTP handlers are bounded; persistence fan-out uses `PERSISTENCE_TASK_TIMEOUT` | Same posture, daemon-side bounds | | Structured errors | `OperationError` DTOs | `ServerMessage::Error { code: ErrorCode, message }`; `TaskFailed` carries `RuntimeErrorInfo` | Same structure, transport envelope differs | | Artifact references/retrieval | In-process `Artifact` handles | `ArtifactRef { id, kind, path, mime_type, summary }` inside outcomes and snapshots; metadata survives the same lifecycle as the task result | Same metadata; bytes stay daemon-side | -| Capability discovery/version negotiation | Feature flags at build time | `Capabilities` → `DaemonCapabilities { runtime, transports }`; `Health` carries `protocol_version`; clients must check it before sending commands | Daemon superset | +| Capability discovery/version negotiation | Feature flags at build time | `Capabilities` → `DaemonCapabilities { runtime, transports, operation_schema }`; `Health` carries `protocol_version`; clients must check it before sending commands | Daemon superset | +| Operation/schema discovery | No daemon — the frontend builds its forms from static knowledge | `DescribeOperations` → `Operations { operations: DescribeOperationsResponse }`: the canonical operation catalog plus the derived request schema, read-only | Daemon superset; a client must degrade to a static form set when `operation_schema` is `false` or the daemon answers `UnsupportedCommand` | | Ownership/RBAC | Single caller | `ClientRole` (Owner/Controller/Observer/Approver) × `CommandPermission`; `GetTaskResult` requires `Observer`; ownership persists across restarts | Daemon superset | ## Result retrieval and reconnect/replay (WS5) diff --git a/docs/ENFORCEMENT_MODES.md b/docs/ENFORCEMENT_MODES.md index c575d8e2a..563ac22d7 100644 --- a/docs/ENFORCEMENT_MODES.md +++ b/docs/ENFORCEMENT_MODES.md @@ -2,7 +2,7 @@ Eggsec intentionally supports two usage families with distinct enforcement postures: -- **Manual operator posture** (CLI/TUI): Human-directed security assessment. Operators may proceed through warnings and explicit confirmations where appropriate. This mode is designed to remain productive and should not inherit agent-grade strictness by default. +- **Manual operator posture** (CLI/TUI/desktop GUI): Human-directed security assessment. Operators may proceed through warnings and explicit confirmations where appropriate. This mode is designed to remain productive and should not inherit agent-grade strictness by default. - **Automated agent posture** (MCP, security agent, CI, REST, gRPC): Programmatic noninteractive execution. Strict, explicitly scoped, non-overridable. Manual overrides are never honored. The contract below is the source of truth for how enforcement behaves per execution surface. All later implementation phases must follow this contract to prevent drift in either direction: over-hardening manual use, or under-hardening agent use. @@ -11,7 +11,7 @@ The contract below is the source of truth for how enforcement behaves per execut | Term | Definition | |------|------------| -| **Execution surface** | Where the request originates. `ExecutionSurface` has 9 variants: `CliManual`, `TuiManual`, `CliManualStrict`, `TuiManualStrict`, `McpServer`, `SecurityAgent`, `Ci`, `RestApi`, `GrpcApi`. | +| **Execution surface** | Where the request originates. `ExecutionSurface` has 10 variants: `CliManual`, `TuiManual`, `DesktopGuiManual`, `CliManualStrict`, `TuiManualStrict`, `McpServer`, `SecurityAgent`, `Ci`, `RestApi`, `GrpcApi`. | | **Execution profile** | Enforcement behavior, represented by `ExecutionProfile` (`ManualPermissive`, `ManualGuarded`, `CiStrict`, `McpStrict`, `AgentStrict`). | | **Manual permissive** | Human-directed default mode (`ManualPermissive`). Warnings and confirmation prompts are available; operator may override low-risk classes. | | **Manual guarded** | Strict human mode (`ManualGuarded`). Equivalent to CLI `--strict-scope` and future TUI guarded toggle. No discretion path. | @@ -30,6 +30,7 @@ The contract below is the source of truth for how enforcement behaves per execut | CLI `--strict-scope` | Manual guarded | `ManualGuarded` | Yes (networked operations) | No | No (treated as deny) | No | No (single evaluation) | | TUI default | Manual permissive | `ManualPermissive` | No (warnings for safe scope misses) | Yes | Yes (with matching `ManualOverride`) | Yes | No (single evaluation) | | TUI guarded | Manual guarded | `ManualGuarded` | Yes (networked operations) | No | No (treated as deny) | No | No (single evaluation) | +| Desktop GUI | Manual permissive | `ManualPermissive` | No (warnings for safe scope misses) | Yes | Yes (with matching `ManualOverride`) | Yes | No (single evaluation) | | MCP server | Agent strict | `McpStrict` | Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes | | Security agent | Agent strict | `AgentStrict` | Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes | | CI | Agent strict | `CiStrict` | Yes (target/networked operations) | No (treated as deny) | No (treated as deny) | No | No (single evaluation) | @@ -37,7 +38,13 @@ The contract below is the source of truth for how enforcement behaves per execut | gRPC API | Agent strict | `McpStrict` | Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes | | Daemon HTTP | Agent strict | `McpStrict` | Yes (networked operations) | No (treated as deny) | No (treated as deny) | No | Yes | -**Key invariant**: `ManualPermissive` behavior must not bleed into MCP, security agent, CI, REST, or gRPC. Agent strict behavior must not become the default for normal CLI/TUI manual use. +**Key invariant**: `ManualPermissive` behavior must not bleed into MCP, security agent, CI, REST, or gRPC. Agent strict behavior must not become the default for normal CLI/TUI/desktop-GUI manual use. + +**Desktop GUI posture**: the desktop GUI is a **manual** surface — a peer of the CLI and TUI default postures, not a new policy class. `ExecutionSurface::DesktopGuiManual` derives the same `ManualPermissive` profile, honors operator overrides, and is never agent-controlled. There is no strict GUI variant, and the GUI reuses the existing `manual_exposable` exposure flag rather than adding a second exposure flag, so it introduces no new policy semantics. + +**Desktop GUI posture, cross-checked against the daemon**: the GUI's session carries the runtime surface `RuntimeSurface::DesktopGuiManual`, and the daemon's manual-approval arm in `check_permission` lists `DesktopGuiManual` alongside `TuiManual` and `CliManual` (`crates/eggsec-daemon-protocol/src/client_registry.rs:191-204`). That is what keeps the daemon's RBAC matrix and `eggsec-policy`'s classification in agreement about which surfaces are manual — a GUI session that the policy crate treats as manual but the daemon treats as strict would be a silent divergence. + +The cross-check is about *classification*, not about approvals being available. `ApprovePolicy` remains unwired: the daemon answers it with `ErrorCode::Unsupported`, so no approval is granted either way. The GUI therefore handles `PolicyDecisionRequired` defensively and offers **no approval affordance** — there is no button that could do anything. The GUI's own enforcement path is the daemon's: it never evaluates policy, never resolves scope, and never dispatches an operation itself. See `architecture/desktop_gui.md`. **REST enforcement specifics**: REST API now constructs `EnforcementContext::for_surface(ExecutionSurface::RestApi, ...)` and dispatches every tool call through `enforcement.evaluate()` before execution. Only `EnforcementOutcome::Allow` permits dispatch. `Warn`, `RequireConfirmation`, and `Deny` all result in HTTP 403 Forbidden with a structured `RestPolicyErrorResponse` (code: `POLICY_DENIED`, includes serialized `PolicyDecision`). REST is noninteractive and programmatic — warning-class ambiguity must not dispatch. Metadata `rest_exposable` flags are enforced before policy evaluation; non-exposed tools fail closed. `RestState` carries `EnforcementContext` instead of `Option`. @@ -108,7 +115,7 @@ The following conditions produce hard denial and must **never** be converted to These invariants hold across all execution paths: 1. **Manual permissive isolation**: Manual permissive behavior must not bleed into MCP, security agent, CI, REST, or gRPC. -2. **Agent strict isolation**: Agent strict behavior must not become the default for normal CLI/TUI manual use. +2. **Agent strict isolation**: Agent strict behavior must not become the default for normal CLI/TUI/desktop-GUI manual use. 3. **Override scope**: Manual override flags are only honored in `ManualPermissive` contexts. 4. **Scope provenance**: Scope provenance for automated networked execution must come from `LoadedScope`, not raw `Scope`. 5. **Shared evaluation**: Every dispatch path must eventually flow through `EnforcementContext::evaluate()`. @@ -192,12 +199,12 @@ Key invariants locked by tests: Phase 8 added a comprehensive enforcement matrix test suite (`crates/eggsec/tests/enforcement_matrix.rs`) that systematically tests all execution surfaces against scope states, risk tiers, capabilities, and override handling. The matrix protects the dual-mode contract by catching: -1. Manual CLI/TUI becoming too strict to be useful. +1. Manual CLI/TUI/GUI becoming too strict to be useful. 2. Agent/MCP/REST/CI becoming too permissive or honoring manual discretion. -**172 tests** covering: +**173 tests** covering: -- **Surface mapping invariants**: All 9 `ExecutionSurface` variants map to correct `ExecutionProfile`. +- **Surface mapping invariants**: `ExecutionSurface` variants map to the correct `ExecutionProfile` (10 variants in the enum; the matrix's own surface list covers all 10). - **Manual permissive invariants**: Safe ops allow, scope misses require confirmation, `assume_yes` is narrow, denied capabilities hard-deny, missing features hard-deny. - **Manual guarded invariants**: Scope misses deny, overrides ignored, high-risk with policy allows. - **MCP invariants**: Missing scope denies, no confirmation path, baseline capabilities allowed, non-baseline requires explicit allow. @@ -238,7 +245,7 @@ Phase 2 verified and hardened the enforcement invariants established in earlier Phase 2 confirmed that all acceptance criteria from the Phase 2 plan are satisfied by existing test infrastructure: -- **Enforcement matrix**: 172 tests in `enforcement_matrix.rs` covering manual permissive, manual guarded, and strict automated surfaces. +- **Enforcement matrix**: 173 tests in `enforcement_matrix.rs` covering manual permissive, manual guarded, and strict automated surfaces. - **Override isolation**: Automated surfaces cannot use manual override flags to proceed. - **Scope provenance**: Automated operations requiring explicit scope fail without explicit manifest provenance. - **Approval token mismatch**: `dispatch_checked` rejects tool mismatch, target mismatch, and allows alias match. @@ -269,7 +276,7 @@ Phase 12 hardened enforcement from convention (call sites expected to evaluate f ### Approval Methods - `EnforcementContext::approve(surface, descriptor)` - Strict: only `Allow` produces a token. `Warn`, `RequireConfirmation`, and `Deny` all fail with `EnforcementError`. Used by REST, MCP, Agent, CI. -- `EnforcementContext::approve_manual(surface, descriptor, manual_override)` - Manual permissive: supports `Warn` (approved with warning) and `RequireConfirmation` when matching override flags are present. Strict/automated surfaces reject overrides. Used by CLI/TUI. +- `EnforcementContext::approve_manual(surface, descriptor, manual_override)` - Manual permissive: supports `Warn` (approved with warning) and `RequireConfirmation` when matching override flags are present. Strict/automated surfaces reject overrides. Used by CLI/TUI/desktop GUI. ### Dispatch Flow @@ -305,7 +312,7 @@ Every meaningful enforcement decision produces a normalized `EnforcementAuditEve - `event_id`: UUID v4 per decision - `timestamp`: UTC timestamp -- `surface`: `ExecutionSurface` (CliManual, TuiManual, CliManualStrict, TuiManualStrict, McpServer, SecurityAgent, Ci, RestApi, GrpcApi) +- `surface`: `ExecutionSurface` (CliManual, TuiManual, DesktopGuiManual, CliManualStrict, TuiManualStrict, McpServer, SecurityAgent, Ci, RestApi, GrpcApi) - `profile`: `ExecutionProfile` (ManualPermissive, ManualGuarded, McpStrict, AgentStrict, CiStrict) - `operation_id`: canonical operation name - `target`: optional target string diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 83c1bc5ce..ae26bb456 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -37,6 +37,16 @@ bash scripts/check-architecture-guards.sh The package-level test commands automatically include all integration tests. Newly added tests run without Makefile maintenance. No `cargo-nextest` is required. Any pull request touching Rust source, workspace configuration, or architecture documentation must pass all of these checks locally before pushing. +The desktop GUI (`eggsec-gui`) is covered in two places. Its **no-shell** profile is already inside `cargo check --workspace --no-default-features` — that profile needs no platform webview SDK. Its **shell** profile adds one gated line to `make check`, one to `make clippy`, and one to `make check-msrv`: + +```bash +cargo check -p eggsec-gui --features shell # in `make check` +cargo clippy -p eggsec-gui --features shell -- -D warnings # in `make clippy` +cargo +1.89 check -p eggsec-gui --features shell # in `make check-msrv` +``` + +Each of those three runs through the `GUI_SHELL_GATE` macro, which **SKIPs with the reason named** when the platform webview prerequisite is absent. See [Desktop GUI platform prerequisites](#desktop-gui-platform-prerequisites). `make check-gui` is the ungated escape hatch for the same two commands. + ### Defect classes covered | Command | Defect class | Why merge-time | @@ -50,6 +60,7 @@ The package-level test commands automatically include all integration tests. New | `cargo test -p eggsec-transport-eggfetch --tests` | Adapter parity/adversarial regressions (67 tests: 52 parity + 6 mapping unit + 5 H2-local + 4 SOCKS5-local) | Proves approved-IP pinning, authorized redirects, TLS/timeout mapping without production wiring | | `cargo test -p eggsec-output --tests` | Report rendering/conversion regressions | Output crate is leaf; distinct defect class | | `cargo test -p eggsec-report-model --tests` | Report contract roundtrip | Model crate is leaf; JSON shape is the cross-domain contract | +| `cargo check -p eggsec-gui --features shell` (gated) | Desktop GUI shell-profile regressions | The GUI's shell profile needs the platform webview SDK; the gate SKIPs with the reason named when it is absent | | `bash scripts/check-architecture-guards.sh` | Architecture drift (dependency boundaries, stale terminology, bypass patterns) | Static grep checks catch regressions not covered by types/tests | ## Mandatory Python contributor contract @@ -88,6 +99,46 @@ vs live commands, expected skips, and release-gating. Contributors generally need local platform testing only for platform-specific changes. +### Desktop GUI platform prerequisites + +The desktop GUI crate (`eggsec-gui`) has two build profiles, and they have +different prerequisites: + +| Profile | Command | Prerequisites | Where it runs | +|---------|---------|---------------|---------------| +| No shell | `cargo check -p eggsec-gui --no-default-features` | None beyond the toolchain | Inside `cargo check --workspace --no-default-features` — already mandatory, every PR | +| Shell (`shell` feature) | `cargo check -p eggsec-gui --features shell`, `cargo clippy -p eggsec-gui --features shell -- -D warnings` | The platform webview development packages (Linux: `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, `librsvg2-dev`, `patchelf`, `pkg-config`; macOS/Windows: the system webview) | Gated lines in `make check`, `make clippy`, and `make check-msrv`; ungated via `make check-gui` | + +### Prerequisite-skip semantics + +The three gated shell-profile lines run through the Makefile's `GUI_SHELL_GATE` +macro, which follows the discipline of `scripts/check-features-individual.sh`: + +- **Prerequisite absent** → the command is **SKIPped** and the reason is named + on the output line. The gate succeeds; the check does not run. On Linux the + gate probes `pkg-config` for `webkit2gtk-4.1` (or `webkit2gtk-4.0`); on + macOS and Windows the system webview is always present, so the gate always + runs the command. +- **Prerequisite present but the build is broken** → a hard **FAIL**. The build + error is never swallowed by the gate. + +A SKIP is not a pass. The shell profile must still be green wherever the +prerequisite is available — which is why CI installs the Linux packages on the +jobs that run these lines. + +`make check-gui` is the **ungated** escape hatch: it always runs the shell +profile's check and clippy, and reports cargo's own error rather than a gate +verdict. Use it when you have the prerequisite installed and want the real +compiler output. + +The GUI's Tauri version pins are exact (`=`), not carets: the next lines up +declare MSRV 1.90, above this workspace's 1.89 floor, and `tauri` declares its +runtime and utils dependencies with caret requirements — so without the direct +exact pins a `cargo update` would float the closure onto the 1.90 line and +break `make check-msrv`. `make check-msrv` therefore covers the GUI's shell +profile under the declared MSRV (`cargo +1.89 check -p eggsec-gui --features +shell`), behind the same gate. See `architecture/desktop_gui.md`. + ## Code MSRV vs release-tool Cargo The declared code MSRV (1.89) is the minimum Rust compiler version for building @@ -216,6 +267,7 @@ See [docs/RELEASING.md](RELEASING.md) for the full procedure. | `make fmt` | Format check | Every PR/push | | `make check-no-default` | No-default-features build | Every PR/push (part of `make check`) | | `make check-msrv` | MSRV compile check | Deep checks only (requires `rustup toolchain install 1.89`) | +| `make check-gui` | Desktop GUI shell-profile check + clippy, **ungated** | Desktop GUI changes; reports cargo's own error rather than a gate verdict | | `make check-feature-profiles` | Representative feature profiles | Pre-release | | `make release-check` | Release validation (no publication) | Pre-release | | `make test-feature-matrix` | Feature metadata validation | Every PR/push (standalone target; `make check` covers the same ground via `--tests`) | diff --git a/plans/000-long-term-specification.md b/plans/000-long-term-specification.md index 184563b7a..9876a6bd9 100644 --- a/plans/000-long-term-specification.md +++ b/plans/000-long-term-specification.md @@ -13,15 +13,17 @@ The keywords MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, and MAY are normative ## 1. Product definition -Eggsec is a Rust-native, scope-enforced security assessment and defense-validation engine with multiple frontends (CLI, TUI, REST, MCP, gRPC, Agent), centralized policy enforcement, and domain execution crates. The engine crate `eggsec` is lib-only (no binary); the binary shell is `eggsec-cli`. +Eggsec is a Rust-native, scope-enforced security assessment and defense-validation engine with multiple frontends (CLI, TUI, desktop GUI, REST, MCP, gRPC, Agent), centralized policy enforcement, and domain execution crates. The engine crate `eggsec` is lib-only (no binary); the binary shell is `eggsec-cli`. The same enforcement and dispatch architecture MUST support all surfaces without creating separate products: ```text -CLI / TUI (manual) ── permissive profile, operator overrides allowed +CLI / TUI / desktop GUI (manual) ── permissive profile, operator overrides allowed REST / MCP / agent / CI (strict) ── no overrides, fail closed ``` +The desktop GUI is a **frontend**, not a second product: it reaches the engine through the same daemon protocol and the same enforcement gate as every other surface, and it MUST NOT introduce a second authorization path. + Manual surfaces evaluate through `EnforcementContext` with operator overrides permitted. Strict surfaces evaluate through the same context with no overrides and dispatch only on `Allow`. ## 2. Primary product goals @@ -60,7 +62,7 @@ These invariants MUST hold across all releases and implementation strategies: ## 5. Crate ownership -The workspace has 20 crates (see `architecture/overview.md` for the verified table). Durable ownership rules: +The workspace has 25 crates (see `architecture/overview.md` for the verified table). Durable ownership rules: - `eggsec-core`: shared primitives only. Zero internal deps. - `eggsec-tool-core`: protocol-neutral tool DTOs. No auth methods. @@ -71,6 +73,8 @@ The workspace has 20 crates (see `architecture/overview.md` for the verified tab - `eggsec-transport-eggfetch`: `HttpTransport` over published `eggfetch-core`. The engine owns the adapter; policy never depends on transport. - `eggsec-db-lab`, `eggsec-web-proxy`, `eggsec-mobile-lab`, `eggsec-nse`: domain crates. They MUST NOT authorize — the caller enforces. - `eggsec-runtime`, `eggsec-daemon`, `eggsec-daemon-protocol`, `eggsec-ui-model`: task lifecycle, session host, IPC types, view DTOs. `eggsec-daemon` default deps are `eggsec-runtime` + `eggsec-daemon-protocol` only. +- `eggsec-frontend-client`: the frontend-neutral runtime-client contract shared by every interactive frontend. It depends on `eggsec-runtime` + `eggsec-daemon-protocol` only — no frontend framework and not the engine — so a second frontend can reuse the contract without inheriting a TUI. It is not an enforcement surface. Authorized by `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md`. +- `eggsec-gui`: desktop GUI frontend. A leaf **application** crate (not a published library) that reaches the engine only through the daemon protocol. It owns presentation, interaction, and client-side adaptation — no authorization, dispatch, scope resolution, or operation semantics. It depends on `eggsec-frontend-client`, `eggsec-runtime`, `eggsec-daemon-protocol`, and `eggsec-ui-model` only; it MUST NOT link the engine, the daemon, the CLI, or the TUI, and it performs no outbound HTTP — all engine traffic goes over the daemon's Unix socket. Its shell framework (Tauri v2, pinned to the 2.11.x line by exact requirements so the closure stays on the workspace's MSRV) is confined to this crate. The engine, daemon, and runtime crates MUST NOT depend on it. Authorized by `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` and `plans/adrs/ADR-0009-gui-shell-technology-selection.md`; roadmap `plans/subsystems/desktop-gui-frontend-roadmap.md`. - `eggsec-agent`: coordination (registry, scheduler, lifecycle, cron). `eggsec-python`: PyO3/maturin bindings. ## 6. Dispatch, runtime, and wire identity @@ -106,6 +110,7 @@ The workspace has 20 crates (see `architecture/overview.md` for the verified tab ## 10. Frontend rules - TUI: use `.get(i)` not `chunks[i]`; input/nav handlers check `!self.is_running()`; `reset()` clears all state; no `println!/eprintln!/print!/eprint!/dbg!` outside `#[cfg(test)]` in production `eggsec-tui`; recoverable errors go through notification/per-tab-error/popup state; single terminal writer; `copy-cli` emits only flags the real Clap tree accepts; fuzz HTTP-session flag is `--http-session`; `TerminalSession` owns terminal setup/teardown with idempotent cleanup + silent `Drop` fallback; daemon sync paths reuse the ambient runtime via `runner::block_on_ambient` (never nested `Runtime::new`); no `Stdio::inherit()` in `eggsec-tui`. +- Desktop GUI: it MUST NOT link the engine crate or import `EnforcementContext`, `EnforcedDispatcher`, `Scope`, or `tool.execute()`; it MUST NOT construct an `ApprovedExecution` bundle; it MUST NOT perform outbound HTTP to remote hosts — all engine traffic goes through the daemon over its local transport; its local transport MUST be loopback-bound, and its content-security policy MUST forbid remote origins; it MUST NOT persist credentials in its own state or logs; it MUST NOT hold authoritative task state (the daemon owns truth, and a GUI restart re-attaches rather than restoring); and its shell framework MUST NOT appear outside the GUI crate. ## 11. Acceptance criteria diff --git a/plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md b/plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md new file mode 100644 index 000000000..789452f98 --- /dev/null +++ b/plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md @@ -0,0 +1,329 @@ +# ADR-0007: Desktop GUI frontend boundary + +Status: accepted + +Date: 2026-10-22 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#1-product-definition` +- `plans/000-long-term-specification.md#5-crate-ownership` +- `plans/000-long-term-specification.md#6-dispatch-runtime-and-wire-identity` +- `plans/001-terminology-and-domain-model.md` +- `plans/002-long-term-roadmap.md#phase-7--standing-maintenance-and-future-capability-open` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Related implementation plans: + +- `plans/implementation/desktop-gui-frontend/001-operation-parameter-schema-publication.md` +- `plans/implementation/desktop-gui-frontend/002-frontend-client-crate-extraction.md` +- `plans/implementation/desktop-gui-frontend/003-desktop-gui-surface-parity.md` + +## Context + +Eggsec's engine is already frontend-neutral. The canonical specification +requires "the same enforcement and dispatch architecture MUST support all +surfaces without creating separate products", and the workspace already ships +CLI, TUI, REST, MCP, gRPC, and Python frontends over one engine. + +The TUI (`crates/eggsec-tui`) is the most complete interactive surface: 33 tabs +and roughly 65,000 lines of `src/`, all bound to the engine through a small +runtime-client abstraction (`crates/eggsec-tui/src/runtime_client/mod.rs:13-35`). +That abstraction is the natural place to add a second interactive frontend, but +it currently lives inside the TUI crate and is named after the TUI. + +The maintainer has directed a desktop GUI frontend with these properties: + +- it must reach every operation the engine exposes; +- the frontend must be swappable without changing the core; +- the underlying core stays the same; +- binary distribution is handled separately from this workstream. + +The forcing constraint is the **frontend boundary**. If a GUI is added as a +consumer of the engine crate directly, it becomes a second engine client in +the same sense the CLI and TUI are, and the core acquires knowledge of a +frontend it must keep compiling. If instead the GUI is a consumer of the +**daemon protocol** — the same contract `DaemonRuntimeClient` already speaks — +then the core is genuinely untouched and the GUI is one more peer of the +existing daemon. + +Two repository facts make the daemon-protocol boundary the right one: + +1. The daemon protocol is already a complete, versioned, serde-based wire + contract over a Unix socket (`crates/eggsec-daemon-protocol/src/protocol.rs`), + with RBAC (`ApprovePolicy`), client declaration, session lifecycle, and a + capabilities handshake. +2. The engine's daemon executor already resolves the acting surface from + **session** state rather than from request payload + (`crates/eggsec/src/runtime_bridge/executor.rs:138`), and fails closed for + strict surfaces when scope cannot be resolved. A GUI that creates its + session with a GUI surface therefore inherits the existing enforcement + semantics without any engine-side special case. + +The outstanding gap is that no `RuntimeSurface` / `ExecutionSurface` value +identifies a desktop GUI. `RuntimeSurface` has ten variants +(`crates/eggsec-runtime/src/request.rs:21-33`) and `ExecutionSurface` has nine +(`crates/eggsec-policy/src/policy.rs:362-381`); neither includes a GUI. A GUI +that borrowed `TuiManual` would work, but would write `surface: "tui-manual"` +into audit records, misattributing desktop actions to the terminal UI. + +## Decision drivers + +- The engine MUST remain unchanged by the presence of a GUI. "Unchanged" is + read strictly: adding a new surface identity is permitted and necessary, but + no existing operation's authorization, dispatch, or wire shape may shift. +- The GUI MUST NOT become a second authorization path. It MUST reach the + engine only through the same enforcement gate every other surface uses. +- The GUI MUST be replaceable. Swapping the GUI framework MUST NOT require + touching the engine, the daemon protocol, or the runtime DTOs. +- The GUI MUST be a leaf. It MUST NOT become a dependency of the engine, the + daemon, or the runtime crates. +- Audit records MUST distinguish GUI-originated actions from TUI-originated + actions. +- The GUI is an **application**, not a library. It is not published to + crates.io and is not consumed as a dependency by other projects. +- Binary distribution, signing, and platform packaging are explicitly out of + scope for this workstream and are handled separately. + +## Considered options + +### Option A — GUI as an engine client (like the TUI) + +The GUI crate depends on the `eggsec` engine crate and calls +`EnforcementContext` / `EnforcedDispatcher` in-process. + +Benefits: the shortest path to a working GUI; the TUI is a working precedent +with all 33 tabs already implemented. + +Costs: the GUI becomes a peer of the engine and the core's compile surface +grows with it. The "swappable frontend" property degrades to "swappable +renderer" — the GUI's Rust code, not just its rendering, is entangled with the +engine. Every engine feature change requires a GUI rebuild and re-review of +whether the GUI's own dispatch path still matches policy. This is precisely +the ownership overlap that the frontend/runtime convergence workstream +(`plans/frontend-runtime-convergence-roadmap-2026-09-10.md`) was chartered to +remove. + +### Option B — GUI as a daemon-protocol client (selected) + +The GUI is a new leaf workspace crate that depends only on frontend-neutral +crates — `eggsec-runtime`, `eggsec-daemon-protocol`, `eggsec-ui-model` — and +talks to the engine through the daemon protocol. It may either attach to an +already-running daemon or spawn one. + +Benefits: the engine is untouched by construction, because the GUI never +appears in the engine's dependency graph; the GUI's authorization identity is +carried in the session it creates, which the executor already honors; the +daemon protocol is already versioned, RBAC-bearing, and exercised by the TUI's +`DaemonRuntimeClient`; and the GUI framework becomes genuinely swappable +because the GUI's Rust side is a protocol client rather than an engine +integration. + +Costs: the daemon protocol must carry everything the GUI needs to drive an +operation. Today it does not fully: there is no operation-parameter schema, so +a GUI would have to hand-build request payloads per operation exactly as the +TUI hand-builds per-tab forms. That gap is real and is addressed by +`plans/adrs/ADR-0008-operation-parameter-schema-publication.md`, not by +weakening this boundary. + +### Option C — GUI as a second engine binary embedding the runtime + +The GUI binary links the engine and hosts an in-process runtime, exposing its +own local IPC surface. + +Benefits: no daemon process; lower latency; works with no system daemon +install. + +Costs: it re-creates the engine-client coupling of Option A in a new place — +the GUI's Rust code would own dispatch, and enforcement would have to be +re-implemented or re-exposed correctly for a second time. It also duplicates +the daemon's session persistence, audit trail, and RBAC. The in-process +runtime already exists as `EmbeddedRuntimeClient` inside the TUI; the correct +home for that capability is a shared frontend-client crate, not a second +engine-linked GUI binary. + +### Option D — GUI as a web application served by the daemon + +The daemon's optional HTTP API (`http-api` feature) serves a static web +application that the operator opens in a browser or a webview shell. + +Benefits: zero new Rust frontend code; maximum reuse of existing +`eggsec-output` HTML rendering. + +Costs: this is not a desktop application. It has no native window management, +no system tray, no OS file dialogs, and no local process lifetime; it inherits +the browser's trust model for a security tool; and it is not deliverable as a +signed desktop binary. It remains valuable as a *complementary* surface and is +explicitly **not** rejected by this ADR — but it is not the desktop GUI this +decision authorizes. + +## Decision + +A desktop GUI is adopted as a **new frontend surface** with the following +binding properties. + +1. **Ownership.** The GUI lives in a new leaf workspace crate, + `crates/eggsec-gui`. It owns presentation, interaction, and client-side + protocol adaptation. It owns **no** authorization, dispatch, scope + resolution, policy evaluation, or operation semantics. + +2. **Dependency direction.** `eggsec-gui` depends only on frontend-neutral + crates (`eggsec-runtime`, `eggsec-daemon-protocol`, `eggsec-ui-model`) and + on the chosen GUI shell framework. The engine MUST NOT depend on + `eggsec-gui`. The daemon MUST NOT depend on `eggsec-gui`. This extends the + existing guards — check 16 (daemon free of TUI and engine dependencies) and + check 21 (engine free of TUI and daemon dependencies) in + `scripts/check-architecture-guards.sh` — to a new, equivalent guard for the + GUI crate. + +3. **Engine access.** The GUI reaches the engine **only** through the daemon + protocol. It MUST NOT link the engine crate, MUST NOT call + `EnforcementContext`, `EnforcedDispatcher`, `Scope::is_target_allowed`, or + `tool.execute()` directly, and MUST NOT construct an `ApprovedExecution` + bundle. + +4. **Surface identity.** A GUI is identified by a new surface variant, + `RuntimeSurface::DesktopGuiManual`, with a matching + `ExecutionSurface::DesktopGuiManual`. It is a **manual** surface: + permissive profile, operator overrides allowed, exactly like CLI and TUI + manual sessions. `ExecutionSurface::honors_manual_override()` MUST include + it (`crates/eggsec-policy/src/policy.rs:417-419`). A strict GUI variant is + NOT introduced at this time; if a headless/automated GUI mode is later + required it must be added as a separate, separately-authorized surface + under its own ADR, never by reusing the manual variant. + +5. **Audit identity.** Sessions, tasks, and audit events originating from the + GUI record the GUI surface label, so desktop actions are never + misattributed to the TUI. + +6. **Swappability.** The GUI shell framework is an implementation detail of + `crates/eggsec-gui`. Changing it MUST NOT require changes to the engine, + the daemon protocol, the runtime DTOs, or the schema publication + mechanism. The framework selection is recorded separately in + `plans/adrs/ADR-0009-gui-shell-technology-selection.md`. + +7. **Not a library.** `eggsec-gui` is an application crate. It is not + published to crates.io and is not a dependency of any other workspace + crate. Its exclusion from the workspace MSRV gate is a consequence of this + property, not a separate concession. + +## Consequences + +### Positive + +- The engine's dependency graph, authorization path, and operation semantics + are provably unaffected by the GUI's existence — verifiable by inspection and + by a static guard, not by convention. +- The GUI inherits the daemon's existing guarantees for free: session + persistence, task history, audit trail, RBAC, cancellation, and the + fail-closed scope resolution that strict surfaces already get. +- The GUI framework becomes replaceable without engine churn, which is the + maintainer-stated goal of a swappable frontend. +- The TUI gains a cleaner boundary as a side effect: the runtime-client + abstraction moves out of the TUI crate into a shared frontend-client crate, + so both interactive frontends consume one contract instead of two copies. +- Schema publication (`ADR-0008`) is reusable by REST, MCP, and Python, so + this workstream also de-brittles existing programmatic surfaces. + +### Negative + +- The GUI cannot reach engine functionality that the daemon protocol does not + expose. This is the real cost of the boundary and it is deliberate: the + protocol becomes the complete, versioned contract for interactive surfaces. +- The GUI adds one network hop (Unix socket) compared with in-process + dispatch. This is immaterial for scan-class operations whose cost is + dominated by the assessment itself, but it must not be claimed as zero for + very short operations. +- One additional surface variant must be added to two enums with exhaustive + matches, and every surface-parity test that enumerates surfaces must be + updated. That is deliberate churn: it is what makes the surface visible to + audit and policy rather than implicit. + +### Neutral or deferred + +- Binary distribution, code signing, notarization, installer formats, and + per-platform release channels are **deferred** — the maintainer has stated + these are handled separately. +- The choice of shell framework is deferred to `ADR-0009`. +- Operation-parameter schema publication is deferred to `ADR-0008`. +- The GUI's visual design language, panel layout, theming, and accessibility + targets are deferred to the shell milestone; this ADR constrains only + ownership and access. +- Automated/headless GUI operation is explicitly **not** in scope. If required + later, it is a strict surface and needs its own ADR. + +## Compatibility and migration + +- **Wire protocol.** No existing daemon message shape changes. The GUI uses + the existing `ClientCommand` / `ServerMessage` vocabulary. The schema + publication described in `ADR-0008` adds a new command rather than altering + existing ones. +- **Existing frontends.** No behavioral change. The TUI, CLI, REST, MCP, gRPC, + and Python surfaces continue to function identically. +- **Enforcement.** No existing operation's policy, risk tier, exposure flags, + or dispatch path changes. `OperationMetadata` entries are untouched. +- **Audit records.** New records may carry a `desktop-gui-manual` surface + label. Existing record consumers that filter on known surface labels MUST + treat the new label as a recognized manual surface rather than an unknown + value, or they may silently mis-handle GUI sessions. +- **Crate graph.** The workspace gains one member. The canonical specification's + crate-ownership section is amended to record the new leaf. + +## Security and reliability implications + +- **Authorization.** The GUI has no authorization capability of its own. Every + operation it requests is evaluated by the engine's `EnforcementContext` on + behalf of the session's surface. The GUI cannot widen its own permissions + because it never holds an `ApprovedExecution` bundle. +- **Scope.** The GUI is a manual surface and may use operator overrides, but + overrides are evaluated by the engine, not the GUI. The GUI cannot bypass + `scope_from_spec` fail-closed conversion because it never performs scope + conversion. +- **Approval flow.** The daemon currently answers `ApprovePolicy` with + `ErrorCode::Unsupported` ("not wired yet", + `crates/eggsec-daemon/src/host.rs:791-812`). Until that is wired, a GUI + operating against a remote daemon MUST fail closed on any operation that + requires interactive approval, and MUST NOT auto-approve on the operator's + behalf. The GUI's own confirmation UX may resolve approvals locally for + embedded use, but it MUST NOT treat a local confirmation as satisfying a + daemon-side policy decision. +- **Local trust boundary.** The GUI shell process hosts untrusted-by-default + web content on some platforms. The shell's content security policy, its + binding to a loopback-only transport, and its exclusion of remote origins + are shell-milestone concerns governed by `ADR-0009`. +- **Secret handling.** Credentials referenced by an operation are owned by the + engine and the daemon; the GUI MUST NOT persist them in its own state or + write them to logs. Any credential the GUI collects for a request is + transmitted over the local daemon transport and is not echoed back in + responses. +- **Reliability.** The GUI holds no authoritative state. Task truth lives in + the daemon and the runtime. A GUI restart re-attaches to existing sessions + and tasks; it does not lose them. Cancellation is requested through the + protocol, not performed locally. + +## Verification + +Implementation is conformant when: + +- a static guard proves the engine, the daemon, and the runtime crates have no + dependency edge to `eggsec-gui`; +- a static guard proves `eggsec-gui` does not link the engine crate and does + not import `EnforcementContext`, `EnforcedDispatcher`, `Scope`, or + `tool.execute()`; +- a test proves a GUI-created session is evaluated with the GUI surface and + that the resulting audit record carries the GUI surface label; +- a test proves a strict surface still fails closed when scope cannot be + resolved, and that the GUI surface does not relax that path; +- `make check` is green, and the architecture guards script reports no new + failures; +- the daemon protocol's existing conformance tests pass unchanged apart from + additions required by `ADR-0008`. + +## Supersession + +None. diff --git a/plans/adrs/ADR-0008-operation-parameter-schema-publication.md b/plans/adrs/ADR-0008-operation-parameter-schema-publication.md new file mode 100644 index 000000000..78acb8f0b --- /dev/null +++ b/plans/adrs/ADR-0008-operation-parameter-schema-publication.md @@ -0,0 +1,312 @@ +# ADR-0008: Operation parameter schema publication + +Status: accepted + +Date: 2026-10-22 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#4-enforcement-invariants` +- `plans/000-long-term-specification.md#5-crate-ownership` +- `plans/000-long-term-specification.md#6-dispatch-runtime-and-wire-identity` +- `plans/001-terminology-and-domain-model.md` +- `plans/002-long-term-roadmap.md#phase-7--standing-maintenance-and-future-capability-open` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Related ADRs: + +- `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` + +Related implementation plans: + +- `plans/implementation/desktop-gui-frontend/001-operation-parameter-schema-publication.md` + +## Context + +`OperationMetadata` is the single source of truth for operation policy. It +lives in `crates/eggsec-policy/src/catalog.rs` and covers 34 canonical +operations plus 42 aliases. Each entry carries identity and policy facts: +`id`, `display_name`, `mode`, `risk`, `intended_uses`, `required_features`, +`required_policy_flags`, `required_capabilities`, `target_policy`, and +per-surface exposure flags (`manual_exposable`, `tui_exposable`, +`mcp_exposable`, `rest_exposable`, `agent_exposable`, `grpc_exposable`). + +**It carries no parameter information.** Neither does the tool registry's +`ToolInfo` (`crates/eggsec/src/tool/registry.rs:212-219`), nor the REST +surface's `ToolListItem` and `ToolDetailResponse` +(`crates/eggsec/src/tool/protocol/rest.rs:189-205`). The Python bindings' +`request_schema` is a human-readable hint string rather than a schema +(`crates/eggsec-python/src/operation_metadata.rs`). + +The consequence is that **no frontend can discover what an operation's +parameters are**. Each frontend must know them out of band. The TUI does this +by hand-building a form per tab — 33 tabs, approximately 65,000 lines of +`crates/eggsec-tui/src/`, with the per-tab form definitions living in +`crates/eggsec-tui/src/tabs/`. That work is correct but non-shareable: the +REST, MCP, gRPC, and Python surfaces each solve the same problem separately, +and a new frontend starts from zero. + +The canonical parameter shapes already exist and are already serializable. +`eggsec-runtime` defines a `TaskKind` enum with 30 variants, each paired with +a typed params struct — `PortScanParams`, `FuzzParams`, `WafParams`, +`DbPentestParams`, and 26 more — all deriving `Serialize` and `Deserialize` +(`crates/eggsec-runtime/src/request.rs`). The runtime crate is deliberately +free of engine and domain dependencies (guard 22), so it is a legitimate home +for schema derivation. + +The gap is therefore not a design question about where parameters live. It is +that the shapes are **not self-describing on the wire**. A frontend that +receives a request DTO can deserialize it, but cannot discover which fields +exist, what they mean, which are required, or what their valid values are — +so it cannot build a form, validate input, or explain a parameter to an +operator. + +## Decision drivers + +- A frontend MUST be able to discover operation parameters at runtime, so + that adding an operation does not require hand-editing every frontend. +- The schema MUST be derived mechanically from the canonical types. A + hand-maintained parallel table would drift and would create a second source + of truth — the failure mode the enforcement invariants exist to prevent. +- The schema MUST NOT become an authorization input. Parameter metadata has a + different trust level from policy metadata, and conflating them would let a + descriptive artifact influence a decision. +- The mechanism MUST be cheap enough that it stays accurate. Derivation at + compile time from the same types that are serialized is the only approach + that cannot drift silently. +- The mechanism MUST be reusable by every frontend, not a GUI-specific + affordance. +- Adding the mechanism MUST NOT force a break in the existing wire contract or + the existing public Rust API of the runtime crate. + +## Considered options + +### Option A — Hand-maintained parameter catalog + +Add a `parameters` field to each `OperationMetadata` entry describing every +operation's fields by hand. + +Benefits: no new dependency; directly readable in one file. + +Costs: this is a second source of truth for operation shape, maintained by +hand, that will drift from the actual request structs — and drift is silent, +because nothing fails when a field is added to a struct and forgotten in the +catalog. It would also require touching the policy crate for what is +descriptive, non-policy data, weakening the "policy is pure data and pure +algorithms" boundary that `eggsec-policy` was extracted to establish. + +### Option B — Derive JSON Schema from the canonical request DTOs (selected) + +Add a `schemars` derivation to the 30 params structs in `eggsec-runtime`, +publish the resulting JSON Schema for the `TaskKind` enum, and expose it over +the daemon protocol as a new read-only command. + +Benefits: the schema cannot drift, because it is generated from the same +types that are actually serialized; it lives in the frontend-neutral runtime +crate that already owns these DTOs; it is directly consumable by any web +frontend (JSON Schema is a web-native format) and by any Rust frontend +(via `schemars`); and it requires no change to any existing message shape. + +Costs: a new workspace dependency (`schemars`) with a supply-chain footprint +that must be admitted through `deny.toml` and documented in +`docs/DEPENDENCY_EXCEPTIONS.md`; a new public item in the runtime crate +(either a `schema` feature or a separate `eggsec-runtime-schema` crate) which +must not force `schemars` onto crates that do not need it; and JSON Schema is +descriptive, so a GUI still needs per-field presentation decisions (labels, +grouping, ordering) that a schema cannot supply. + +### Option C — Publish the request DTOs as opaque JSON and let clients introspect + +Publish the Rust type names and let each frontend hard-code its knowledge of +the fields. + +Benefits: almost no implementation cost. + +Costs: this is Option A with extra steps — the field knowledge still lives in +each frontend, still drifts, and still must be hand-written per frontend. It +does not solve the problem the GUI is blocked on. + +### Option D — Have the GUI reuse the CLI's argument definitions + +The GUI builds an argv vector per operation, exactly as the TUI's +`cli_argv()` does, and lets the Clap tree parse it. + +Benefits: reuses an existing, tested definition of every parameter. + +Costs: it couples the GUI's data model to the CLI's textual interface. The +GUI would have to reverse-engineer argument names, handle the CLI's +multi-word subcommands and aliases, and lose type information — an integer +timeout and a string timeout become indistinguishable. It also means the GUI +can only offer operations the CLI exposes, and it keeps a user-facing command +surface alive as a de-facto API. Rejected. + +## Decision + +Operation parameters are published as a **mechanically derived JSON Schema** +over the canonical request DTOs, exposed as a **descriptive, non-authoritative** +artifact. + +1. **Derivation.** The 30 params structs in `crates/eggsec-runtime/src/request.rs` + and the `TaskKind` enum that binds them gain `schemars` schema derivation. + The schema is generated from the same types that are serialized at runtime. + There is no hand-written parameter table anywhere in the repository. + +2. **Location.** The schema capability lives in the frontend-neutral runtime + layer. Two placements are permitted and the implementation plan selects + between them on measured dependency payoff: + - a `schema` feature on `eggsec-runtime`, or + - a new leaf crate `eggsec-runtime-schema` that depends on + `eggsec-runtime` and owns the derivation. + + The second is preferred if the feature would otherwise force `schemars` onto + every consumer of `eggsec-runtime`, because the workspace's stated rule is + that new crates are created only on measured dependency payoff. The + implementation plan MUST record which placement was chosen and why. + +3. **Exposure.** The schema is reachable over the daemon protocol through a + new read-only client command, `DescribeOperations`, returning the schema + for the `TaskKind` operation set together with the per-operation identity + and policy metadata that `OperationMetadata` already owns. The command is + additive: no existing `ClientCommand` or `ServerMessage` variant changes + shape, so existing clients are unaffected and older daemons answer the new + command with the protocol's existing `UnsupportedCommand` error. + +4. **Descriptive, not authoritative.** The schema MUST NOT participate in + authorization. `OperationMetadata` remains the single source of truth for + operation policy, and the schema MUST NOT be consulted by + `EnforcementContext`, by the dispatcher, or by any adapter that decides + whether an operation may run. A schema is a description of a request + shape; a request that satisfies the schema is not thereby authorized. + +5. **Single source of truth for shape.** Field names, types, optionality, and + defaults in the schema are those of the canonical request DTOs by + construction. Any frontend that hand-maintains a parallel parameter + definition is violating this decision. + +6. **Frontend presentation is separate.** Labels, grouping, ordering, widget + choice, and per-field help text are frontend concerns and live in the + frontend. The schema supplies structure; the frontend supplies meaning. + +7. **Reuse.** The mechanism is published for all surfaces. The REST, MCP, and + Python surfaces MAY consume the same artifact in later milestones; doing so + is encouraged but is not required by this decision. + +## Consequences + +### Positive + +- The GUI can build forms from discovered structure instead of hand-writing 34 + of them, which is the difference between a two-week and a multi-quarter GUI + effort. +- Adding a field to an operation's request struct automatically updates every + frontend that renders from the schema. Drift becomes impossible for shape. +- The schema is web-native, so a web-based frontend consumes it directly with + no adapter, while a native Rust frontend consumes it through `schemars`. +- The runtime crate gains a genuinely useful public capability that is useful + independently of any GUI. +- REST, MCP, and Python surfaces can later reuse the same artifact, which + addresses the same duplication in the programmatic surfaces. + +### Negative + +- A new workspace dependency enters the supply-chain policy surface and must + be admitted explicitly. `schemars` must be added to `deny.toml` (and to + `docs/DEPENDENCY_EXCEPTIONS.md` with an owner and a review-by date) or the + `make check-deps` gate fails closed. +- Deriving schemas over 30 structs adds compile time to any crate that pulls + the derivation in. This is why feature-gating or crate-splitting is + required rather than deriving unconditionally in the runtime crate. +- JSON Schema cannot express Eggsec-specific semantics such as "this field is + mutually exclusive with that one" or "this value must be a member of the + engine's known scope set". Frontends must implement those rules themselves + or the engine must reject them at submission time. The engine's existing + validation remains authoritative. +- A schema published over the wire is a public artifact describing the + request surface of every operation. It is a reconnaissance aid for the + operation surface and MUST be treated as such: it should be exposed only + through the same local transport and access controls as the rest of the + daemon protocol, and it must not become the only discoverable route to + operation details. + +### Neutral or deferred + +- The schema format version is tied to the daemon protocol version. A schema + change that alters an existing operation's shape is a wire-compatible break + only if it is additive to that operation's request struct; a breaking shape + change must follow the daemon protocol's compatibility rules. +- Per-field help text, labels, and grouping are deferred to the frontend. +- The REST and MCP surfaces' adoption of the artifact is deferred to later + milestones of their own roadmaps. + +## Compatibility and migration + +- **Wire protocol.** Additive only. `DescribeOperations` is a new command. + Existing commands and message shapes are unchanged. A client that receives + `UnsupportedCommand` from an older daemon degrades to a static, hand-built + form set — it does not fail to launch. +- **Rust API.** `eggsec-runtime`'s existing public API is unchanged. If the + schema is exposed behind a feature or a separate crate, the default build + of `eggsec-runtime` gains no new dependency and no new required items. +- **Enforcement.** No change to any operation's policy, risk tier, exposure + flags, dispatch path, or approval semantics. +- **Existing frontends.** No change required. The TUI continues to use its + hand-built forms; migrating it to the schema is a separate, optional + milestone and is not a prerequisite for the GUI. +- **Dependency policy.** `schemars` MUST be admitted to `deny.toml` and + recorded in `docs/DEPENDENCY_EXCEPTIONS.md` with an owner and a review-by + date before the implementation is considered complete. The canonical + `deny.toml` remains the only dependency-policy configuration; no + `.cargo/audit.toml` may be introduced. + +## Security and reliability implications + +- **No authorization effect.** The schema is descriptive. It MUST NOT be read + by `EnforcementContext`, `EnforcedDispatcher`, or any scope or policy + decision path. A request that conforms to the schema is not authorized; the + engine's evaluation is unchanged and remains the only authorization gate. +- **No policy effect.** `OperationMetadata` remains the single source of truth + for operation policy. Publishing a schema alongside metadata does not create + a second policy surface, and consumers MUST NOT treat schema-derived facts + as policy facts. +- **Information exposure.** The schema enumerates operation parameter shapes + across the whole operation surface. This is a reconnaissance aid for anyone + who can reach the daemon protocol. It MUST be served only over the daemon's + local transport under the same access controls as other commands, and it + MUST NOT be exposed on a non-loopback interface without the daemon's normal + authorization checks. +- **Validation authority.** Schema-conformant requests are still subject to + the engine's own validation, scope enforcement, and per-operation checks at + execution time. The schema is advisory to clients and never a substitute for + server-side validation. +- **Reliability.** Schema publication is a read-only operation with no state + and no effect on task execution. A failure to derive or serve a schema + MUST NOT block operation execution for existing clients. + +## Verification + +Implementation is conformant when: + +- a test proves the published schema round-trips: every `TaskKind` variant is + present, every params struct's fields appear, and the schema's variant set + matches the enum's variant set; +- a test fails if a params struct gains a field and the published schema does + not change — proving the derivation is live rather than snapshot; +- a test proves the `DescribeOperations` command returns identity and policy + metadata consistent with `OperationMetadata`, and that the two are read from + the same registry rather than duplicated; +- a guard proves no hand-written parameter table has been introduced into the + frontend-neutral crates; +- `make check` and `make check-deps` are green, with `schemars` admitted to + `deny.toml` and documented in `docs/DEPENDENCY_EXCEPTIONS.md`; +- an explicit test proves the schema is not consulted on the authorization + path — that is, that enforcement decisions are unchanged when a schema is + present. + +## Supersession + +None. diff --git a/plans/adrs/ADR-0009-gui-shell-technology-selection.md b/plans/adrs/ADR-0009-gui-shell-technology-selection.md new file mode 100644 index 000000000..fd3f20781 --- /dev/null +++ b/plans/adrs/ADR-0009-gui-shell-technology-selection.md @@ -0,0 +1,372 @@ +# ADR-0009: GUI shell technology selection + +Status: accepted + +Date: 2026-10-22 + +Ratified: 2026-10-23 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#5-crate-ownership` +- `plans/000-long-term-specification.md#8-runtime-and-dependency-baselines` +- `plans/000-long-term-specification.md#10-frontend-rules` +- `plans/002-long-term-roadmap.md#phase-7--standing-maintenance-and-future-capability-open` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Related ADRs: + +- `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` +- `plans/adrs/ADR-0008-operation-parameter-schema-publication.md` + +Related implementation plans: + +- `plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md` +- `plans/implementation/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard.md` + +## Context + +`ADR-0007` fixes the desktop GUI's **boundary** — a leaf application crate that +reaches the engine only through the daemon protocol — without fixing the +**shell technology** that renders it. The shell is the largest single +dependency-family decision in this workstream, and it is the one most likely +to be regretted if chosen for the wrong reason. + +Eggsec's GUI surface is unusually demanding for a UI toolkit. It must present +roughly 30 operation kinds across 33 logical panels, each with its own input +form, its own result rendering, and its own live progress and log stream. It +must handle dense, sortable, filterable result tables. It must stay +responsive while the engine performs network I/O. It must run on macOS, Linux, +and Windows. It must be operable by a security practitioner, who expects a +polished, information-dense tool rather than a developer debug UI. + +The workspace constrains the choice more than most: + +- `rust-version = "1.89"` is a declared, CI-enforced contract + (`Makefile:93-98` runs `cargo +1.89 check --workspace`). +- `deny.toml` is a closed license allow-list — MIT, Apache-2.0, BSD-2/3, + ISC, Unicode-3.0, MPL-2.0, CC0-1.0, Unlicense, Zlib, BSL-1.0, 0BSD, + CDLA-Permissive-2.0 — and `make check-deps` fails closed when + `cargo-deny` is absent. +- TLS is ring-only everywhere; `reqwest` uses `rustls-no-provider`, never + `rustls`. A GUI shell that pulls its own HTTP stack with a different TLS + posture would violate this. +- The repository has **no JavaScript toolchain today**. The root + `package.json` is an empty object (`{}`). +- The maintainer has stated that **binary distribution is handled + separately**, which removes packaging, signing, and installer concerns from + this decision — but does not remove build-time or runtime concerns. + +A prior survey of the candidate space produced three findings that materially +shape this decision: + +1. **A prior art exists for exactly this shape.** A team building a + data-heavy table application benchmarked egui, iced, Slint, and GTK, hit + walls in every native toolkit, and shipped Electron for the UI with Rust + for the core. Eggsec's GUI is the same shape — dense tables, live streams, + many panels — so this result is directly relevant rather than adjacent. +2. **Webview-backed shells cost memory.** Measured figures put webview-backed + desktop apps at roughly 208–211 MiB peak RSS versus 79–109 MiB for native + Rust toolkits. Eggsec runs concurrent network assessments; resident memory + is a real operational cost. +3. **Toolkit accessibility is the weakest common denominator.** Self-drawn + Rust toolkits ship weaker accessibility than platform-native widget sets, + and a webview inherits the platform webview's accessibility tree. + +Verified dependency facts as of 2026-10-22: + +| Crate | Latest stable | MSRV | Edition | License | +|---|---|---|---|---| +| `tauri` | 2.12.5 (2026-10-21) | 1.90 | 2024 | Apache-2.0 OR MIT | +| `tauri` | 2.11.4 (2026-06-30) | **1.77.2** | 2021 | Apache-2.0 OR MIT | +| `tauri-runtime-wry` | 2.12.3 (2026-10-21) | 1.90 | 2024 | Apache-2.0 OR MIT | +| `tauri-runtime-wry` | 2.11.4 (2026-06-30) | **1.77.2** | 2021 | Apache-2.0 OR MIT | +| `tauri` | 3.0.0-alpha.5 (2026-10-14) | 1.95 | 2024 | Apache-2.0 OR MIT | +| `egui` | 0.33.0 (2025-10-09) | **1.88** | 2024 | MIT OR Apache-2.0 | + +The MSRV column is the load-bearing one. The Tauri 2.12 line raised its MSRV +to 1.90, above the workspace's 1.89 — but the **2.11.4 line still declares +MSRV 1.77.2**, comfortably below the workspace floor. `egui` 0.33.0 declares +MSRV 1.88, also below 1.89. **Both leading candidates can be used without +changing the workspace MSRV or excluding the GUI crate from +`make check-msrv`**, provided the dependency is pinned to a specific +version rather than floating on `^`. + +Tauri's `wry` feature resolves to `webview2-com` on Windows and +`webkit2gtk` on Linux; there is no bundled webview on Linux, so the GUI's +Linux build has a system dependency on `webkit2gtk-4.1`, which requires +Ubuntu 22.04 / Debian 12 or newer. + +## Decision drivers + +- The UI must support dense tables, live streaming output, and many + parameterized panels without bespoke widget work per panel. +- The shell MUST NOT weaken any workspace invariant: MSRV, license allow-list, + ring-only TLS, dependency direction, or the `make check` contract. +- The shell MUST be replaceable without engine changes — this is the whole + point of `ADR-0007`. +- A JavaScript build step is acceptable, but it is a **new** toolchain in a + Rust-only repository and must be justified, not assumed. +- The shell's runtime trust boundary must be defensible for a security tool. +- The choice must not foreclose the fallback: if the shell proves unsuitable, + swapping it must be a contained change to `crates/eggsec-gui` only. + +## Considered options + +### Option A — Tauri v2 (Rust shell + system webview + web frontend) + +Benefits: the highest UI ceiling per unit of effort for dense, data-heavy +interfaces — the web ecosystem's table, chart, and form libraries are mature +and directly consumable; the published JSON Schema from `ADR-0008` is +web-native, so the schema-driven form renderer needs no adapter; the binary +uses the operating system's webview rather than bundling Chromium, keeping +footprint small; Rust owns the protocol client, so the daemon-protocol +boundary from `ADR-0007` is preserved; both `tauri` and `tauri-runtime-wry` +are Apache-2.0 OR MIT, already inside the `deny.toml` allow-list. + +Costs: introduces a Node-based frontend build into a Rust-only repository; +Linux builds gain a `webkit2gtk-4.1` system dependency that excludes older +distributions; the webview process raises resident memory relative to a +native toolkit; the `wry`/`webkit2gtk`/`webview2-com` dependency closure must +clear `cargo deny` under `--all-features`, which is a real admission task; +the 2.12 line's MSRV of 1.90 forces an explicit pin to the 2.11.4 line unless +the workspace MSRV is bumped; and a content-security-policy and +loopback-binding discipline becomes a first-class security requirement. + +### Option B — egui / eframe (pure Rust immediate-mode) + +Benefits: no new toolchain — the repository stays Rust-only and the +`make check` contract is untouched; immediate mode is a natural fit for a +**schema-driven generic form renderer**, because a form is redrawn from +current state each frame rather than requiring a per-operation widget tree; +`egui_extras::Table` covers dense result tables; `egui_kittest` enables +headless screenshot testing, which fits the repository's evidence-heavy +verification culture; MSRV 1.88 is below the workspace floor; license is +MIT OR Apache-2.0. + +Costs: the visual language is custom-rendered, so the result reads as a +developer tool unless substantial styling work is done; widget breadth for +complex data presentation is narrower than the web ecosystem's; accessibility +is provided via AccessKit but is generally weaker than a platform webview's +tree; there is no built-in system-tray or native menu integration; and the +prior-art benchmark above found walls in exactly this kind of toolkit for a +data-heavy table application. + +### Option C — Iced (pure Rust retained) + +Benefits: Elm-style architecture; pure Rust; consistent cross-platform +rendering. + +Costs: weaker accessibility story than egui, no built-in menu or tray +integration, a smaller widget ecosystem for dense data presentation, and the +same prior-art warning. Strictly worse than Option B for this use case. + +### Option D — Slint (declarative, product-grade) + +Benefits: a polished product-UI aesthetic closer to a commercial tool; a +declarative model that maps well onto a schema-driven form; integrated +accessibility. + +Costs: the `.slint` DSL is a second language and a second toolchain; the +community and Rust ecosystem are smaller than egui's or the web's; the +licensing model (GPL-3.0, a royalty-free tier carrying an attribution +requirement, or a commercial license) is a materially different posture from +Eggsec's MIT license and would need legal review; and the current MSRV is +above the workspace floor. + +### Option E — Electron + Rust sidecar + +Benefits: the widest ecosystem and the most mature desktop packaging. + +Costs: bundles Chromium, producing a large binary and high resident memory +for what is a single-operator security tool; a Node toolchain plus an +additional IPC hop; and it duplicates capabilities a system-webview shell +already provides at a fraction of the cost. Rejected on footprint. + +### Option F — Web application served by the daemon's HTTP API + +Benefits: zero new Rust frontend code; reuses `eggsec-output`'s HTML +renderer; lowest implementation cost. + +Costs: this is not a desktop application — no native window, no system tray, +no OS file dialogs, no local process lifetime — and it inherits the +browser's trust model. `ADR-0007` explicitly retains it as a *complementary* +surface rather than the desktop GUI. Rejected as the desktop GUI; not +rejected as a surface. + +### Option G — Qt via `qt-rs` / `cxx` + +Benefits: the most capable native widget set; native accessibility. + +Costs: a C++ build dependency, a very large binding surface, substantial +complexity, and a licensing posture (GPL/LGPL/commercial) that requires +legal review. Disproportionate to this problem. + +## Decision + +**Accepted: Option A — Tauri v2 — with a pinned dependency line.** + +The maintainer ratified this proposal on 2026-10-23. The decision remains +deliberately conditional on three specific, checkable conditions, each of +which the shell milestone MUST satisfy before it is allowed to close: + +1. **Version pin.** The `tauri` dependency MUST be pinned to the **2.11.x** + line (latest published patch 2.11.6, MSRV 1.77.2) rather than floating on + `^2.12`, because the 2.12 line declares MSRV 1.90, above the workspace's + 1.89. The pin is recorded in the workspace manifest and re-verified by + `make check-msrv`. Raising the workspace MSRV to 1.90 in order to adopt + the 2.12 line is **not** part of this decision — that would be a separate + recorded trade, requiring its own ADR, not an accident. + +2. **Dependency admission.** The `wry` / `webkit2gtk` / `webview2-com` + closure MUST pass `cargo deny --workspace --all-features` under the + existing `deny.toml` allow-list without new license exceptions beyond + what is recorded in `docs/DEPENDENCY_EXCEPTIONS.md` with an owner and a + review-by date. **Tauri's TLS posture MUST NOT introduce a second TLS + stack**: the `rustls-tls` feature must not be used if it would pull + `rustls` with default features; the GUI does not perform outbound HTTP + of its own — all engine traffic goes through the daemon. + +3. **Linux system-dependency declaration.** The GUI crate MUST declare its + Linux prerequisites explicitly, and the supported Linux baseline MUST be + recorded as a documented platform floor (webkit2gtk-4.1 implies Ubuntu + 22.04 / Debian 12 or newer). Where a distribution below that floor + matters for the target audience, the egui fallback in the next paragraph + is the escape hatch. + +**Fallback: Option B — egui / eframe.** If any of the three conditions above +cannot be met, the GUI shell is implemented with egui instead, and the +fallback is exercised behind the same `ADR-0007` boundary. The fallback is +**sanctioned in advance** so that a switch is a contained change to +`crates/eggsec-gui` rather than a re-plan. + +The framework choice is a **property of `crates/eggsec-gui` only**. It MUST +NOT appear in the engine, the daemon protocol, the runtime DTOs, the schema +publication mechanism, or any shared frontend contract. A test or guard must +be able to demonstrate that swapping the shell requires no change outside +`crates/eggsec-gui`. + +### Rationale for selecting Tauri over egui + +The deciding factor is the shape of the workload, not a general preference for +web technology. Eggsec's GUI is a **data-heavy table application** with live +streams and many parameterized panels — the precise shape where the prior-art +benchmark found native toolkits insufficient and the team shipped a web UI +with a Rust core. Tauri provides that web UI capability while keeping the +Rust protocol client and the daemon boundary intact, and without Electron's +bundled-Chromium footprint. The `ADR-0008` schema artifact is also natively +consumable by a web frontend with no adapter layer. + +The egui fallback is preserved precisely because the prior art also shows +this class of project can succeed with a native toolkit given enough +styling investment, and because the repository's Rust-only, guard-heavy +culture makes a zero-new-toolchain path valuable. + +## Consequences + +### Positive + +- The GUI can achieve a high-quality, information-dense interface in a + fraction of the effort a bespoke native toolkit would require for 33 + panels. +- The `ADR-0008` JSON Schema is consumed natively by a web frontend. +- The workspace MSRV contract is preserved without a gate exclusion. +- Both candidate licenses sit inside the existing `deny.toml` allow-list. +- The fallback is pre-sanctioned, so the framework decision is reversible at + bounded cost. + +### Negative + +- A Node-based frontend build is introduced into a Rust-only repository. This + adds a toolchain, a lockfile, and a supply-chain surface that the current + dependency policy does not cover — `deny.toml` governs Rust crates, and the + JavaScript dependency tree needs its own review. +- Linux gains a `webkit2gtk-4.1` system dependency, raising the platform + floor and complicating packaging on older enterprise distributions. +- The webview raises resident memory relative to a native toolkit. +- The pinned 2.11.x line forgoes 2.12 features and fixes until the workspace + MSRV is revisited. +- The shell introduces a content-security-policy, local-transport-binding, + and remote-origin-exclusion discipline that the TUI does not have to + satisfy, because a terminal has no origin model. + +### Neutral or deferred + +- Binary distribution, code signing, notarization, and installer formats are + out of scope — handled separately per the maintainer's direction. +- JavaScript-side dependency auditing policy is deferred to the shell + milestone, where the actual frontend dependency tree exists. +- The GUI's visual design language is deferred; this ADR constrains only the + technology and its boundary. +- A strict or headless GUI mode is out of scope; see `ADR-0007`. + +## Compatibility and migration + +- **Engine and daemon.** Unaffected. The shell is confined to + `crates/eggsec-gui`. +- **Rust workspace.** The `tauri` dependency enters only the GUI crate's + manifest. The workspace `rust-version` stays 1.89 provided the 2.11.x pin + holds. +- **Dependency policy.** The Rust dependency closure must clear `deny.toml`. + The JavaScript closure is a new surface and must have a documented review + policy before the shell milestone closes. +- **MSRV.** `make check-msrv` must remain green, including the GUI crate, if + the 2.11.x pin holds. Excluding the GUI crate from the MSRV gate is + permitted only as an explicitly recorded fallback if the pin proves + infeasible, and is not the default. + +## Security and reliability implications + +- **Content security policy.** The GUI shell MUST ship with a restrictive CSP + that forbids remote origins, and the webview MUST be bound such that it + cannot load operator-supplied remote content. A security tool whose UI can + fetch arbitrary URLs is a confused-deputy risk. +- **Local transport binding.** Any local transport the shell exposes MUST bind + to loopback only, on an unpredictable port, with the daemon's own + authorization still applying. The shell MUST NOT proxy engine traffic + around the daemon's access controls. +- **TLS.** The GUI MUST NOT introduce a second TLS stack. Engine traffic is + the daemon's; the GUI's own transport is loopback-only. If the GUI's + frontend build requires an HTTP client, it MUST NOT weaken the ring-only + policy for the Rust side. +- **Secret handling.** Credentials collected by a GUI form are transmitted to + the daemon over the local transport and MUST NOT be persisted in the + frontend's own storage or echoed in logs. +- **Reliability.** The shell holds no authoritative state; task truth remains + in the daemon and the runtime. A shell crash MUST NOT lose or corrupt + running tasks, and re-launch MUST re-attach to existing sessions. +- **Update surface.** A Tauri application performs its own update checks in + some configurations. The GUI MUST NOT self-update without explicit + operator action, and update checks MUST NOT be enabled by default, because + an unsolicited network fetch from a security tool is itself a risk. + +## Verification + +Implementation is conformant when: + +- the pinned `tauri` version and its MSRV are recorded in the workspace + manifest and `make check-msrv` is green **including** the GUI crate; +- `cargo deny --workspace --all-features check` is green, and any new + exception is recorded in `deny.toml` **and** + `docs/DEPENDENCY_EXCEPTIONS.md` with an owner and a review-by date; +- the GUI crate's Rust dependency closure contains no `rustls` with default + features, and the ring-only TLS invariant is demonstrably intact; +- a guard proves the shell framework is referenced only within + `crates/eggsec-gui` and is absent from the engine, daemon protocol, + runtime, and shared frontend contracts; +- a test or inspection demonstrates that the GUI performs no direct outbound + HTTP to remote hosts and that its local transport is loopback-bound; +- the Linux system prerequisites and the supported platform floor are + documented. + +## Supersession + +None. If a later decision selects Option B (egui) instead, this ADR is +superseded by a replacement that records the egui selection and the reasons +the Tauri conditions could not be met — the proposal history MUST be +preserved. diff --git a/plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md b/plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md new file mode 100644 index 000000000..90708d41e --- /dev/null +++ b/plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md @@ -0,0 +1,264 @@ +# Desktop GUI Frontend Milestone 001 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/001-operation-parameter-schema-publication.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Repository baseline reviewed: `203ab5dd958415340d39cd47fb1add432c687edd` + +Implementation commits or pull requests: + +- Uncommitted working-tree change on branch `feat/auto-20261022-76692679`. + +## 1. Executive finding + +The milestone's capability boundary is complete. The operation-parameter gap +that made a GUI expensive — no operation published the shape of its own request +parameters — is closed by a **derived**, never-transcribed JSON Schema served +over one read-only daemon command. + +Three things make this trustworthy rather than merely present: + +1. The schema is **derived** from the canonical request DTOs, so it cannot + describe a shape the runtime would reject. +2. The published identity and policy metadata are **read** from + `OperationMetadata`, so the wire description cannot disagree with the + engine's own operation catalog. +3. The artifact is **descriptive only**. It is unreachable from every + authorization, dispatch, scope, and policy path, and that is enforced + structurally by a guard rather than by convention. + +What the milestone deliberately did **not** deliver: no GUI crate, no shell, no +form rendering. Those are M4–M6, and M4 is blocked on the ADR-0009 ratification. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Schema derived from the canonical request DTOs, never transcribed | `crates/eggsec-runtime/src/request.rs` — `#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]` on `TaskKind` and all 30 params structs | pass | The derive cannot live in another crate: `schemars` cannot implement `JsonSchema` for a type it does not own. | +| Published identity read from the canonical accessors, not copied | `crates/eggsec-runtime/src/schema.rs` — `task_kind_schemas()` calls `TaskKind::operation_id()` / `TaskKind::capability_name()` | pass | A sample value per variant exists only to reach those accessors; it is never submitted. | +| Catalog metadata read from `OperationMetadata`, not copied | `crates/eggsec-daemon-protocol/src/operations.rs` — `describe_operation()` | pass | Proven field-for-field by `published_operations_match_the_catalog_field_for_field`. | +| No hand-written parameter table | Guard 152 | pass | No frontend-neutral crate outside `crates/eggsec-runtime/src/request.rs` may define a `pub struct *Params`. | +| The schema never appears on an authorization path | Guard 151 | pass | No reference to `schemars`, `schema_for!`, `eggsec_runtime::schema`, `describe_operations`, or `DescribeOperations` under the engine's dispatch, runtime-bridge, config-policy, config-scope, or the policy kernel; and neither the engine nor the policy kernel gained a `schemars` dependency. | +| One read-only command serves the schema | `ClientCommand::DescribeOperations` → `ServerMessage::Operations` | pass | Read-only: creates no session, mutates no task state, takes part in no authorization decision. | +| The daemon's default dependency set stays `eggsec-runtime` + `eggsec-daemon-protocol` only | `crates/eggsec-daemon/Cargo.toml` gained **no** dependency | pass | The catalog is read in the protocol crate, which gained `eggsec-policy`. See §7 for the recorded deviation from the plan's wording. | +| Older daemons degrade gracefully | `ErrorCode::UnsupportedCommand` path; `DaemonCapabilities.operation_schema` is `#[serde(default)]` | pass | A client that sees `false`, or that gets `UnsupportedCommand`, must degrade to a static form set rather than fail. | +| Access control: a declared client is required | `crates/eggsec-daemon/src/host.rs` — the `DescribeOperations` arm is preceded by the same declaration check the other daemon-wide reads use | pass | The command carries no session id, so it is answerable before any session exists. | +| No credential, secret, or scope material in the response | `operations.rs::response_carries_no_credential_or_scope_material` | pass | Closed field set on the metadata half; no `cidr` / `scope_rules` / `api_key` / `secret` / `bearer` anywhere in the payload. | +| The published variant set cannot drift from `TaskKind` | `schema.rs::published_variants_cover_every_task_kind`, `per_variant_and_whole_enum_schemas_agree` | pass | The per-variant map and the whole-enum adjacently-tagged document must agree. | + +## 3. Production implementation evidence + +**Derivation (`crates/eggsec-runtime`).** The crate gained an optional +`schemars` dependency and a `schema` feature, off by default. A new +feature-gated module `crates/eggsec-runtime/src/schema.rs` publishes: + +- `task_kind_schemas() -> Vec` — one entry per `TaskKind` + variant (30), each carrying the wire `kind` discriminator, the canonical + `operation_id`, the `capability_name`, and a JSON Schema document for that + variant's params struct; +- `task_kind_schema() -> serde_json::Value` — the whole `TaskKind` schema in + its adjacently-tagged wire shape (`{"kind": ..., "params": ...}`), so a + client can post a valid payload without guessing the envelope. + +The schema is returned as `serde_json::Value`, so `schemars` types never enter +the runtime crate's public API. + +**Catalog publication (`crates/eggsec-daemon-protocol`).** A new module +`operations.rs` defines `OperationDescription`, `TaskKindDescription`, and +`DescribeOperationsResponse`, plus `describe_operations()`. Every identity and +policy field is read from `eggsec_policy::ALL_OPERATION_METADATA`. + +**Wire surface.** `ClientCommand::DescribeOperations` (16 variants, was 15) and +`ServerMessage::Operations` (15 variants, was 14). `DaemonCapabilities` gained +`operation_schema: bool`, marked `#[serde(default)]`. + +**Daemon arm (`crates/eggsec-daemon/src/host.rs`).** The command is answered +from immutable registry data — no session, no task state, no registry mutation — +and is concurrency-safe and reproducible. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggsec-runtime --features schema +cargo test -p eggsec-daemon-protocol +cargo test -p eggsec-daemon --lib +make check-deps +bash scripts/check-architecture-guards.sh +cargo fmt --all --check +cargo clippy -p eggsec-runtime --features schema -p eggsec-daemon-protocol -- -D warnings +``` + +### Results + +| Check | Result | +|---|---| +| `eggsec-runtime` (with `schema`) | 92 lib tests pass, including 6 new schema tests | +| `eggsec-daemon-protocol` | 79 tests pass, including 5 new `operations` tests and 2 new protocol tests | +| `eggsec-daemon` | 92 lib tests pass, including 6 new tests | +| `make check-deps` | `bans ok, licenses ok, sources ok`; `advisories FAILED` for pre-existing reasons — see §10 | +| Architecture guards | ALL PASSED, including new checks 151 and 152 | +| Guard negative test | Deliberate violations of checks 151 and 152 each failed as designed; both passed again after restore | +| `cargo fmt --all --check` | clean | +| Clippy on the changed crates | clean | + +The **load-bearing negative test** the plan required was implemented +structurally rather than as a single runtime assertion: guard 151 makes the +schema unreachable from every authorization path, so the engine *cannot* consult +it, and therefore an enforcement decision cannot depend on its presence. The +guard was demonstrated to fail when the condition is violated and to pass when +restored. + +## 5. Invariant review + +| Invariant | Evidence | Status | +|---|---|---| +| `EnforcementContext::evaluate()` remains the mandatory pre-dispatch gate | Guard 151: no dispatch-path file references the schema. No dispatch code was changed. | holds | +| Strict surfaces fail closed without an explicit scope | No strict path was touched; the engine's strict-surface code is unchanged. | holds | +| `OperationMetadata` is the single source of truth for operation policy | The published description is read from it field for field (`published_operations_match_the_catalog_field_for_field`); the catalog itself was not modified. | holds, strengthened | +| `TaskKind::operation_id()` / `canonical_target()` remain the single wire-side match | The schema module calls those accessors; it does not define a parallel table. | holds | +| The daemon's default dependency set | `crates/eggsec-daemon/Cargo.toml` gained no dependency. | holds | +| Workspace Tokio baseline (`default-features = false`, per-crate lists) | `schemars` pulls no Tokio. | holds | +| TLS is ring-only | `schemars` pulls no TLS stack. | holds | +| Never `let _ =` / `filter_map(|e| e.ok())` | No such pattern was introduced; the schema module has no fallible discard. | holds | +| `make check` contract | Extended, not weakened: the `Makefile` clippy target now also lints `eggsec-runtime --features schema` and `eggsec-daemon-protocol`. | holds | + +## 6. Failure and recovery review + +- **Duplicate delivery:** `describe_operations()` is a pure function of + immutable registry data. `payload_is_reproducible` asserts two calls produce + identical payloads. +- **Cancellation races:** not applicable — the command creates no task. +- **Daemon restart:** not applicable — the command reads no persisted state, so + it answers identically before and after a restart. +- **Partial persistence failure:** not applicable — the command writes nothing. +- **Malformed or unauthorized input:** the command takes no fields beyond its + own identity, so there is no input to malform. An undeclared client is + rejected with `ErrorCode::ClientNotDeclared` before the arm runs. +- **Denial-of-service bounds:** the payload is bounded by the catalog (34 + operations) and the task-kind set (30). The command creates no task, so it + consumes no runtime capacity and cannot be used to flood the engine. +- **Concurrent access:** `describe_operations_is_concurrency_safe` asserts two + concurrent calls return identical payloads. + +## 7. Migration and compatibility review + +- **Schema migration:** none — the schema is a derived artifact, not stored + state. +- **Backward compatibility:** `DaemonCapabilities.operation_schema` is + `#[serde(default)]`, so a newer daemon's capabilities decode against an older + client and vice versa. `daemon_capabilities_decode_without_the_operation_schema_flag` + pins this. +- **Protocol negotiation:** the command is additive. A daemon too old to know it + answers `ErrorCode::UnsupportedCommand`; the plan requires a client to treat + that as "schema unavailable" and degrade to a static form set rather than + fail. +- **Configuration behavior:** unchanged. +- **Rollback:** the feature and the command are additive; reverting removes + them without a data migration. +- **Legacy-path status:** no legacy path was removed. The optional `schema` + feature means `eggsec-runtime`'s default build gains no new dependency for + consumers that do not enable it. + +**Recorded deviation from the plan's wording.** The plan's §4 says "any new +dependency must be feature-gated and optional". That clause is written about +*the daemon*, and the daemon gains no new dependency. The catalog is read in +`eggsec-daemon-protocol`, whose dependency on `eggsec-policy` is **not** +feature-gated, for a concrete reason: gating it would make the `ServerMessage` +variant set depend on the build, and a client built without the feature could +not deserialize an `Operations` message at all. That is a wire-contract hazard +for a published IPC protocol, and the repo already has a guard asserting the +protocol crate carries no Tokio and no network dependency — `eggsec-policy` is a +pure semantic kernel and satisfies both. + +**Recorded deviation from the plan's drift detector.** The plan's acceptance +criterion reads "the schema's variant keys equal the set of +`TaskKind::operation_id()` values". That is unachievable as written: 30 task +kinds map to 26 distinct operation ids, because the three packet kinds share +`packet`, `Pipeline` and `Resume` share `pipeline`, and `Wireless` and +`WirelessActive` share `wireless`. A map keyed by operation id would silently +drop four wire shapes. The published artifact is therefore keyed by +**task-kind variant** (30 entries), each carrying its `operation_id`, and +`shared_operation_ids_are_the_expected_ones` pins the exact multiplicities. +This is a strictly stronger drift detector than the plan's wording. + +## 8. Security review + +- **Authorization:** the schema is descriptive and grants nothing. The engine's + own enforcement remains the only authority, and the daemon enforces it. + Guard 151 proves the schema cannot be consulted on an enforcement path. +- **Scope checks:** the published payload contains no scope material and no + scope rule (`response_carries_no_credential_or_scope_material`). +- **Secret handling:** no credential, secret, or bearer material is published. + The parameter half is a JSON Schema — property names, types, and the serde + defaults of the request structs — which contains no request *values*. +- **Privilege boundaries:** the command requires a declared client identity, so + it is not reachable by an anonymous peer on the socket. +- **Denial-of-service bounds:** the payload is bounded by the catalog size and + the command creates no task. +- **Audit behavior:** the command is read-only and creates no state. It is not + separately audited; the daemon's existing command-level audit trail covers + command dispatch. +- **Redaction:** not applicable — nothing in the payload is secret. + +## 9. Documentation and operations + +- `architecture/overview.md` — crate table, module index, dependency map, + dependency-guardrails list, and the `eggsec-runtime` / `eggsec-daemon-protocol` + rows updated for the optional `schema` feature, the `operations` module, the + `eggsec-policy` dependency, and the new command/message counts. +- `architecture/runtime.md` — the `schema` module and the optional `schemars` + dependency. +- `architecture/daemon.md` — the `DescribeOperations` command, the `Operations` + response, the `DaemonCapabilities.operation_schema` flag with its + `#[serde(default)]` compatibility rule, and the audit-trail surface labels. +- `docs/DAEMON_PARITY.md` — the `DaemonCapabilities` shape and an + operation/schema-discovery parity row. +- `docs/CI_ARCHITECTURE_GUARDS.md` — a "Checks 151–154" section. +- `.opencode/skills/eggsec-daemon/SKILL.md` — the new command and the + capability flag. +- `plans/000-long-term-specification.md` — crate count and the + `eggsec-frontend-client` ownership rule. +- `plans/registry.md` and `plans/subsystems/desktop-gui-frontend-roadmap.md` — + milestone status updated. +- Static guards: 151 (schema stays off the authorization path) and 152 (no + hand-written parameter table). + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | `make check-deps` reports `advisories FAILED` against `rustls 0.21.12` (via `tiberius` → `sqlx-mysql`) and related crates — RUSTSEC-2026-0346/0347/0348/0349, 0367/0368/0369, 0381/0382/0383, RUSTSEC-2024-0449. None is in this milestone's dependency delta, and none of the four crates this milestone added (`schemars`, `schemars_derive`, `dyn-clone`, `serde_derive_internals`) appears in any advisory. The `deny.toml` advisory ignore list was last reviewed 2026-09-13. | The mandatory dependency gate stays red for reasons unrelated to this milestone. | Maintainer-led dependency-exception review. `deny.toml` is the canonical place; each exception needs an owner and a review-by date in `docs/DEPENDENCY_EXCEPTIONS.md`. **Deliberately left unfixed here.** | +| low | `clipboard-win 5.4.1` (→ `arboard` → `eggsec-tui`) was yanked upstream on 2026-10-23 and was already in the baseline lock file. | `cargo deny` failed on the yanked crate before this milestone could run the dependency gate at all. | **Repaired**: one-line lock bump to the non-yanked `5.4.3`. Changes no first-party dependency edge and no first-party code. | +| low | The plan's drift-detector wording is unachievable as written (30 task kinds → 26 operation ids). | None — the implemented detector is stronger. | None; recorded in §7. | + +## 11. Roadmap disposition + +**Milestone closed and the next dependency may proceed.** + +- **M1 (this milestone): closed.** +- **M2** (frontend-client contract extraction): closed — see + `002-frontend-client-contract-extraction-closure.md`. +- **M3** (desktop GUI surface parity): closed — see + `003-desktop-gui-surface-parity-closure.md`. +- **M4** (GUI shell skeleton): still blocked on ratification of ADR-0009 + (Tauri v2 vs. egui). Nothing in this milestone depends on that decision. + +## 12. Registry updates + +`plans/registry.md`: the `desktop-gui-frontend` subsystem status is updated to +*active* with M1–M3 closed; the plan bullet is marked **closed 2026-10-23** and +names this closure record; the *Closure work and current control points* row +for the Desktop GUI frontend names the closure records. + +`plans/subsystems/desktop-gui-frontend-roadmap.md`: milestone 1's row is +updated to **closed 2026-10-23** with this record; the roadmap's front-matter +status becomes *active*. diff --git a/plans/closure/desktop-gui-frontend/002-frontend-client-contract-extraction-closure.md b/plans/closure/desktop-gui-frontend/002-frontend-client-contract-extraction-closure.md new file mode 100644 index 000000000..55d4c785f --- /dev/null +++ b/plans/closure/desktop-gui-frontend/002-frontend-client-contract-extraction-closure.md @@ -0,0 +1,232 @@ +# Desktop GUI Frontend Milestone 002 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/002-frontend-client-contract-extraction.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Repository baseline reviewed: `203ab5dd958415340d39cd47fb1add432c687edd` + +Implementation commits or pull requests: + +- Uncommitted working-tree change on branch `feat/auto-20261022-76692679`. + +## 1. Executive finding + +The milestone's capability boundary is complete. The frontend runtime-client +contract is no longer trapped inside the terminal UI. + +Before this milestone, a second frontend could not reuse the contract without +depending on `eggsec-tui` — and therefore on ratatui, crossterm, the theme +pack, and the clipboard stack. The contract was also *named* for the TUI +(`TuiRuntimeClient`), which would have baked that dependency into every future +frontend's vocabulary. + +Both obstacles are gone. The contract now lives in its own frontend-neutral +leaf crate, `eggsec-frontend-client`, under the neutral name `RuntimeClient`, +and the TUI consumes it with no observable behavior change. The workspace is +now 24 crates. + +What the milestone deliberately did **not** deliver: no GUI crate, no shell, no +form rendering. The plan's constraint that this must be "a move, not a +redesign" was honoured — the moved code is byte-comparable, and the only +non-mechanical changes are a trait rename, one newly-public error type, and +three log strings that described the old home. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| The contract lives in a frontend-neutral crate | `crates/eggsec-frontend-client/` | pass | New leaf crate. | +| The crate depends on no frontend framework and not on the engine | Guard 153 | pass | The manifest must not reference `eggsec =`, `eggsec-tui`, `ratatui`, `crossterm`; the source must not reference `ratatui`, `crossterm`, `eggsec_tui`, or `eggsec::`. | +| The trait is no longer TUI-named | `RuntimeClient` in `crates/eggsec-frontend-client/src/lib.rs` | pass | `RuntimeClientFuture` and `RuntimeEventReceiverHandle` were already neutral and kept their names. | +| `DaemonClientError` is publicly reachable | Re-exported from the crate root | pass | It was crate-private before the move; a frontend must be able to distinguish a closed connection from a protocol error. | +| The TUI's observable behavior is unchanged | Only types and import paths changed; the TUI's own `runtime_client` field name and all call sites were kept | pass | 1002 TUI tests pass. | +| The daemon client's shared-connection behavior survives the move | The `Arc` shape, the `FxHashMap` pending-response registry, and the `RwLock>>` event fan-out were moved verbatim | pass | Cloning the connection instead of the client would silently break event delivery to every other subscriber. | +| The extracted crate carries at least one test | 6 tests in `crates/eggsec-frontend-client/src/lib.rs` | pass | Object safety, session create/list/snapshot, unknown-session errors, event delivery, the public error type, and reported capabilities. | +| The crate joins the mandatory lint gate | `Makefile`'s `clippy` target | pass | `cargo clippy -p eggsec-frontend-client -- -D warnings` is clean. | +| The TUI still passes | `cargo test -p eggsec-tui --lib` | pass | 1002 tests. | + +## 3. Production implementation evidence + +**New crate `crates/eggsec-frontend-client/`.** Public API: +`RuntimeClient`, `RuntimeClientFuture`, `RuntimeEventReceiverHandle`, +`EmbeddedRuntimeClient`, `DaemonRuntimeClient`, `DaemonClientError`. + +Dependencies: `eggsec-runtime`, `eggsec-daemon-protocol`, `serde_json`, +`thiserror`, `tracing`, `rustc-hash`, and Tokio with exactly `rt`, `sync`, +`time`, `io-util`, `net` — no `rt-multi-thread`, no `macros`. + +**The trait.** `RuntimeClient` keeps its 8 methods and its +`Send + Sync + 'static` supertraits, so `Arc` +remains the holder type every frontend uses. `RuntimeClientFuture` stays a +boxed `Send + 'static` future of `Result` — deliberately coarse, +because that is the contract the existing frontends already bind to. + +**The implementations.** `EmbeddedRuntimeClient` wraps an in-process +`Arc`; `DaemonRuntimeClient` speaks the daemon's JSON-lines protocol +over a Unix socket and is `Clone`, with every clone sharing one +`Arc`. + +**TUI migration.** `crates/eggsec-tui/src/runtime_client/` was deleted. The TUI +now depends on `eggsec-frontend-client` and no longer on `eggsec-daemon-protocol` +directly — it depends on the client contract, not on the wire protocol. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggsec-frontend-client +cargo test -p eggsec-tui --lib +cargo check -p eggsec-frontend-client +cargo check --workspace --all-targets +cargo check --workspace --no-default-features +bash scripts/check-architecture-guards.sh +cargo clippy -p eggsec-frontend-client -- -D warnings +cargo fmt --all --check +``` + +### Results + +| Check | Result | +|---|---| +| `eggsec-frontend-client` | 6 tests pass | +| `eggsec-tui` | 1002 tests pass, 0 fail | +| `cargo check -p eggsec-frontend-client` | clean | +| `cargo check --workspace --all-targets` | clean, no errors | +| `cargo check --workspace --no-default-features` | clean | +| Architecture guards | ALL PASSED, including new check 153 | +| Guard negative test | Adding `ratatui` to the new crate's manifest made check 153 fail as designed; the manifest was restored and the check passed again | +| Clippy | clean | +| `cargo fmt --all --check` | clean | + +## 5. Invariant review + +| Invariant | Evidence | Status | +|---|---|---| +| The engine never depends on a frontend | Guard 153; the new crate does not depend on the engine, so the edge cannot exist in either direction. | holds | +| The daemon never depends on a frontend | Unchanged; the daemon's manifest gained no dependency. | holds | +| `eggsec-runtime` stays free of engine and domain crates | Unchanged; the new crate depends on the runtime, never the reverse. | holds | +| The canonical executor imports no frontend types | Unchanged. The executor does not import the new crate. | holds | +| `OperationMetadata` remains the single source of truth | Unchanged; the move touched no catalog or policy code. | holds | +| Workspace Tokio baseline | The new crate uses a narrower Tokio feature set than the TUI it came from. | holds | +| `make check` contract | Extended: the new crate joined the `make clippy` gate. | holds | + +## 6. Failure and recovery review + +- **Duplicate delivery:** not applicable — the crate is a library with no + delivery path. +- **Cancellation races:** unchanged. The moved daemon client preserves its + request-id → oneshot response registry and its cancellation plumbing + verbatim. +- **Daemon restart:** unchanged. A daemon client reconnects by re-declaring + and re-subscribing, exactly as before the move. +- **Partial persistence failure:** not applicable — the crate persists nothing. +- **Stale generation or lease:** not applicable. +- **Contention and resource release:** the pending-response registry is + cleaned per request; the moved code is unchanged. +- **Malformed or unauthorized input:** unchanged. The client is a transport + shim; the daemon still applies every access control. +- **Bounded event and artifact behavior:** unchanged. The event fan-out still + goes through the shared `Arc`. +- **Regression risk introduced by the move:** a clone of the *connection + internals* instead of the client would break fan-out. The moved code keeps + the `Arc` shape, and the crate's own tests exercise the embedded path. + +## 7. Migration and compatibility review + +- **Schema migration:** none. +- **Backward compatibility:** the Rust API of `eggsec-tui` is unchanged from a + consumer's point of view — only the crate that supplies the trait moved. The + TUI's internal field name and call sites were kept. +- **Protocol negotiation:** unchanged. The wire protocol is untouched by this + milestone. +- **Configuration behavior:** unchanged. +- **Rollback:** reverting restores the previous module location; the new crate + would be deleted. No data migration is involved. +- **Legacy-path status:** `crates/eggsec-tui/src/runtime_client/` is removed. + Nothing else referenced it. + +**Recorded deviation.** The plan's requirement that the extracted crate carry +at least one test was met, but with six. The moved code had **no** tests at all +before the move — the plan's premise that the extraction would carry existing +coverage was wrong — so the tests are new and cover the contract's observable +behavior (object safety, session lifecycle, error surfacing, event delivery) +rather than a port of prior coverage. + +## 8. Security review + +- **Authorization enforcement:** the crate is **not** an enforcement surface. It + carries no authorization decision: the daemon applies its own access + controls, and the embedded runtime applies the engine's. The contract's error + type is `String`, deliberately coarse, exactly as before the move — moving + the contract did not widen it. +- **Scope checks:** unchanged; the crate never resolves or checks scope. +- **Secret handling:** unchanged; the crate handles no credentials. +- **Privilege boundaries:** the move introduced no new network reach. The + daemon client still speaks only over a Unix socket, and the embedded client + still wraps an in-process runtime. +- **Transport checkpoints:** unchanged. +- **Denial-of-service bounds:** unchanged. The client issues one request per + call and applies a request timeout, as before. +- **Audit behavior:** unchanged by this milestone. + +## 9. Documentation and operations + +- `architecture/frontend_client.md` — **new** deep-dive doc: role, boundary + rule, the three source files, the public API, both implementations, the + `Arc` sharing requirement, and why the crate is not an + enforcement surface. +- `architecture/overview.md` — crate count 23 → 24, new crate-table row, module + index row, key-types row, dependency map, dependency-guardrails list, and the + footer verification note. +- `architecture/tui.md` — the contract's new location and the `RuntimeClient` + name. +- `docs/ARCHITECTURE.md` — crate count and the new crate row. +- `docs/CI_ARCHITECTURE_GUARDS.md` — a "Checks 151–154" section and a + frontend-client crate-boundary bullet. +- `CONTRIBUTING.md` — the TUI tree no longer lists `runtime_client/`, and the + new leaf crate is explained. +- `.opencode/skills/eggsec-frontend-client/SKILL.md` — **new** skill for the + crate. +- `.opencode/skills/eggsec-tui/SKILL.md` — the remote-attach section now + points at the shared crate and the renamed trait. +- `plans/000-long-term-specification.md` — crate count and the + `eggsec-frontend-client` ownership rule. +- Static guard: 153 (the crate stays framework-free and engine-free). + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | The moved contract had **no** prior test coverage, so the plan's premise that the extraction would carry existing tests was wrong. | The extraction could have shipped a silently broken client. | **Resolved in this milestone**: 6 new tests now cover object safety, the session lifecycle, error surfacing, event delivery, the public error type, and reported capabilities. | +| low | The workspace-wide `make check-deps` advisory failure is recorded in the M1 closure record and is unrelated to this milestone. | The mandatory dependency gate stays red for pre-existing reasons. | Tracked under the M1 closure record. | + +## 11. Roadmap disposition + +**Milestone closed and the next dependency may proceed.** + +- **M2 (this milestone): closed.** +- **M1** (operation parameter schema publication): closed — see + `001-operation-parameter-schema-publication-closure.md`. +- **M3** (desktop GUI surface parity): closed — see + `003-desktop-gui-surface-parity-closure.md`. +- **M4** (GUI shell skeleton): still blocked on ratification of ADR-0009. This + crate is the seam that milestone consumes, so nothing about it depends on the + framework choice. + +## 12. Registry updates + +`plans/registry.md`: the `desktop-gui-frontend` subsystem status is updated to +*active* with M1–M3 closed; the plan bullet is marked **closed 2026-10-23** and +names this closure record; the *Closure work and current control points* row +for the Desktop GUI frontend names the closure records. + +`plans/subsystems/desktop-gui-frontend-roadmap.md`: milestone 2's row is +updated to **closed 2026-10-23** with this record. diff --git a/plans/closure/desktop-gui-frontend/003-desktop-gui-surface-parity-closure.md b/plans/closure/desktop-gui-frontend/003-desktop-gui-surface-parity-closure.md new file mode 100644 index 000000000..29f0f43b6 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/003-desktop-gui-surface-parity-closure.md @@ -0,0 +1,296 @@ +# Desktop GUI Frontend Milestone 003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/003-desktop-gui-surface-parity.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Repository baseline reviewed: `203ab5dd958415340d39cd47fb1add432c687edd` + +Implementation commits or pull requests: + +- Uncommitted working-tree change on branch `feat/auto-20261022-76692679`. + +## 1. Executive finding + +The milestone's capability boundary is complete. The desktop GUI is a +first-class **manual** surface: a peer of the CLI and the TUI, not a new policy +class and not a second enforcement mode. + +Three properties were made true and then *tested*, rather than assumed: + +1. The GUI derives the **same** `ManualPermissive` profile the CLI and TUI + manual surfaces derive — no more, no less. +2. The GUI honors operator overrides and never lands on the strict side of the + manual/strict split. +3. GUI activity is **attributable**: the daemon's persisted audit trail now + records the session's runtime surface, so a GUI session is auditable as + `desktop-gui-manual` and a TUI session as `tui-manual`. + +The third property required a deliberate **behavior change** to the daemon's +audit trail, because the plan's premise about it turned out to be false. See +§3 and §7. + +No new policy surface was created: the GUI reuses the existing +`manual_exposable` exposure flag, there is no `gui_exposable` flag, and there is +no strict GUI variant. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| A GUI surface exists in the runtime enum | `crates/eggsec-runtime/src/request.rs` — `RuntimeSurface::DesktopGuiManual` (11 variants, was 10) | pass | `label()` is `desktop-gui-manual`; the serde encoding is `DesktopGuiManual`; `Unknown` remains the `#[default]` and is still rejected. | +| A GUI surface exists in the policy enum | `crates/eggsec-policy/src/policy.rs` — `ExecutionSurface::DesktopGuiManual` (10 variants, was 9) | pass | | +| The bridge converts it in both directions | `crates/eggsec/src/runtime_bridge/surface.rs` | pass | It remains the single exhaustive conversion table. | +| It is a manual surface, not a strict one | `policy.rs::desktop_gui_derives_the_manual_permissive_profile` | pass | Equal to `CliManual`/`TuiManual`; unequal to both strict profiles. | +| It honors operator overrides | `policy.rs::execution_surface_honors_manual_override`; `surface.rs::manual_surfaces_honor_override_only_for_permissive` | pass | | +| It is not agent-controlled | `policy.rs::execution_surface_is_agent_controlled` | pass | | +| No `gui_exposable` flag was added | `crates/eggsec-policy/src/catalog.rs` is unchanged — the exposure flag set is unchanged | pass | The GUI reuses `manual_exposable`, so it is not a second policy surface. | +| A strict surface with no explicit scope still fails closed | No strict path was modified; the strict surfaces are untouched and `CliManualStrict`/`TuiManualStrict` keep `ManualGuarded` | pass | Confirmed by the enforcement matrix, which runs the strict surfaces against every scope state. | +| The GUI label is distinct from the CLI and TUI labels | `policy.rs::desktop_gui_labels_are_distinct`; `surface.rs::desktop_gui_is_a_manual_surface` | pass | `Desktop GUI manual` / `desktop-gui-manual`. | +| Existing surface encodings did not change | `surface.rs::existing_surface_wire_encodings_are_unchanged` | pass | A snapshot over all 10 pre-existing variants. | +| The GUI behaves identically to its manual peers **in enforcement** | `crates/eggsec/tests/enforcement_matrix.rs` — the GUI was added to `ALL_SURFACES`, `PERMISSIVE_SURFACES`, and `OVERRIDE_HONORING_SURFACES`, so every risk-tier, scope-state, capability, and override-isolation assertion in the matrix now runs against it. 173 tests pass. | pass | This is the load-bearing cross-surface evidence. | +| The audit trail distinguishes GUI from TUI | `host.rs::gui_session_audit_trail_carries_the_gui_surface_label` | pass | Both `desktop-gui-manual` and `tui-manual` are persisted, and no session-scoped event carries the blanket `daemon` label. | +| Session-less audit events keep the daemon label | `host.rs::session_less_audit_events_keep_the_daemon_label` | pass | | +| A future edit cannot silently demote the GUI | Guard 154 | pass | Pins the variant's presence in both enums, both conversions, its manual classification, and its profile. | +| The Python bindings can name the new surface | `crates/eggsec-python/src/audit.rs` and `daemon.rs` | pass | See §3. | + +## 3. Production implementation evidence + +**Runtime surface.** `RuntimeSurface::DesktopGuiManual` was added beside the +other manual variants. `Unknown` remains the `#[default]` and is still rejected +by the runtime bridge. + +**Policy surface.** `ExecutionSurface::DesktopGuiManual` was added with the +identical `ManualPermissive` profile as `CliManual`/`TuiManual`, +`honors_manual_override() == true`, `is_agent_controlled() == false`, and +`requires_explicit_manifest_for_networked() == false`. + +**Runtime bridge.** `crates/eggsec/src/runtime_bridge/surface.rs` converts the +new variant in both directions. It remains the single exhaustive conversion +table; no parallel table was introduced. + +**Daemon audit trail (behavior change).** Session-scoped audit events +(`create-session`, `submit-task`, `cancel-task`, `cancel-active`, +`close-session`, `command-denied`) now record the **session's** runtime surface +label in `PersistedAuditEvent.surface` instead of the blanket literal +`"daemon"`. Events with no session (`declare-client`, `daemon-recovery`, +`approve-policy`) keep `"daemon"` — they are genuinely daemon-level. A +test-only read-back helper (`SqliteStore::audit_surfaces`) makes the persisted +rows assertable. + +**Python bindings.** The GUI surface was added to the two string parsers that +enumerate surfaces: + +- `crates/eggsec-python/src/audit.rs` — `parse_execution_surface()` now + accepts `"desktop-gui-manual"`. Without this, a Python caller could not + construct an audit event for a GUI session. +- `crates/eggsec-python/src/daemon.rs` — `parse_surface()` now accepts + `"desktop_gui_manual"` / `"DesktopGuiManual"`, and the exhaustive + `server_message_to_response()` match gained an `Operations` arm (it would + otherwise fail to compile). + +The Python `ExecutionSurface` **class** was deliberately **not** given a +`desktop_gui_manual()` constructor: that class is part of a versioned Python +public API with a generated compatibility baseline +(`crates/eggsec-python/tests/compatibility_baseline.json`), and adding a public +symbol would require regenerating the baseline and touching the separate Python +release contract. The string parsers cover the functional need without +changing the Python public symbol set, so the baseline stays valid. + +The CLI's own `parse_surface()` was also left unchanged: it deliberately +offers the automation surfaces and already excludes the human-interactive +`tui-manual`. Adding `desktop-gui-manual` there would have been inconsistent +with that existing decision. + +**Enforcement matrix.** `crates/eggsec/tests/enforcement_matrix.rs` now +iterates all **10** `ExecutionSurface` variants. This closed a pre-existing gap +as well: `GrpcApi` was never in the matrix's surface list. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggsec-policy --tests +cargo test -p eggsec --features rest-api,cli --lib runtime_bridge +cargo test -p eggsec --features rest-api,cli --test enforcement_matrix +cargo test -p eggsec --features rest-api,cli,grpc-api --test frontend_surface_matrix +cargo test -p eggsec-daemon --lib +cargo check -p eggsec-python --features daemon-client +cargo check -p eggsec-daemon --features http-api,full-executor +cargo check -p eggsec-cli --all-targets +bash scripts/check-architecture-guards.sh +cargo clippy -p eggsec-policy -p eggsec-runtime --features schema -- -D warnings +cargo fmt --all --check +``` + +### Results + +| Check | Result | +|---|---| +| `eggsec-policy` | 87 tests pass, including 3 new tests | +| Engine runtime-bridge unit tests | 66 pass, including 3 new tests | +| `enforcement_matrix` | 171 pass with `--features rest-api,cli` (166 with default features); 173 `#[test]` cases in the file, now covering all 10 surfaces | +| `frontend_surface_matrix` | 16 pass, including 1 new test | +| `eggsec-daemon` | 92 lib tests pass, including 2 new audit tests | +| `eggsec-python` (with `daemon-client`) | compiles | +| `eggsec-daemon` (`http-api`, `full-executor`) | compiles | +| `eggsec-cli` (`--all-targets`) | compiles | +| Architecture guards | ALL PASSED, including new check 154 | +| Guard negative test | Deliberate violations of checks 151, 152 and 153 each failed as designed; all passed again after restore | +| Clippy | clean | +| `cargo fmt --all --check` | clean | + +## 5. Invariant review + +| Invariant | Evidence | Status | +|---|---|---| +| `EnforcementContext::evaluate()` remains the mandatory pre-dispatch gate | The GUI surface routes through the same gate as every other manual surface; the enforcement matrix runs the GUI through every assertion. | holds | +| Strict surfaces fail closed without an explicit scope | No strict path was modified. The enforcement matrix's scope-state matrix still runs `CliManualStrict`/`TuiManualStrict` against DefaultEmpty, explicit allow, allow miss, and exclusion. | holds | +| `LoadedScope` on strict surfaces, never raw `Scope` | Unchanged; no scope code was touched. | holds | +| Strict surfaces dispatch only via `EnforcedDispatcher::dispatch_execution()` | Unchanged. | holds | +| `OperationMetadata` remains the single source of truth for operation policy | The catalog was not modified and no exposure flag was added. | holds | +| The executor reads the surface from the **session** context, not the request payload | Unchanged. | holds | +| `runtime_bridge` owns both conversion directions and rejects `Unknown` | Preserved and extended to the new variant in both directions; `Unknown` is still rejected. | holds | +| The daemon's default dependency set | Unchanged — the daemon's manifest gained no dependency. | holds | +| Workspace Tokio baseline / ring-only TLS | Untouched by this milestone. | holds | + +## 6. Failure and recovery review + +- **Duplicate delivery:** the new surface is an enum variant; there is no + delivery path to duplicate. +- **Cancellation races:** unchanged. +- **Daemon restart:** the audit surface label is derived from the session's + surface, which is re-established at session creation, so a restart does not + change the label. +- **Partial persistence failure:** if the audit write fails, the daemon's + existing `record_audit_event_logged` path handles it as before; the label + change does not alter that failure mode. +- **Stale generation or lease:** not applicable. +- **Contention and resource release:** the surface label is read from the + session-access map under the same lock the daemon already takes. +- **Malformed or unauthorized input:** an unrecognized surface string is still + rejected by the parsers; the new value was added to both. +- **Bounded event and artifact behavior:** unchanged. + +## 7. Migration and compatibility review + +- **Schema migration:** none. +- **Backward compatibility:** the new enum variants are additive. A peer that + does not know `DesktopGuiManual` cannot decode it, which is why the surface + is only used by a client that opts in — the same additive-protocol posture the + daemon's `DaemonCapabilities` flag uses. +- **Protocol negotiation:** unchanged. `RuntimeSurface` has no version + negotiation; the daemon maps an unknown surface to `ErrorCode::InvalidSurface`. +- **Configuration behavior:** a daemon's `default_surface` may now be set to + `desktop-gui-manual`; no other configuration changed. +- **Rollback:** removing the enum variants is a compile-time change; the audit + trail's label format reverts with it. No data migration is involved — the + persisted audit rows carry a label string, and older rows keep their + `"daemon"` value, which remains a valid, meaningful label. + +**Recorded deviation — the audit trail change was larger than the plan +assumed.** The plan stated that "the surface label that reaches the audit trail +is derived from the surface identity established at session creation". +Inspecting the daemon showed the opposite: **every** daemon audit event +recorded the literal `"daemon"`, so nothing distinguished TUI activity from CLI +activity — the plan's premise was false. Making the plan's acceptance criterion +satisfiable therefore required changing the daemon to record the session's +surface label for session-scoped events. + +This is a deliberate behavior change to the persisted audit trail and a strict +improvement: a reader of the audit log can now tell which frontend produced an +action. Session-less events were deliberately left as `"daemon"`, and the +`session_less_audit_events_keep_the_daemon_label` test pins that distinction so +a later change cannot blur it. + +**Recorded deviation — the engine-side audit path needed no change.** +`EnforcementAuditEvent.surface` is already an `ExecutionSurface`, so the new +variant flows into the engine's audit trail automatically once the bridge maps +it. The daemon-side label was the only gap. + +## 8. Security review + +- **Authorization enforcement:** the new surface is permissive by design and no + more permissive than its peers — it derives the identical `ManualPermissive` + profile that the CLI and TUI manual surfaces derive, so an operator at a GUI + gets exactly the capabilities an operator at a CLI gets. +- **Scope checks:** unchanged. The GUI surface does not alter scope resolution; + a GUI session without an explicit scope behaves exactly as a manual CLI + session without one. +- **Manual override rule:** explicitly tested rather than assumed. The GUI is + on the manual side of `honors_manual_override()` and is *never* classified as + strict (`desktop_gui_derives_the_manual_permissive_profile` asserts its + profile differs from both strict profiles). +- **Agent-controlled paths:** the GUI is not agent-controlled + (`execution_surface_is_agent_controlled`), so it never gains the automated + surface's ability to run without a human. +- **Privilege boundaries:** unchanged. The GUI adds no capability that the + engine would not grant to an equivalent manual CLI session. +- **Audit behavior:** the GUI's activity becomes *attributable* rather than + anonymous, which is a security improvement, and it does so without weakening + any authorization check. +- **Denial-of-service bounds:** unchanged. + +## 9. Documentation and operations + +- `architecture/overview.md` — the `ExecutionSurface` surface table gained the + `DesktopGuiManual` row; the footer records the 9 → 10 change. +- `architecture/config.md` — the surface → profile mapping table gained the GUI + row, with the note that the GUI is a frontend, not a new policy class. +- `architecture/dispatch.md` — the manual-surfaces heading now reads + "CLI/TUI/Desktop GUI" with a peer paragraph. +- `architecture/runtime_bridge.md` — the conversion table gained the GUI row; + the override rule names the GUI; the flow diagram's variant count is 11. +- `architecture/runtime.md` — `RuntimeSurface` 10 → 11 with the + `desktop-gui-manual` row. +- `architecture/audit.md` — the GUI added to the per-surface audit table. +- `architecture/daemon.md` — a new audit-trail section documenting the surface + labels versus the literal `"daemon"`. +- `docs/ENFORCEMENT_MODES.md` — `ExecutionSurface` 9 → 10, a GUI row in the + behavior matrix, a "Desktop GUI posture" paragraph, and the matrix-coverage + claim corrected to all 10 surfaces. +- `docs/ARCHITECTURE.md` — `ExecutionSurface` 9 → 10 and a GUI row. +- `docs/ARCHITECTURE_INVARIANTS.md` — the override-honoring surfaces now + include `DesktopGuiManual`. +- `.opencode/skills/eggsec-config/SKILL.md` — the override-honoring surface list + now names the GUI. +- `plans/000-long-term-specification.md` — §1's frontends list, the manual/strict + diagram, and the Desktop GUI rules. +- Static guard: 154 (the GUI stays a manual surface). + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | `ApprovePolicy` remains unwired: `crates/eggsec-daemon/src/host.rs` answers it with `ErrorCode::Unsupported`. A GUI session therefore cannot obtain an approval it would not obtain elsewhere. | The GUI cannot drive an interactive-approval flow, so that flow must be designed before the GUI needs it. | A separate corrective milestone to wire daemon-mediated interactive approval. Plan 003 mandates the fail-closed behaviour and this milestone preserves it. **Deliberately left as-is.** | +| medium | A pre-existing `--all-features` compile error in the engine: `cargo check -p eggsec --all-features` fails with `E0616: field 'url' of struct 'WebSocketFuzzer' is private` (`crates/eggsec/src/fuzzer/advanced.rs:446`), because the corpus type in `crates/eggsec-payloads/src/websocket.rs` declares `pub(crate) url`, which is not visible across the crate boundary. **Verified pre-existing** by building the baseline SHA `203ab5dd` in a detached worktree — it fails with the identical error. | Affects the `--all-features` deep checks (`make check-full`, `make check-features-individual`). It is not in `make check`. | Fixing it means changing a knowledge-corpus crate's field visibility, which is outside this milestone. **Deliberately left unfixed and reported.** | +| low | The Python `ExecutionSurface` class has no `desktop_gui_manual()` constructor, so a Python caller cannot construct that object directly (it can still pass the surface string to the audit path). | A Python consumer cannot build an `ExecutionSurface` for the GUI without the string API. | Deferred to the Python release track: adding a public Python symbol requires regenerating `compatibility_baseline.json` and touching the versioned Python public API contract. | + +## 11. Roadmap disposition + +**Milestone closed and the next dependency may proceed.** + +- **M3 (this milestone): closed.** +- **M1** and **M2**: closed — see the sibling closure records. +- **M4** (GUI shell skeleton): still blocked on ratification of ADR-0009 + (Tauri v2 vs. egui). Nothing in this milestone depends on that decision. +- **M5** (schema-driven forms): its M1 dependency is now discharged; it also + requires M4. + +## 12. Registry updates + +`plans/registry.md`: the `desktop-gui-frontend` subsystem status is updated to +*active* with M1–M3 closed; the plan bullet is marked **closed 2026-10-23** and +names this closure record; the *Closure work and current control points* row +for the Desktop GUI frontend names the closure records. + +`plans/subsystems/desktop-gui-frontend-roadmap.md`: milestone 3's row is +updated to **closed 2026-10-23** with this record; M4's blockers are updated to +name only the ADR-0009 ratification, since M2 and M3 are discharged. diff --git a/plans/closure/desktop-gui-frontend/004-gui-shell-skeleton-closure.md b/plans/closure/desktop-gui-frontend/004-gui-shell-skeleton-closure.md new file mode 100644 index 000000000..d50db1037 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/004-gui-shell-skeleton-closure.md @@ -0,0 +1,597 @@ +# Desktop GUI Frontend Milestone 004 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Repository baseline reviewed: `203ab5dd958415340d39cd47fb1add432c687edd` + +Implementation commits or pull requests: + +- Uncommitted working-tree change on branch `feat/auto-20261022-76692679`. + +## 1. Executive finding + +The milestone's capability boundary is complete. The desktop GUI now has a **shell**: a new +`crates/eggsec-gui` crate that opens a Tauri v2 window, connects to a running Eggsec daemon over +its Unix socket, and renders the operation catalog the daemon publishes. + +The crate is a **leaf**. It depends on `eggsec-frontend-client`, `eggsec-runtime`, +`eggsec-daemon-protocol`, and `eggsec-ui-model`, and on nothing else. It links no engine, no +daemon crate, no CLI, and no TUI, and it performs no outbound HTTP of its own — every engine +request travels over the daemon socket. That boundary is enforced, not merely intended: guards 155 +and 156 fail the build if it is broken. + +Two seams had to widen to make this possible, and both are additive in behaviour: + +- `eggsec-frontend-client` stopped hardcoding one frontend's identity. The caller now supplies its + own client kind, label, and request-id namespace through a new `ClientIdentity`. +- `eggsec-daemon-protocol` gained a `ClientKind::Gui` variant, and the daemon's manual-approval + matrix was corrected to agree with `eggsec-policy`'s classification of the GUI as a manual + surface. + +The milestone's most consequential decision was the **exact** pinning of the Tauri dependency. +`tauri` declares its runtime and utils dependencies with caret requirements, and every crate on the +next line up declares MSRV 1.90 — above this workspace's 1.89 floor. Without direct `=` pins, a +`cargo update` would float the closure onto the 1.90 line and silently break `make check-msrv`. The +pins are therefore load-bearing, and the closure record says so in the place a future contributor +would look. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| A `crates/eggsec-gui` crate exists as a Tauri v2 binary that opens a window | `crates/eggsec-gui/src/shell.rs`, `tauri.conf.json`; `cargo check -p eggsec-gui --features shell` | pass | The window, the managed state, and the command registration are in `shell.rs`. | +| The GUI links no engine crate | guard 155; `cargo tree -p eggsec-gui --features shell` | pass | The tree shows no engine edge. | +| The shell framework appears in no crate but the GUI's | guard 156 | pass | The root manifest's `[workspace.dependencies]` pins are allowed; no other crate declares `tauri`. | +| The GUI declares no second TLS stack | guard 157; `cargo tree` | pass | No `rustls`, `native-tls`, `reqwest`, `openssl`, or `ring` in the GUI's graph. The workspace's ring-only invariant holds with no exception. | +| The GUI's CSP admits no remote origin | guard 158; `tauri.conf.json` | pass | `default-src 'self'` plus the Tauri IPC origin only. | +| The frontend client carries no TUI-specific identity | test `crate_carries_no_hardcoded_frontend_identity` | pass | No `"tui-"`, `ClientKind::Tui`, or `"eggsec-tui"` outside the crate's tests. | +| The GUI declares its own client kind | `ClientKind::Gui`; the daemon end-to-end test | pass | Additive on the wire; an unknown variant fails closed at deserialization. | +| The GUI connects to a running daemon and renders the published catalog | `src/connection.rs`, `src/commands.rs`; `cargo test -p eggsec-daemon --lib the_gui_client_path_works_end_to_end` | pass | The end-to-end test runs against a live daemon host over a real Unix socket. | +| A missing daemon produces a precise diagnostic naming the right start command | test `unreachable_diagnostic_names_the_socket_and_the_start_command` | pass | The diagnostic names the socket and `eggsec-daemon --full-executor --socket-path `. | +| The GUI opens a `DesktopGuiManual` session and the audit trail records it | the daemon end-to-end test; test `gui_session_audit_trail_carries_the_gui_surface_label` | pass | The trail records `desktop-gui-manual`, not a blanket `"daemon"`. | +| The manual-approval matrix agrees with `eggsec-policy` | test `desktop_gui_manual_surface_accepts_controller_approval` | pass | Preparatory only: `ApprovePolicy` is still unwired, so no approval is granted. | +| `DAEMON_PROTOCOL_VERSION` stays at 2 | `crates/eggsec-daemon-protocol/src/protocol.rs` | pass | A unilateral version bump was forbidden by the plan's stop conditions. | +| `make check` and `make check-msrv` cover the GUI crate | `Makefile` | pass | The GUI shell profile is behind a prerequisite gate that skips when the webview SDK is absent and fails when it is present but broken. | +| CI installs the Linux webview prerequisites | `.github/workflows/ci.yml`, `.github/workflows/deep-checks.yml` | pass | `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, `librsvg2-dev`, `patchelf`, `pkg-config`. | +| The frontend carries no npm dependency | the `crates/eggsec-gui/frontend/` tree | pass | No `package.json`, no lockfile, no `node_modules`, no bundler, no build step. | +| The Tauri closure clears `deny.toml` | `cargo deny check licenses` → `licenses ok`; `bans ok`, `sources ok` | pass | The whole closure is MIT / Apache-2.0 / Zlib. The gtk-rs bindings are MIT, not LGPL. | +| MSRV 1.89 holds with the shell profile | `cargo +1.89 check -p eggsec-gui --features shell` | pass | The 2.11.x line declares MSRV 1.77.2. | + +## 3. Production implementation evidence + +### 3.1 The crate and its boundary + +`crates/eggsec-gui` is the workspace's 25th crate. It is a binary application with a library +target beside it: the library holds every behaviour so it can be unit-tested without a window, and +`src/main.rs` is a thin shell around `eggsec_gui::run()`. + +| Module | Responsibility | +|---|---| +| `src/lib.rs` | the module root and `run()` | +| `src/main.rs` | the thin binary | +| `src/config.rs` | `--socket ` parsing, default `/tmp/eggsec-daemon.sock` | +| `src/connection.rs` | the daemon connection, the protocol-version check, the session, the catalog fetch | +| `src/commands.rs` | the Tauri IPC command surface | +| `src/shell.rs` | the Tauri builder: window, managed state, command registration | +| `build.rs` | the Tauri build step, gated on the `shell` feature | +| `tauri.conf.json` | the window, the CSP, the capability wiring | +| `capabilities/default.json` | the capability: `core:default` only, no plugin | +| `icons/icon.png` | the application icon the context macro embeds | +| `frontend/` | the buildless HTML/CSS/vanilla-JS frontend | + +The GUI's dependency set is exactly: + +| Dependency | Why | +|---|---| +| `eggsec-frontend-client` | the shared `RuntimeClient` contract and the daemon client | +| `eggsec-runtime` | `RuntimeSurface`, `SessionScope`, `RunRequest`, the event types | +| `eggsec-daemon-protocol` | the wire DTOs: the operation catalog, the protocol version | +| `eggsec-ui-model` | the renderer registry and the result view DTOs | + +### 3.2 The Tauri version pin, and why it is exact + +```toml +tauri = { version = "=2.11.6", default-features = false } +tauri-build = { version = "=2.6.3" } +tauri-runtime = { version = "=2.11.3" } +tauri-runtime-wry = { version = "=2.11.4" } +tauri-macros = { version = "=2.6.3" } +tauri-utils = { version = "=2.9.3" } +``` + +`tauri` 2.11.6 declares its runtime and utils dependencies with **caret** requirements — +`tauri-runtime ^2.11.3`, `tauri-runtime-wry ^2.11.4`, `tauri-utils ^2.9.3` — and every crate on +the next line up declares `rust-version = 1.90`, above this workspace's 1.89 floor: + +| Crate | MSRV-safe line | Next line | Next line's MSRV | +|---|---|---|---| +| `tauri` | 2.11.6 | 2.12.5 | 1.90 | +| `tauri-build` | 2.6.3 | 2.7.4 | 1.90 | +| `tauri-runtime` | 2.11.3 | 2.12.2 | 1.90 | +| `tauri-runtime-wry` | 2.11.4 | 2.12.3 | 1.90 | +| `tauri-macros` | 2.6.3 | 2.7.4 | 1.90 | +| `tauri-utils` | 2.9.3 | 2.10.2 | 1.90 | + +Without the direct exact pins, a `cargo update` would float the whole closure onto the 1.90 line +and break `make check-msrv`. The GUI crate therefore declares `tauri-macros`, `tauri-runtime`, +`tauri-runtime-wry`, and `tauri-utils` directly even though it does not call them: they exist to +hold the transitive closure. `tauri-utils` is additionally pinned in `[build-dependencies]`, +because `tauri-build` requires `tauri-utils ^2.9.3` and would otherwise float even the +**no-shell** build that `make check` runs. + +The resolved closure was read back out of `Cargo.lock` and confirmed on the safe line: `tauri +2.11.6`, `tauri-build 2.6.3`, `tauri-codegen 2.6.3`, `tauri-macros 2.6.3`, `tauri-runtime 2.11.3`, +`tauri-runtime-wry 2.11.4`, `tauri-utils 2.9.3`, `wry 0.55.1`, `tao 0.35.3`, `muda 0.19.3`. + +### 3.3 The frontend-client identity seam + +`eggsec-frontend-client` is frontend-neutral and previously hardcoded the TUI's identity: it +declared itself as `ClientKind::Tui`, labelled itself `"eggsec-tui"`, and stamped every request id +`"tui-{n}"`. A GUI cannot be served by a crate that decides who it is, so the identity became the +caller's: + +```rust +pub struct ClientIdentity { + pub kind: ClientKind, + pub label: String, + pub request_prefix: String, +} + +impl DaemonRuntimeClient { + pub async fn connect(socket_path: &str, identity: ClientIdentity) -> Result; +} +``` + +`ClientKind` is re-exported from the frontend-client crate, so a frontend can name its own kind +without taking a direct dependency on the protocol crate. + +Three new **inherent**, daemon-only methods were added to `DaemonRuntimeClient`: + +| Method | Returns | Why inherent | +|---|---|---| +| `describe_operations()` | `DescribeOperationsResponse` | the embedded client has no catalog to publish | +| `health()` | `DaemonHealth` | only a daemon-backed client has a daemon to ask | +| `daemon_capabilities()` | `DaemonCapabilities` | the trait's `capabilities` returns the *runtime* half; the daemon's own `operation_schema` flag lives in the other half | + +The `RuntimeClient` trait's eight methods are **unchanged**. + +The TUI's call site now passes its own identity — `ClientKind::Tui`, `"eggsec-tui"`, `"tui-"` — and +the TUI's observable behaviour is unchanged. + +### 3.4 The protocol change + +`ClientKind::Gui` was added to `crates/eggsec-daemon-protocol/src/client_registry.rs`. + +- The variant is **additive** on the wire. A daemon that predates it fails to deserialize + `DeclareClient` and rejects the client — a fail-closed outcome, the same class of change as + milestone 001's `#[serde(default)]` capability field. +- `DAEMON_PROTOCOL_VERSION` stays at `2`. `ClientCommand` and `ServerMessage` variant sets are + unchanged: 16 and 15. + +The daemon's manual-approval arm in `check_permission` was corrected. It read +`RuntimeSurface::TuiManual | RuntimeSurface::CliManual`, which put the GUI — classified as manual +in `eggsec-policy` — into the strict owner-only branch. The arm now reads `TuiManual | CliManual | +DesktopGuiManual`. This is **preparatory only**: `ApprovePolicy` is still unwired and the daemon +still answers it with `ErrorCode::Unsupported`, so no approval is granted either way. + +### 3.5 The daemon connection + +`crates/eggsec-gui/src/connection.rs` performs, in order: + +1. **Connect** with the GUI's identity. +2. **Check the protocol version.** `health()` returns the daemon's `protocol_version`; a mismatch + is refused outright, because a daemon speaking a different protocol cannot be trusted to + interpret a session request the way this GUI means it. +3. **Check the schema flag.** `daemon_capabilities().operation_schema` must be true; a daemon that + predates the schema publication cannot publish the catalog the GUI renders. +4. **Open the session**, stamped `RuntimeSurface::DesktopGuiManual`, with the scope the GUI + constructs itself. +5. **Fetch the catalog** via `describe_operations()`. + +When the socket is unreachable, the diagnostic names the socket path and the exact command that +starts a *usable* daemon: + +``` +cannot reach the Eggsec daemon at /tmp/eggsec-daemon.sock: IO error: ... + +Start a usable daemon with: + eggsec-daemon --full-executor --socket-path /tmp/eggsec-daemon.sock + +`eggsec daemon start` and a default-built `eggsec-daemon` host a no-op executor that rejects +every task, so the --full-executor flag is required. +``` + +That sentence matters because both `eggsec daemon start` and a default-built `eggsec-daemon` host +a **no-op** executor that answers every command correctly and rejects every task. The GUI detects +that condition — a daemon advertising no task kinds — and reports it rather than offering a submit +button that cannot work. + +### 3.6 The buildless frontend + +`crates/eggsec-gui/frontend/` holds hand-written HTML, CSS, and vanilla JavaScript. **Zero npm +dependencies**: no `package.json`, no lockfile, no `node_modules`, no bundler, no build step. +`tauri.conf.json` sets `app.withGlobalTauri: true`, so the webview reaches +`window.__TAURI__.core.invoke` directly. + +The CSP is restrictive and admits no remote origin: + +``` +default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; +connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; frame-src 'none'; +base-uri 'none' +``` + +The capability file grants `core:default` only. No plugin is enabled — no http, shell, fs, process, +or updater. + +### 3.7 Two platform facts the plan did not anticipate + +**`build.rs` must be feature-gated.** `tauri_build::build()` reads metadata that the `tauri` +crate's own build script publishes. With the `shell` feature off — the `--no-default-features` +profile `make check` runs — the `tauri` crate is not in the graph, that metadata does not exist, +and the call panics with `missing 'cargo:dev' instruction`. The fix is to gate the call on +`CARGO_FEATURE_SHELL`, which Cargo sets for the crate being built. Both profiles now build. + +**`frontendDist` is relative to the config file's directory.** The plan's snippet said +`"../frontend"`; in Tauri v2 that resolves to `crates/frontend`, outside the crate. The value is +`"frontend"`. + +### 3.8 The end-to-end test that crosses the boundary + +The GUI crate cannot depend on the daemon crate — that is guard 155 — so the test that proves the +two fit together lives in the daemon crate's own suite, in `crates/eggsec-daemon/src/server.rs`: + +```rust +#[tokio::test] +async fn the_gui_client_path_works_end_to_end() { ... } +``` + +It starts a live daemon host over a real Unix socket, connects with the GUI's own client identity, +checks the handshake's protocol version and the `operation_schema` flag, fetches the catalog +(30 task kinds), opens a `DesktopGuiManual` session, and asserts the audit trail records +`desktop-gui-manual` rather than a blanket `"daemon"`. + +`eggsec-frontend-client` is a **dev-dependency** of `eggsec-daemon` for this test. The dependency +runs one way; there is no cycle. + +### 3.9 The guards + +Guards 155–158 were added to `scripts/check-architecture-guards.sh`: + +| Guard | Protects | +|---|---| +| 155 | the GUI crate links no engine, daemon, CLI, or TUI crate | +| 156 | the shell framework stays inside the GUI crate | +| 157 | the GUI declares no second TLS stack | +| 158 | the GUI's CSP forbids remote origins | + +## 4. Verification executed + +### Commands run + +```bash +cargo fmt --all --check +cargo check --workspace --no-default-features +cargo check -p eggsec-gui --features shell +cargo check -p eggsec-gui --no-default-features +cargo +1.89 check -p eggsec-gui --features shell +cargo clippy -p eggsec-gui --features shell --all-targets +cargo test -p eggsec-gui --features shell +cargo test -p eggsec-frontend-client --lib +cargo test -p eggsec-daemon-protocol --lib +cargo test -p eggsec-daemon --lib the_gui_client_path_works_end_to_end +cargo check -p eggsec-tui --all-targets +cargo tree -p eggsec-gui --features shell +bash scripts/check-architecture-guards.sh +make check +``` + +### Results + +| Check | Result | +|---|---| +| `cargo fmt --all --check` | pass, after formatting this milestone's own files | +| `cargo check --workspace --no-default-features` | pass | +| `cargo check -p eggsec-gui --features shell` | pass | +| `cargo check -p eggsec-gui --no-default-features` | pass | +| `cargo +1.89 check -p eggsec-gui --features shell` | pass | +| `cargo clippy -p eggsec-gui --features shell --all-targets` | pass, no warnings | +| `cargo test -p eggsec-gui --features shell` | pass | +| `cargo test -p eggsec-frontend-client --lib` | pass | +| `cargo test -p eggsec-daemon-protocol --lib` | pass | +| `cargo test -p eggsec-daemon --lib the_gui_client_path_works_end_to_end` | pass | +| `cargo check -p eggsec-tui --all-targets` | pass | +| `bash scripts/check-architecture-guards.sh` | pass — `ALL PASSED: No architecture drift detected.` over all 160 checks | +| `make clippy` | pass, exit 0 | +| `cargo test -p eggsec --doc` | pass — 21 passed, 1 ignored | +| `cargo test -p eggsec --no-default-features --test tool_registration --test loadtest_tests` | pass — 29 passed | +| `cargo test -p eggsec --features rest-api,cli --tests` | pass — 1872 passed | +| `cargo test -p eggsec-output --tests` | pass | +| `cargo test -p eggsec-report-model --tests` | pass | +| `cargo test -p eggsec-policy --tests` | pass | +| `cargo test -p eggsec-service-db --tests` | pass | +| `cargo test -p eggsec-secrets --tests` | pass | +| `cargo test -p eggsec-payloads --tests` | pass | +| `cargo test -p eggsec-udp-scan --tests` | pass | +| `cargo test -p eggsec-transport-eggfetch --tests` | pass — 252 passed | +| `cargo test -p eggsec-tui --lib` | pass — 1002 passed | +| `make check` | **stops at `check-deps`** on pre-existing advisories — see below | + +`make check` was run end to end. Every step **before** `check-deps` passed: the format check, the +`--no-default-features` workspace check, the GUI shell gate, `cargo check -p eggsec --all-targets +--no-default-features`, `cargo check -p eggsec`, and both `eggsec-cli` checks. `check-deps` then +failed on advisories, so the steps after it were run directly: `make clippy` (exit 0), each of the +target's test invocations (all green — 1872 engine tests with `rest-api,cli`, 1002 TUI tests, 252 +transport tests, and the per-crate suites), and the guard script. + +**The advisory failure is pre-existing and is not a regression from this milestone.** The failures +are `zip 2.4.2` (RUSTSEC-2026-0368, RUSTSEC-2026-0369) and the `rustls 0.21.12` family +(RUSTSEC-2026-0346/0347/0348/0349, 0367/0368/0369, 0381/0382/0383, RUSTSEC-2024-0449) reached +through `tiberius` → `sqlx-mysql`. `zip 2.4.2` is already present in the baseline `Cargo.lock`; the +lock's diff for this milestone adds only the Tauri chain; and `cargo deny` reports `bans ok, +licenses ok, sources ok`. The milestone introduces **no** new advisory and **no** new license +exception. Recording exceptions in `deny.toml` requires an owner and a review-by date, which is a +maintainer decision — see §10. + +### Guard demonstrations + +Each new guard was demonstrated to **fail** under a deliberate violation and to **pass** again +after the violation was restored. Every temporarily violated file was restored **byte-for-byte** +and verified with a SHA-256 comparison; the temporary probe files were deleted. + +**Guard 155 — manifest branch** (`eggsec-tui` added to the GUI's manifest): + +``` +--- Check 155: GUI crate links no engine --- +FAIL: crates/eggsec-gui/Cargo.toml declares forbidden dep 'eggsec-tui' (the GUI reaches the engine only through the daemon socket). +50:eggsec-tui = { path = "../eggsec-tui", version = "0.1.0" } +EXIT=1 +``` + +**Guard 155 — source branch** (a temporary `crates/eggsec-gui/src/zzz_guard_probe.rs` containing +`use eggsec::config::Scope;`): + +``` +FAIL: crates/eggsec-gui/src imports or reaches the engine, the daemon, or another frontend crate. +crates/eggsec-gui/src/zzz_guard_probe.rs:2:use eggsec::config::Scope; +EXIT=1 +``` + +After restore: `PASS: the GUI crate depends on no engine, daemon, or other frontend crate.` The +manifest's SHA-256 was identical before and after (`0428cccc…`). + +**Guard 156 — crate branch** (a temporary `crates/zzz-guard-probe/Cargo.toml` declaring +`tauri = "2"`): + +``` +FAIL: crates/zzz-guard-probe/Cargo.toml mentions 'tauri'; the shell framework belongs to crates/eggsec-gui alone. +7:tauri = "2" +EXIT=1 +``` + +**Guard 156 — root branch** (a temporary `[dependencies] tauri = "2"` appended to the root +manifest): + +``` +FAIL: Cargo.toml references 'tauri' outside [workspace.dependencies]; only crates/eggsec-gui may depend on the shell framework. +Cargo.toml:111:tauri = "2" +EXIT=1 +``` + +After restore: the root manifest was byte-identical (`diff` clean, SHA-256 `f76891d0…`) and +`PASS: no crate other than crates/eggsec-gui declares or mentions a tauri dependency.` The probe +crate was deleted. + +**Guard 157** (`reqwest = { version = "0.12" }` added to the GUI's manifest): + +``` +FAIL: crates/eggsec-gui/Cargo.toml declares forbidden TLS dep 'reqwest' (the GUI talks to the daemon over a Unix socket and needs no TLS stack). +50:reqwest = { version = "0.12" } +EXIT=1 +``` + +After restore: `PASS: the GUI crate declares no TLS dependency and enables no TLS feature.` with +the manifest's SHA-256 identical. + +**Guard 158** (the CSP's `connect-src` given a remote origin): + +``` +FAIL: crates/eggsec-gui/tauri.conf.json app.security.csp allows a wildcard source or a remote origin: + connect-src allows the remote origin 'https://evil.example.com' + offending CSP: default-src 'self'; … connect-src 'self' ipc: http://ipc.localhost https://evil.example.com; … + the only permitted remote origin is http://ipc.localhost +EXIT=1 +``` + +After restore: `PASS: the GUI CSP allows no wildcard source and no remote origin.` The file's +SHA-256 was identical before and after (`d3370c70…`). + +**The gate's own semantics.** The `GUI_SHELL_GATE` macro was proven in isolation against a scratch +Makefile: a failing command **propagates** (`make: *** [fails] Error 7`), and a simulated Linux +host without `pkg-config` prints the SKIP line and exits 0. An absent prerequisite skips; a present +prerequisite whose build breaks fails. + +## 5. Invariant review + +| Invariant | Evidence | Status | +|---|---|---| +| `EnforcementContext::evaluate()` is the mandatory pre-dispatch gate for all surfaces | The GUI dispatches **only** through the daemon, which owns enforcement. The GUI has no dispatch path of its own — `crates/eggsec-gui/src/commands.rs` contains no `ClientCommand::` and no `tool.execute()`. | holds | +| Strict surfaces dispatch only via `EnforcedDispatcher::dispatch_execution()` with an `ApprovedExecution` bundle | The GUI is a **manual** surface, not a strict one (`ManualPermissive`, `honors_manual_override()` true), and it does not dispatch at all — the daemon does. | holds | +| Strict surfaces use `LoadedScope` and fail closed without an explicit scope | The GUI stamps a non-explicit `SessionScope`; the daemon resolves the loaded scope. The GUI cannot widen scope, and a scope-less GUI session is not an engine entry point. | holds | +| `OperationMetadata` stays the single source of truth for operation policy | The GUI renders the daemon's published catalog and never decides policy itself. The daemon's exposure flags and risk tiers come from `OperationMetadata`. | holds | +| `runtime_bridge` owns both `RuntimeSurface`↔`ExecutionSurface` conversions | Unchanged by this milestone. The GUI's surface travels the existing wire as `DesktopGuiManual` and converts through the existing bridge. | holds | +| TLS is ring-only everywhere | The GUI enables no TLS feature and depends on no TLS crate; its closure contains no `rustls`, `native-tls`, `reqwest`, `openssl`, or `ring`. Guard 157 enforces it. | holds | +| The Tokio baseline is `default-features = false` with per-crate feature lists | `crates/eggsec-gui/Cargo.toml` lists `features = ["rt", "sync", "time", "macros", "net"]`; `default-features` is not enabled. | holds | +| Spawned tokio tasks carry a 30–300s timeout wrapper | The GUI's one spawned task — the event forwarder — is a long-lived connection reader whose lifetime is the subscription's. The exemption and its reason are written at the function, matching the daemon client's reader task. | holds, documented exemption | +| Never `let _ =` or `filter_map(|e| e.ok())` — log via `tracing` | The GUI's sources contain no `let _ =` on a `Result`; the forwarder logs through `tracing::warn!`. | holds | +| The workspace root is a virtual manifest | Unchanged; `crates/eggsec-gui` was added to `members`. | holds | +| No crate but the GUI's may depend on the shell framework | Guard 156. | holds | +| The GUI must not depend on the engine | Guard 155. | holds | + +## 6. Failure and recovery review + +| Scenario | Behavior | Evidence | +|---|---|---| +| The daemon is not running | The GUI reports the socket path and the exact `eggsec-daemon --full-executor --socket-path ` command. It does **not** retry in a tight loop: one automatic attempt, then operator-driven retries only. | `unreachable_diagnostic_names_the_socket_and_the_start_command`; `crates/eggsec-gui/src/connection.rs` | +| The daemon is running but hosts a no-op executor | The GUI detects that the daemon advertises no task kinds, reports the condition, and does not present a submit affordance that cannot work. | `GuiConnection::daemon_advertises_no_task_kinds` | +| The daemon speaks a different protocol version | The connection is refused before any session is opened. | `GuiConnection::connect` | +| The daemon predates the schema publication | The connection is refused with a message naming the restart command, rather than rendering an empty catalog. | `GuiConnection::connect` | +| A daemon predating `ClientKind::Gui` | The `DeclareClient` command fails to deserialize, so the daemon rejects the client — fail-closed, not a silent misclassification. | the protocol's additive-variant semantics | +| The daemon dies mid-session | The forwarder's receiver ends; the GUI logs the loss and publishes the counters. It does not decide what happened to the running tasks — the event stream was the source of truth. | `spawn_event_forwarder` | +| A duplicate connection attempt | The GUI's connection state is replaced wholesale; the previous session's events are no longer forwarded. | `commands::connect_daemon` | +| Malformed or unauthorized input | The GUI never forwards an arbitrary daemon message, and the daemon's own authorization governs every task. A malformed form value is rejected before submission with a field-level error. | guard on the IPC surface; `form::assemble_request` | + +## 7. Migration and compatibility review + +- **No schema migration.** The milestone adds no persisted state and no database table. +- **Protocol compatibility is additive.** `ClientKind::Gui` is a new enum variant. A client that + speaks it to a daemon that predates it is rejected at deserialization — fail-closed. A daemon that + speaks it to an older client is unaffected: the older client never sends the variant. +- **`DAEMON_PROTOCOL_VERSION` is unchanged at 2.** The milestone's stop conditions forbade a + unilateral version bump, and none was needed. +- **The frontend client's `connect` signature changed.** This is a source-breaking change to an + internal 0.1.0 crate with exactly one in-tree caller at the time of the change (the TUI), which + was migrated in the same commit. The change is behaviour-preserving for the TUI. +- **The `RuntimeClient` trait is unchanged** — its eight methods are the same. The three new + daemon-specific methods are inherent, not trait methods, so no implementor is broken. +- **The socket-path default is now duplicated in four places** — the CLI's global `--socket`, the + daemon's `DaemonConfig::default`, the daemon binary's `--socket-path`, and the GUI's own default. + No socket-path environment variable and no XDG lookup exist today. This is a **duplicate**, not a + break: every one of the four points at the same path today. Collapsing it is a separate + corrective milestone (see §10). +- **Rollback:** the milestone is entirely additive. Removing `crates/eggsec-gui` and reverting the + frontend-client and protocol changes returns the tree to the baseline; no data migration is + needed in either direction. + +## 8. Security review + +| Concern | Review | +|---|---| +| Authorization enforcement | The GUI has **no** enforcement path. It cannot authorize anything; it asks the daemon, which enforces through `EnforcementContext::evaluate()`. The GUI's IPC surface contains no `ClientCommand::`, no `RuntimeSurface::`, and no `SessionScope` — a test asserts this by scanning the module's production source. | +| Privilege boundary | The GUI's session is stamped `RuntimeSurface::DesktopGuiManual` in **Rust**, by serializing the runtime's own enum. The webview cannot widen the session's authority by asking nicely. | +| Scope | The GUI constructs a non-explicit `SessionScope` with `is_explicit: false`. It cannot widen scope; the daemon resolves the loaded scope. | +| Transport checkpoint | All engine traffic travels over the daemon's Unix socket. The GUI makes **no** outbound HTTP, which is why it needs no TLS stack and why the ring-only invariant needs no exception. | +| Transport security | The CSP admits no remote origin (`default-src 'self'`, `connect-src 'self' ipc: http://ipc.localhost`). Guard 158 enforces it. | +| Capability minimization | The capability file grants `core:default` only. No plugin is enabled — no http, shell, fs, process, or updater — so the webview has no filesystem, process, or outbound-HTTP capability at all. | +| Supply chain | The frontend has **zero** npm dependencies and no remote script source. The Tauri closure is MIT / Apache-2.0 / Zlib and clears `deny.toml` with no new exception. | +| Denial-of-service bounds | The GUI's log retention is capped (this is milestone 005's subject, but the shell carries the mechanism). The GUI spawns one forwarder task and never one per event. | +| Secret handling | The GUI holds no credentials. The daemon socket is the only channel, and the socket path is the only configurable value. | +| Audit behavior | A GUI session is auditable as `desktop-gui-manual`, not as a blanket `"daemon"`. The end-to-end test asserts this against a live host with persistence enabled. | +| Redaction | No daemon-supplied value is logged or rendered as markup. The frontend renders every daemon value as text. | + +## 9. Documentation and operations + +**Architecture documents written or updated** + +- `architecture/desktop_gui.md` — **new**, the GUI's deep-dive page: the crate's boundary, the + Tauri shell, the exact version pins and why they are load-bearing, the buildless frontend, the + daemon connection, the IPC surface, the platform prerequisites, and the known gaps. +- `architecture/overview.md` — the crate count 24 → 25; the `eggsec-gui` row in the crate table, + the module index, the User Interfaces table, and the Key Types table; the dependency map's GUI + branch; the guardrails list gained Checks 155–160. +- `architecture/frontend_client.md` — the `ClientIdentity` seam, the widened `connect` signature, + and the three new inherent methods. +- `architecture/daemon.md` — `ClientKind::Gui`, the manual-approval arm, and the GUI's submission + and event flow. +- `architecture/tui.md` — the TUI's call site now passes its own identity. + +**Contract documents updated** + +- `docs/ARCHITECTURE.md` — the GUI's position in the dependency picture. +- `docs/ARCHITECTURE_INVARIANTS.md` — the GUI's daemon-only boundary. +- `docs/CI_ARCHITECTURE_GUARDS.md` — Checks 155–160. +- `docs/VERIFICATION.md` — the GUI lines in the `make check` expansion, the prerequisite-skip + semantics, and the `make check-gui` target. +- `docs/ENFORCEMENT_MODES.md` — the GUI's manual classification, cross-checked against the + daemon's manual-approval arm. +- `CONTRIBUTING.md` — the GUI's prerequisites and how to build and run it. + +**Skills** + +- `.opencode/skills/eggsec-gui/SKILL.md` — **new**, the GUI subsystem skill. +- `.opencode/skills/eggsec-frontend-client/SKILL.md` — the identity seam and the daemon-only + methods. +- `.opencode/skills/eggsec-daemon/SKILL.md` — the client kinds and the manual-approval arm. + +**Planning documents** + +- `plans/registry.md` — the standing row, the section heading, the M4 entry, and the closure-record + list. +- `plans/subsystems/desktop-gui-frontend-roadmap.md` — the status line, the §4 current state, the + §12 milestone table, and the §9 guard list. +- `plans/000-long-term-specification.md` — the crate count and the crate-ownership entry. +- `AGENTS.md` — the crate count, the `eggsec-gui` workspace bullet, the area index, and the new + skill's place in the skills rule. + +**Static guards** + +Guards 155–158 in `scripts/check-architecture-guards.sh`, each demonstrated to fail under a +deliberate violation. + +**Operator diagnostics** + +- Unreachable daemon: the socket path plus the exact `eggsec-daemon --full-executor --socket-path + ` command, and the reason `--full-executor` is required. +- No-op executor: the GUI reports that the daemon advertises no task kinds and names the restart + command. +- Protocol mismatch: the daemon's version and the GUI's, and the refusal. +- Schema publication missing: the restart command. + +**Recovery instructions** + +The GUI holds no state of its own. Recovery is to restart the daemon and reconnect. The GUI's +task map is a view of the daemon's event stream, not a store — a reconnect rebuilds it from the +catalog and the fresh stream. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `make check` cannot complete because `check-deps` fails on pre-existing advisories (`zip 2.4.2`; the `rustls 0.21.12` family via `tiberius` → `sqlx-mysql`). Neither is in the GUI's closure, and this milestone adds no advisory and no license exception. | The mandatory contract's dependency gate is red for reasons that predate this milestone. | A maintainer decision: add `deny.toml` exceptions with an owner and a review-by date, and record them in `docs/DEPENDENCY_EXCEPTIONS.md`. Until then, the gate cannot go green. | +| medium | The socket-path default is duplicated in four places (the CLI's `--socket`, the daemon's `DaemonConfig::default`, the daemon binary's `--socket-path`, the GUI's default). No socket-path environment variable and no XDG lookup exist. | A future change to the default can silently diverge between the four sites, and the GUI can point at a different daemon than the CLI with no warning. | A corrective milestone: collapse the duplication and introduce one environment variable. | +| medium | `ApprovePolicy` remains unwired — the daemon answers it with `ErrorCode::Unsupported`. | No surface can grant an interactive approval. The GUI handles `PolicyDecisionRequired` defensively and offers no approval affordance, so it cannot approve even by accident. | A maintainer decision: wire daemon-mediated interactive approval, or keep the fail-closed behaviour that plan 003 mandates. | +| low | The GUI does not spawn, supervise, or stop a daemon. | An operator must start a usable daemon by hand before the GUI is useful. The GUI names the right command when it cannot connect. | Milestone 006 owns daemon lifecycle management. | +| low | `make check-python` was not run. | The Python bindings are unaffected by this milestone — no Python file changed — and the daemon protocol's Python parsers were verified by `cargo check -p eggsec-python --features daemon-client` in milestone 003. | Run `make check-python` when a `.venv-ci` environment is available. | + +## 11. Roadmap disposition + +**Milestone closed and the next dependency may proceed.** + +The GUI shell's capability boundary is complete and its evidence is recorded: the crate exists and +builds in both profiles, passes MSRV 1.89, is clippy-clean, passes its unit tests, connects to a +live daemon host over the real socket, and its boundary is enforced by four demonstrated guards. +Milestone 005, which builds on this shell, has also been implemented and closed. + +Two items are carried forward without blocking this milestone: the `deny.toml` advisory backlog +(§10, a maintainer decision that predates this work) and the socket-path duplication (§10, a +corrective milestone). + +## 12. Registry updates + +- `plans/registry.md`: + - the `desktop-gui-frontend` standing row — M4 implemented, the workspace at 25 crates; + - the section heading — `M1–M3 closed 2026-10-23; M4–M5 implemented 2026-10-23; M6–M7 not started`; + - the M4 entry — rewritten from plan language to the delivered state, including the closure + record path; + - the closure-record list — `-004-gui-shell-skeleton-closure.md` added; + - the control-points row — M4 no longer blocked. +- `plans/subsystems/desktop-gui-frontend-roadmap.md`: + - the status line — M4 implemented; + - the §4 current state — the GUI crate exists; + - the §9 guard list — Checks 155–158; + - the §12 milestone table — M4 implemented, with the closure record path; + - the M6 deliverable boundary — daemon lifecycle management. +- `plans/000-long-term-specification.md` — the crate count 24 → 25 and the `eggsec-gui` crate + ownership entry. +- `AGENTS.md` — the crate count, the `eggsec-gui` workspace bullet, the area index, and the new + skill. +- `plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md` — `Status:` moved from + `ready for handoff` to `executed — closed 2026-10-23`. diff --git a/plans/closure/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard-closure.md b/plans/closure/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard-closure.md new file mode 100644 index 000000000..a21d2e24b --- /dev/null +++ b/plans/closure/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard-closure.md @@ -0,0 +1,505 @@ +# Desktop GUI Frontend Milestone 005 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/005-schema-driven-forms-and-task-dashboard.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +Repository baseline reviewed: `203ab5dd958415340d39cd47fb1add432c687edd` + +Implementation commits or pull requests: + +- Uncommitted working-tree change on branch `feat/auto-20261022-76692679`. + +## 1. Executive finding + +The milestone's capability boundary is complete. The desktop GUI now has a **form engine and a +task dashboard**, both driven entirely by the schema the daemon publishes. + +The milestone's central property is that **the GUI contains no per-operation code**. There is no +match or switch over the thirty task-kind variants, no hand-written table of field names, and no +list of operations in either the Rust or the JavaScript. A task kind the engine has not published +yet gets a working form with no GUI change at all. Guard 159 enforces this by **reading the +variant names out of the runtime** rather than transcribing them, so the guard cannot itself +become the hand-written table it exists to prevent. + +Two things made that possible, and both are measurements rather than assumptions: + +1. The published schema's exact shape, probed against the live catalog. +2. The DTOs' own serde defaults, probed the same way — which turned out to matter for safety. + +The safety finding is the milestone's most consequential result. Four published parameters carry +non-null serde defaults, and one of them is a **fail-safe**: `dry_run` defaults to `true` so the +operation simulates instead of transmitting. A GUI that sent `false` for an untouched field would +silently turn a simulation into a live action. The GUI therefore sends `null` for a blank field +and **omits** a non-nullable optional field entirely, so the request DTO applies its own default. +The engine decides what an untouched field means, not the GUI. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| One schema property maps to one control, with no per-operation code | `form::control_for`; guard 159; the frontend carries no operation name | pass | The guard reads the variant names from the runtime and fails if any appear in the GUI's production sources or its frontend. | +| Every published task kind gets a form | test `assemble_request_round_trips_every_published_task_kind` | pass | All 30 variants assemble into a typed request. | +| Five control kinds, no dropdowns | test `control_for_covers_every_measured_shape` | pass | The schema carries zero `enum` constraints, so it cannot drive a dropdown. | +| The controls are ordered deterministically | test `controls_are_ordered_required_first_then_alphabetically` | pass | Required first, then alphabetical, for every variant. | +| The controls cover the schema exactly | test `controls_match_every_published_schema` | pass | One control per property across all 30 variants; the total field count is 149. | +| The submitted request deserializes into the same DTO the engine deserializes | `form::assemble_request`; layer 2 of the validation model | pass | The assembled value is deserialized into `RunRequest` by `serde_json::from_value`. | +| A wrong-typed value is rejected with a field-level error | test `a_wrongly_typed_value_names_the_field_and_the_expected_type` | pass | The error names the field and the expected type. | +| A missing required field is rejected with a field-level error | test `a_missing_required_field_names_the_field` | pass | The error names the field. | +| An out-of-range value is rejected before it reaches the engine | test `an_out_of_range_number_is_rejected` | pass | The upper bound comes from the schema's `format`. | +| The schema is never consulted for authorization | guard 159; `form.rs` reads only `type`, `format`, `minimum`, `description`, and `required` | pass | The schema drives form *shape* only. Exposure and risk come from the daemon's catalog. | +| An untouched optional field keeps the DTO's own default | test `an_untouched_optional_field_keeps_the_dto_s_own_default` | pass | `dry_run` stays `true`; `frame_count` stays 100. | +| An untouched nullable field is sent as `null` | test `an_untouched_nullable_field_is_sent_as_null` | pass | | +| The GUI holds a bounded number of log lines per task | `MAX_LOG_LINES_PER_TASK` = 200; test `a_log_flood_is_bounded_and_counted` | pass | 10 000 log lines retain exactly 200 and count the drops; the newest line survives. | +| Dropped lines are reported, not silently swallowed | the per-task and dashboard dropped counters reach the webview | pass | The operator sees "… 42 earlier lines dropped". | +| The event stream is the source of truth; the GUI's map is a view | `TaskRegistry::apply` | pass | The GUI holds a bounded view, never a store. | +| Events about unknown tasks are counted | test `unknown_task_events_are_counted` | pass | | +| The GUI subscribes once per session | `spawn_event_forwarder` | pass | One forwarder for the session's lifetime; never a task per event. | +| Availability comes from the daemon's live capabilities | `list_task_kinds`; the submit path's independent check | pass | The join key is `capability_name` against `RuntimeCapabilities.task_kinds[].name`. | +| Result rendering goes through the renderer registry | `tasks::result_view`; `eggsec-ui-model` | pass | An unknown kind degrades to a generic JSON render, never an empty view. | +| The IPC surface is narrow | test `ipc_surface_exposes_only_narrow_commands` | pass | No `ClientCommand::`, no `RuntimeSurface::`, no `SessionScope`, no `send_command`. | +| The IPC argument naming is stated in the code | test `every_command_declares_its_argument_naming` | pass | All eight commands declare `rename_all = "snake_case"`. | +| The frontend carries no npm dependency | the `crates/eggsec-gui/frontend/` tree | pass | No `package.json`, no lockfile, no `node_modules`, no bundler, no build step. | +| `ADR-0009`'s deferred JavaScript dependency policy is discharged | the empty dependency set | pass | The question is settled by the dependency set staying empty. | + +## 3. Production implementation evidence + +### 3.1 The measured schema, and why it was measured + +The plan did not assume the schema's shape; it measured it, with a throwaway probe crate against +the live catalog: + +| Property | Measured value | +|---|---| +| Task kinds published | 30 | +| Fields across all variants | 149 | +| `$ref` / `$defs` | 0 / 0 | +| `enum` constraints | 0 | +| Nested objects | 0 | +| Array item type | always `{"type": "string"}` | +| Formats | `uint`, `uint16`, `uint32`, `uint64` | +| Distinct type signatures | `string`, `string\|null`, `integer`, `integer\|null`, `boolean`, `boolean\|null`, `array\|null`, and exactly one untyped property | + +Two consequences fell out of the measurement: **no dropdowns** (the schema carries zero `enum` +constraints, so there is nothing to offer in a select) and **one unconstrained property** +(`IntegrationsParams::config`, whose schema is the boolean `true`, which accepts any JSON value +and renders as a JSON text area). + +### 3.2 The form engine — `crates/eggsec-gui/src/form.rs` + +One mapping from a published JSON Schema property to one control descriptor: + +| Schema shape | Control | Behaviour | +|---|---|---| +| `"type": "string"` | `text` | single-line input | +| `"type": ["string","null"]` | `text` | blank means *not provided* | +| `"type": "integer"` | `number` | `min`/`max` from the schema | +| `"type": ["integer","null"]` | `number` | | +| `"type": "boolean"` | `checkbox` | tri-state: unset / true / false | +| `"type": ["boolean","null"]` | `checkbox` | | +| `"type": ["array","null"]`, items `string` | `list` | repeatable rows | +| unconstrained (`true`) | `json` | free-form JSON text area | + +The documented fallback for a shape the engine has not published before is never lossy: an object +or a non-string array becomes a `json` control (a free-text field would lose the structure), and +an unknown scalar becomes a `text` control. It never panics and never drops a field. + +Controls are ordered deterministically — **required first, then alphabetically** — so the form's +layout does not shift between runs. The numeric upper bound is derived from the schema's `format`, +because the schema states a `minimum` but never a `maximum`: `uint16` → 65535, `uint32` → +4294967295, `uint64`/`uint` → `u64::MAX`. + +### 3.3 The three-layer validation model + +| Layer | Source | What it settles | +|---|---|---| +| 1 — advisory | the published schema | the control's declared type and bounds | +| 2 — exact | the DTOs | the assembled request is deserialized into the same `RunRequest` the engine will deserialize | +| 3 — authoritative | the engine | whether the task may run at all | + +Layers one and two exist to save the operator a round trip. They never stand in for layer three, +and **neither encodes a per-operation rule** — layer one reads the schema's own `type` keyword, +and layer two is the engine's own deserialization. + +### 3.4 The "not provided" rule — the safety finding + +A blank control sends **`null`** — never `""`, never `0`, never `false`, never `[]`. The Rust +assembly path then does one of two things: + +- a field that **accepts `null`** is sent as `null`; +- a field that is **not required and whose type does not accept `null`** is **omitted** from the + request, so the request DTO applies its own default. + +Why it matters: the measurement found **four** fields that are non-nullable yet optional, and +**all four carry a non-null serde default** — and they are all in one variant: + +| Field | Type | Default | +|---|---|---| +| `WirelessActive.attack_type` | string | `"deauth"` | +| `WirelessActive.dry_run` | boolean | `true` | +| `WirelessActive.frame_count` | integer | `100` | +| `WirelessActive.rate_limit` | integer | `10` | + +`dry_run` is a **fail-safe**: it defaults to `true` so the operation simulates instead of +transmitting. A GUI that sent `false` for an untouched field would silently turn a simulation into +a live action. The remaining 19 properties that carry a default all default to `null`, so sending +`null` for them is equivalent to omitting them. The rule is uniform from the operator's point of +view: *blank means not provided*. + +### 3.5 The bounded task state — `crates/eggsec-gui/src/tasks.rs` + +| Element | Bound | Why | +|---|---|---| +| Retained log lines per task | `MAX_LOG_LINES_PER_TASK` = 200 | `TaskLog` is the high-cardinality event type; a task that floods must not be able to grow the GUI's memory without bound | +| Log lines forwarded per flush | `MAX_LOG_LINES_PER_FLUSH` = 50 | a task that logs faster than the UI renders must not build an unbounded queue in the GUI | + +Both are named constants, not tuning knobs, and both **report what they drop**. The per-task ring +is a `VecDeque` with an explicit capacity, not a `Vec` that grows. The registry keeps tasks in +insertion order, so the dashboard does not reshuffle between renders, and events about unknown +tasks are ignored but counted in `unknown_task_events`. + +The GUI subscribes **once** per session and never spawns a task per event. The event-forwarding +task is the one deliberate exemption from the workspace's 30–300s timeout rule, and the reason is +written down at the function: it is a long-lived connection reader whose lifetime is the +subscription's, and killing it would sever the event stream silently. The daemon client's reader +task holds the same exemption for the same reason. + +### 3.6 The IPC surface + +Milestone 004 shipped two commands. Milestone 005 made the surface eight, each a narrow +pass-through: + +| Command | Argument | Returns | +|---|---|---| +| `connect_daemon` | `socket` | `CatalogView` | +| `list_operations` | — | `OperationRow[]` | +| `list_task_kinds` | — | `TaskKindRow[]` | +| `form_for` | `variant` | `FormView` | +| `submit_task` | `variant`, `values` | `TaskIdView` | +| `cancel_task` | `task_id` | — | +| `cancel_active` | — | — | +| `task_snapshot` | — | `TaskDashboardView` | + +There is **no generic "send any command to the daemon" entry point**, and nothing sets the +session surface or the scope. A test asserts this by scanning the module's production source for +`ClientCommand::`, `RuntimeSurface::`, `SessionScope`, and `send_command`. + +**The surface is stamped in Rust.** `submit_task` builds the request through the form engine, +which sets `RuntimeSurface::DesktopGuiManual` by *serializing the runtime's own enum* — never by +hand-writing the string. The webview cannot widen the session's authority by asking nicely. + +**Every command declares its argument naming explicitly** (`rename_all = "snake_case"`). Tauri's +default is camelCase from the webview; the GUI's contract is snake_case on both sides, so the +attribute is stated in the code rather than left to a framework default. A test asserts that all +eight commands carry it, because without it the webview's `task_id` would silently stop arriving. + +One event is published on the bus: `eggsec://task-event`, carrying `task_upsert`, `logs`, or +`counters` payloads. + +### 3.7 Availability + +**M5 reports; a later milestone hides.** The join key is `TaskKindDescription::capability_name` +against `RuntimeCapabilities.task_kinds[].name` — the daemon's live capabilities, never the GUI's +own reasoning. An operation that is not exposed on the manual surface is marked unavailable with a +reason, and the submit path refuses it independently of what the UI shows. + +### 3.8 Result rendering + +Results are rendered through `eggsec-ui-model`'s `RENDERER_REGISTRY` — the only source of +per-kind metadata. The GUI does not carry its own table of result kinds. An unknown kind degrades +to a generic JSON render, never an empty view, and the view says so (`generic: true`). +`supports_rich_tui` describes the TUI's capability and is **not** a capability query for the GUI. + +### 3.9 The JavaScript dependency policy — discharged + +`ADR-0009` deferred a JavaScript dependency review policy to this milestone, to be settled either +by keeping the dependency set empty or by recording a policy. **The dependency set is empty**, so +the question is discharged: + +- no `package.json`, no lockfile, no `node_modules`, no bundler, no build step; +- no remote script source and no CDN import — a remote source would defeat the CSP and add + supply-chain surface to a security tool; +- the frontend is hand-written HTML, CSS, and vanilla JavaScript, loaded with a plain + ` +``` + +The GUI's CSP (`crates/eggsec-gui/tauri.conf.json:23`) sets +`default-src 'self'; script-src 'self'; …` — no remote origin is permitted, +and guard 158 (`scripts/check-architecture-guards.sh:4656-4681`) enforces that +mechanically. In addition, the renderer emits no `` element (so the +chart never draws anyway) and `frame-src 'none'` forbids an iframe. The +current `eggsec-output` HTML renderer **cannot** be used as-is for the GUI's +embedded HTML display. + +### 3.10 A working export implementation to model from + +The TUI already exports reports (`crates/eggsec-tui/src/app/export.rs`). Its +documented lessons carry over: the extension map is duplicated and +error-prone (the TUI's `get_export_extension` maps `Junit` → `"xml"` at +`crates/eggsec-tui/src/app/mod.rs:427-438`, while the export module keeps its +own list `["html", "md", "sarif", "junit", "xml", "json"]` at +`crates/eggsec-tui/src/app/export.rs:10` and documents the `.xml`-vs-`junit` +stripping bug that the list exists to fix, `:5-10,39-49`); every failure mode +is an `Err`, so a broken conversion can never be written out and then reported +as a success (`:51-70`); and an existing export is **backed up**, not +overwritten, with a non-regular-file destination refused (`:78-110`). + +The GUI MUST NOT introduce a second divergent extension map. One map, in one +place, in the GUI crate. + +### 3.11 Known gaps at the baseline + +- No coverage model: the GUI has no notion of "all 30 variants", only the + catalog rows it happens to receive. +- No feature-availability resolution: `unavailable_reason` + (`crates/eggsec-gui/src/commands.rs:319-331`) has exactly two reasons. +- No daemon lifecycle: the GUI "never spawns, supervises, or stops a daemon" + (`crates/eggsec-gui/src/connection.rs:3-7`, + `crates/eggsec-gui/src/shell.rs:12-16`). +- No report export at all: no `eggsec-output` dependency, no export command, no + report view. +- The socket-path duplication is documented incorrectly in two places (§3.2). + +### 3.12 Known pre-existing failures (inherited, not attributable to M006) + +These are **inherited** at the baseline. M006 MUST NOT silently widen its +scope to fix them, and MUST NOT claim them as M006 regressions. + +| Failure | Evidence | Blocks | +|---|---|---| +| `make check-deps` fails on advisories. **Not all of them are unrelated to the GUI.** The engine-side entries are `zip 2.4.2` (RUSTSEC-2026-0367, -0368, -0369 — three, not two) and the `rustls 0.21.12` family via `tokio-rustls 0.24.1` → `tiberius 0.12.3` → `eggsec` (not `tiberius` → `sqlx-mysql`; `sqlx-mysql` is a sibling under `sqlx`). **Seven advisory entries are reachable only through the GUI's Tauri closure** and are therefore attributable to `crates/eggsec-gui`: `glib 0.18.5` (RUSTSEC-2024-0429), `glib-macros 0.18.5` → `proc-macro-error 1.0.4` (RUSTSEC-2024-0370), and the five `unic-*` crates (RUSTSEC-2025-0081, -0075, -0080, -0100, -0098). A further four (`rustls 0.23.45`, `rustls-webpki 0.103.15`, `webpki-root-certs 1.0.9`, `tokio 1.53.1`) are **shared** with the engine but are attributed by `cargo deny` to a chain that passes through `eggsec-gui` → `tauri` → `reqwest`, because `cargo deny` resolves over the lockfile graph while the GUI's feature-resolved build declines Tauri's `rustls-tls` feature. `bans ok, licenses ok, sources ok`. | `Cargo.lock` pins `zip 2.4.2` (`:11488-11489`) and `rustls 0.21.12` (`:7596-7597`); `deny.toml:25-37` records ignores for the *webpki* advisories on that path but not for the `zip` triple; `plans/implementation/desktop-gui-frontend/007-packaging-and-platform-qualification.md` §3.9 carries the full per-advisory table | the `make check` contract, and therefore M6's closure | +| `cargo check --workspace --all-features` fails with `E0616: field 'url' of struct 'WebSocketFuzzer' is private` | `WebSocketFuzzer.url` is `pub(crate)` in `crates/eggsec-payloads/src/websocket.rs:41-45`, but the engine reads it at `crates/eggsec/src/fuzzer/advanced.rs:446` | `make check-features-individual`, which the roadmap requires before M6 closure (`plans/subsystems/desktop-gui-frontend-roadmap.md:641-644`) | +| `make check-python` was not run (needs `.venv-ci/`) | — | nothing in M6; recorded for completeness | + +Recording a `deny.toml` exception is a **maintainer decision** (owner + +review-by date), not an implementation task M006 may take on itself. + +## 4. Invariants that must not regress + +- **The engine stays behind the daemon protocol.** The GUI MUST NOT depend on + `eggsec`, `eggsec-daemon`, `eggsec-cli`, or `eggsec-tui` (guard 155, + `scripts/check-architecture-guards.sh:4516-4552`). +- **`EnforcementContext::evaluate()` remains the mandatory pre-dispatch + gate.** The GUI MUST NOT import `EnforcementContext`, + `EnforcedDispatcher`, `Scope::is_target_allowed`, or `tool.execute()`. +- **The GUI never widens scope.** A form field is not a scope rule. +- **`OperationMetadata` remains the single source of truth for operation + policy.** The GUI renders what the daemon publishes; it MUST NOT compute + risk, exposure, or feature requirements itself. +- **The published schema and catalog are descriptive, never authoritative.** + The catalog's `required_features` is a *requirement list*, not a state + report; the GUI MUST NOT infer "the feature is on" from the catalog alone. +- **Strict surfaces fail closed.** The GUI is manual + (`RuntimeSurface::DesktopGuiManual`), but a manual GUI still gets no wider + scope than the operator supplied. +- **The daemon protocol changes additively only.** No existing `ClientCommand` + or `ServerMessage` shape changes. The pinned empty-payload envelope contract + (`crates/eggsec/tests/runtime_contract_closure.rs:618-619`) MUST stay green. +- **Ring-only TLS everywhere.** The GUI performs no outbound HTTP of its own. +- **Bounded concurrency and bounded retention.** The GUI MUST NOT retain an + unbounded event log, an unbounded report store, or an unbounded report + payload. +- **Never `let _ =` or `filter_map(|e| e.ok())`** — log via `tracing`. +- **Spawned tokio tasks carry a 30–300s timeout wrapper**, except a task that + is long-lived by nature — in which case the exemption and its reason MUST be + documented. +- **Cancellation goes through `eggsec-runtime::race_with_cancel`** + (`crates/eggsec-runtime/src/cancel.rs:27-43`). The GUI MUST NOT hand-roll a + `tokio::select!` on a cancellation token in adapter code. +- **The shell framework stays inside `crates/eggsec-gui`** (guard 156). +- **The GUI declares no second TLS stack** (guard 157). +- **The CSP names no wildcard source and no remote origin** (guard 158). +- **No per-operation form code** (guard 159) — M006's coverage model MUST NOT + become a hand-written per-operation table. +- **Bounded event retention** (guard 160). +- **The frontend keeps zero npm dependencies and no build step.** M006's + export view MUST NOT introduce one. +- **The `make check` contract** — the GUI crate still compiles in the + `--no-default-features` profile (`crates/eggsec-gui/Cargo.toml:28`). + +## 5. Scope + +### In scope + +- A **coverage model** in the GUI: for every published task kind, the variant, + its `operation_id`, its `capability_name`, the catalog's + `required_features`, and the GUI's reachability verdict — plus a coverage + test that pins the exact multiplicities. +- **Availability resolution**: an additive read path publishing the connected + daemon's enabled features, a denial-driven fallback that turns a + `FeatureMissing` denial into a clear unavailability report, and the + hide-or-report behaviour the roadmap requires. +- **Daemon lifecycle**: an explicit decision, an opt-in operator-supplied + daemon executable path enabling spawn-and-supervise, a pre-flight liveness + check, a bounded readiness wait, the no-op-executor trap, and clean + teardown. +- **Report data acquisition** through an additive read path. +- **Report export** through `eggsec-output`, matching the CLI's artifacts, with + an embedded HTML display that satisfies the CSP. +- A **coverage test** asserting every `TaskKind` variant is reachable. +- New guards and the documentation updates in §12. + +### Explicitly out of scope + +- **PDF export.** It lives only in the engine + (`crates/eggsec/src/output/pdf.rs:22-26`, `#[cfg(feature = "pdf")]`). The GUI + MUST NOT link the engine to produce it. +- **Changing the pinned empty-payload envelope contract.** That is not + additive and requires an ADR (§14). +- **A general `PipelineReport → ScanReportData` bridge for every domain.** + M006 needs the bridge for the report-producing families it exports; a + workspace-wide bridge for all 30 variants is a separate corrective + milestone. +- **Collapsing the socket-path duplication** (§3.2). Six literals exist; M006 + records the count correctly and adds no seventh. Collapsing them is a + separate corrective milestone. +- **Fixing the inherited `--all-features` compile error or the inherited + `make check-deps` advisory failures** (§3.12). Both are recorded as stop + conditions for the exit conditions they block. +- **A strict or headless GUI mode** — an ADR decision point + (`plans/subsystems/desktop-gui-frontend-roadmap.md:662-665`). +- **Interactive policy approval.** `ApprovePolicy` stays unwired; the GUI + MUST NOT offer an approval affordance. +- **Per-operation bespoke forms or result visuals.** M005's engine stays; M006 + adds reachability, not per-operation code. +- **Engine-side validation changes.** +- **Binary distribution, signing, notarization, installers** — milestone 007 + and the separate distribution workstream. +- **A new daemon process-management facility for other frontends.** The TUI's + embedded fallback (`crates/eggsec-tui/src/app/mod.rs:378-412`) is unchanged. + +## 6. Required production changes + +### Core/domain + +- `crates/eggsec-gui/src/coverage.rs` — **new**. The coverage model: + - `TaskCoverage` — one record per published task kind: `variant`, + `operation_id`, `capability_name`, `required_features`, and the + reachability verdict. + - `Reachability` — the verdict enum: `Available`, `HiddenByDaemon` (the + daemon does not advertise the capability), `HiddenByFeature` (the daemon + advertises the capability but the feature is off), `NotExposed` (the + operation is not `manual_exposable`), `Unverified` (the daemon's feature + set is unknown — the fallback state). + - `coverage_for(catalog, capabilities, enabled_features) -> Vec` + — the single derivation, driven entirely by published data. +- `crates/eggsec-gui/src/availability.rs` — **new**. The availability + resolver: the join of the catalog's `required_features`, the daemon's + advertised capabilities, and the daemon's published enabled-feature set, + producing the reachability verdict and the operator-facing reason. +- The model MUST NOT contain a hardcoded list of variant names — the 30 + variants are read from the published catalog + (`DescribeOperationsResponse.task_kinds`, + `crates/eggsec-daemon-protocol/src/operations.rs:89`), exactly as guard 159 + requires of the form engine — and the GUI MUST NOT re-derive + `operation_id` or `capability_name`, which are published per task kind + (`crates/eggsec-daemon-protocol/src/operations.rs:75,77`) and are the + engine's own tables. + +### Storage and migrations + +- **None.** The GUI owns no authoritative storage. The task list is a bounded + in-memory view; the export destination is an operator-chosen path on the + operator's filesystem, written by the GUI's Rust side (the Tauri `fs` plugin + is **not** enabled — `crates/eggsec-gui/capabilities/default.json:6` — and + MUST NOT be enabled for this). +- No data migration is required, because no milestone changes an existing + persisted representation (`plans/subsystems/desktop-gui-frontend-roadmap.md:551-557`). +- The daemon-side report store (Work package D) is **engine/daemon-owned + runtime state**, bounded and cleared with its session — not a persisted + representation, so it needs no migration. + +### Protocol and DTOs + +Three additive changes, and one hard prohibition. + +**(P1) The daemon's enabled-feature set.** `DaemonCapabilities` gains one +field (`crates/eggsec-daemon-protocol/src/protocol.rs:46-51`): + +```rust +#[serde(default)] +pub enabled_features: Vec, +``` + +This is strictly additive in both directions: a **new** daemon's capabilities +decoded by an **old** client works, because serde ignores unknown fields by +default; an **old** daemon's capabilities decoded by a **new** client works, +because `#[serde(default)]` supplies an empty vector. The protocol version +therefore stays at `DAEMON_PROTOCOL_VERSION` — the same reason milestone 003 +kept it at 2 when `ClientKind::Gui` was added. + +The daemon's value comes from the executor, which gains one **defaulted** +method (`crates/eggsec-runtime/src/runtime.rs:40-57`): + +```rust +/// The engine features compiled into this executor's build. +/// +/// An empty result means "unknown", not "none": a no-op executor +/// advertises nothing because it links no engine at all. +fn enabled_features(&self) -> Vec { Vec::new() } +``` + +A defaulted method is additive at the Rust level — every existing +implementation (`NoopExecutorStub` at `crates/eggsec-daemon/src/host.rs:3553-3575`, +`NoopExecutor` at `crates/eggsec-cli/src/daemon_cli.rs:584-607`) keeps +compiling unchanged. The engine's `EggsecRuntimeExecutor` overrides it with +`eggsec::policy_bridge::features::current_enabled_features()` +(`crates/eggsec/src/policy_bridge/features.rs:11-17`), which reads the +engine's own authoritative compile-time registry +(`crates/eggsec/src/config/feature_registry.rs:110`). + +**An empty vector is ambiguous** and the GUI MUST treat it as *unknown*, not as +*nothing is enabled*. The daemon MUST therefore distinguish "I link no engine" +from "I link an engine with these features" — for example by returning +`Option>` (`None` = unknown) rather than an empty vector. **The +implementer MUST pick one and document it**; the GUI's fallback behaviour +depends on it. + +**(P2) The report read path.** One new read-only command and one new +response: + +```rust +ClientCommand::GetTaskReport { request_id, session_id, task_id } +ServerMessage::TaskReport { request_id, session_id, task_id, report } +``` + +An old daemon receiving `GetTaskReport` answers `ErrorCode::UnsupportedCommand` +(`crates/eggsec-daemon-protocol/src/protocol.rs:72`) — the protocol already +defines that error for exactly this purpose (`:54-59`, `:181`). A new client +MUST treat it as a graceful degradation (no export), never as a launch failure. + +**(P3) The frontend-client accessor.** `DaemonRuntimeClient` gains an inherent +method — **not** a `RuntimeClient` trait method, mirroring milestone 004's +decision for `describe_operations`. The trait +(`crates/eggsec-frontend-client/src/lib.rs:66-88`) stays frontend-neutral and +unchanged. + +**(P-HARD) The prohibition.** `TaskResultEnvelope.payload` and +`TaskResultEnvelope.artifacts` MUST continue to be `json!({})` and `vec![]` +for every result variant, and `crates/eggsec/tests/runtime_contract_closure.rs:618-619` +MUST stay green. Filling the payload is **not additive** and is a stop +condition (§14). + +**The GUI's dependency on `eggsec-output`.** `crates/eggsec-gui/Cargo.toml` +gains `eggsec-output`. This is permitted — `eggsec-output` has no engine edge +(`crates/eggsec-output/Cargo.toml:16-32`) — but it widens the GUI's closure +with `eggsec-core` (→ `subtle`, `zeroize`), `chrono`, `quick-xml`, +`unicode-normalization` (→ `tinyvec`), `lru`, `hostname`, `rustc-hash`, and +`tokio`/`io-util`. `deny.toml` is a **closed** license allow-list +(`deny.toml:39-56`); every one of those crates' licenses must clear it, and +`make check-deps` fails closed if any does not. The implementer MUST run +`make check-deps` and record the outcome rather than assume the closure is +clean. No new **tokio feature** is required by `eggsec-output`; its `io-util` +need comes in through the dependency. + +### Runtime and concurrency + +- The GUI's availability state is a **bounded, in-memory** projection of the + daemon's published catalog plus the daemon's enabled-feature set. It is + recomputed when the daemon publishes new data, never accumulated. +- The export path is a **finite** operation and its spawned task MUST carry a + 30–300s timeout wrapper. +- The spawn-and-supervise path (Work package C) owns one child process at a + time. The GUI MUST NOT spawn more than one. +- Every spawned task's failure is reported through `tracing`. No `let _ =`, no + `filter_map(|e| e.ok())`. +- Cancellation of an in-flight export goes through + `eggsec-runtime::race_with_cancel` (`crates/eggsec-runtime/src/cancel.rs:27-43`). + +### Frontend or operator surface + +- `crates/eggsec-gui/src/commands.rs` — additional IPC commands: + `coverage()` (the per-variant reachability table with each variant's verdict + and reason), `export_report(task_id, format, path)`, and `daemon_status()` + (the daemon's lifecycle state and, when the operator supplied a daemon + binary, the ability to start/stop the supervised child). +- `crates/eggsec-gui/src/export.rs` — **new**. The export module: + - `ReportFormat` — the six formats the CLI supports, minus PDF, plus the + extension map. **One** map, in this module. + - `export(report, format, path) -> Result` — + renders through `eggsec-output`'s `convert_to_*` and writes the artifact. + - The write follows the TUI's discipline: back up an existing regular file + to `.bak` before overwriting, refuse a non-regular-file destination, + and make every failure an `Err` so a partial write is never reported as a + success (`crates/eggsec-tui/src/app/export.rs:51-110`). + - The path MUST come from the operator. The GUI MUST NOT write outside the + operator-chosen path and MUST NOT choose a default output directory. +- `crates/eggsec-gui/src/daemon.rs` — **new**. The daemon lifecycle module: + the pre-flight liveness check, the spawn, the bounded readiness wait, the + supervision loop, and the teardown (Work package C). +- `crates/eggsec-gui/frontend/app.js` — the coverage table (all 30 rows with + the verdict and the reason), the export controls, the export result view, and + the daemon status panel. **Zero npm dependencies.** No per-operation branch. +- The webview MUST receive the coverage table as **data** and render it. It + MUST NOT contain a per-variant table, a per-variant branch, or a hardcoded + field list. +- **Embedded HTML display.** The `eggsec-output` HTML renderer cannot be + embedded as-is (§3.9). The bounded options are (1) a **self-contained + rendering mode added to `eggsec-output`** — the renderer omits the CDN + `\n"; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HtmlConfig { pub title: String, @@ -41,7 +49,32 @@ impl HtmlReport { self } + /// Generate the default rendering of this report. + /// + /// This is the CLI's artifact: it carries the remote chart library + /// reference and is byte-for-byte stable. pub fn generate(&self) -> String { + self.build_document(true) + } + + /// Generate the self-contained variant of this report. + /// + /// Identical to [`Self::generate`] except that the remote chart library + /// reference is omitted, so the document carries no remote origin and + /// can be embedded under a Content Security Policy that forbids one. + /// + /// The default rendering is unchanged: a caller that wants the CLI's + /// artifact, byte-for-byte, calls [`Self::generate`]. + pub fn generate_self_contained(&self) -> String { + self.build_document(false) + } + + /// Build the report document. + /// + /// `include_remote_chart` decides whether the remote chart library + /// reference is emitted. The two variants differ only in that one + /// reference, so the default rendering is unaffected by the flag. + fn build_document(&self, include_remote_chart: bool) -> String { let theme = if self.config.theme == "dark" { self.dark_theme() } else { @@ -55,6 +88,15 @@ impl HtmlReport { .collect::>() .join("\n"); + // The remote chart library is the document's only remote origin. + // The self-contained variant drops the whole line, so the two + // documents differ only by that reference. + let chart_script = if include_remote_chart { + REMOTE_CHART_SCRIPT + } else { + "" + }; + format!( r#" @@ -65,8 +107,7 @@ impl HtmlReport { - - +{}
@@ -139,6 +180,7 @@ impl HtmlReport { "#, escape_html(&self.config.title), theme, + chart_script, escape_html(&self.summary.timestamp), escape_html(&self.summary.target), escape_html(&self.summary.scan_type), @@ -323,3 +365,15 @@ pub fn generate_html_report( let report = HtmlReport::new(summary, findings); report.generate() } + +/// Generate the self-contained variant of an HTML report. +/// +/// The document carries no remote origin reference, so it can be embedded +/// under a Content Security Policy that forbids one. +pub fn generate_self_contained_html_report( + summary: super::markdown::ScanSummary, + findings: Vec, +) -> String { + let report = HtmlReport::new(summary, findings); + report.generate_self_contained() +} diff --git a/crates/eggsec-output/src/lib.rs b/crates/eggsec-output/src/lib.rs index 0b64ca7c9..074517884 100644 --- a/crates/eggsec-output/src/lib.rs +++ b/crates/eggsec-output/src/lib.rs @@ -61,9 +61,9 @@ pub use agent::{ }; pub use audit_summary::AuditSummary; pub use convert::{ - convert_to_csv, convert_to_html, convert_to_junit, convert_to_markdown, convert_to_sarif, - load_scan_report, FindingData, PortData, ScanReportData, ServiceData, - WirelessNetworkReportData, + convert_to_csv, convert_to_html, convert_to_html_self_contained, convert_to_junit, + convert_to_markdown, convert_to_sarif, load_scan_report, FindingData, PortData, ScanReportData, + ServiceData, WirelessNetworkReportData, }; pub use csv::{CsvExporter, EndpointCsv, FindingCsv, OutputFormat as ExportFormat, PortCsv}; pub use diff::DiffSummary; diff --git a/crates/eggsec-output/tests/html_self_contained.rs b/crates/eggsec-output/tests/html_self_contained.rs new file mode 100644 index 000000000..0c93956a0 --- /dev/null +++ b/crates/eggsec-output/tests/html_self_contained.rs @@ -0,0 +1,178 @@ +//! Integration tests for the self-contained HTML rendering mode. +//! +//! The self-contained variant exists for embedders whose Content Security +//! Policy forbids any remote origin. It must carry no remote reference at +//! all, while the default rendering keeps the CLI's artifact unchanged. + +use eggsec_output::convert::{convert_to_html, convert_to_html_self_contained}; +use eggsec_output::html::HtmlReport; +use eggsec_output::markdown::{Finding, ScanSummary}; +use eggsec_output::{FindingData, PortData, ScanReportData, ServiceData}; + +/// The remote chart-library reference the default rendering emits, as one +/// whole line (indentation and trailing newline included). +const REMOTE_CHART_SCRIPT_LINE: &str = + " \n"; + +/// A minimal report with one finding, one port, one service, and one +/// wireless network. Its content carries no URL, so the remote-origin +/// assertions measure the renderer rather than the fixture. +fn sample_report() -> ScanReportData { + ScanReportData { + target: "example.test".to_string(), + scan_type: "web".to_string(), + timestamp: "2026-01-01T00:00:00Z".to_string(), + findings: vec![FindingData { + title: "Reflected XSS in search".to_string(), + severity: "High".to_string(), + category: "xss".to_string(), + description: "Unescaped query parameter reflected in the response.".to_string(), + location: "/search?q=test".to_string(), + evidence: Some("Response body reflects the query parameter verbatim.".to_string()), + remediation: Some("Escape the output before echoing it back.".to_string()), + cwe_ids: vec!["CWE-79".to_string()], + }], + open_ports: vec![PortData { + port: 443, + status: "open".to_string(), + protocol: Some("tcp".to_string()), + state: Some("open".to_string()), + service: Some("nginx".to_string()), + version: Some("1.24.0".to_string()), + banner: None, + }], + services: vec![ServiceData { + service: "nginx".to_string(), + version: Some("1.24.0".to_string()), + banner: None, + }], + duration_ms: 1234, + wireless_networks: vec![], + policy_summary: None, + } +} + +#[test] +fn default_html_keeps_the_remote_chart_library_reference() { + let report = sample_report(); + + let html = convert_to_html(&report); + + assert!( + html.contains(REMOTE_CHART_SCRIPT_LINE), + "the default rendering must keep the CLI's remote chart-library reference" + ); + assert!(html.contains("https://cdn.jsdelivr.net/npm/chart.js")); +} + +#[test] +fn self_contained_html_carries_no_remote_origin_reference() { + let report = sample_report(); + + let html = convert_to_html_self_contained(&report); + + assert!( + !html.contains("http://"), + "self-contained HTML must not reference an http origin: {html}" + ); + assert!( + !html.contains("https://"), + "self-contained HTML must not reference an https origin: {html}" + ); + assert!(!html.contains("cdn.jsdelivr.net")); +} + +#[test] +fn self_contained_html_fetches_nothing_from_a_remote_origin() { + // The guarantee that matters for a Content Security Policy is about the + // document's own references -- the attributes a browser would resolve + // against a remote origin. Report *content* may legitimately quote a + // URL (a finding's evidence, an advisory link); such a string is inert + // text, not a fetch, and stripping it would corrupt the report. + let mut report = sample_report(); + report.findings[0].description = "Advisory: https://example.test/advisory".to_string(); + + let html = convert_to_html_self_contained(&report); + + assert!(!html.contains("src=\"http")); + assert!(!html.contains("href=\"http")); + assert!(!html.contains("url(http")); + assert!(!html.contains("src='http")); + assert!(!html.contains("href='http")); + // The URL survives as escaped text, which is correct and inert. + assert!(html.contains("https://example.test/advisory")); +} + +#[test] +fn self_contained_html_keeps_the_report_substantive_content() { + let report = sample_report(); + + let html = convert_to_html_self_contained(&report); + + assert!( + html.contains("example.test"), + "the target must survive the self-contained rendering" + ); + assert!( + html.contains("Reflected XSS in search"), + "the finding title must survive the self-contained rendering" + ); + assert!( + html.contains("xss"), + "the finding category must survive the self-contained rendering" + ); + assert!( + html.contains("/search?q=test"), + "the finding location must survive the self-contained rendering" + ); +} + +#[test] +fn self_contained_html_differs_from_the_default_only_by_the_remote_reference() { + let report = sample_report(); + + let default_html = convert_to_html(&report); + let self_contained_html = convert_to_html_self_contained(&report); + + assert!( + default_html.contains(REMOTE_CHART_SCRIPT_LINE), + "the default rendering must carry the remote reference to strip" + ); + assert_eq!( + default_html.replace(REMOTE_CHART_SCRIPT_LINE, ""), + self_contained_html, + "the two renderings must differ only by the remote chart-library line" + ); +} + +#[test] +fn html_report_self_contained_renders_no_remote_reference() { + let report = sample_report(); + let summary = ScanSummary::from(&report); + let findings: Vec = report.findings.iter().map(|f| f.into()).collect(); + let html_report = HtmlReport::new(summary, findings); + + let default_html = html_report.generate(); + let self_contained_html = html_report.generate_self_contained(); + + assert!(default_html.contains(REMOTE_CHART_SCRIPT_LINE)); + assert!(!self_contained_html.contains("http://")); + assert!(!self_contained_html.contains("https://")); + assert_eq!( + default_html.replace(REMOTE_CHART_SCRIPT_LINE, ""), + self_contained_html + ); +} + +#[test] +fn html_report_self_contained_keeps_the_report_content() { + let report = sample_report(); + let summary = ScanSummary::from(&report); + let findings: Vec = report.findings.iter().map(|f| f.into()).collect(); + let html_report = HtmlReport::new(summary, findings); + + let html = html_report.generate_self_contained(); + + assert!(html.contains("example.test")); + assert!(html.contains("Reflected XSS in search")); +} diff --git a/crates/eggsec-python/src/daemon.rs b/crates/eggsec-python/src/daemon.rs index df294c2eb..9c3a3f5b5 100644 --- a/crates/eggsec-python/src/daemon.rs +++ b/crates/eggsec-python/src/daemon.rs @@ -261,6 +261,14 @@ pub(crate) fn server_message_to_response( ), error_code: None, }, + ServerMessage::TaskReport { + request_id, report, .. + } => DaemonResponsePy { + ok: true, + request_id, + message: format!("report ({} bytes)", report.to_string().len()), + error_code: None, + }, } } diff --git a/crates/eggsec-runtime/src/lib.rs b/crates/eggsec-runtime/src/lib.rs index 5fdef3c19..53f1603e2 100644 --- a/crates/eggsec-runtime/src/lib.rs +++ b/crates/eggsec-runtime/src/lib.rs @@ -4,6 +4,7 @@ pub mod dispatcher; pub mod error; pub mod event; pub mod ids; +pub mod report; pub mod request; pub mod runtime; pub mod runtime_config; @@ -20,6 +21,7 @@ pub use event::{ TaskOutcome, TaskProgress, TaskResultEnvelope, TaskStatus, }; pub use ids::{ClientId, SessionId, TaskId}; +pub use report::{RuntimeReportStore, MAX_RETAINED_REPORTS}; pub use request::{LoadTestParams, RunRequest, RuntimeSurface, TaskKind}; pub use runtime::{Runtime, RuntimeTaskExecutor}; pub use runtime_config::{RuntimeConfig, SessionOptions}; diff --git a/crates/eggsec-runtime/src/report.rs b/crates/eggsec-runtime/src/report.rs new file mode 100644 index 000000000..6d5c2f478 --- /dev/null +++ b/crates/eggsec-runtime/src/report.rs @@ -0,0 +1,216 @@ +//! Bounded retention of completed-task report documents. +//! +//! The runtime owns task lifecycle but not report *semantics*: the engine +//! decides what a completed result means, and the daemon serves what the +//! engine produced. What lives here is only the bounded store between them — +//! a key/value map from task id to the report document the engine derived +//! from that task's result. +//! +//! Retention is bounded on purpose. A long-lived daemon would otherwise +//! accumulate one report document per task for the life of the process, and +//! report documents are the largest payloads the runtime ever holds. The +//! bound is small (see [`MAX_RETAINED_REPORTS`]) and the eviction order is +//! oldest-first, so a burst of tasks cannot grow the store without limit. +//! +//! The payload is `serde_json::Value` rather than a report-model type on +//! purpose: the runtime crate deliberately carries no domain types, and a +//! report document crosses the wire as JSON anyway. The consumer — the +//! desktop GUI — deserializes it into the canonical report model. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Mutex; + +use crate::ids::TaskId; + +/// The maximum number of completed-task reports a runtime retains. +/// +/// Oldest-first eviction applies once the store is full, so the bound is a +/// hard ceiling on retained report documents rather than a soft target. +pub const MAX_RETAINED_REPORTS: usize = 64; + +/// A bounded, in-memory store of completed-task report documents. +/// +/// The store is cheap to clone-share: it is used behind an `Arc` and every +/// method takes `&self`, so a producer and a consumer can hold the same +/// store without either owning it. +/// +/// The internal lock is a `std::sync::Mutex` and is never held across an +/// await point — every method is synchronous and its critical section is a +/// map operation. That keeps the store usable from the synchronous parts of +/// an executor without forcing an async signature on the read path. +#[derive(Debug)] +pub struct RuntimeReportStore { + inner: Mutex, +} + +#[derive(Debug)] +struct ReportStoreInner { + reports: HashMap, + /// Insertion order, used for oldest-first eviction. + order: VecDeque, +} + +impl RuntimeReportStore { + /// Create an empty store. + pub fn new() -> Self { + Self { + inner: Mutex::new(ReportStoreInner { + reports: HashMap::new(), + order: VecDeque::new(), + }), + } + } + + /// Record the report document for a completed task. + /// + /// Re-inserting an existing task id replaces its document and keeps its + /// original position in the eviction order; a task is inserted once, so + /// this is only a defensive path. + /// + /// When the store is at [`MAX_RETAINED_REPORTS`], the oldest entry is + /// evicted to make room. + pub fn insert(&self, task_id: TaskId, report: serde_json::Value) { + let mut inner = self.lock(); + if inner.reports.insert(task_id, report).is_none() { + inner.order.push_back(task_id); + } + while inner.order.len() > MAX_RETAINED_REPORTS { + if let Some(evicted) = inner.order.pop_front() { + inner.reports.remove(&evicted); + } + } + } + + /// The report document recorded for a task, if one is retained. + pub fn get(&self, task_id: &TaskId) -> Option { + let inner = self.lock(); + inner.reports.get(task_id).cloned() + } + + /// The number of retained report documents. + pub fn len(&self) -> usize { + self.lock().reports.len() + } + + /// Whether the store holds no report documents. + pub fn is_empty(&self) -> bool { + self.lock().reports.is_empty() + } + + /// Drop every retained report document. + pub fn clear(&self) { + let mut inner = self.lock(); + inner.reports.clear(); + inner.order.clear(); + } + + /// Take the store's lock, recovering from poisoning rather than + /// propagating it. + /// + /// A poisoned lock means some other holder panicked while holding it. + /// The store's invariants are still intact — the critical sections are + /// map operations that cannot leave the map half-updated — so the + /// poisoned state is recovered and the event is logged rather than + /// turned into a panic in every subsequent caller. + fn lock(&self) -> std::sync::MutexGuard<'_, ReportStoreInner> { + self.inner.lock().unwrap_or_else(|poisoned| { + tracing::warn!("the runtime report store lock was poisoned; recovering state"); + poisoned.into_inner() + }) + } +} + +impl Default for RuntimeReportStore { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn task() -> TaskId { + TaskId::new() + } + + fn doc(marker: &str) -> serde_json::Value { + serde_json::json!({ "marker": marker }) + } + + #[test] + fn a_fresh_store_is_empty() { + let store = RuntimeReportStore::new(); + assert!(store.is_empty()); + assert_eq!(store.len(), 0); + } + + #[test] + fn an_inserted_report_is_readable_back() { + let store = RuntimeReportStore::new(); + let id = task(); + store.insert(id, doc("first")); + assert_eq!(store.len(), 1); + assert_eq!( + store.get(&id), + Some(serde_json::json!({ "marker": "first" })), + "the stored document comes back unchanged" + ); + } + + #[test] + fn an_unknown_task_has_no_report() { + let store = RuntimeReportStore::new(); + assert!(store.get(&task()).is_none()); + } + + #[test] + fn retention_is_bounded_and_evicts_the_oldest_first() { + let store = RuntimeReportStore::new(); + let ids: Vec = (0..MAX_RETAINED_REPORTS + 5).map(|_| task()).collect(); + for (index, id) in ids.iter().enumerate() { + store.insert(*id, doc(&index.to_string())); + } + assert_eq!( + store.len(), + MAX_RETAINED_REPORTS, + "the store never grows past its bound" + ); + for id in &ids[..5] { + assert!( + store.get(id).is_none(), + "the oldest entries are evicted first" + ); + } + for id in &ids[5..] { + assert!( + store.get(id).is_some(), + "the most recent entries are retained" + ); + } + } + + #[test] + fn reinserting_a_task_replaces_its_document() { + let store = RuntimeReportStore::new(); + let id = task(); + store.insert(id, doc("first")); + store.insert(id, doc("second")); + assert_eq!(store.len(), 1, "a replacement is not a second entry"); + assert_eq!( + store.get(&id), + Some(serde_json::json!({ "marker": "second" })), + "the newer document replaces the older one" + ); + } + + #[test] + fn clearing_drops_every_document() { + let store = RuntimeReportStore::new(); + let id = task(); + store.insert(id, doc("first")); + store.clear(); + assert!(store.is_empty()); + assert!(store.get(&id).is_none()); + } +} diff --git a/crates/eggsec-runtime/src/runtime.rs b/crates/eggsec-runtime/src/runtime.rs index 0c8cea779..b677f6f02 100644 --- a/crates/eggsec-runtime/src/runtime.rs +++ b/crates/eggsec-runtime/src/runtime.rs @@ -68,6 +68,38 @@ pub trait RuntimeTaskExecutor: Send + Sync + 'static { fn supported_task_kinds(&self) -> Vec { RuntimeCapabilities::daemon_conservative().task_kinds } + + /// The engine features compiled into this executor's build. + /// + /// This is a *build* fact, not a runtime capability: it says which + /// feature-gated operations the linked engine could run at all. A host + /// publishes it so a client can tell "this operation is unavailable + /// because the daemon was built without its feature" apart from "this + /// operation is unavailable because the daemon does not advertise it". + /// + /// `None` means **unknown**: the executor links no engine, or does not + /// publish the fact. `Some(vec![])` means an engine is linked with no + /// features enabled — a different, knowable fact. The distinction + /// matters because an empty vector must never be read as "unknown", + /// which would let a client report a wrong reason for an unavailable + /// operation. + /// + /// The default is `None` so every existing implementor keeps its current + /// behaviour and no host has to change to compile. + fn enabled_features(&self) -> Option> { + None + } + + /// The report document for a completed task, if this executor produced one. + /// + /// `None` means "no report for this task" — either the executor produces + /// no reports at all, or this particular result has no report form. A + /// host reads this to answer a client's report request; it is a read + /// path, and the executor's own retention policy decides how long a + /// report stays available. + fn report_for(&self, _task_id: &TaskId) -> Option { + None + } } struct RuntimeState { @@ -95,6 +127,19 @@ pub struct Runtime { /// while building its own derived capability list, without taking an /// async lock in a constructor. supported_task_kinds: Vec, + /// The executor's published enabled-feature set, captured at construction. + /// + /// `None` means the executor did not publish one (it links no engine, or + /// predates the declaration). It lives outside the state mutex for the + /// same reason `supported_task_kinds` does: a host reads it synchronously + /// while building its own published capability list. + enabled_features: Option>, + /// The executor behind this runtime. + /// + /// It is held outside the state mutex as well as inside it, so the + /// synchronous read paths (`report_for`) never have to take a lock that + /// an async caller might be holding. + executor: Arc, } impl Runtime { @@ -102,17 +147,39 @@ impl Runtime { pub fn new(config: RuntimeConfig, executor: impl RuntimeTaskExecutor) -> Self { let (event_tx, _) = broadcast::channel(config.event_channel_capacity); let supported_task_kinds = executor.supported_task_kinds(); + let enabled_features = executor.enabled_features(); + let executor: Arc = Arc::new(executor); Self { state: Arc::new(Mutex::new(RuntimeState { sessions: HashMap::new(), config, event_tx, - executor: Arc::new(executor), + executor: Arc::clone(&executor), })), supported_task_kinds, + enabled_features, + executor, } } + /// The enabled-feature set the executor behind this runtime published. + /// + /// `None` means the executor published nothing — it links no engine, or + /// it does not know the fact. A caller MUST NOT read `None` as "no + /// features are enabled"; it means the answer is unknown. + pub fn enabled_features(&self) -> Option<&[String]> { + self.enabled_features.as_deref() + } + + /// The report document the executor recorded for a completed task. + /// + /// `None` means no report is available for that task, which covers both + /// "the executor produces no reports" and "this task's result has no + /// report form". + pub fn report_for(&self, task_id: &TaskId) -> Option { + self.executor.report_for(task_id) + } + /// The task kinds the executor behind this runtime declares it can run. /// /// A host derives its published capability list from this, so the diff --git a/crates/eggsec/src/runtime_bridge/executor.rs b/crates/eggsec/src/runtime_bridge/executor.rs index 9b11c206b..bc2146017 100644 --- a/crates/eggsec/src/runtime_bridge/executor.rs +++ b/crates/eggsec/src/runtime_bridge/executor.rs @@ -1,9 +1,12 @@ use std::future::Future; use std::pin::Pin; +use std::sync::Arc; use eggsec_runtime::event::{LogLevel, TaskOutcome}; use eggsec_runtime::request::RunRequest; -use eggsec_runtime::{RuntimeError, RuntimeEventSink, RuntimeTaskExecutor, TaskId}; +use eggsec_runtime::{ + RuntimeError, RuntimeEventSink, RuntimeReportStore, RuntimeTaskExecutor, TaskId, +}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; @@ -25,16 +28,21 @@ use super::bundle::approve_run_request_bundle; /// canonical execution boundary shared with embedded TUI execution). /// 4. Converts `TaskResult` → `TaskOutcome` via the single engine-owned /// envelope mapping for the runtime lifecycle. +/// 5. Derives the canonical report document for a completed result and keeps +/// it in the bounded [`RuntimeReportStore`], so a host can serve the report +/// without the envelope carrying a payload. /// /// # Trust boundary /// /// The executor receives an `eggsec_runtime::session::RuntimeExecutionContext` carrying the session's /// creation surface and scope metadata. For strict surfaces (MCP, REST, gRPC, /// Agent, CI), the executor **fails closed** if scope cannot be resolved from -/// the stored path. Manual surfaces (CLI, TUI) fall back to permissive defaults -/// when no explicit scope is available. +/// the stored path. Manual surfaces (CLI, TUI, desktop GUI) fall back to +/// permissive defaults when no explicit scope is available. pub struct EggsecRuntimeExecutor { policy: ExecutionPolicy, + /// The bounded store of report documents this executor produced. + reports: Arc, } impl Default for EggsecRuntimeExecutor { @@ -46,14 +54,15 @@ impl Default for EggsecRuntimeExecutor { impl EggsecRuntimeExecutor { /// Create a new executor with the default permissive policy. pub fn new() -> Self { - Self { - policy: ExecutionPolicy::default(), - } + Self::with_policy(ExecutionPolicy::default()) } /// Create a new executor with a custom execution policy. pub fn with_policy(policy: ExecutionPolicy) -> Self { - Self { policy } + Self { + policy, + reports: Arc::new(RuntimeReportStore::new()), + } } /// Resolve a `LoadedScope` from session scope metadata. @@ -66,10 +75,14 @@ impl EggsecRuntimeExecutor { scope: &Option, surface: eggsec_runtime::RuntimeSurface, ) -> Option { - // Determine if this surface honors manual overrides. + // Determine if this surface honors manual overrides. The desktop GUI + // is a manual surface (ADR-0007): a peer of the CLI and the TUI, not + // a new policy class, so it gets the same permissive default scope. let is_permissive = matches!( surface, - eggsec_runtime::RuntimeSurface::CliManual | eggsec_runtime::RuntimeSurface::TuiManual + eggsec_runtime::RuntimeSurface::CliManual + | eggsec_runtime::RuntimeSurface::TuiManual + | eggsec_runtime::RuntimeSurface::DesktopGuiManual ); match scope { @@ -126,9 +139,30 @@ impl EggsecRuntimeExecutor { } impl RuntimeTaskExecutor for EggsecRuntimeExecutor { + /// The engine features compiled into this build. + /// + /// `Some` is correct here: this executor links the engine, so its feature + /// set is a knowable build fact. `None` is reserved for executors that + /// link no engine at all. + fn enabled_features(&self) -> Option> { + let enabled = crate::policy_bridge::features::current_enabled_features(); + Some( + crate::config::ALL_FEATURES + .iter() + .filter(|entry| enabled.contains(entry.name)) + .map(|entry| entry.name.to_string()) + .collect(), + ) + } + + /// The report document derived from a completed task, if one was kept. + fn report_for(&self, task_id: &TaskId) -> Option { + self.reports.get(task_id) + } + fn execute( &self, - _task_id: TaskId, + task_id: TaskId, request: RunRequest, context: eggsec_runtime::RuntimeExecutionContext, sink: RuntimeEventSink, @@ -136,6 +170,7 @@ impl RuntimeTaskExecutor for EggsecRuntimeExecutor { ) -> Pin> + Send + 'static>> { let policy = self.policy.clone(); let surface = context.surface.clone(); + let reports = Arc::clone(&self.reports); Box::pin(async move { // Check cancellation before starting. @@ -217,6 +252,21 @@ impl RuntimeTaskExecutor for EggsecRuntimeExecutor { tracing::warn!(?error, "runtime progress forwarder failed"); } + // Derive the canonical report document for the completed result + // and keep it in the bounded report store. This is a *separate* + // path from the task envelope: the envelope's payload and + // artifacts stay empty, and the report body is served from the + // store instead. + if let Some(report) = super::report::report_for_result(&task_result) { + match serde_json::to_value(&report) { + Ok(document) => reports.insert(task_id, document), + Err(error) => tracing::warn!( + %error, + "the report document could not be serialized; no report is available for this task" + ), + } + } + // Convert TaskResult → TaskOutcome. let outcome = Self::task_result_to_outcome(&task_result); @@ -229,6 +279,114 @@ impl RuntimeTaskExecutor for EggsecRuntimeExecutor { mod tests { use super::*; + /// The desktop GUI is a manual surface (ADR-0007): it must resolve the + /// permissive default scope exactly as the CLI and the TUI do. Before the + /// fix it fell onto the strict branch and every GUI task was denied. + #[test] + fn a_desktop_gui_session_receives_the_permissive_default_scope() { + let scope = EggsecRuntimeExecutor::resolve_loaded_scope( + &None, + eggsec_runtime::RuntimeSurface::DesktopGuiManual, + ) + .expect("the desktop GUI is a manual surface and must not be denied a scope"); + + assert_eq!( + scope.source, + crate::config::ScopeSource::DefaultEmpty, + "the permissive default scope is the one the CLI and TUI get" + ); + assert!( + scope.scope.allowed_targets.is_empty(), + "the default scope carries no explicit targets" + ); + } + + /// A GUI session that carries non-explicit scope metadata resolves the + /// same way: the metadata is not a manifest, so the permissive default + /// applies. + #[test] + fn a_desktop_gui_session_with_non_explicit_scope_metadata_is_permissive() { + let session_scope = eggsec_runtime::SessionScope { + is_explicit: false, + source: "default-empty".to_string(), + path: None, + }; + + let scope = EggsecRuntimeExecutor::resolve_loaded_scope( + &Some(session_scope), + eggsec_runtime::RuntimeSurface::DesktopGuiManual, + ) + .expect("the desktop GUI is a manual surface and must not be denied a scope"); + + assert_eq!(scope.source, crate::config::ScopeSource::DefaultEmpty); + } + + /// The strict surfaces stay strict: with no explicit scope they have no + /// manifest to load, so the executor fails closed and denies the task. + #[test] + fn a_strict_surface_without_an_explicit_scope_is_denied() { + for surface in [ + eggsec_runtime::RuntimeSurface::RestApi, + eggsec_runtime::RuntimeSurface::Ci, + eggsec_runtime::RuntimeSurface::McpServer, + eggsec_runtime::RuntimeSurface::SecurityAgent, + ] { + assert!( + EggsecRuntimeExecutor::resolve_loaded_scope(&None, surface.clone()).is_none(), + "{surface:?} is a strict surface and must fail closed" + ); + } + } + + /// The CLI and TUI manual surfaces keep the permissive scope they always + /// had; the fix did not move them. + #[test] + fn the_cli_and_tui_manual_surfaces_stay_permissive() { + for surface in [ + eggsec_runtime::RuntimeSurface::CliManual, + eggsec_runtime::RuntimeSurface::TuiManual, + ] { + let scope = EggsecRuntimeExecutor::resolve_loaded_scope(&None, surface) + .expect("a manual surface resolves the permissive default scope"); + assert_eq!(scope.source, crate::config::ScopeSource::DefaultEmpty); + } + } + + /// The engine executor links the engine, so its feature set is knowable + /// and is published rather than reported as unknown. + #[test] + fn the_executor_publishes_its_enabled_features() { + let executor = EggsecRuntimeExecutor::new(); + let features = executor + .enabled_features() + .expect("the engine executor knows its feature set"); + + assert!( + features.contains(&"cli".to_string()), + "the build under test has the cli feature compiled in" + ); + assert!( + !features.contains(&"definitely-not-a-feature".to_string()), + "only registry features are published" + ); + for entry in crate::config::ALL_FEATURES { + assert_eq!( + features.contains(&entry.name.to_string()), + entry.enabled, + "feature '{}' must match the compile-time registry", + entry.name + ); + } + } + + /// A task with no report keeps the store empty rather than storing an + /// invented document. + #[test] + fn an_unknown_task_has_no_report() { + let executor = EggsecRuntimeExecutor::new(); + assert!(executor.report_for(&TaskId::new()).is_none()); + } + #[test] fn task_result_port_scan_to_outcome() { let result = TaskResult::PortScan(crate::scanner::PortScanResults { diff --git a/crates/eggsec/src/runtime_bridge/mod.rs b/crates/eggsec/src/runtime_bridge/mod.rs index 1d86fc88e..2a40d88a5 100644 --- a/crates/eggsec/src/runtime_bridge/mod.rs +++ b/crates/eggsec/src/runtime_bridge/mod.rs @@ -13,8 +13,8 @@ //! # Invariants //! //! - [`RuntimeSurface::Unknown`](eggsec_runtime::RuntimeSurface::Unknown) is never executable. -//! - Manual surfaces (`CliManual`, `TuiManual`) retain operator-directed semantics -//! whether embedded or daemon-backed. +//! - Manual surfaces (`CliManual`, `TuiManual`, `DesktopGuiManual`) retain +//! operator-directed semantics whether embedded or daemon-backed. //! - Automated surfaces (`McpServer`, `RestApi`, `GrpcApi`, `SecurityAgent`, `Ci`) //! never honor manual overrides. //! - Any new [`RuntimeSurface`](eggsec_runtime::RuntimeSurface) variant must update @@ -25,6 +25,7 @@ mod bundle; mod descriptor; mod executor; mod manual; +pub mod report; mod surface; pub use bundle::{ diff --git a/crates/eggsec/src/runtime_bridge/report.rs b/crates/eggsec/src/runtime_bridge/report.rs new file mode 100644 index 000000000..fc11b850b --- /dev/null +++ b/crates/eggsec/src/runtime_bridge/report.rs @@ -0,0 +1,712 @@ +//! Engine-side report bridge: a completed task result → the canonical report +//! document. +//! +//! The runtime owns task *lifecycle*; the engine owns report *semantics*. This +//! module is the engine half of that split: it turns a completed +//! [`TaskResult`] into the canonical [`ScanReportData`] document that the +//! runtime's bounded report store retains and the daemon serves. +//! +//! # Purity +//! +//! The bridge is pure. It performs no I/O, reads no state, consults no clock +//! and opens no network connection, so the same result always yields the same +//! document. A result whose type carries no scan timestamp therefore yields a +//! document whose `timestamp` field is empty rather than one stamped with the +//! bridge's own clock reading — a timestamp the result does not know is a +//! value the bridge would have to invent. +//! +//! The per-domain bridges this module reuses are the engine's existing ones +//! and are called verbatim; those carry their own report timestamps. +//! +//! # Scope +//! +//! The bridge covers the result families that have a natural report form: +//! +//! | family | report form | +//! |---|---| +//! | port scan | target, open ports, detected services, duration | +//! | pipeline | target, open ports, services, prioritized findings, duration | +//! | fingerprint | target, detected services, duration | +//! | fuzz | target, the session's vulnerable payloads | +//! | recon | target, detected secrets and takeover candidates | +//! | wireless, wireless-active, db-pentest, c2 | the engine's existing per-domain bridges, reused verbatim | +//! +//! Every other [`TaskResult`] variant yields `None`. "No report available" is +//! the honest answer for a result with no report form; a lossy document +//! pretending to be a report is not. +//! +//! # Relationship to the task envelope +//! +//! This is a **separate** path from [`crate::dispatch::task_result_envelope`]. +//! The envelope's `payload` stays `json!({})` and its `artifacts` stay empty: +//! the report body is derived here and handed to the runtime's bounded report +//! store, never folded into the envelope. + +use crate::dispatch::TaskResult; +use crate::output::convert::{FindingData, PortData, ScanReportData, ServiceData}; +use crate::scanner::{FingerprintResults, PortResult, PortScanResults, ServiceFingerprint}; + +/// Build the canonical report document for a completed task result. +/// +/// Pure: the same result always yields the same document, and no state is +/// read or written. `None` means this result has no report form — the +/// caller reports "no report available" rather than inventing one. +pub fn report_for_result(result: &TaskResult) -> Option { + match result { + TaskResult::PortScan(scan) => Some(port_scan_report(scan)), + TaskResult::Pipeline(report) => Some(pipeline_report(report)), + TaskResult::Fingerprint(results) => Some(fingerprint_report(results)), + TaskResult::Fuzz(session) => Some(fuzz_report(session)), + TaskResult::Recon(recon) => Some(recon_report(recon)), + #[cfg(feature = "wireless")] + TaskResult::Wireless(scan) => Some(crate::wireless::to_scan_report_data(scan)), + #[cfg(feature = "wireless-advanced")] + TaskResult::WirelessActive(attack) => { + Some(crate::wireless::active::to_active_scan_report_data(attack)) + } + #[cfg(feature = "db-pentest")] + TaskResult::DbPentest(report) => Some(crate::db_pentest::to_scan_report_data_db(report)), + #[cfg(feature = "c2")] + TaskResult::C2(report) => Some(crate::c2::to_scan_report_data(report)), + _ => None, + } +} + +/// The canonical `scan_type` discriminators this bridge emits. +mod scan_type { + /// A port scan. + pub const PORT_SCAN: &str = "port-scan"; + /// A full pipeline run. + pub const PIPELINE: &str = "pipeline"; + /// A service fingerprint run. + pub const FINGERPRINT: &str = "fingerprint"; + /// A fuzzing session. + pub const FUZZ: &str = "fuzz"; + /// A reconnaissance run. + pub const RECON: &str = "recon"; +} + +/// Build the report document for a port scan. +/// +/// The scanner's own `open_ports` collection is mapped verbatim, verdict and +/// all: a UDP run fills that collection with a per-port verdict, and dropping +/// the non-open rows would misreport the run. +fn port_scan_report(scan: &PortScanResults) -> ScanReportData { + let open_ports: Vec = scan.open_ports.iter().map(port_data).collect(); + + // The scanner records the detected service name per port; the report + // lists the distinct names it detected. + let mut services: Vec = Vec::new(); + for port in &scan.open_ports { + let name = port.service.trim(); + if name.is_empty() { + continue; + } + if services.iter().any(|s| s.service == name) { + continue; + } + services.push(ServiceData { + service: name.to_string(), + version: None, + banner: None, + }); + } + + ScanReportData { + target: scan.host.clone(), + scan_type: scan_type::PORT_SCAN.to_string(), + timestamp: String::new(), + findings: Vec::new(), + open_ports, + services, + duration_ms: scan.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a pipeline run. +/// +/// The pipeline's findings are the ones its vulnerability assessment +/// prioritized; a run without an assessment simply carries no findings. +fn pipeline_report(report: &crate::pipeline::PipelineReport) -> ScanReportData { + let findings: Vec = report + .vuln_assessment + .iter() + .flat_map(|assessment| assessment.prioritized_findings.iter()) + .map(|finding| FindingData { + title: finding.title.clone(), + severity: finding.severity.as_str().to_string(), + category: "pipeline-vulnerability".to_string(), + description: format!( + "Priority {} finding from the pipeline's vulnerability assessment.", + finding.priority_rank + ), + location: report.target.clone(), + evidence: Some(format!( + "finding_id={} combined_score={:.1}", + finding.finding_id, finding.risk_score.combined_score + )), + remediation: None, + cwe_ids: Vec::new(), + }) + .collect(); + + ScanReportData { + target: report.target.clone(), + scan_type: scan_type::PIPELINE.to_string(), + timestamp: report + .manifest + .as_ref() + .map(|manifest| manifest.started_at.to_rfc3339()) + .unwrap_or_default(), + findings, + open_ports: report.open_ports.iter().map(port_data).collect(), + services: report.services.iter().map(service_data).collect(), + duration_ms: report.total_duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a service fingerprint run. +/// +/// A fingerprint run knows which services it identified but not the port +/// verdict behind them, so the report lists the services and no ports. +fn fingerprint_report(results: &FingerprintResults) -> ScanReportData { + ScanReportData { + target: results.host.clone(), + scan_type: scan_type::FINGERPRINT.to_string(), + timestamp: String::new(), + findings: Vec::new(), + open_ports: Vec::new(), + services: results.results.iter().map(service_data).collect(), + duration_ms: results.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a fuzzing session. +/// +/// Only the payloads the session found vulnerable become findings; a payload +/// that was sent and rejected is not a finding. +fn fuzz_report(session: &crate::fuzzer::engine::FuzzSession) -> ScanReportData { + let findings: Vec = session + .results + .iter() + .filter(|result| result.is_vulnerable()) + .map(|result| { + let category = result + .owasp_category + .clone() + .unwrap_or_else(|| "fuzz".to_string()); + let mut evidence = vec![format!("payload_type={}", result.payload.payload_type)]; + if !result.leaks_found.is_empty() { + evidence.push(format!("leaks={}", result.leaks_found.join(", "))); + } + if result.is_anomaly { + evidence.push("timing_anomaly=true".to_string()); + } + if result.is_redos_suspected { + evidence.push("redos_suspected=true".to_string()); + } + FindingData { + title: format!("{} payload finding", result.payload.payload_type), + severity: result.detected_severity.as_str().to_string(), + category, + description: result.payload.description.clone(), + location: session.target_url.clone(), + evidence: Some(evidence.join("; ")), + remediation: None, + cwe_ids: Vec::new(), + } + }) + .collect(); + + ScanReportData { + target: session.target_url.clone(), + scan_type: scan_type::FUZZ.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: session.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a reconnaissance run. +/// +/// Two recon facts are findings: a credential pattern detected in a response, +/// and a subdomain that a known service would let an attacker take over. +/// A takeover candidate that probed safe or unknown is not a finding. +fn recon_report(recon: &crate::recon::FullReconResult) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + if let Some(secrets) = &recon.secrets { + for secret in secrets { + findings.push(FindingData { + title: format!("{} detected", secret.secret_type), + severity: secret.severity.as_str().to_string(), + category: "recon-secret".to_string(), + description: secret.description.clone(), + location: secret.location.clone(), + evidence: Some(secret.value_preview.clone()), + remediation: None, + cwe_ids: Vec::new(), + }); + } + } + + if let Some(takeovers) = &recon.takeover { + for takeover in takeovers { + if takeover.status != crate::recon::takeover::TakeoverStatus::Vulnerable { + continue; + } + findings.push(FindingData { + title: format!( + "Subdomain takeover candidate for {}", + takeover.target.subdomain + ), + severity: takeover.severity.as_str().to_string(), + category: "recon-takeover".to_string(), + description: match &takeover.service { + Some(service) => format!("Takeover by {service}."), + None => "Subdomain takeover candidate.".to_string(), + }, + location: takeover.target.subdomain.clone(), + evidence: Some(takeover.evidence.clone()), + remediation: None, + cwe_ids: Vec::new(), + }); + } + } + + ScanReportData { + target: recon.target.clone(), + scan_type: scan_type::RECON.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: 0, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Map one scanned port onto the report model's port record. +fn port_data(port: &PortResult) -> PortData { + PortData { + port: port.port, + status: port.status.as_str().to_string(), + protocol: Some(port.protocol.as_str().to_string()), + state: None, + service: Some(port.service.clone()).filter(|service| !service.is_empty()), + version: None, + banner: None, + } +} + +/// Map one identified service onto the report model's service record. +fn service_data(service: &ServiceFingerprint) -> ServiceData { + ServiceData { + service: service.service.clone(), + version: service.version.clone(), + banner: service.banner.clone(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::scanner::ports::PortStatus; + + fn port(port_number: u16, status: PortStatus, service: &str) -> PortResult { + PortResult { + port: port_number, + status, + protocol: crate::scanner::ports::PortProtocol::Tcp, + service: service.to_string(), + } + } + + #[test] + fn a_port_scan_reports_its_target_ports_and_services() { + let scan = PortScanResults { + host: "10.0.0.1".into(), + ports_scanned: 1000, + open_ports: vec![ + port(22, PortStatus::Open, "ssh"), + port(80, PortStatus::Open, "http"), + port(443, PortStatus::Open, "http"), + ], + total_open_ports: 3, + results_truncated: false, + duration_ms: 500, + spoof_stats: None, + #[cfg(feature = "udp-scan")] + udp_host_state: None, + #[cfg(feature = "udp-scan")] + udp_evidence: None, + }; + + let report = + report_for_result(&TaskResult::PortScan(scan)).expect("a port scan has a report"); + + assert_eq!(report.target, "10.0.0.1"); + assert_eq!(report.scan_type, "port-scan"); + assert_eq!(report.duration_ms, 500); + assert_eq!(report.open_ports.len(), 3); + assert_eq!(report.open_ports[0].port, 22); + assert_eq!(report.open_ports[0].status, "open"); + assert_eq!(report.open_ports[0].protocol.as_deref(), Some("tcp")); + assert_eq!(report.open_ports[0].service.as_deref(), Some("ssh")); + assert_eq!( + report.services.len(), + 2, + "the same detected service is listed once" + ); + assert_eq!(report.services[0].service, "ssh"); + } + + #[test] + fn a_port_scan_keeps_the_verdict_of_every_scanned_port() { + let scan = PortScanResults { + host: "10.0.0.2".into(), + ports_scanned: 2, + open_ports: vec![ + port(53, PortStatus::Filtered, ""), + port(161, PortStatus::OpenFiltered, "snmp"), + ], + total_open_ports: 2, + results_truncated: false, + duration_ms: 10, + spoof_stats: None, + #[cfg(feature = "udp-scan")] + udp_host_state: None, + #[cfg(feature = "udp-scan")] + udp_evidence: None, + }; + + let report = + report_for_result(&TaskResult::PortScan(scan)).expect("a port scan has a report"); + + assert_eq!(report.open_ports.len(), 2); + assert_eq!(report.open_ports[0].status, "filtered"); + assert_eq!(report.open_ports[1].status, "open|filtered"); + assert_eq!( + report.open_ports[0].service, None, + "a port with no detected service carries no service name" + ); + } + + #[test] + fn a_pipeline_reports_its_target_ports_services_and_findings() { + let mut report = crate::pipeline::PipelineReport { + target: "example.com".into(), + total_duration_ms: 4200, + stage_results: Vec::new(), + open_ports: vec![port(443, PortStatus::Open, "https")], + services: vec![ServiceFingerprint { + port: 443, + service: "https".into(), + banner: Some("nginx".into()), + version: Some("1.25.0".into()), + product: None, + extra: None, + confidence: 90, + }], + endpoints: Vec::new(), + checkpoint_error: None, + manifest: None, + vuln_assessment: None, + load_test_results: None, + #[cfg(feature = "web-proxy")] + web_proxy_report: None, + }; + + let mut assessment = crate::vuln::VulnAssessment::new("standard"); + assessment + .prioritized_findings + .push(crate::vuln::PrioritizedFinding { + finding_id: "F-1".into(), + title: "Outdated TLS configuration".into(), + severity: crate::types::Severity::Medium, + risk_score: crate::vuln::RiskScore { + cvss_score: 5.0, + exploitability_score: 2.0, + asset_criticality: 1.0, + combined_score: 4.5, + priority_level: crate::vuln::PriorityLevel::P2, + }, + exploit_info: None, + asset_criticality: None, + priority_rank: 1, + }); + report.vuln_assessment = Some(assessment); + + let document = + report_for_result(&TaskResult::Pipeline(report)).expect("a pipeline run has a report"); + + assert_eq!(document.target, "example.com"); + assert_eq!(document.scan_type, "pipeline"); + assert_eq!(document.duration_ms, 4200); + assert_eq!(document.open_ports.len(), 1); + assert_eq!(document.services.len(), 1); + assert_eq!(document.services[0].version.as_deref(), Some("1.25.0")); + assert_eq!(document.findings.len(), 1); + assert_eq!(document.findings[0].title, "Outdated TLS configuration"); + assert_eq!(document.findings[0].severity, "medium"); + assert_eq!(document.findings[0].category, "pipeline-vulnerability"); + } + + #[test] + fn a_fingerprint_reports_its_detected_services() { + let results = FingerprintResults { + host: "10.0.0.3".into(), + ports_scanned: 100, + services_identified: 1, + total_services_identified: 1, + duration_ms: 120, + results: vec![ServiceFingerprint { + port: 22, + service: "ssh".into(), + banner: Some("OpenSSH 9.6".into()), + version: Some("9.6".into()), + product: None, + extra: None, + confidence: 80, + }], + }; + + let document = report_for_result(&TaskResult::Fingerprint(results)) + .expect("a fingerprint has a report"); + + assert_eq!(document.target, "10.0.0.3"); + assert_eq!(document.scan_type, "fingerprint"); + assert_eq!(document.duration_ms, 120); + assert_eq!(document.services.len(), 1); + assert_eq!(document.services[0].service, "ssh"); + assert_eq!(document.services[0].banner.as_deref(), Some("OpenSSH 9.6")); + assert!( + document.open_ports.is_empty(), + "a fingerprint run knows no port verdict" + ); + } + + #[test] + fn a_fuzz_session_reports_only_its_vulnerable_payloads() { + let vulnerable = crate::fuzzer::engine::FuzzResult { + payload: crate::fuzzer::payloads::Payload { + payload_type: crate::fuzzer::payloads::PayloadType::Sqli, + payload: "1' OR '1'='1".into(), + description: "SQL injection probe".into(), + severity: crate::types::Severity::High, + tags: vec![], + }, + status_code: 200, + response_time_ms: 12, + response_length: Some(1024), + response_body: None, + is_waf_blocked: false, + is_anomaly: false, + is_redos_suspected: false, + leaks_found: vec!["password".into()], + error: None, + owasp_category: Some("A03:2021".into()), + detected_severity: crate::types::Severity::High, + }; + let rejected = crate::fuzzer::engine::FuzzResult { + payload: crate::fuzzer::payloads::Payload { + payload_type: crate::fuzzer::payloads::PayloadType::Xss, + payload: " @@ -450,7 +561,7 @@ produce PDF without linking the engine. PDF is out of scope. The GUI's CSP (`crates/eggsec-gui/tauri.conf.json:23`) sets `default-src 'self'; script-src 'self'; …` — no remote origin is permitted, -and guard 158 (`scripts/check-architecture-guards.sh:4656-4681`) enforces that +and guard 158 (`scripts/check-architecture-guards.sh:4708-4766`) enforces that mechanically. In addition, the renderer emits no `` element (so the chart never draws anyway) and `frame-src 'none'` forbids an iframe. The current `eggsec-output` HTML renderer **cannot** be used as-is for the GUI's @@ -477,10 +588,10 @@ place, in the GUI crate. - No coverage model: the GUI has no notion of "all 30 variants", only the catalog rows it happens to receive. - No feature-availability resolution: `unavailable_reason` - (`crates/eggsec-gui/src/commands.rs:319-331`) has exactly two reasons. + (`crates/eggsec-gui/src/commands.rs:458-470`) has exactly two reasons. - No daemon lifecycle: the GUI "never spawns, supervises, or stops a daemon" (`crates/eggsec-gui/src/connection.rs:3-7`, - `crates/eggsec-gui/src/shell.rs:12-16`). + `crates/eggsec-gui/src/shell.rs:13-25`). - No report export at all: no `eggsec-output` dependency, no export command, no report view. - The socket-path duplication is documented incorrectly in two places (§3.2). @@ -503,7 +614,7 @@ review-by date), not an implementation task M006 may take on itself. - **The engine stays behind the daemon protocol.** The GUI MUST NOT depend on `eggsec`, `eggsec-daemon`, `eggsec-cli`, or `eggsec-tui` (guard 155, - `scripts/check-architecture-guards.sh:4516-4552`). + `scripts/check-architecture-guards.sh:4768-4834`). - **`EnforcementContext::evaluate()` remains the mandatory pre-dispatch gate.** The GUI MUST NOT import `EnforcementContext`, `EnforcedDispatcher`, `Scope::is_target_allowed`, or `tool.execute()`. @@ -562,6 +673,13 @@ review-by date), not an implementation task M006 may take on itself. - **Report export** through `eggsec-output`, matching the CLI's artifacts, with an embedded HTML display that satisfies the CSP. - A **coverage test** asserting every `TaskKind` variant is reachable. +- **The `DesktopGuiManual` permissive-set fix** (user-directed; work package + G). `crates/eggsec/src/runtime_bridge/executor.rs` treats only `CliManual` + and `TuiManual` as permissive surfaces, so a desktop-GUI session whose + scope is not explicit takes the strict branch and fails closed. The + desktop GUI is a permissive manual surface under ADR-0007, and every GUI + task dispatched through the daemon-hosted executor is affected, so the fix + is a precondition of this milestone's own end-to-end verification. - New guards and the documentation updates in §12. ### Explicitly out of scope @@ -643,42 +761,44 @@ field (`crates/eggsec-daemon-protocol/src/protocol.rs:46-51`): ```rust #[serde(default)] -pub enabled_features: Vec, +pub enabled_features: Option>, ``` +> **Resolved in §0, ambiguity 1.** The shape is `Option>`, not +> `Vec`. `None` means **unknown**; `Some(vec![])` means an engine is +> linked with no features enabled. The distinction is the whole point of the +> field: an empty vector would be ambiguous, and a client that read it as +> "unknown" would report the wrong reason for an unavailable operation. + This is strictly additive in both directions: a **new** daemon's capabilities decoded by an **old** client works, because serde ignores unknown fields by default; an **old** daemon's capabilities decoded by a **new** client works, -because `#[serde(default)]` supplies an empty vector. The protocol version -therefore stays at `DAEMON_PROTOCOL_VERSION` — the same reason milestone 003 -kept it at 2 when `ClientKind::Gui` was added. +because `#[serde(default)]` supplies `None`. The protocol version therefore +stays at `DAEMON_PROTOCOL_VERSION` — the same reason milestone 003 kept it at 2 +when `ClientKind::Gui` was added. The GUI MUST NOT abort its connection when +the field is absent: a defaulted field can be absent on an old daemon, and +the GUI degrades to "availability unverified" instead. The daemon's value comes from the executor, which gains one **defaulted** -method (`crates/eggsec-runtime/src/runtime.rs:40-57`): +method (`crates/eggsec-runtime/src/runtime.rs`): ```rust /// The engine features compiled into this executor's build. /// -/// An empty result means "unknown", not "none": a no-op executor -/// advertises nothing because it links no engine at all. -fn enabled_features(&self) -> Vec { Vec::new() } +/// `None` means unknown: the executor links no engine, or does not publish +/// the fact. `Some(vec![])` means an engine is linked with no features +/// enabled — a different, knowable fact. +fn enabled_features(&self) -> Option> { None } ``` A defaulted method is additive at the Rust level — every existing -implementation (`NoopExecutorStub` at `crates/eggsec-daemon/src/host.rs:3553-3575`, -`NoopExecutor` at `crates/eggsec-cli/src/daemon_cli.rs:584-607`) keeps -compiling unchanged. The engine's `EggsecRuntimeExecutor` overrides it with -`eggsec::policy_bridge::features::current_enabled_features()` -(`crates/eggsec/src/policy_bridge/features.rs:11-17`), which reads the -engine's own authoritative compile-time registry -(`crates/eggsec/src/config/feature_registry.rs:110`). - -**An empty vector is ambiguous** and the GUI MUST treat it as *unknown*, not as -*nothing is enabled*. The daemon MUST therefore distinguish "I link no engine" -from "I link an engine with these features" — for example by returning -`Option>` (`None` = unknown) rather than an empty vector. **The -implementer MUST pick one and document it**; the GUI's fallback behaviour -depends on it. +implementation (`NoopExecutorStub` at `crates/eggsec-daemon/src/host.rs`, +the daemon binary's fallback executor) keeps compiling unchanged, and the +no-op executor's `None` is exactly right: it links no engine, so its +feature set is unknown. The engine's `EggsecRuntimeExecutor` overrides it +with the engine's own authoritative compile-time registry +(`crates/eggsec/src/config/feature_registry.rs`, whose entries each carry a +`cfg!()`-derived `enabled` flag). **(P2) The report read path.** One new read-only command and one new response: @@ -688,10 +808,39 @@ ClientCommand::GetTaskReport { request_id, session_id, task_id } ServerMessage::TaskReport { request_id, session_id, task_id, report } ``` -An old daemon receiving `GetTaskReport` answers `ErrorCode::UnsupportedCommand` -(`crates/eggsec-daemon-protocol/src/protocol.rs:72`) — the protocol already -defines that error for exactly this purpose (`:54-59`, `:181`). A new client -MUST treat it as a graceful degradation (no export), never as a launch failure. +> **Corrected at the current baseline.** The plan said an old daemon +> answers `ErrorCode::UnsupportedCommand` for a command it does not know. +> It does not: the daemon deserializes the line straight into +> `ClientCommand`, so an unknown discriminant is a *deserialization +> failure*, answered with `ErrorCode::InvalidRequest` **and an empty +> `request_id`** (`crates/eggsec-daemon/src/server.rs`). Because the +> frontend client routes responses by request id, the pending request is +> never resolved and the client **hangs for its 30-second timeout** +> instead of receiving an error. +> +> M006 MUST fix that, because M006 is the milestone that adds a command +> older daemons will not know. The daemon MUST distinguish "this client +> sent a command this daemon does not know" from "this client sent a +> malformed command", answer the former with `ErrorCode::UnsupportedCommand` +> **and the request id echoed back**, and answer the latter with +> `ErrorCode::InvalidRequest`. The protocol therefore also gains a way for +> the daemon to enumerate the commands it knows +> (`ClientCommand::command_names()`). + +The report document itself is carried as `serde_json::Value` on the wire +rather than as a typed report-model struct, so the protocol crate keeps no +report-model dependency; the GUI deserializes it into the canonical +`ScanReportData`. The engine produces it through a **pure** bridge from the +completed task result, and it is held in a **bounded** store +(`eggsec_runtime::RuntimeReportStore`) so a long-lived daemon cannot +accumulate one report document per task for the life of the process. The +store lives behind the executor and is read through the runtime, so the +daemon never learns a report's domain semantics — it only serves what the +engine produced. + +The read path MUST NOT touch `TaskResultEnvelope` (see P-HARD). A new client +MUST treat `ErrorCode::UnsupportedCommand` and a "no report for this task" +answer as a graceful degradation (no export), never as a launch failure. **(P3) The frontend-client accessor.** `DaemonRuntimeClient` gains an inherent method — **not** a `RuntimeClient` trait method, mirroring milestone 004's @@ -758,19 +907,33 @@ need comes in through the dependency. - The webview MUST receive the coverage table as **data** and render it. It MUST NOT contain a per-variant table, a per-variant branch, or a hardcoded field list. -- **Embedded HTML display.** The `eggsec-output` HTML renderer cannot be - embedded as-is (§3.9). The bounded options are (1) a **self-contained - rendering mode added to `eggsec-output`** — the renderer omits the CDN - ` + + +
+
+

🛡️ Security Scan Report

+

+
+ +
+

Summary

+
+
+
Target
+
127.0.0.1
+
+
+
Scan Type
+
port-scan
+
+
+
Duration
+
0s
+
+
+
Requests
+
0
+
+
+ +
+
🔴 0
+
🟠 0
+
🟡 0
+
🔵 0
+
⚪ 0
+
+
+ +
+

Findings (0)

+ +
+ +
+

Generated by Eggsec |

+
+
+ + + + \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.export.json b/docs/evidence/gui-qualification/macos-2026-10-24.export.json new file mode 100644 index 000000000..6a66c1957 --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.export.json @@ -0,0 +1,25 @@ +{ + "target": "127.0.0.1", + "scan_type": "port-scan", + "timestamp": "", + "findings": [], + "open_ports": [ + { + "port": 22, + "status": "open", + "protocol": "tcp", + "state": null, + "service": "SSH", + "version": null, + "banner": null + } + ], + "services": [ + { + "service": "SSH", + "version": null, + "banner": null + } + ], + "duration_ms": 1 +} \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.export.md b/docs/evidence/gui-qualification/macos-2026-10-24.export.md new file mode 100644 index 000000000..61e8c00bc --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.export.md @@ -0,0 +1,23 @@ +# Security Scan Report + +## Summary + +| Field | Value | +|-------|-------| +| Target | 127.0.0.1 | +| Scan Type | port-scan | +| Timestamp | | +| Duration | 0 seconds | +| Total Requests | 0 | +| Critical | 0 | +| High | 0 | +| Medium | 0 | +| Low | 0 | +| Info | 0 | + +## Findings + + +No vulnerabilities were found in this scan. + + diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.export.sarif b/docs/evidence/gui-qualification/macos-2026-10-24.export.sarif new file mode 100644 index 000000000..57adac32c --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.export.sarif @@ -0,0 +1,24 @@ +{ + "version": "2.1.0", + "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", + "runs": [ + { + "tool": { + "driver": { + "name": "Eggsec", + "version": "0.1.0", + "information_uri": "https://github.com/eggstack/eggsec", + "rules": [] + } + }, + "results": [], + "invocations": [ + { + "start_time_utc": "2026-10-24T20:44:24.326090Z", + "end_time_utc": "2026-10-24T20:44:24.326093Z", + "execution_successful": true + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.export.xml b/docs/evidence/gui-qualification/macos-2026-10-24.export.xml new file mode 100644 index 000000000..ff0de6b1f --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.export.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.md b/docs/evidence/gui-qualification/macos-2026-10-24.md new file mode 100644 index 000000000..a99678cad --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.md @@ -0,0 +1,200 @@ +# GUI qualification evidence — macos 2026-10-24 + +This file is the run record for one desktop-GUI qualification run. It is produced by `scripts/gui_qualification.sh` and it is what the matrix's cells cite. + +--- + +## Identity + +| Field | Value | +|---|---| +| Platform | `macos` | +| Qualification column(s) this run supports | `Build`, `Connect`, `Submit`, `Cancel`, `Render`, `Export` | +| Date of the run (UTC) | 2026-10-24 | +| Operator or CI job | `ci` | +| Commit SHA (`git rev-parse HEAD`) | `0f5dbb26e7ab215613e5b6e2295d9c124374bf9f` | +| Tree state (`git status --porcelain` empty?) | `dirty` | +| Host OS version | macos 25.6.0 | +| Architecture | aarch64 | +| Process architecture | x86_64 (the architecture of the running process, which differs from the targeted one under Rosetta) | +| Target triple | aarch64-apple-darwin | +| Toolchain | `rustc 1.99.1 (58cf8f9c3 2026-10-13)` | +| Cargo version | `cargo 1.99.1 (5f94df478 2026-08-27)` | +| Feature set | requested ['shell'], resolved ['default', 'shell'] | + +## Environment + +| Field | Value | +|---|---| +| Prerequisite probe result | `bash scripts/check_gui_prereqs.sh` -> exit 0 (BUILDABLE) | +| Webview SDK version | see the prerequisite probe's output below | +| Daemon version and build features | /tmp/eggsec-qualify-bin/eggsec-daemon (sha256 69018207176a1ba8098533c782a7e026a787695e3d99aed5c71283c4a04195df) (features: service) | +| Daemon socket path used | `/var/folders/2j/dlwhrpps66scv9bw8f7vdfg40000gq/T//eggsec-gui-qualification-42689.sock` | +| Scope in force | surface `DesktopGuiManual`, source `gui-default` | +| Window probe | the window probe ran on this host | + +## Commands run + +``` +# 1. bash scripts/check_gui_prereqs.sh +0 + +# 2. cargo test -p eggsec-gui --no-default-features --test qualification +0 +``` + +## Observed output + +The harness's transcript: + +``` +running 5 tests +test the_column_identifiers_are_the_seven_the_matrix_publishes ... ok +test the_outcome_file_round_trips_and_names_what_is_wrong_with_it ... ok +test the_export_refuses_a_non_regular_destination_and_backs_up_a_real_one ... ok +test the_live_daemon_half_records_its_outcomes ... ok +test every_report_format_renders_writes_and_digests ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.15s +``` + +## Pass criterion and outcome + +| Column | Pass criterion | Outcome | Met? | +|---|---|---|---| +| `build` | the runbook's Step 1 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-applicable` | yes | +| `launch` | the runbook's Step 2 (`docs/GUI_BUILD.md` §5) | scripted `not-performed`, operator `not-performed` | partial | +| `connect` | the runbook's Step 3 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-performed` | yes | +| `submit` | the runbook's Step 4 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-performed` | yes | +| `cancel` | the runbook's Step 5 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-performed` | yes | +| `render` | the runbook's Step 6 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-performed` | yes | +| `export` | the runbook's Step 7 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `not-performed` | yes | + +Each column's reason: + +- `build` — the release build produced `eggsec-gui.build.json` and its SHA-256 is recorded +- `launch` — no `eggsec-gui` process is running on this host, so the probe had no window to find; the launch step is an operator action +- `connect` — the GUI's own client connected to the daemon and read its catalogue +- `submit` — the GUI's own form engine assembled the `PortScan` request and the daemon accepted it as task task:6b6618eb-fdd4-4546-a130-54f1690da054 +- `cancel` — the daemon accepted the cancellation and the event stream reported `cancelled` +- `render` — the daemon's report for the task rendered as 0 findings and 1 open ports against `127.0.0.1` +- `export` — the GUI's own export path wrote the daemon's report in 6 formats, and each written file's bytes equal the renderer's output + +## Deviations and notes + +- None. The run followed `docs/GUI_BUILD.md` §5 as written. + +## The run record + +The block below is the `eggsec-gui-qualification-record/v1` record. `scripts/check_gui_qualification.py` reads it. + +```json +{ + "schema": "eggsec-gui-qualification-record/v1", + "platform": "macos", + "mode": "ci", + "date": "2026-10-24", + "commit": "0f5dbb26e7ab215613e5b6e2295d9c124374bf9f", + "tree_state": "dirty", + "host": { + "os": "macos", + "os_version": "25.6.0", + "arch": "aarch64", + "process_arch": "x86_64", + "target_triple": "aarch64-apple-darwin" + }, + "toolchain": { + "rustc": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "cargo": "cargo 1.99.1 (5f94df478 2026-08-27)" + }, + "features": { + "requested": [ + "shell" + ], + "resolved": [ + "default", + "shell" + ] + }, + "prerequisite_probe": { + "command": "bash scripts/check_gui_prereqs.sh", + "exit": 0, + "verdict": "BUILDABLE" + }, + "daemon": { + "socket": "/var/folders/2j/dlwhrpps66scv9bw8f7vdfg40000gq/T//eggsec-gui-qualification-42689.sock", + "ready": true, + "version": "/tmp/eggsec-qualify-bin/eggsec-daemon (sha256 69018207176a1ba8098533c782a7e026a787695e3d99aed5c71283c4a04195df)", + "features": "service", + "task_kinds": "30", + "scope": { + "surface": "DesktopGuiManual", + "source": "gui-default" + } + }, + "window": { + "probe": "osascript", + "windows": "0", + "screenshot": "", + "reason": "the window probe ran on this host" + }, + "columns": [ + { + "column": "build", + "scripted": "pass", + "operator": "not-applicable", + "artifact": "macos-2026-10-24.build.json", + "sha256": "741905d478d8d360f5e8097e94d7068fc0ff7159c93b843e519938980f6d8387", + "reason": "the release build produced `eggsec-gui.build.json` and its SHA-256 is recorded" + }, + { + "column": "launch", + "scripted": "not-performed", + "operator": "not-performed", + "artifact": "", + "sha256": "", + "reason": "no `eggsec-gui` process is running on this host, so the probe had no window to find; the launch step is an operator action" + }, + { + "column": "connect", + "scripted": "pass", + "operator": "not-performed", + "artifact": "", + "sha256": "", + "reason": "the GUI's own client connected to the daemon and read its catalogue" + }, + { + "column": "submit", + "scripted": "pass", + "operator": "not-performed", + "artifact": "", + "sha256": "", + "reason": "the GUI's own form engine assembled the `PortScan` request and the daemon accepted it as task task:6b6618eb-fdd4-4546-a130-54f1690da054" + }, + { + "column": "cancel", + "scripted": "pass", + "operator": "not-performed", + "artifact": "", + "sha256": "", + "reason": "the daemon accepted the cancellation and the event stream reported `cancelled`" + }, + { + "column": "render", + "scripted": "pass", + "operator": "not-performed", + "artifact": "", + "sha256": "", + "reason": "the daemon's report for the task rendered as 0 findings and 1 open ports against `127.0.0.1`" + }, + { + "column": "export", + "scripted": "pass", + "operator": "not-performed", + "artifact": "macos-2026-10-24.export.json", + "sha256": "3dfb128f2e3fafd596b5c54ede645e39bd31cb4d6234d1145633effc97fd21c1", + "reason": "the GUI's own export path wrote the daemon's report in 6 formats, and each written file's bytes equal the renderer's output" + } + ], + "deviations": [] +} +``` diff --git a/docs/python/examples/local_vs_daemon_execution.py b/docs/python/examples/local_vs_daemon_execution.py index 02816beaf..192d4d4be 100644 --- a/docs/python/examples/local_vs_daemon_execution.py +++ b/docs/python/examples/local_vs_daemon_execution.py @@ -10,8 +10,15 @@ Usage: python3 docs/python/examples/local_vs_daemon_execution.py [target] + +The daemon's socket path comes from ``EGGSEC_DAEMON_SOCKET`` when it is set, +and from the daemon's built-in default otherwise. The default is stated once, +in ``crates/eggsec-runtime/src/daemon_endpoint.rs``; the Python bindings +carry no copy of it, so this example reads the same environment variable the +daemon binary reads. Pass a path as the second argument to override both. """ +import os import sys import eggsec @@ -20,6 +27,14 @@ def main(): target = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1" + # The daemon's socket path: the operator's override, else the daemon's + # own default. The default lives in the daemon's canonical crate, so the + # example asks the daemon rather than carrying a copy of it. + socket_path = ( + sys.argv[2] + if len(sys.argv) > 2 + else os.environ.get("EGGSEC_DAEMON_SOCKET", "").strip() + ) scope = Scope.allow_hosts([target]) request = PortScanRequest(target=target, ports=[22, 80, 443]) @@ -35,7 +50,13 @@ def main(): import asyncio async def daemon_run(): - client = daemon_connect("/tmp/eggsec-daemon.sock") + if not socket_path: + print( + "No socket path: set EGGSEC_DAEMON_SOCKET or pass one as the " + "second argument (the daemon's own default is not duplicated here)." + ) + return + client = daemon_connect(socket_path) health = await eggsec.async_daemon_health(client) print(f"Daemon health: {health}") client.close() diff --git a/plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md b/plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md new file mode 100644 index 000000000..a10e91879 --- /dev/null +++ b/plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md @@ -0,0 +1,274 @@ +# ADR-0013: Daemon Endpoint Default and Bind Contract + +Status: proposed + +Date: 2026-10-24 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#4-enforcement-invariants` +- `plans/000-long-term-specification.md#6-dispatch-runtime-and-wire-identity` +- `plans/000-long-term-specification.md#10-frontend-rules` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +## Context + +The daemon's socket path had no single owner. At the baseline the literal +`/tmp/eggsec-daemon.sock` was transcribed in six places in the workspace's +executable surface — the daemon binary's `--socket-path` default +(`crates/eggsec-daemon/src/main.rs`), the daemon's `DaemonConfig::default()` +(`crates/eggsec-daemon/src/config.rs`), the engine's global `--socket` +(`crates/eggsec/src/cli/mod.rs`), the GUI's Rust options +(`crates/eggsec-gui/src/config.rs`), the GUI's webview JavaScript constant and +its HTML `value` attribute (`crates/eggsec-gui/frontend/`), and the daemon +profile build script (`scripts/build-daemon-profile.sh`). A change to one copy +would have silently failed to change the others, and the GUI's webview copy was +already known to be able to drift away from the Rust copy. + +The repository also *named* an environment variable for this without +implementing it: `scripts/build-daemon-profile.sh` read `EGGSEC_DAEMON_SOCKET` +and fell back to the literal, so the script's line was a promise the binaries +did not keep. The alternative spelling `EGGSEC_SOCKET` is named and rejected in +`docs/GUI_DISTRIBUTION_HANDOFF.md`. + +The second question is separate but adjacent. `run_server` +(`crates/eggsec-daemon/src/server.rs`) removed the socket path **before** it +bound, unconditionally. A daemon that was already serving that path therefore +lost its socket file to a second daemon's start, and the live daemon kept +running but became unreachable. The pre-flight probe narrows that window; it +does not close it, because the evidence (the socket file) is destroyed before +the bind. + +The decision required here is **where the default lives**, **what the +environment override is called and how it is resolved**, and **what the bind +contract is**. + +## Decision drivers + +- One owner for the default, reachable by the engine, the daemon and the GUI + without a new dependency edge and without the GUI linking a daemon crate + (ADR-0007, guard 155). +- One precedence rule, applied identically by every surface, so that a flag, an + environment value and a built-in default cannot disagree. +- The webview must not hold a copy of a value the Rust side owns; there is no + build step and no inline script the CSP would permit + (`crates/eggsec-gui/tauri.conf.json`). +- One liveness notion: "live" means "a daemon answered `Health` on this path", + decided by `probe_daemon_liveness` + (`crates/eggsec-daemon/src/host.rs`). No `stat`-based check, no lock file, no + PID file. +- A refusal must be actionable and fail-closed: the server must not unlink a + path it has not proven stale. +- A daemon that crashed and left its socket file behind must still be able to + start on that path. + +## Considered options + +### Option A — The default lives in `eggsec-daemon` + +Rejected. The GUI links no engine, daemon, CLI or TUI crate (ADR-0007, guard +155), so the GUI could not reach the constant without a forbidden dependency +edge, and the GUI's Rust side would have to keep a copy — the duplication the +decision is meant to remove. + +### Option B — The default lives in `eggsec-core` + +Rejected. `eggsec-core` is blocked for the daemon by guard 16, and it does not +depend on `eggsec-runtime`; adopting it would add an edge rather than remove +one. + +### Option C — The default lives in `eggsec-runtime` + +Accepted. `eggsec-runtime` is the unique intersection of the crates that +transcribe the default: the engine, the daemon and the GUI already depend on +it, and the CLI depends on it transitively. A `&'static str` constant and two +pure functions need no new edge, no new crate and no `deny.toml` decision. +Guard 22 forbids the runtime from depending on the engine or the domain crates; +this decision does neither. The cost is that the runtime's charter — task +lifecycle and session host — now also owns a *deployment endpoint* fact. That +is a durable cross-crate ownership statement, which is why it is recorded here. + +### Option D — Each surface keeps its own copy + +Rejected. That is the status quo, and it is the defect: six copies of one +default, and a webview copy that can drift from the Rust copy. + +## Decision + +**Option C.** `eggsec-runtime` owns the daemon's endpoint facts. + +1. **One owner.** `crates/eggsec-runtime/src/daemon_endpoint.rs` is the only + place in the workspace's executable surface that states the daemon's default + socket path, the environment variable's name, and the precedence rule. The + module exposes exactly four items: + + ```rust + pub const DAEMON_SOCKET_ENV_VAR: &str = "EGGSEC_DAEMON_SOCKET"; + pub const DEFAULT_DAEMON_SOCKET_PATH: &str = "/tmp/eggsec-daemon.sock"; + pub fn resolve_daemon_socket_path(env_value: Option<&str>) -> &str; + pub fn daemon_socket_path_from_env() -> String; + ``` + +2. **The environment variable is `EGGSEC_DAEMON_SOCKET`.** That is the name the + repository already used in `scripts/build-daemon-profile.sh`, so adopting it + turns a promise into a fact. It is not `EGGSEC_SOCKET`, which is named and + rejected in `docs/GUI_DISTRIBUTION_HANDOFF.md`. + +3. **One precedence, everywhere: explicit flag → `EGGSEC_DAEMON_SOCKET` → + built-in default.** The rule is applied by the resolver, not by the call + sites. An absent, empty or whitespace-only environment value is **absent**, + not an empty path: a daemon must never be asked to bind the empty path. A + value with surrounding whitespace is trimmed. The trim lives in the + resolver. + +4. **The resolver is pure; the environment is read in one place.** + `resolve_daemon_socket_path` takes the raw value and returns the resolved + one, and never touches the process environment — which is what makes the + precedence testable without mutating a process-global. + `daemon_socket_path_from_env` is the only function in the workspace that + reads `EGGSEC_DAEMON_SOCKET`; the surfaces call it and never read the + environment themselves. + +5. **The surfaces resolve, they do not transcribe.** The daemon binary's + `--socket-path`, the engine's global `--socket` (and therefore the CLI + binary and the TUI), the daemon's `DaemonConfig::default()` and the GUI's + `GuiOptions::default()` all name the canonical items. `DaemonConfig::default()` + stays **pure** — it returns the built-in default and does not read the + environment; the environment override is applied by the surfaces that parse + the operator's flags. This is deliberate: `Default` is a library-level fact, + and a third-party embedder that constructs `DaemonConfig::default()` + directly gets the built-in default. + +6. **The webview holds no copy.** The GUI's JavaScript constant and the HTML + `value` attribute are gone. The webview learns the path from Rust through + the **existing** `daemon_status` command, which gains a + `default_socket_path` field — a field, not a new command, so the IPC + command count stays at 13. An empty socket field is resolved by the **Rust** + side of `connect_daemon` to the GUI's own default, so the connection still + targets the right path even when the IPC call that would have filled the + field failed. + +7. **The bind contract: bind first, refuse over a live daemon, reclaim only a + proven-stale path.** `run_server` binds the socket path **without unlinking + it first**. If the bind fails with `AddrInUse`, the server asks the shared + probe whether the occupant is live: + + - **Live** → the server **refuses**. It returns a dedicated error that names + the path, says a live daemon holds it, gives that daemon's protocol + version, and names both remedies — stop the running daemon, or use a + different path. The socket file is **not** removed: the live daemon's + clients depend on it. + - **Not live** → the path holds no daemon. The server removes the file + **once** and binds again. If that second bind fails with `AddrInUse`, + another daemon took the path in between; the server refuses with a + distinct claim ("another daemon took the path") and does not unlink + again. + + The probe is `probe_daemon_liveness` with the pre-flight's own bound + (`PREFLIGHT_PROBE_TIMEOUT`, 5 s). The liveness notion is not changed, and + `DaemonLiveness::NotLive` keeps its recorded meaning — "not proven live" — + which includes a probe timeout. + +8. **A refused bind is fail-closed.** The server never unlinks a path it has + not proven stale. The residual window — between the probe and the reclaim, a + third actor could remove the stale path and a live daemon could bind it — is + one `remove_file` call wide and is stated as a residual, not as a closed + race. + +## Consequences + +### Positive + +- The daemon's default socket path is stated once in the executable surface, + in a crate the engine, the daemon, the GUI and the CLI all depend on. +- The environment override is real: `EGGSEC_DAEMON_SOCKET` works for the daemon + binary, the CLI, the TUI and the GUI, with one precedence. +- The webview cannot drift: it has no copy of the default to drift with. +- A second daemon can no longer displace a live daemon's socket file. The + loser of a bind race always observes the winner's socket in place, and the + probe then finds the winner live and refuses. + +### Negative + +- The runtime crate's charter widens by one module: it now owns a deployment + endpoint fact (the constant, the variable's name, the precedence rule). +- The daemon's start behaviour changes for launchers outside this repository: + a start that used to displace a live daemon now refuses. This is the point of + the decision, and it is a behaviour change for any embedder that relied on + the displacement. +- `DaemonConfig::default()` is pure while `GuiOptions::default()` is not. The + asymmetry is deliberate and documented: the GUI's options describe a process + that is about to connect to a daemon, so they honour the operator's + environment, while `DaemonConfig` is a library-level default that the + launchers set explicitly. + +### Neutral or deferred + +- The wire protocol is unchanged. No `ClientCommand`, no `ServerMessage`, no + field on either. +- The GUI's IPC command count is unchanged at 13; `daemon_status` gains a + field. +- `DaemonLiveness`'s shape is unchanged. "Proven dead" is a different notion + and would be a new variant and a new ADR. +- The reclaim window between the probe and the `remove_file` is not closed. It + needs a third actor to open and is one call wide. + +## Compatibility and migration + +- **No dependency change.** No crate is added, no `deny.toml` decision is + needed, and no existing dependency edge changes. `clap`'s `env` feature is + **not** enabled: the environment variable's name would then be transcribed a + second time as a clap attribute literal, and the rule would live in two + mechanisms that can drift. +- **Public API.** `eggsec-runtime` gains a module and four items. The engine's + `Cli::socket` keeps its type (`String`); the daemon binary's `socket_path` + keeps its type (`String`). The GUI keeps its `DEFAULT_SOCKET_PATH` name as a + re-export. +- **Behavioural change.** A start against a socket path that a live daemon is + holding now **refuses** instead of displacing the live daemon. The refusal + exits non-zero and prints an actionable message. +- **No storage migration.** Nothing is persisted. + +## Security and reliability implications + +- **Authorisation**: unchanged. The environment override chooses *where* the + daemon listens; it grants no access the operator could not already reach, and + the socket's owner-only (0600) permissions still gate who may connect. +- **Fail-closed**: the server unlinks only a path a probe has shown to hold no + daemon. +- **No leak**: the refusal carries the path the operator supplied and the live + daemon's protocol version — facts the operator already has. +- **No second liveness notion**: no lock file, no PID file, no `stat`-based + check. The bind guard uses the pre-flight's own probe. + +## Verification + +- `crates/eggsec-runtime`: unit tests for the resolver's five rows and for the + constant's value. +- `crates/eggsec-daemon`: the config default resolves to the canonical + constant; two servers against one path — exactly one binds, the other is + refused with the actionable message, the survivor keeps answering `Health`, + and the live daemon's socket file is still there and still 0600. +- `crates/eggsec-gui`: the options default resolves to the canonical constant; + `daemon_status` reports `default_socket_path`; `connect_daemon` with an empty + socket resolves to the GUI's default; the IPC command count is still 13. +- `crates/eggsec`: the global `--socket` default resolves to the canonical + constant, and an explicit `--socket` wins. +- Subprocess tests: with `EGGSEC_DAEMON_SOCKET` set, the operator's path is + used; with it set to the empty string, the built-in default is used; with it + set *and* an explicit flag, the flag wins. +- Static guards 177–179 pin that the default exists in one place, that the + server binds before it unlinks, and that the environment variable has one + name and one resolver. + +## Supersession + +This ADR supersedes nothing. It records the ownership decision that milestone +012 of `plans/subsystems/desktop-gui-frontend-roadmap.md` implements; the +implementation plan is +`plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md`. diff --git a/scripts/build-daemon-profile.sh b/scripts/build-daemon-profile.sh index 80d46195f..f389dbb8d 100755 --- a/scripts/build-daemon-profile.sh +++ b/scripts/build-daemon-profile.sh @@ -26,6 +26,11 @@ # What the script never does: no signing, no bundling, no packaging, no # installer, no updater, no npm step. It produces a binary and a record. # +# The script carries no copy of the daemon's default socket path: the binary +# owns that default and honours `EGGSEC_DAEMON_SOCKET` itself. The printed +# hint names the operator's override when there is one, and otherwise lets the +# binary apply its own default. +# # The probe calls the engine's OWN platform matrix # (`crates/eggsec/src/platform/prereqs.rs` -> `PlatformReport::collect` -> # `report_for` per domain) through `eggsec doctor`'s JSON mode, so it reports @@ -42,7 +47,11 @@ OUT_DIR="" ALLOW_DIRTY=0 MSRV_FLOOR="1.89" VALID_PROFILES="service" -SOCKET_PATH="${EGGSEC_DAEMON_SOCKET:-/tmp/eggsec-daemon.sock}" +# The script carries no copy of the daemon's default socket path. The binary +# owns that default (`eggsec_runtime::DEFAULT_DAEMON_SOCKET_PATH`) and honours +# `EGGSEC_DAEMON_SOCKET` itself, so the hint below only has to name the +# operator's override when there is one. +SOCKET_PATH="${EGGSEC_DAEMON_SOCKET:-}" ENGINE_MANIFEST="crates/eggsec/Cargo.toml" DAEMON_MANIFEST="crates/eggsec-daemon/Cargo.toml" @@ -511,4 +520,9 @@ echo "metadata sidecar: $METADATA_PATH" echo "" echo "Next step (the runtime flag is unchanged — it is a different mechanism" echo "from the cargo feature, and it still selects the engine executor):" -echo " $BINARY_PATH --full-executor --socket-path $SOCKET_PATH" +if [[ -n "$SOCKET_PATH" ]]; then + echo " $BINARY_PATH --full-executor --socket-path $SOCKET_PATH" +else + echo " $BINARY_PATH --full-executor" + echo " (the daemon applies its own default socket path; set EGGSEC_DAEMON_SOCKET to choose another)" +fi diff --git a/scripts/check-architecture-guards.sh b/scripts/check-architecture-guards.sh index f2bbfcfda..19523b168 100755 --- a/scripts/check-architecture-guards.sh +++ b/scripts/check-architecture-guards.sh @@ -5482,11 +5482,15 @@ problems = [] # The status vocabulary is closed. A cell that invents a status is not a # qualification. +# +# `pending M6` was retired by milestone 014: the token described a block that +# no longer exists, and Check 182 forbids it outright now that the export +# affordance exists. It is dropped here so this guard's vocabulary is the +# matrix's vocabulary, not a superset of it. ALLOWED = { "qualified", "partially qualified", "not qualified", - "pending M6", "out of scope", } @@ -5888,6 +5892,1014 @@ else FAIL=$((FAIL + 1)) fi +# 177. The daemon's default socket path exists in exactly one place. +# Milestone 012 (ADR-0013). +# +# The default socket path was transcribed in six places: the daemon binary's +# flag default, the daemon's config default, the engine's global flag, the +# GUI's Rust options, the GUI's webview (a JS constant and an HTML attribute) +# and the daemon profile build script. A change to one copy would silently +# fail to change the others, and the webview's copy could drift away from the +# Rust one entirely. +# +# The canonical crate owns the literal. Documentation, skills and plan history +# legitimately quote the operator-facing default, so the scan is scoped to +# `crates/` and `scripts/` -- the same discipline `check_doc_references.py` +# uses when it skips `plans/`. +# +# `code_search` is NOT used here: it strips string literals before matching +# (`sed -e 's/"[^"]*"/""/g'`), so it would blank the very literal this guard +# looks for and pass vacuously. +echo "" +echo "--- Check 177: the default socket path exists in exactly one place ---" +SECTION_FAIL=0 +CANONICAL_CRATE="crates/eggsec-runtime" +CANONICAL_RS="crates/eggsec-runtime/src/daemon_endpoint.rs" +SOCKET_LITERAL="/tmp/eggsec-daemon.sock" +# This guard has to NAME the literal in order to search for it, so the guard's +# own file is excluded from its own scan. A check that matches itself is not a +# check: without the exclusion this guard fails on its own search term and +# says nothing about the repository. +GUARD_SELF="scripts/check-architecture-guards.sh" + +# Every hit in the executable surface must live in the canonical crate. That +# crate may hold more than one occurrence -- the constant and the test that +# pins its value -- so the rule is the crate, not the file. +while IFS= read -r HIT; do + [[ -z "$HIT" ]] && continue + HIT_FILE="${HIT%%:*}" + if [[ "$HIT_FILE" != "$CANONICAL_CRATE"/* ]]; then + echo "FAIL: the default socket path is stated outside the canonical crate: $HIT" + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done < <(rg -H -n --fixed-strings "$SOCKET_LITERAL" crates/ scripts/ 2>/dev/null | grep -v "^${GUARD_SELF}:" || true) + +# The GUI's webview assets must hold no copy: the webview learns the path +# from Rust, through the existing `daemon_status` command. +if rg -q --fixed-strings "$SOCKET_LITERAL" crates/eggsec-gui/frontend/ 2>/dev/null; then + echo "FAIL: the GUI's webview assets still hold a copy of the default socket path." + rg -H -n --fixed-strings "$SOCKET_LITERAL" crates/eggsec-gui/frontend/ 2>/dev/null || true + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +# The shell scripts must hold no copy, so the build script cannot re-introduce +# one. +SCRIPT_HITS="$(rg -H -n --fixed-strings "$SOCKET_LITERAL" scripts/ 2>/dev/null | grep -v "^${GUARD_SELF}:" || true)" +if [[ -n "$SCRIPT_HITS" ]]; then + echo "FAIL: a shell script still holds a copy of the default socket path." + printf '%s\n' "$SCRIPT_HITS" + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +# The canonical crate must still state it. +if ! rg -q --fixed-strings "$SOCKET_LITERAL" "$CANONICAL_RS" 2>/dev/null; then + echo "FAIL: the canonical crate no longer states the default socket path." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the default socket path exists in exactly one place." +else + FAIL=$((FAIL + 1)) +fi + +# 178. The server refuses to bind over a live socket. +# Milestone 012 (ADR-0013). +# +# `run_server` used to unlink the socket path before it bound, so a second +# daemon displaced a live daemon's socket and its clients broke. The bind +# guard binds first, asks the shared liveness probe whether the occupant is +# live, and refuses without unlinking when it is. +# +# This guard pins the *shape*; the behaviour is pinned by the Rust tests, +# because a static check cannot observe a race. +echo "" +echo "--- Check 178: the server refuses to bind over a live socket ---" +SECTION_FAIL=0 +SERVER_RS="crates/eggsec-daemon/src/server.rs" + +# The hits in a file's PRODUCTION half. Comment lines, `pub use` re-exports +# and the test module are all skipped, so a doc comment that NAMES a call -- +# or a test that mentions one -- can neither satisfy nor break a check. +production_hits_fixed() { + local needle="$1" file="$2" limit + limit="$(rg -H -n --fixed-strings '#[cfg(test)]' "$file" 2>/dev/null | head -1 | cut -d: -f2 || true)" + [[ -z "$limit" ]] && limit=999999 + rg -H -n --fixed-strings "$needle" "$file" 2>/dev/null \ + | grep -v ':[[:space:]]*//' \ + | grep -v 'pub use' \ + | awk -F: -v limit="$limit" 'NF >= 2 && $2 + 0 < limit + 0' \ + || true +} + +# The first production line that mentions a needle. +first_production_line() { + production_hits_fixed "$1" "$2" | head -1 | cut -d: -f2 || true +} + +# The first removal of the socket path must come after the first bind. A +# removal before the bind is the defect: it destroys the evidence of whether +# the path held a live daemon. +FIRST_BIND="$(first_production_line 'UnixListener::bind' "$SERVER_RS")" +FIRST_REMOVE="$(first_production_line 'remove_file' "$SERVER_RS")" +if [[ -z "$FIRST_BIND" ]]; then + echo "FAIL: the server no longer binds a Unix listener." + SECTION_FAIL=$((SECTION_FAIL + 1)) +elif [[ -n "$FIRST_REMOVE" ]] && (( FIRST_REMOVE < FIRST_BIND )); then + echo "FAIL: the server removes the socket path (line $FIRST_REMOVE) before it binds it (line $FIRST_BIND)." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +# The refusal branch must exist. +if [[ -z "$(production_hits_fixed 'AddrInUse' "$SERVER_RS")" ]]; then + echo "FAIL: the server has no AddrInUse refusal branch." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +# The bind path must consult the shared probe, so that a second liveness +# notion cannot be introduced. +if [[ -z "$(production_hits_fixed 'probe_daemon_liveness' "$SERVER_RS")" ]]; then + echo "FAIL: the server's bind path does not consult the shared liveness probe." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +# The liveness notion stays singular: no lock file, no PID file, no lease. +for LOCK_LIKE in 'flock' 'lock_file' 'lockfile' 'pid_file' 'pidfile' '.lock'; do + if [[ -n "$(production_hits_fixed "$LOCK_LIKE" "$SERVER_RS")" ]]; then + echo "FAIL: the server's bind path references $LOCK_LIKE; the liveness notion must stay singular." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done + +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the server refuses to bind over a live socket." +else + FAIL=$((FAIL + 1)) +fi + +# 179. The environment override has one name and one resolver. +# Milestone 012 (ADR-0013). +# +# The environment variable's name and the precedence rule live in one crate. +# A second spelling of the name -- in the daemon, the engine, the GUI or the +# CLI -- is a transcription that can drift from the rule it names. +echo "" +echo "--- Check 179: the environment override has one name and one resolver ---" +SECTION_FAIL=0 + +# The name may be stated only in the canonical crate. +while IFS= read -r HIT; do + [[ -z "$HIT" ]] && continue + HIT_FILE="${HIT%%:*}" + if [[ "$HIT_FILE" != "$CANONICAL_CRATE"/* ]]; then + echo "FAIL: the socket environment variable's name is transcribed outside the canonical crate: $HIT" + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done < <(rg -H -n --fixed-strings 'EGGSEC_DAEMON_SOCKET' crates/ 2>/dev/null || true) + +# The canonical crate must own the four items the other surfaces name. +for ITEM in \ + 'pub const DAEMON_SOCKET_ENV_VAR' \ + 'pub const DEFAULT_DAEMON_SOCKET_PATH' \ + 'pub fn resolve_daemon_socket_path' \ + 'pub fn daemon_socket_path_from_env'; do + if ! rg -q --fixed-strings "$ITEM" "$CANONICAL_RS" 2>/dev/null; then + echo "FAIL: the canonical crate does not declare $ITEM." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done + +# The four surfaces must resolve through the canonical items rather than +# re-deriving the rule. A bare `pub use` re-export does not count, and +# neither does a mention in the test module: the surface must actually +# resolve a path through the canonical item. +for SURFACE in \ + "crates/eggsec-daemon/src/main.rs" \ + "crates/eggsec/src/cli/mod.rs" \ + "crates/eggsec-daemon/src/config.rs" \ + "crates/eggsec-gui/src/config.rs"; do + if [[ ! -f "$SURFACE" ]]; then + echo "FAIL: $SURFACE is missing; the surface cannot be checked." + SECTION_FAIL=$((SECTION_FAIL + 1)) + continue + fi + SURFACE_LIMIT="$(rg -H -n --fixed-strings '#[cfg(test)]' "$SURFACE" 2>/dev/null | head -1 | cut -d: -f2 || true)" + [[ -z "$SURFACE_LIMIT" ]] && SURFACE_LIMIT=999999 + SURFACE_HITS="$(rg -H -n 'daemon_socket_path_from_env|DEFAULT_DAEMON_SOCKET_PATH' "$SURFACE" 2>/dev/null \ + | grep -v ':[[:space:]]*//' \ + | grep -v 'pub use' \ + | awk -F: -v limit="$SURFACE_LIMIT" 'NF >= 2 && $2 + 0 < limit + 0' \ + || true)" + if [[ -z "$SURFACE_HITS" ]]; then + echo "FAIL: $SURFACE does not resolve the socket path through the canonical daemon endpoint." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done + +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the environment override has one name and one resolver." +else + FAIL=$((FAIL + 1)) +fi +# 180. The report bridge's coverage table and the bridge's arms agree. +# Milestone 013. +# +# The report bridge tells the operator which canonical operations produce a +# report document. That answer lives in exactly one place -- the coverage +# table in `crates/eggsec/src/runtime_bridge/report_coverage.rs` -- and the +# bridge consults it before it builds anything. +# +# Three facts must not rot: +# +# 1. The table must account for EVERY result variant the engine declares. +# A new `TaskResult` variant that no row names would silently fall +# through the bridge and produce no report, with nothing to show for it. +# 2. Every variant the table calls canonical must have a bridge arm, and +# every bridge arm must be a variant the table calls canonical. A +# disagreement between the two is the internal error the bridge logs at +# error level -- it must not be reachable from the source. +# 3. The table must live in ONE place. A second copy would be a second +# hand-maintained catalog: it would drift silently, and the drift would +# show up as a missing row rather than as a failure. +# +# The names are READ FROM THEIR OWNERS, not transcribed here: a guard that +# hardcoded the variant names would itself be the second source of truth this +# check exists to prevent. +# +# The extractions are MULTILINE-AWARE (`rg -U`, and an awk that accumulates +# across lines), because `rustfmt` breaks a long `variants:` array across +# several lines. A single-line extraction would read a reformatted table as a +# missing row, and the guard would fail on a tree that had not drifted. +echo "" +echo "--- Check 180: the report bridge's coverage table and its arms agree ---" +SECTION_FAIL=0 +COVERAGE_SOURCE="crates/eggsec/src/runtime_bridge/report_coverage.rs" +BRIDGE_SOURCE="crates/eggsec/src/runtime_bridge/report.rs" +TYPES_SOURCE="crates/eggsec/src/dispatch/types.rs" +EXECUTOR_SOURCE="crates/eggsec/src/runtime_bridge/executor.rs" + +# The variants the engine declares, read from the result type itself. +ENUM_VARIANTS="" +if [[ -f "$TYPES_SOURCE" ]]; then + ENUM_VARIANTS="$(sed -n '/^pub enum TaskResult {/,/^}/p' "$TYPES_SOURCE" \ + | sed -n 's/^ \([A-Z][A-Za-z0-9]*\)[ ({,].*$/\1/p' | sort -u)" +fi +if [[ -z "$ENUM_VARIANTS" ]]; then + echo "FAIL: could not read the result variants from $TYPES_SOURCE; the guard cannot run." + SECTION_FAIL=$((SECTION_FAIL + 1)) +else + # The variants the coverage table names: the rows' variant lists plus the + # terminal result shape, which no operation produces. + COVERAGE_VARIANTS="" + if [[ -f "$COVERAGE_SOURCE" ]]; then + COVERAGE_VARIANTS="$( + { + rg -U -o 'variants: &\[[^\]]*\]' "$COVERAGE_SOURCE" + rg -U -o 'TERMINAL_RESULT_VARIANTS:[^=]*= *&\[[^\]]*\]' "$COVERAGE_SOURCE" + } | rg -o '"[A-Za-z][A-Za-z0-9]*"' | tr -d '"' | sort -u + )" + fi + if [[ -z "$COVERAGE_VARIANTS" ]]; then + echo "FAIL: could not read the coverage table's variants from $COVERAGE_SOURCE; the guard cannot run." + SECTION_FAIL=$((SECTION_FAIL + 1)) + elif [[ "$ENUM_VARIANTS" == "$COVERAGE_VARIANTS" ]]; then + echo "PASS: the coverage table accounts for every result variant the engine declares." + else + echo "FAIL: the coverage table and the engine's result variants disagree." + echo " only in the result type:" + comm -23 <(printf '%s\n' "$ENUM_VARIANTS") <(printf '%s\n' "$COVERAGE_VARIANTS") | sed 's/^/ /' + echo " only in the coverage table:" + comm -13 <(printf '%s\n' "$ENUM_VARIANTS") <(printf '%s\n' "$COVERAGE_VARIANTS") | sed 's/^/ /' + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + # The table's rows, read as "verdict|variants". The awk accumulates across + # lines so a reformatted (multi-line) variants array reads as one row. + COVERAGE_ROWS="" + if [[ -f "$COVERAGE_SOURCE" ]]; then + COVERAGE_ROWS="$(awk ' + /variants: &\[/ { + line = $0 + sub(/^.*variants: &\[/, "", line) + if (line ~ /\]/) { + sub(/\].*$/, "", line) + names = line + collecting = 0 + } else { + names = line + collecting = 1 + } + next + } + collecting { + line = $0 + if (line ~ /\]/) { + sub(/\].*$/, "", line) + names = names " " line + collecting = 0 + } else { + names = names " " line + } + next + } + /form: ReportForm::/ { + verdict = $0 + sub(/^.*form: ReportForm::/, "", verdict) + sub(/,.*$/, "", verdict) + print verdict "|" names + names = "" + next + } + ' "$COVERAGE_SOURCE")" + fi + if [[ -z "$COVERAGE_ROWS" ]]; then + echo "FAIL: could not read the coverage rows from $COVERAGE_SOURCE; the guard cannot run." + SECTION_FAIL=$((SECTION_FAIL + 1)) + else + CANONICAL_VARIANTS="$(printf '%s\n' "$COVERAGE_ROWS" \ + | rg '^Canonical\|' | cut -d'|' -f2 | rg -o '"[A-Za-z][A-Za-z0-9]*"' | tr -d '"' | sort -u)" + EXCLUDED_VARIANTS="$(printf '%s\n' "$COVERAGE_ROWS" \ + | rg '^NoCleanMapping\|' | cut -d'|' -f2 | rg -o '"[A-Za-z][A-Za-z0-9]*"' | tr -d '"' | sort -u)" + + # The bridge's arms: the PRODUCTION half only. A test may name a variant + # as a fixture, but only a real arm counts here. + BRIDGE_PRODUCTION="" + BRIDGE_ARMS="" + if [[ -f "$BRIDGE_SOURCE" ]]; then + BRIDGE_PRODUCTION="$(sed '/#\[cfg(test)\]/,$d' "$BRIDGE_SOURCE")" + BRIDGE_ARMS="$(printf '%s' "$BRIDGE_PRODUCTION" | rg -o 'TaskResult::[A-Za-z][A-Za-z0-9]*' \ + | sed 's/TaskResult:://' | sort -u)" + fi + if [[ -z "$BRIDGE_ARMS" ]]; then + echo "FAIL: could not read the bridge's arms from $BRIDGE_SOURCE; the guard cannot run." + SECTION_FAIL=$((SECTION_FAIL + 1)) + else + for variant in $CANONICAL_VARIANTS; do + if ! printf '%s' "$BRIDGE_PRODUCTION" | rg -q "TaskResult::${variant}\b"; then + echo "FAIL: the coverage table calls '$variant' canonical, but the bridge has no TaskResult::$variant arm." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + done + for arm in $BRIDGE_ARMS; do + if ! printf '%s\n' "$CANONICAL_VARIANTS" | rg -qx "$arm"; then + echo "FAIL: the bridge has a TaskResult::$arm arm, but the coverage table does not call it canonical." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + done + for variant in $EXCLUDED_VARIANTS; do + if printf '%s' "$BRIDGE_PRODUCTION" | rg -q "TaskResult::${variant}\b"; then + echo "FAIL: the bridge has a TaskResult::$variant arm, but the coverage table excludes that variant." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + done + fi + fi + + # The table lives in exactly one place. + COVERAGE_TABLE_FILES="$(rg -l 'pub const REPORT_COVERAGE' crates/ --glob '*.rs' 2>/dev/null | sort | tr '\n' ' ')" + COVERAGE_TABLE_FILES="${COVERAGE_TABLE_FILES% }" + if [[ "$COVERAGE_TABLE_FILES" != "$COVERAGE_SOURCE" ]]; then + echo "FAIL: the report coverage table must live in exactly one place; found: ${COVERAGE_TABLE_FILES:-none}" + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + # The engine publishes its own table; it does not restate it. + if [[ -f "$EXECUTOR_SOURCE" ]]; then + if ! rg -q 'REPORT_COVERAGE' "$EXECUTOR_SOURCE"; then + echo "FAIL: the engine's executor does not publish the coverage table; the daemon would have no coverage to republish." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + fi +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the report bridge's coverage table and its arms agree." +else + FAIL=$((FAIL + 1)) +fi +# 181. The export procedure is written. +# Milestone 014. +# +# The export step is the step whose procedure was missing: a matrix column +# with no procedure is a column nobody can run, and a procedure that still +# says "not yet defined" is worse than no procedure, because it reads like +# one. +echo "" +echo "--- Check 181: the export procedure is written ---" +SECTION_FAIL=0 +BUILD_DOC="docs/GUI_BUILD.md" +EXPORT_SECTION="$(sed -n '/^### 5\.7 Step 7 — Export/,/^### 5\.8 /p' "$BUILD_DOC")" +if [[ -z "$EXPORT_SECTION" ]]; then + echo "FAIL: $BUILD_DOC has no §5.7 export step." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if printf '%s' "$EXPORT_SECTION" | rg -q 'Not yet defined'; then + echo "FAIL: $BUILD_DOC §5.7 still says 'Not yet defined'." + printf '%s' "$EXPORT_SECTION" | rg -n 'Not yet defined' || true + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +for ROW in 'Action' 'Pass criterion' 'Evidence artefact'; do + if ! printf '%s' "$EXPORT_SECTION" | rg -q "\| \*\*$ROW\*\* \| .+ \|"; then + echo "FAIL: $BUILD_DOC §5.7 has no non-empty $ROW row." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done +if ! printf '%s' "$EXPORT_SECTION" | rg -q 'export_report'; then + echo "FAIL: $BUILD_DOC §5.7 does not name the export_report command." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +for FORMAT in json csv html md sarif xml; do + if ! printf '%s' "$EXPORT_SECTION" | rg -q "\`$FORMAT\`"; then + echo "FAIL: $BUILD_DOC §5.7 does not name the $FORMAT format." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +done +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the export procedure names its action, its criterion, its artefact, and its six formats." +else + FAIL=$((FAIL + 1)) +fi + +# 182. The retired milestone token stays retired. +# Milestone 014. +# +# The matrix once claimed the GUI had no export affordance and blocked its +# export column on a milestone. The affordance exists, so the token that +# described the block is a token that lies. It expires with the affordance, +# not with a date. +echo "" +echo "--- Check 182: the retired milestone token stays retired ---" +SECTION_FAIL=0 +MATRIX="docs/GUI_PLATFORM_QUALIFICATION.md" +APP_JS="crates/eggsec-gui/frontend/app.js" +if rg -q 'export_report' "$APP_JS" 2>/dev/null; then + if rg -q 'pending M6' "$MATRIX" 2>/dev/null; then + echo "FAIL: $MATRIX still carries the retired 'pending M6' token, but the export affordance exists." + rg -n 'pending M6' "$MATRIX" || true + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi +else + echo "FAIL: the export affordance is gone from $APP_JS; guard 182's premise no longer holds." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the matrix carries no retired blocking token." +else + FAIL=$((FAIL + 1)) +fi + +# 183. `qualified` means resolvable evidence. +# Milestone 014. +# +# A cell that claims `qualified` is a claim about a run that happened. If the +# run record cannot be found, the claim is not a claim about anything, and the +# matrix stops being a statement of fact and becomes a statement of intent. +echo "" +echo "--- Check 183: a qualified cell names resolvable evidence ---" +SECTION_FAIL=0 +python3 - <<'PY' +import os +import re +import sys + +matrix_path = "docs/GUI_PLATFORM_QUALIFICATION.md" +evidence_dir = "docs/evidence/gui-qualification" +ci_runs_path = os.path.join(evidence_dir, "CI-RUNS.md") + +with open(matrix_path, encoding="utf-8") as handle: + lines = handle.read().splitlines() + +ci_runs = "" +if os.path.isfile(ci_runs_path): + with open(ci_runs_path, encoding="utf-8") as handle: + ci_runs = handle.read() + +failures = 0 +for number, line in enumerate(lines, start=1): + if not line.startswith("| `"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + if len(cells) < 2: + continue + platform = cells[0].strip("`") + for index, cell in enumerate(cells[1:], start=1): + match = re.match(r"^\*\*([^*]+)\*\*", cell) + if match is None or match.group(1).strip() != "qualified": + continue + references = re.findall(r"docs/evidence/gui-qualification/([A-Za-z0-9._-]+\.md)", cell) + urls = re.findall(r"https://github\.com/\S+/actions/runs/\d+", cell) + if not references and not urls: + print(f"FAIL: {matrix_path}:{number} the {platform} cell names no evidence reference.") + failures += 1 + continue + for name in references: + if not os.path.isfile(os.path.join(evidence_dir, name)): + print(f"FAIL: {matrix_path}:{number} cites `{name}`, which does not exist.") + failures += 1 + for url in urls: + if url not in ci_runs: + print(f"FAIL: {matrix_path}:{number} cites {url}, which is not in {ci_runs_path}.") + failures += 1 + +sys.exit(1 if failures else 0) +PY +if [[ $? -ne 0 ]]; then + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: every qualified cell names evidence that resolves." +else + FAIL=$((FAIL + 1)) +fi + +# 184. The matrix shape is exact. +# Milestone 014. +# +# The matrix is read by a validator, a guard, and a runbook, and all three +# read it by position. A column added in the middle, a row dropped, or a cell +# removed silently changes what every one of those readers believes. +echo "" +echo "--- Check 184: the matrix shape is exact ---" +SECTION_FAIL=0 +python3 - <<'PY' +import re +import sys + +matrix_path = "docs/GUI_PLATFORM_QUALIFICATION.md" +header = "| Platform | Build | Launch | Connect | Submit | Cancel | Render | Export |" + +with open(matrix_path, encoding="utf-8") as handle: + lines = handle.read().splitlines() + +failures = 0 +if not any(line.strip() == header for line in lines): + print(f"FAIL: {matrix_path} has no header row exactly `{header}`.") + failures += 1 + +rows = [] +for line in lines: + if not line.startswith("| `"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + platform = cells[0].strip("`") + if platform in ("linux", "macos", "windows"): + rows.append((platform, len(cells) - 1)) + +if sorted(platform for platform, _ in rows) != ["linux", "macos", "windows"]: + print(f"FAIL: {matrix_path} must have exactly one row per platform (linux, macos, windows); found {sorted(platform for platform, _ in rows)}.") + failures += 1 + +for platform, cells in rows: + if cells != 7: + print(f"FAIL: {matrix_path} the `{platform}` row has {cells} cells; it must have 7.") + failures += 1 + +if failures == 0 and sum(cells for _, cells in rows) != 21: + print(f"FAIL: {matrix_path} has {sum(cells for _, cells in rows)} cells; it must have 21.") + failures += 1 + +sys.exit(1 if failures else 0) +PY +if [[ $? -ne 0 ]]; then + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the matrix has the exact header, three rows, and twenty-one cells." +else + FAIL=$((FAIL + 1)) +fi + +# 185. The runbook derives its steps from the matrix. +# Milestone 014. +# +# The runbook is the procedure for the matrix's columns. If the two lists +# drift, an operator follows a procedure for a column the matrix does not +# have, and a cell the matrix does have has no procedure. +echo "" +echo "--- Check 185: the runbook's steps are the matrix's columns ---" +SECTION_FAIL=0 +python3 - <<'PY' +import re +import sys + +matrix_path = "docs/GUI_PLATFORM_QUALIFICATION.md" +build_path = "docs/GUI_BUILD.md" + +with open(matrix_path, encoding="utf-8") as handle: + matrix_lines = handle.read().splitlines() + +header = None +for line in matrix_lines: + if line.strip() == "| Platform | Build | Launch | Connect | Submit | Cancel | Render | Export |": + header = [cell.strip() for cell in line.strip().strip("|").split("|")] + break + +if header is None: + print("FAIL: the matrix has no header row.") + sys.exit(1) + +columns = [column.lower() for column in header[1:]] + +with open(build_path, encoding="utf-8") as handle: + build_lines = handle.read().splitlines() + +steps = [] +for line in build_lines: + match = re.match(r"^### 5\.\d+ Step (\d+) — (.+)$", line.strip()) + if match: + steps.append((int(match.group(1)), match.group(2).strip().lower())) + +failures = 0 +if [name for _, name in steps] != columns: + print(f"FAIL: {build_path} §5's steps are {[name for _, name in steps]}; the matrix's columns are {columns}.") + failures += 1 +for number, name in steps: + if number != steps.index((number, name)) + 1: + print(f"FAIL: {build_path} §5's step numbers are not 1..7 in order.") + failures += 1 + break + +sys.exit(1 if failures else 0) +PY +if [[ $? -ne 0 ]]; then + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the runbook's seven steps are the matrix's seven columns, in order." +else + FAIL=$((FAIL + 1)) +fi + +# 186. The harness's identifiers are the matrix's columns. +# Milestone 014. +# +# The harness reports on the matrix's columns. An identifier it invents, or a +# column it forgets, is a column the matrix can never promote — and the run +# record's schema is the contract every writer and every reader shares. +echo "" +echo "--- Check 186: the harness's identifiers and record schema are pinned ---" +SECTION_FAIL=0 +python3 - <<'PY' +import re +import sys + +matrix_path = "docs/GUI_PLATFORM_QUALIFICATION.md" +harness_path = "crates/eggsec-gui/tests/qualification.rs" +schema = "eggsec-gui-qualification-record/v1" +schema_files = [ + harness_path, + "scripts/gui_qualification.sh", + "scripts/check_gui_qualification.py", + "docs/evidence/gui-qualification/TEMPLATE.md", +] + +with open(matrix_path, encoding="utf-8") as handle: + matrix_lines = handle.read().splitlines() + +columns = [] +for line in matrix_lines: + if line.strip() == "| Platform | Build | Launch | Connect | Submit | Cancel | Render | Export |": + columns = [ + cell.strip().lower() + for cell in line.strip().strip("|").split("|")[1:] + ] + break + +if not columns: + print("FAIL: the matrix has no header row.") + sys.exit(1) + +with open(harness_path, encoding="utf-8") as handle: + harness = handle.read() + +match = re.search( + r"COLUMN_IDENTIFIERS[^=]*=\s*&?\[(.*?)\]", harness, re.DOTALL +) +if match is None: + print(f"FAIL: {harness_path} declares no COLUMN_IDENTIFIERS.") + sys.exit(1) + +identifiers = re.findall(r'"([a-z]+)"', match.group(1)) +failures = 0 +if identifiers != columns: + print(f"FAIL: {harness_path}'s identifiers are {identifiers}; the matrix's columns are {columns}.") + failures += 1 + +for path in schema_files: + try: + with open(path, encoding="utf-8") as handle: + content = handle.read() + except OSError: + print(f"FAIL: {path} does not exist.") + failures += 1 + continue + if schema not in content: + print(f"FAIL: {path} does not carry the record schema `{schema}`.") + failures += 1 + +sys.exit(1 if failures else 0) +PY +if [[ $? -ne 0 ]]; then + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the harness's identifiers are the matrix's columns, and every writer and reader carries the same record schema." +else + FAIL=$((FAIL + 1)) +fi + +# 187. The procedure is hermetic. +# Milestone 014. +# +# The procedure runs on a developer's machine and on a CI runner. It writes +# artefacts, so it has to say where it writes them, and it must never need +# privileges the operator has to go and find. +echo "" +echo "--- Check 187: the qualification procedure is hermetic ---" +SECTION_FAIL=0 +PROCEDURE="scripts/gui_qualification.sh" +if rg -q '\bsudo\b' "$PROCEDURE" 2>/dev/null; then + echo "FAIL: $PROCEDURE elevates its privileges." + rg -n '\bsudo\b' "$PROCEDURE" || true + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if rg -q 'rm\s+-[a-z]*r' "$PROCEDURE" 2>/dev/null; then + echo "FAIL: $PROCEDURE removes things recursively." + rg -n 'rm\s+-[a-z]*r' "$PROCEDURE" || true + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +# Every absolute path LITERAL the procedure names must be inside the +# temporary root. A path built from a shell expansion ("$OUT_DIR/...") is not +# a literal: it is wherever the caller pointed it, and the caller chooses. +OFFENDING="$(python3 - "$PROCEDURE" <<'PYEOF' +import re +import sys + +with open(sys.argv[1], encoding="utf-8") as handle: + body = handle.read() + +literals = set(re.findall(r"[\"'](/[^\"'\$]*)", body)) +allowed = {"/dev/null"} +offending = sorted( + literal + for literal in literals + if literal not in allowed and not literal.startswith("/tmp/") + and literal != "/tmp" +) +for literal in offending: + print(literal) +PYEOF +)" +if [[ -n "$OFFENDING" ]]; then + echo "FAIL: $PROCEDURE names absolute path literals outside the temporary root." + printf '%s\n' "$OFFENDING" + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if ! rg -q 'TMPDIR' "$PROCEDURE" 2>/dev/null; then + echo "FAIL: $PROCEDURE does not confine its scratch writes to the temporary root." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the procedure needs no privileges and writes only under its output and the temporary root." +else + FAIL=$((FAIL + 1)) +fi + +# 188. The promotion validator is green. +# Milestone 014. +# +# The matrix's rules are enforced by a program, not by a reader's diligence. +# If the validator fails, the matrix's claims are not being checked, and every +# other check in this file is only a floor. +echo "" +echo "--- Check 188: the promotion validator passes ---" +SECTION_FAIL=0 +if ! python3 scripts/check_gui_qualification.py; then + echo "FAIL: scripts/check_gui_qualification.py rejects the matrix." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the promotion validator is green." +else + FAIL=$((FAIL + 1)) +fi + +# 189. The CI job publishes the qualification record. +# Milestone 014. +# +# A CI run that nobody can read is not evidence. The record has to leave the +# runner as an artefact, or the Linux row can never be promoted by CI at all. +echo "" +echo "--- Check 189: the CI job publishes the qualification record ---" +SECTION_FAIL=0 +WORKFLOW=".github/workflows/deep-checks.yml" +GUI_JOB="$(sed -n '/^ gui-platform:/,/^ [a-z-]*:$/p' "$WORKFLOW")" +if [[ -z "$GUI_JOB" ]]; then + echo "FAIL: $WORKFLOW has no gui-platform job." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if ! printf '%s' "$GUI_JOB" | rg -q 'scripts/gui_qualification\.sh'; then + echo "FAIL: the gui-platform job does not run the qualification procedure." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if ! printf '%s' "$GUI_JOB" | rg -q 'gui-qualification-\$\{\{ matrix\.os \}\}'; then + echo "FAIL: the gui-platform job does not publish a gui-qualification artefact." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if ! printf '%s' "$GUI_JOB" | rg -q 'upload-artifact'; then + echo "FAIL: the gui-platform job does not upload the run record as an artefact." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: the gui-platform job runs the procedure and publishes the run record." +else + FAIL=$((FAIL + 1)) +fi +# 190. Every dependency exception is owned and dated. +# Milestone 015. +# +# A dependency exception is a decision to ship a known-bad advisory. It is +# only a decision while somebody owns it and somebody has promised to look +# at it again. An ignore with no owner and no review-by date is a silent +# permanent waiver, and the 23-entry advisory set that milestone 015 closed +# was exactly a backlog of such waivers that nobody was tracking. +# +# `deny.toml` deliberately carries no owner field -- the house style puts the +# ownership data in the exception document -- so the check has to read both +# files. It must also fail closed: a parse that finds nothing is not +# evidence that there is nothing to find. A guard that silently passes is +# worse than none. +echo "" +echo "--- Check 190: every dependency exception is owned and dated ---" +SECTION_FAIL=0 +DENY_TOML="deny.toml" +EXCEPTIONS_DOC="docs/DEPENDENCY_EXCEPTIONS.md" + +if [[ ! -f "$DENY_TOML" ]]; then + echo "FAIL: $DENY_TOML is missing; the canonical dependency-policy source cannot be checked." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi +if [[ ! -f "$EXCEPTIONS_DOC" ]]; then + echo "FAIL: $EXCEPTIONS_DOC is missing; the exception record cannot be checked." + SECTION_FAIL=$((SECTION_FAIL + 1)) +fi + +if [[ $SECTION_FAIL -eq 0 ]]; then + # Slice the `[advisories]` ignore array out of the policy file. The array is + # the only place an advisory ID may be suppressed, so the parse is scoped to + # that section rather than to the whole file. + IGNORE_BLOCK=$(awk ' + /^\[advisories\]/ { in_adv = 1; next } + /^\[/ { in_adv = 0 } + in_adv && /^[[:space:]]*ignore[[:space:]]*=/ { in_ign = 1; next } + in_ign && /^[[:space:]]*\]/ { in_ign = 0; next } + in_ign { print } + ' "$DENY_TOML" 2>/dev/null || true) + + if [[ -z "$IGNORE_BLOCK" ]]; then + echo "FAIL: the [advisories] ignore array could not be parsed from $DENY_TOML." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + IGNORE_ENTRIES=$(rg -o '\{[^{}]*\}' <<< "$IGNORE_BLOCK" 2>/dev/null || true) + if [[ -z "$IGNORE_ENTRIES" ]]; then + echo "FAIL: no advisory ignore entries were parsed from $DENY_TOML." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + # Every `###` section of the exception document, reduced to the facts the + # guard needs: the advisory IDs it covers, its owner, and its review-by date. + # A section runs from its heading to the next `###` or `##` heading. + SECTION_FACTS=$(awk ' + function flush( ids, s, id, n, arr, i) { + if (title == "") return; + ids = ""; + s = title "\n" body; + while (match(s, /RUSTSEC-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/)) { + id = substr(s, RSTART, RLENGTH); + if (index(" " ids " ", " " id " ") == 0) ids = ids (ids == "" ? "" : " ") id; + s = substr(s, RSTART + RLENGTH); + } + n = split(ids, arr, " "); + for (i = 1; i <= n; i++) { + if (arr[i] == "") continue; + printf "%s\t%s\t%s\t%s\n", arr[i], owner, reviewby, title; + } + } + /^### / { + flush(); title = $0; owner = ""; reviewby = ""; body = ""; next; + } + /^## / { + flush(); title = ""; owner = ""; reviewby = ""; body = ""; next; + } + { + if (title == "") next; + body = body $0 "\n"; + if ($0 ~ /^\|[[:space:]]*Owner[[:space:]]*\|/) { + v = $0; sub(/^\|[[:space:]]*Owner[[:space:]]*\|/, "", v); + sub(/[[:space:]]*\|[[:space:]]*$/, "", v); + gsub(/^[[:space:]]+|[[:space:]]+$/, "", v); owner = v; + } + if ($0 ~ /^\|[[:space:]]*Review-by[[:space:]]*\|/) { + v = $0; sub(/^\|[[:space:]]*Review-by[[:space:]]*\|/, "", v); + sub(/[[:space:]]*\|[[:space:]]*$/, "", v); + gsub(/^[[:space:]]+|[[:space:]]+$/, "", v); reviewby = v; + } + } + END { flush() } + ' "$EXCEPTIONS_DOC" 2>/dev/null || true) + + if [[ -z "$SECTION_FACTS" ]]; then + echo "FAIL: no exception records could be parsed from $EXCEPTIONS_DOC." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + # Advisory IDs carried by a RESOLVED heading. Their ignores were removed + # when the dependency left the graph; a RESOLVED ID that is ignored again + # is a resurrected exception. + RESOLVED_IDS=$(awk ' + /^### / { + if (title == "") { title = $0; next } + if (title ~ /RESOLVED/) { + s = title; + while (match(s, /RUSTSEC-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/)) { + print substr(s, RSTART, RLENGTH); + s = substr(s, RSTART + RLENGTH); + } + } + title = $0; + next; + } + /^## / { title = ""; next } + ' "$EXCEPTIONS_DOC" 2>/dev/null || true) + + # (a) Every ignore entry has a non-empty reason. + # (b) Every reason references the exception document. + # (c) Every ignored ID has an owned and dated record. + IGNORED_IDS="" + while IFS= read -r ENTRY; do + if [[ -z "$ENTRY" ]]; then continue; fi + ENTRY_ID=$(printf '%s\n' "$ENTRY" | rg -o 'RUSTSEC-[0-9]{4}-[0-9]{4}' | head -1 || true) + if [[ -z "$ENTRY_ID" ]]; then + echo "FAIL: an ignore entry in $DENY_TOML carries no advisory ID: $ENTRY" + SECTION_FAIL=$((SECTION_FAIL + 1)) + continue + fi + IGNORED_IDS="$IGNORED_IDS $ENTRY_ID" + + ENTRY_REASON_RAW=$(printf '%s\n' "$ENTRY" | rg -o 'reason[[:space:]]*=[[:space:]]*"[^"]*"' || true) + if [[ -z "$ENTRY_REASON_RAW" ]]; then + echo "FAIL: $ENTRY_ID has no reason in $DENY_TOML." + SECTION_FAIL=$((SECTION_FAIL + 1)) + continue + fi + ENTRY_REASON="${ENTRY_REASON_RAW#*\"}" + ENTRY_REASON="${ENTRY_REASON%\"}" + if [[ -z "${ENTRY_REASON//[[:space:]]/}" ]]; then + echo "FAIL: $ENTRY_ID has an empty reason in $DENY_TOML." + SECTION_FAIL=$((SECTION_FAIL + 1)) + continue + fi + if [[ "$ENTRY_REASON" != *"docs/DEPENDENCY_EXCEPTIONS.md"* ]]; then + echo "FAIL: $ENTRY_ID's reason does not reference docs/DEPENDENCY_EXCEPTIONS.md." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + + # (c) The owner and the review-by date live in the exception document. + MATCHED=$(printf '%s\n' "$SECTION_FACTS" | rg "^${ENTRY_ID} " || true) + if [[ -z "$MATCHED" ]]; then + echo "FAIL: $ENTRY_ID is ignored in $DENY_TOML but has no record in $EXCEPTIONS_DOC." + SECTION_FAIL=$((SECTION_FAIL + 1)) + continue + fi + OWNED_AND_DATED=0 + while IFS=$'\t' read -r _SEC_ID _SEC_OWNER _SEC_REVIEW _SEC_TITLE; do + if [[ -z "${_SEC_OWNER//[[:space:]]/}" ]]; then continue; fi + if [[ "$_SEC_REVIEW" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || [[ "$_SEC_REVIEW" == "— (closed)" ]]; then + OWNED_AND_DATED=1 + fi + done <<< "$MATCHED" + if [[ $OWNED_AND_DATED -eq 0 ]]; then + echo "FAIL: $ENTRY_ID has no record with a non-empty '| Owner |' and a dated '| Review-by |' in $EXCEPTIONS_DOC." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + done <<< "$IGNORE_ENTRIES" + + # (d) No RESOLVED exception retains a live ignore. + while IFS= read -r RESOLVED_ID; do + if [[ -z "$RESOLVED_ID" ]]; then continue; fi + if [[ " $IGNORED_IDS " == *" $RESOLVED_ID "* ]]; then + echo "FAIL: $RESOLVED_ID is RESOLVED in $EXCEPTIONS_DOC but is still ignored in $DENY_TOML." + SECTION_FAIL=$((SECTION_FAIL + 1)) + fi + done <<< "$RESOLVED_IDS" +fi + +if [[ $SECTION_FAIL -eq 0 ]]; then + echo "PASS: every dependency exception is owned and dated." +else + FAIL=$((FAIL + 1)) +fi + echo "" echo "=== Summary ===" if [[ $FAIL -gt 0 ]]; then diff --git a/scripts/check_gui_qualification.py b/scripts/check_gui_qualification.py new file mode 100644 index 000000000..bbb0e7292 --- /dev/null +++ b/scripts/check_gui_qualification.py @@ -0,0 +1,1104 @@ +#!/usr/bin/env python3 +"""Check the desktop GUI's platform-qualification matrix against its evidence. + +WHAT THIS IS. `docs/GUI_PLATFORM_QUALIFICATION.md` states which platforms the +desktop GUI is qualified on. A matrix is only worth reading if a cell's status +can be checked against the artefact it claims, so this script is the check: it +reads the matrix, reads the promotion rules the matrix itself publishes, and +rejects any cell whose claim is not backed. + +THE PROMOTION RULE LIVES IN THE MATRIX. The rules table in +`docs/GUI_PLATFORM_QUALIFICATION.md` §6 is the single source of truth for which +columns exist, which status tokens are legal, and what each column needs before +it may be promoted. This script reads all three from there and implements the +*semantics*; it does not keep a second copy. A rule added to the matrix is +enforced here without a second edit, and a rule removed from the matrix stops +being enforced the moment the table stops naming it. + +THE RECORD SCHEMA LIVES HERE TOO. This script writes the run record as well as +reading it, because a record that is written under one shape and read under +another is a record nobody can trust. The producer +(`scripts/gui_qualification.sh`) hands this script the facts a run observed and +asks for the record back. + +EXIT STATUS. 0 when every cell is consistent with its evidence; 1 otherwise. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +MATRIX_PATH = os.path.join("docs", "GUI_PLATFORM_QUALIFICATION.md") +EVIDENCE_DIR = os.path.join("docs", "evidence", "gui-qualification") +CI_RUNS_PATH = os.path.join(EVIDENCE_DIR, "CI-RUNS.md") +TEMPLATE_PATH = os.path.join(EVIDENCE_DIR, "TEMPLATE.md") + +#: The schema string that versions the run-record format. A record that +#: declares another schema is rejected by name rather than half-read. +RECORD_SCHEMA = "eggsec-gui-qualification-record/v1" + +#: The matrix's header row, in order. The header is the canonical list of +#: behaviours; the harness's identifiers and the runbook's steps are the same +#: seven. +MATRIX_HEADER = [ + "Platform", + "Build", + "Launch", + "Connect", + "Submit", + "Cancel", + "Render", + "Export", +] + +#: The platforms the matrix has a row for. +MATRIX_PLATFORMS = ["linux", "macos", "windows"] + +#: The kind of a cell's status token: `**status** — explanation`. +CELL_PATTERN = re.compile(r"^\*\*(?P[^*]+)\*\*\s+—\s*(?P.*)$") + +#: A date, as an evidence reference must carry. +DATE_PATTERN = re.compile(r"\b\d{4}-\d{2}-\d{2}\b") + +#: A CI run URL. +CI_RUN_PATTERN = re.compile(r"https://github\.com/\S+/actions/runs/\d+") + +#: An ADR reference. +ADR_PATTERN = re.compile(r"ADR-\d+") + + +# ── Markdown helpers ──────────────────────────────────────────────────────── + + +def read_text(path: str) -> str: + """Read a file, returning an empty string when it is absent.""" + try: + with open(path, "r", encoding="utf-8", errors="replace") as handle: + return handle.read() + except OSError: + return "" + + +def split_row(line: str) -> Optional[List[str]]: + """Split a Markdown table row into its cells, or `None` if it is not one.""" + stripped = line.strip() + if not stripped.startswith("|"): + return None + body = stripped[1:] + if body.endswith("|"): + body = body[:-1] + return [cell.strip() for cell in body.split("|")] + + +def is_separator(cells: Sequence[str]) -> bool: + """Whether a row is a table's `---` separator row.""" + return bool(cells) and all(cell and set(cell) <= set("-: ") for cell in cells) + + +def tables(lines: Iterable[str]) -> List[List[List[str]]]: + """Every Markdown table in a document, as lists of rows.""" + found: List[List[List[str]]] = [] + current: List[List[str]] = [] + for line in lines: + cells = split_row(line) + if cells is None: + if current: + found.append(current) + current = [] + continue + if is_separator(cells): + continue + if current: + current.append(cells) + else: + current = [cells] + if current: + found.append(current) + return found + + +def find_table( + rows: Sequence[Sequence[str]], header: Sequence[str] +) -> Optional[List[List[str]]]: + """The table whose header row equals `header`.""" + for table in tables(rows): + if list(table[0]) == list(header): + return [list(row) for row in table[1:]] + return None + + +def strip_code(cell: str) -> str: + """A cell's text without its backticks.""" + return cell.strip().strip("`").strip() + + +# ── The matrix ────────────────────────────────────────────────────────────── + + +class Rule: + """One promotion rule, as the matrix's rules table states it.""" + + def __init__( + self, + identifier: str, + kind: str, + platforms: Sequence[str], + columns: Sequence[str], + requires: str, + outcome: str, + attestation: str, + artefact: str, + ) -> None: + self.identifier = identifier + self.kind = kind + self.platforms = [p.strip().strip("`").strip().lower() for p in platforms] + self.columns = [c.strip().strip("`").strip() for c in columns] + self.requires = requires + self.outcome = outcome + self.attestation = attestation + self.artefact = artefact + + def applies_to(self, platform: str, column: str) -> bool: + """Whether the rule governs this cell.""" + if platform.lower() not in self.platforms: + return False + return any(c.lower() == column.lower() for c in self.columns) + + def __repr__(self) -> str: # pragma: no cover - diagnostics only + return f"" + + +class Matrix: + """The qualification matrix, parsed.""" + + def __init__(self, text: str) -> None: + self.text = text + lines = text.splitlines() + self.vocabulary = self._parse_vocabulary(lines) + self.columns = self._parse_columns(lines) + self.rows = self._parse_rows(lines) + self.rules = self._parse_rules(lines) + self.commit = self._parse_commit(lines) + + @staticmethod + def _parse_vocabulary(lines: Sequence[str]) -> List[str]: + table = find_table(lines, ["Status", "Meaning"]) + if table is None: + return [] + return [strip_code(row[0]) for row in table if row] + + @staticmethod + def _parse_columns(lines: Sequence[str]) -> List[str]: + table = find_table(lines, MATRIX_HEADER) + if table is None: + return [] + return [column.lower() for column in MATRIX_HEADER[1:]] + + @staticmethod + def _parse_rows(lines: Sequence[str]) -> Dict[str, Dict[str, str]]: + table = find_table(lines, MATRIX_HEADER) + if table is None: + return {} + rows: Dict[str, Dict[str, str]] = {} + for row in table: + if len(row) != len(MATRIX_HEADER): + continue + platform = strip_code(row[0]).lower() + cells = { + MATRIX_HEADER[index].lower(): row[index] + for index in range(1, len(MATRIX_HEADER)) + } + rows[platform] = cells + return rows + + @staticmethod + def _parse_rules(lines: Sequence[str]) -> List[Rule]: + header = [ + "Rule", + "Kind", + "Platforms", + "Columns", + "Requires", + "Required outcome", + "Required attestation", + "Artefact", + ] + table = find_table(lines, header) + if table is None: + return [] + rules: List[Rule] = [] + for row in table: + if len(row) != len(header): + continue + rules.append( + Rule( + identifier=strip_code(row[0]), + kind=strip_code(row[1]), + platforms=[ + strip_code(part) for part in strip_code(row[2]).split(",") + ], + columns=[strip_code(part) for part in strip_code(row[3]).split(",")], + requires=row[4], + outcome=strip_code(row[5]), + attestation=strip_code(row[6]), + artefact=strip_code(row[7]), + ) + ) + return rules + + @staticmethod + def _parse_commit(lines: Sequence[str]) -> str: + """The commit the matrix was regenerated at.""" + for line in lines: + match = re.search(r"\*\*Last regenerated:\*\*.*?`([0-9a-f]{7,40})`", line) + if match: + return match.group(1) + for line in lines: + match = re.search(r"`([0-9a-f]{40})`", line) + if match: + return match.group(1) + return "" + + +# ── The record ────────────────────────────────────────────────────────────── + + +def parse_record(text: str) -> Tuple[Optional[Dict[str, Any]], List[str]]: + """The run record embedded in an evidence file. + + Returns the record and the problems found while reading it. An evidence + file that carries no record block is **not** malformed: it is a file from + before the record format existed, and it is simply not sufficient to + promote a cell. + """ + problems: List[str] = [] + blocks = re.findall(r"```json\s*\n(.*?)```", text, re.DOTALL) + for block in blocks: + try: + candidate = json.loads(block) + except json.JSONDecodeError as error: + problems.append(f"the embedded json block does not parse: {error}") + continue + if not isinstance(candidate, dict): + continue + if candidate.get("schema") != RECORD_SCHEMA: + problems.append( + f"the embedded record declares the schema " + f"`{candidate.get('schema')}`, but only `{RECORD_SCHEMA}` is accepted" + ) + continue + return candidate, problems + return None, problems + + +def file_digest(path: str) -> Optional[str]: + """The SHA-256 of a file, or `None` when it cannot be read.""" + try: + with open(path, "rb") as handle: + return hashlib.sha256(handle.read()).hexdigest() + except OSError: + return None + + +def is_ancestor(older: str, newer: str) -> Optional[bool]: + """Whether `older` is an ancestor of `newer`, or `None` when unknown.""" + if not older or not newer: + return None + try: + completed = subprocess.run( + ["git", "merge-base", "--is-ancestor", older, newer], + cwd=REPO_ROOT, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + return completed.returncode == 0 + + +# ── The checks ────────────────────────────────────────────────────────────── + + +class Checker: + """The matrix's cells, checked against the evidence.""" + + def __init__(self, matrix: Matrix, evidence_dir: str) -> None: + self.matrix = matrix + self.evidence_dir = evidence_dir + self.problems: List[str] = [] + self.ci_runs = read_text(os.path.join(evidence_dir, "CI-RUNS.md")) + + def fail(self, message: str) -> None: + self.problems.append(message) + + def check_shape(self) -> None: + """The matrix's shape is exact: seven columns and three platforms.""" + if not self.matrix.columns: + self.fail( + "the matrix has no header row " + f"`| {' | '.join(MATRIX_HEADER)} |`" + ) + return + if self.matrix.columns != [c.lower() for c in MATRIX_HEADER[1:]]: + self.fail( + "the matrix's header row must be exactly " + f"`| {' | '.join(MATRIX_HEADER)} |`, found " + f"`{' | '.join(self.matrix.columns)}`" + ) + for platform in MATRIX_PLATFORMS: + if platform not in self.matrix.rows: + self.fail(f"the matrix has no `{platform}` row") + for platform in self.matrix.rows: + if platform not in MATRIX_PLATFORMS: + self.fail( + f"the matrix has a `{platform}` row, which is not one of " + f"{', '.join(MATRIX_PLATFORMS)}" + ) + for platform, cells in self.matrix.rows.items(): + for column in MATRIX_HEADER[1:]: + if column.lower() not in cells: + self.fail(f"the `{platform}` row has no `{column}` cell") + + def check_vocabulary(self) -> None: + """The status vocabulary is the matrix's own, and no other.""" + if not self.matrix.vocabulary: + self.fail("the matrix publishes no status vocabulary") + return + if "pending M6" in self.matrix.vocabulary: + self.fail( + "the matrix's vocabulary still carries the `pending M6` token; " + "the export affordance exists, so the token is illegal" + ) + + def check_rules(self) -> None: + """The matrix publishes the rules the validator enforces.""" + identifiers = [rule.identifier for rule in self.matrix.rules] + for expected in ["P1", "P2", "P3", "P4", "P5", "P6"]: + if expected not in identifiers: + self.fail(f"the matrix's rules table has no `{expected}` rule") + + def check_cells(self) -> None: + """Every cell follows the grammar and its rule.""" + for platform in MATRIX_PLATFORMS: + cells = self.matrix.rows.get(platform) + if cells is None: + continue + for column in MATRIX_HEADER[1:]: + cell = cells.get(column.lower()) + if cell is None: + continue + self.check_cell(platform, column, cell) + + def check_cell(self, platform: str, column: str, cell: str) -> None: + """One cell, checked.""" + where = f"the `{platform}` row's `{column}` cell" + match = CELL_PATTERN.match(cell.strip()) + if match is None: + self.fail( + f"{where} is not `**status** — explanation`: {cell.strip()[:120]!r}" + ) + return + status = strip_code(match.group("status")) + explanation = match.group("explanation").strip() + + if status not in self.matrix.vocabulary: + self.fail( + f"{where} carries the status `{status}`, which is not one of " + f"{', '.join(self.matrix.vocabulary)}" + ) + return + if not explanation.strip("—- "): + self.fail(f"{where} carries no explanation") + return + + for rule in self.matrix.rules: + if not rule.applies_to(platform, column): + continue + if rule.kind == "completeness": + continue + if rule.kind == "status": + if status != rule.outcome: + self.fail( + f"{where} carries the status `{status}`, but rule " + f"{rule.identifier} requires `{rule.outcome}`" + ) + if not ADR_PATTERN.search(explanation): + self.fail( + f"{where} does not cite the decision that excludes the " + f"platform, which rule {rule.identifier} requires" + ) + continue + if rule.kind == "evidence" and status == "qualified": + self.check_qualified(platform, column, explanation, rule) + + if status == "partially qualified": + if "qualified subset" not in explanation: + self.fail( + f"{where} is partially qualified but does not name the " + "qualified subset" + ) + if "missing part" not in explanation: + self.fail(f"{where} is partially qualified but does not name the missing part") + + def check_qualified( + self, platform: str, column: str, explanation: str, rule: Rule + ) -> None: + """A `qualified` cell: its evidence must resolve, and it must hold.""" + where = f"the `{platform}` row's `{column}` cell" + + references = re.findall( + r"docs/evidence/gui-qualification/([A-Za-z0-9._-]+\.md)", explanation + ) + urls = CI_RUN_PATTERN.findall(explanation) + + if not references and not urls: + self.fail(f"{where} says `qualified` but names no evidence reference") + return + if not DATE_PATTERN.search(explanation): + self.fail( + f"{where} says `qualified` but names no date for the run; an " + "evidence reference is a path, a command, and a date" + ) + return + + for name in references: + path = os.path.join(self.evidence_dir, name) + if not os.path.isfile(path): + self.fail(f"{where} cites `{name}`, which does not exist") + continue + self.check_record(platform, column, name, path, rule) + for url in urls: + if url not in self.ci_runs: + self.fail( + f"{where} cites the CI run {url}, which is not recorded in " + f"{CI_RUNS_PATH}" + ) + + def check_record( + self, platform: str, column: str, name: str, path: str, rule: Rule + ) -> None: + """The record an evidence file carries, checked against the rule.""" + where = f"the `{platform}` row's `{column}` cell" + record, problems = parse_record(read_text(path)) + for problem in problems: + self.fail(f"{where} cites `{name}`, whose record is rejected: {problem}") + if record is None: + # A file from before the record format existed is not malformed. + # It is simply not sufficient to promote a cell, so the cell + # cannot be `qualified` on its strength alone. + self.fail( + f"{where} says `qualified` on the strength of `{name}`, which " + f"carries no `{RECORD_SCHEMA}` record block; an evidence file " + "without a record cannot promote a cell" + ) + return + + if record.get("platform") != platform: + self.fail( + f"{where} cites `{name}`, whose record qualifies " + f"`{record.get('platform')}`, not `{platform}`" + ) + return + + columns = record.get("columns") + if not isinstance(columns, list): + self.fail(f"{where} cites `{name}`, whose record carries no columns") + return + matches = [ + entry + for entry in columns + if isinstance(entry, dict) and entry.get("column") == column.lower() + ] + if len(matches) == 0: + self.fail( + f"{where} cites `{name}`, whose record has no `{column}` column" + ) + return + if len(matches) > 1: + self.fail( + f"{where} cites `{name}`, whose record has {len(matches)} " + f"`{column}` columns; it must have exactly one" + ) + return + + entry = matches[0] + if entry.get("scripted") != rule.outcome: + self.fail( + f"{where} says `qualified`, but `{name}` records the `{column}` " + f"column's scripted outcome as `{entry.get('scripted')}`, and " + f"rule {rule.identifier} requires `{rule.outcome}`" + ) + attestation = entry.get("operator") + if rule.attestation == "not-applicable": + if attestation not in ("not-applicable", "pass"): + self.fail( + f"{where} says `qualified`, but `{name}` records the " + f"`{column}` column's operator outcome as `{attestation}`, " + f"and rule {rule.identifier} requires `not-applicable`" + ) + elif attestation != rule.attestation: + self.fail( + f"{where} says `qualified`, but `{name}` records the `{column}` " + f"column's operator outcome as `{attestation}`, and rule " + f"{rule.identifier} requires `{rule.attestation}`" + ) + + artefact = entry.get("artifact") or "" + if rule.artefact == "required" and not artefact: + self.fail( + f"{where} says `qualified`, but `{name}` names no artefact for " + f"the `{column}` column, and rule {rule.identifier} requires one" + ) + if artefact: + artefact_path = os.path.join(self.evidence_dir, artefact) + if not os.path.isfile(artefact_path): + self.fail( + f"{where} says `qualified`, but the artefact `{artefact}` " + f"that `{name}` names does not exist under " + f"{self.evidence_dir}" + ) + return + observed = file_digest(artefact_path) + if observed != entry.get("sha256"): + self.fail( + f"{where} says `qualified`, but the artefact `{artefact}` " + f"digests to `{observed}`, not to the " + f"`{entry.get('sha256')}` that `{name}` records" + ) + + self.check_commit(where, name, record) + + def check_commit(self, where: str, name: str, record: Dict[str, Any]) -> None: + """A record's commit is the matrix's commit or a descendant of it.""" + matrix_commit = self.matrix.commit + record_commit = record.get("commit") or "" + if not matrix_commit or not record_commit: + return + if matrix_commit == record_commit: + return + ancestor = is_ancestor(matrix_commit, record_commit) + if ancestor is None: + self.fail( + f"{where} cites `{name}`, whose record was made at " + f"`{record_commit}`, but the matrix was regenerated at " + f"`{matrix_commit}` and the relationship cannot be checked" + ) + elif not ancestor: + self.fail( + f"{where} cites `{name}`, whose record was made at " + f"`{record_commit}`, which is not a descendant of the " + f"matrix's regenerated-at commit `{matrix_commit}`" + ) + + def run(self) -> List[str]: + """Every check, and the problems found.""" + self.check_shape() + self.check_vocabulary() + self.check_rules() + self.check_cells() + return self.problems + + +def validate(matrix_path: str, evidence_dir: str) -> List[str]: + """Validate a matrix against its evidence directory.""" + matrix = Matrix(read_text(matrix_path)) + return Checker(matrix, evidence_dir).run() + + +# ── Writing a record ─────────────────────────────────────────────────────── + + +def build_record(facts: Dict[str, Any]) -> Dict[str, Any]: + """Assemble the run record from the facts a run observed.""" + columns: List[Dict[str, Any]] = [] + + build = facts.get("build", {}) + columns.append( + { + "column": "build", + "scripted": build.get("status", "skipped"), + "operator": "not-applicable", + "artifact": build.get("artifact", ""), + "sha256": build.get("sha256", ""), + "reason": build.get("reason", ""), + } + ) + + launch = facts.get("launch", {}) + columns.append( + { + "column": "launch", + "scripted": launch.get("status", "not-performed"), + "operator": "not-performed", + "artifact": launch.get("artifact", ""), + "sha256": launch.get("sha256", ""), + "reason": launch.get("reason", ""), + } + ) + + harness = facts.get("harness", {}) + outcome_path = harness.get("outcome") or "" + harness_columns: List[Dict[str, Any]] = [] + if outcome_path and os.path.isfile(outcome_path): + try: + with open(outcome_path, "r", encoding="utf-8") as handle: + harness_columns = json.load(handle).get("columns", []) + except (OSError, json.JSONDecodeError): + harness_columns = [] + by_column = {entry.get("column"): entry for entry in harness_columns} + + export = facts.get("export", {}) + for column in ["connect", "submit", "cancel", "render", "export"]: + entry = dict(by_column.get(column) or {}) + entry["column"] = column + entry.setdefault("scripted", "skipped") + entry.setdefault("operator", "not-performed") + entry.setdefault("artifact", "") + entry.setdefault("sha256", "") + entry.setdefault("reason", "the harness did not report this column") + if column == "export" and entry.get("artifact"): + # The artefact is copied into the evidence directory under a name + # that says what it is; the digest travels with it. + entry["artifact"] = export.get("artifact", "") + entry["sha256"] = export.get("sha256", "") + columns.append(entry) + + window = facts.get("window", {}) + probe = facts.get("prerequisite_probe", {}) + daemon = facts.get("daemon", {}) + host = facts.get("host", {}) + + return { + "schema": RECORD_SCHEMA, + "platform": facts.get("platform", ""), + "mode": facts.get("mode", ""), + "date": facts.get("date", ""), + "commit": facts.get("commit", ""), + "tree_state": facts.get("tree_state", ""), + "host": host, + "toolchain": facts.get("toolchain", {}), + "features": facts.get("features", {}), + "prerequisite_probe": { + "command": probe.get("command", ""), + "exit": probe.get("exit", 1), + "verdict": probe.get("verdict", "UNKNOWN"), + }, + "daemon": { + "socket": daemon.get("socket", ""), + "ready": daemon.get("ready", False), + "version": daemon.get("version", ""), + "features": daemon.get("features", ""), + "task_kinds": daemon.get("task_kinds", ""), + "scope": daemon.get( + "scope", {"surface": "DesktopGuiManual", "source": "gui-default"} + ), + }, + "window": { + "probe": window.get("probe", ""), + "windows": window.get("windows", ""), + "screenshot": window.get("screenshot", ""), + "reason": window.get("reason", ""), + }, + "columns": columns, + "deviations": [], + } + + +def trim_transcript(output: str) -> str: + """The harness's observations, without the build machinery's noise. + + A cargo transcript carries the compiler's and the test runner's progress + lines, and a path-like line in it (`Running tests/qualification.rs`) reads + to a documentation-reference checker as a file reference. The record wants + the observations: which test ran, what it said, and what the run concluded. + """ + kept = [] + for line in output.splitlines(): + stripped = line.strip() + if stripped.startswith(("running ", "test ", "SKIP:", "error", "warning:")): + kept.append(stripped) + if not kept: + return output.strip() + return "\n".join(kept) + + +def write_record_markdown(record: Dict[str, Any], facts: Dict[str, Any], path: str) -> None: + """Write the evidence file: the template's fields and the record block.""" + host = record.get("host", {}) + toolchain = record.get("toolchain", {}) + probe = record.get("prerequisite_probe", {}) + daemon = record.get("daemon", {}) + window = record.get("window", {}) + harness = facts.get("harness", {}) + + steps = {column.lower(): index + 1 for index, column in enumerate(MATRIX_HEADER[1:])} + + lines: List[str] = [] + lines.append(f"# GUI qualification evidence — {record['platform']} {record['date']}") + lines.append("") + lines.append( + "This file is the run record for one desktop-GUI qualification run. It " + "is produced by `scripts/gui_qualification.sh` and it is what the " + "matrix's cells cite." + ) + lines.append("") + lines.append("---") + lines.append("") + lines.append("## Identity") + lines.append("") + lines.append("| Field | Value |") + lines.append("|---|---|") + lines.append(f"| Platform | `{record['platform']}` |") + lines.append( + "| Qualification column(s) this run supports | " + + ", ".join( + f"`{column}`" + for column in MATRIX_HEADER[1:] + if any( + entry["column"] == column.lower() and entry["scripted"] == "pass" + for entry in record["columns"] + ) + ) + + " |" + ) + lines.append(f"| Date of the run (UTC) | {record['date']} |") + lines.append(f"| Operator or CI job | `{record.get('mode', 'operator')}` |") + lines.append(f"| Commit SHA (`git rev-parse HEAD`) | `{record['commit']}` |") + lines.append(f"| Tree state (`git status --porcelain` empty?) | `{record['tree_state']}` |") + lines.append(f"| Host OS version | {host.get('os', '')} {host.get('os_version', '')} |") + lines.append(f"| Architecture | {host.get('arch', '')} |") + if host.get("process_arch") and host.get("process_arch") != host.get("arch"): + lines.append( + f"| Process architecture | {host.get('process_arch')} " + "(the architecture of the running process, which differs from the " + "targeted one under Rosetta) |" + ) + lines.append(f"| Target triple | {host.get('target_triple', '')} |") + lines.append(f"| Toolchain | `{toolchain.get('rustc', '')}` |") + lines.append(f"| Cargo version | `{toolchain.get('cargo', '')}` |") + lines.append( + f"| Feature set | requested {record.get('features', {}).get('requested', [])}, " + f"resolved {record.get('features', {}).get('resolved', [])} |" + ) + lines.append("") + lines.append("## Environment") + lines.append("") + lines.append("| Field | Value |") + lines.append("|---|---|") + lines.append( + f"| Prerequisite probe result | `{probe.get('command', '')}` -> exit " + f"{probe.get('exit', '')} ({probe.get('verdict', '')}) |" + ) + lines.append("| Webview SDK version | see the prerequisite probe's output below |") + lines.append( + f"| Daemon version and build features | {daemon.get('version', '')} " + f"(features: {daemon.get('features', '')}) |" + ) + lines.append(f"| Daemon socket path used | `{daemon.get('socket', '')}` |") + scope = daemon.get("scope", {}) + lines.append( + f"| Scope in force | surface `{scope.get('surface', '')}`, source " + f"`{scope.get('source', '')}` |" + ) + lines.append(f"| Window probe | {window.get('reason', '')} |") + lines.append("") + lines.append("## Commands run") + lines.append("") + lines.append("```") + lines.append(f"# 1. {probe.get('command', '')}") + lines.append(f"{probe.get('exit', '')}") + lines.append("") + lines.append(f"# 2. {harness.get('command', '')}") + lines.append(f"{harness.get('exit', '')}") + lines.append("```") + lines.append("") + lines.append("## Observed output") + lines.append("") + lines.append("The harness's transcript:") + lines.append("") + lines.append("```") + lines.append(trim_transcript(harness.get("output", "") or "")) + lines.append("```") + lines.append("") + lines.append("## Pass criterion and outcome") + lines.append("") + lines.append("| Column | Pass criterion | Outcome | Met? |") + lines.append("|---|---|---|---|") + for entry in record["columns"]: + column = entry["column"] + step = steps.get(column.lower(), 0) + outcome = f"scripted `{entry['scripted']}`, operator `{entry['operator']}`" + met = "yes" if entry["scripted"] == "pass" else "partial" + lines.append( + f"| `{column}` | the runbook's Step {step} (`docs/GUI_BUILD.md` §5) | " + f"{outcome} | {met} |" + ) + lines.append("") + lines.append("Each column's reason:") + lines.append("") + for entry in record["columns"]: + lines.append(f"- `{entry['column']}` — {entry['reason']}") + lines.append("") + lines.append("## Deviations and notes") + lines.append("") + deviations = record.get("deviations") or [] + if deviations: + for deviation in deviations: + lines.append(f"- {deviation}") + else: + lines.append("- None. The run followed `docs/GUI_BUILD.md` §5 as written.") + lines.append("") + lines.append("## The run record") + lines.append("") + lines.append( + f"The block below is the `{RECORD_SCHEMA}` record. " + "`scripts/check_gui_qualification.py` reads it." + ) + lines.append("") + lines.append("```json") + lines.append(json.dumps(record, indent=2)) + lines.append("```") + lines.append("") + + with open(path, "w", encoding="utf-8") as handle: + handle.write("\n".join(lines)) + + +# ── The self-test ─────────────────────────────────────────────────────────── + + +def self_test(matrix_path: str, evidence_dir: str) -> int: + """Prove that the validator rejects what it is supposed to reject. + + Every case below is a deliberate corruption of a known-good input. The + validator must reject each one, and it must say which cell it rejected. + """ + original_matrix = read_text(matrix_path) + original_evidence = {} + if os.path.isdir(evidence_dir): + for name in os.listdir(evidence_dir): + path = os.path.join(evidence_dir, name) + if os.path.isfile(path): + with open(path, "rb") as handle: + original_evidence[name] = handle.read() + + failures: List[str] = [] + + def check_case(name: str, expectation: str, mutate) -> None: + import tempfile + + with tempfile.TemporaryDirectory() as workspace: + matrix_copy = os.path.join(workspace, "matrix.md") + evidence_copy = os.path.join(workspace, "evidence") + os.makedirs(evidence_copy) + with open(matrix_copy, "w", encoding="utf-8") as handle: + handle.write(original_matrix) + for filename, content in original_evidence.items(): + with open(os.path.join(evidence_copy, filename), "wb") as handle: + handle.write(content) + mutate(matrix_copy, evidence_copy) + problems = validate(matrix_copy, evidence_copy) + if not problems: + failures.append(f"{name}: the validator accepted it") + return + if expectation and expectation not in " ".join(problems): + failures.append( + f"{name}: the validator rejected it, but not with `{expectation}`: " + f"{problems[0]}" + ) + return + print(f"ok: {name} -> {problems[0]}") + + def rewrite_matrix(matrix_copy: str, old: str, new: str) -> None: + with open(matrix_copy, "r", encoding="utf-8") as handle: + text = handle.read() + if old not in text: + raise SystemExit(f"the self-test's mutation target is absent: {old[:60]!r}") + with open(matrix_copy, "w", encoding="utf-8") as handle: + handle.write(text.replace(old, new, 1)) + + def rewrite_records(evidence_copy: str, old: str, new: str) -> None: + """Rewrite a string inside a record's json block, and only there.""" + touched = False + for name in sorted(os.listdir(evidence_copy)): + if not name.endswith(".md"): + continue + path = os.path.join(evidence_copy, name) + with open(path, "r", encoding="utf-8") as handle: + text = handle.read() + blocks = list(re.finditer(r"```json\s*\n(.*?)```", text, re.DOTALL)) + if not blocks: + continue + block = blocks[0].group(1) + if old not in block: + continue + mutated = text[: blocks[0].start(1)] + block.replace(old, new, 1) + text[blocks[0].end(1) :] + with open(path, "w", encoding="utf-8") as handle: + handle.write(mutated) + touched = True + if not touched: + raise SystemExit(f"the self-test's record mutation target is absent: {old[:60]!r}") + + def replace_cell(matrix_copy: str, platform: str, index: int, content: str) -> None: + """Replace one cell of one matrix row, wholesale.""" + with open(matrix_copy, "r", encoding="utf-8") as handle: + lines = handle.read().splitlines() + for number, line in enumerate(lines): + if not line.startswith(f"| `{platform}` |"): + continue + cells = line.split("|") + # The first and last elements are the row's empty edges. + cells[index + 1] = content + lines[number] = "|".join(cells) + with open(matrix_copy, "w", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + return + raise SystemExit(f"the self-test's matrix row is absent: {platform}") + + def blank_a_cell(matrix_copy: str, _evidence_copy: str) -> None: + replace_cell(matrix_copy, "macos", 1, " **qualified** — ") + + def unknown_status(matrix_copy: str, _evidence_copy: str) -> None: + rewrite_matrix(matrix_copy, "**qualified** — evidence:", "**almost qualified** — evidence:") + + def pending_token(matrix_copy: str, _evidence_copy: str) -> None: + rewrite_matrix( + matrix_copy, + "| `out of scope` | The platform is excluded by a recorded decision.", + "| `pending M6` | The behaviour cannot exist yet.", + ) + + def windows_promoted(matrix_copy: str, _evidence_copy: str) -> None: + rewrite_matrix(matrix_copy, "**out of scope** — `ADR-0010`", "**qualified** — `ADR-0010`") + + def missing_artefact(matrix_copy: str, evidence_copy: str) -> None: + rewrite_records(evidence_copy, '"artifact": "macos-', '"artifact": "absent-macos-') + + def wrong_digest(matrix_copy: str, evidence_copy: str) -> None: + def mutate(path: str, text: str) -> str: + return re.sub(r'"sha256": "[0-9a-f]{64}"', '"sha256": "' + "0" * 64 + '"', text) + + for name in sorted(os.listdir(evidence_copy)): + if not name.endswith(".md"): + continue + path = os.path.join(evidence_copy, name) + with open(path, "r", encoding="utf-8") as handle: + text = handle.read() + if RECORD_SCHEMA not in text: + continue + with open(path, "w", encoding="utf-8") as handle: + handle.write(mutate(path, text)) + + def unknown_schema(matrix_copy: str, evidence_copy: str) -> None: + rewrite_records(evidence_copy, RECORD_SCHEMA, "eggsec-gui-qualification-record/v0") + + def missing_column(matrix_copy: str, evidence_copy: str) -> None: + rewrite_records( + evidence_copy, + '"column": "build",', + '"column": "build-renamed",', + ) + + def missing_evidence_file(matrix_copy: str, _evidence_copy: str) -> None: + rewrite_matrix( + matrix_copy, + "docs/evidence/gui-qualification/macos-2026-10-24.md", + "docs/evidence/gui-qualification/macos-9999-01-01.md", + ) + + check_case("a blank cell is rejected", "carries no explanation", blank_a_cell) + check_case("an unknown status token is rejected", "not one of", unknown_status) + check_case("the retired milestone token is rejected", "pending M6", pending_token) + check_case( + "a promoted Windows cell is rejected", "requires `out of scope`", windows_promoted + ) + check_case("a missing artefact is rejected", "does not exist", missing_artefact) + check_case("a wrong digest is rejected", "digests to", wrong_digest) + check_case("an unknown record schema is rejected", "schema", unknown_schema) + check_case("a record without the column is rejected", "column", missing_column) + check_case("a missing evidence file is rejected", "does not exist", missing_evidence_file) + + if failures: + for failure in failures: + print(f"FAIL: {failure}") + return 1 + print("ok: every deliberate corruption was rejected") + return 0 + + +# ── The entry point ───────────────────────────────────────────────────────── + + +def main(argv: Sequence[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--matrix", + default=os.path.join(REPO_ROOT, MATRIX_PATH), + help="the matrix to validate", + ) + parser.add_argument( + "--evidence-dir", + default=os.path.join(REPO_ROOT, EVIDENCE_DIR), + help="the directory the evidence files live in", + ) + parser.add_argument( + "--write-record", + metavar="PATH", + help="write the run record's json to this path and exit", + ) + parser.add_argument( + "--run-inputs", + metavar="PATH", + help="the facts a run observed, as json", + ) + parser.add_argument( + "--record-markdown", + metavar="PATH", + help="write the evidence file to this path", + ) + parser.add_argument( + "--self-test", + action="store_true", + help="prove that the validator rejects what it must reject", + ) + arguments = parser.parse_args(argv) + + if arguments.self_test: + return self_test(arguments.matrix, arguments.evidence_dir) + + if arguments.write_record: + if not arguments.run_inputs: + print("--write-record needs --run-inputs", file=sys.stderr) + return 2 + with open(arguments.run_inputs, "r", encoding="utf-8") as handle: + facts = json.load(handle) + record = build_record(facts) + with open(arguments.write_record, "w", encoding="utf-8") as handle: + json.dump(record, handle, indent=2) + handle.write("\n") + if arguments.record_markdown: + write_record_markdown(record, facts, arguments.record_markdown) + return 0 + + problems = validate(arguments.matrix, arguments.evidence_dir) + if problems: + for problem in problems: + print(f"FAIL: {problem}") + print(f"\n{len(problems)} problem(s) in {arguments.matrix}") + return 1 + print(f"ok: {arguments.matrix} is consistent with its evidence") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/gui_qualification.sh b/scripts/gui_qualification.sh new file mode 100644 index 000000000..67e3c2768 --- /dev/null +++ b/scripts/gui_qualification.sh @@ -0,0 +1,678 @@ +#!/usr/bin/env bash +# +# The desktop GUI's platform-qualification procedure. +# +# WHAT THIS IS. `docs/GUI_PLATFORM_QUALIFICATION.md` states which platforms the +# desktop GUI is qualified on. This script is the procedure that produces the +# evidence for those claims: it builds the shell, starts a daemon, runs the +# harness (`crates/eggsec-gui/tests/qualification.rs`), probes for the window, +# and writes a run record that the matrix's cells can cite. +# +# WHAT THIS IS NOT. It is not a window-automation driver. It does not click, +# type, or move a mouse, and it does not judge what a human saw: the window +# half of the qualification is an operator observation, recorded by hand in the +# run record. The script measures what a machine can measure and leaves the +# rest named. +# +# THE RULES. The promotion rules live in the matrix's own rules table +# (`docs/GUI_PLATFORM_QUALIFICATION.md` §6), and `scripts/check_gui_qualification.py` +# enforces them. This script does not carry a second copy of them; it only +# produces the record they read. +# +# HERMETICITY. This script writes only under `--out` and `${TMPDIR:-/tmp}`. It +# never elevates its privileges, never runs as root, and never removes anything +# outside those two roots. +# +# EXIT STATUS. 0 when every column's scripted outcome is `pass`, `skipped`, or +# `not-applicable`; 1 when a column's scripted outcome is `fail`, when the +# record could not be written, or when `--mode ci` could not run the harness +# at all. A skipped column is not a failed column: a named skip is an honest +# outcome, and the matrix's promotion rules refuse to promote a skipped cell. + +set -euo pipefail + +SCRIPT_NAME="$(basename "$0")" +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" + +# ── Defaults ──────────────────────────────────────────────────────────────── +PLATFORM="" +MODE="operator" +SOCKET="" +DAEMON_BIN="" +OUT_DIR="$REPO_ROOT/docs/evidence/gui-qualification" +RUN_DATE="" +SKIP_WINDOW=0 + +# The schema of the run record this procedure produces. The validator owns the +# record's shape and writes it; the procedure names the schema it expects and +# checks the record it got back against it. The harness, the validator, and the +# evidence template carry the same string, and the static guard (check 186) +# asserts that the four copies agree. +RECORD_SCHEMA="eggsec-gui-qualification-record/v1" + +# ── Output helpers ────────────────────────────────────────────────────────── +log() { printf '%s\n' "$*"; } +warn() { printf '%s\n' "$*" >&2; } +die() { + printf '%s: %s\n' "$SCRIPT_NAME" "$*" >&2 + exit 1 +} + +usage() { + cat <<'USAGE' +Usage: bash scripts/gui_qualification.sh [options] + + --platform The platform being qualified. Defaults to the host. + --mode `operator` attaches to a daemon the operator + started; `ci` starts its own daemon and fails when + it cannot. Defaults to `operator`. + --socket The daemon's Unix socket. + --daemon-bin The daemon binary to start when one is needed. + --out Where the record and the artefacts are written. + Defaults to `docs/evidence/gui-qualification`. + --date The record's date. Defaults to today (UTC). + --skip-window Do not attempt the window probe. + -h, --help This message. +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --platform) + PLATFORM="${2:-}" + shift 2 + ;; + --mode) + MODE="${2:-}" + shift 2 + ;; + --socket) + SOCKET="${2:-}" + shift 2 + ;; + --daemon-bin) + DAEMON_BIN="${2:-}" + shift 2 + ;; + --out) + OUT_DIR="${2:-}" + shift 2 + ;; + --date) + RUN_DATE="${2:-}" + shift 2 + ;; + --skip-window) + SKIP_WINDOW=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + die "unknown option \`$1\` (try --help)" + ;; + esac +done + +# ── The host ──────────────────────────────────────────────────────────────── +host_os() { + case "$(uname -s)" in + Linux) printf 'linux\n' ;; + Darwin) printf 'macos\n' ;; + *) printf 'unknown\n' ;; + esac +} + +HOST_OS="$(host_os)" +HOST_ARCH="$(uname -m)" +HOST_OS_VERSION="$(uname -r)" + +if [[ -z "$PLATFORM" ]]; then + PLATFORM="$HOST_OS" +fi +case "$PLATFORM" in + linux|macos) ;; + *) die "\`--platform\` must be \`linux\` or \`macos\`, not \`$PLATFORM\`" ;; +esac + +case "$MODE" in + operator|ci) ;; + *) die "\`--mode\` must be \`operator\` or \`ci\`, not \`$MODE\`" ;; +esac + +if [[ -z "$RUN_DATE" ]]; then + RUN_DATE="$(date -u +%Y-%m-%d)" +fi +if [[ ! "$RUN_DATE" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then + die "\`--date\` must be \`YYYY-MM-DD\`, not \`$RUN_DATE\`" +fi + +for tool in git python3; do + command -v "$tool" >/dev/null 2>&1 || die "\`$tool\` is required and was not found on PATH" +done + +mkdir -p "$OUT_DIR" +OUT_DIR="$(cd "$OUT_DIR" && pwd)" +WORK_DIR="${TMPDIR:-/tmp}/eggsec-gui-qualification-$$" +mkdir -p "$WORK_DIR" +RECORD_NAME="$PLATFORM-$RUN_DATE" +RECORD_PATH="$OUT_DIR/$RECORD_NAME.md" + +# The daemon this run started, if any. The cleanup trap stops it and removes +# its socket on every exit path, including SIGINT and SIGTERM. +DAEMON_PID="" +DAEMON_SOCKET="" +DAEMON_SHA="" +DAEMON_TASK_KINDS="" +OWNED_SOCKET="" + +cleanup() { + local status=$? + if [[ -n "$DAEMON_PID" ]] && kill -0 "$DAEMON_PID" 2>/dev/null; then + kill -TERM "$DAEMON_PID" 2>/dev/null || true + for _ in $(seq 1 20); do + kill -0 "$DAEMON_PID" 2>/dev/null || break + sleep 0.25 + done + if kill -0 "$DAEMON_PID" 2>/dev/null; then + kill -KILL "$DAEMON_PID" 2>/dev/null || true + fi + wait "$DAEMON_PID" 2>/dev/null || true + fi + if [[ -n "$OWNED_SOCKET" && -S "$OWNED_SOCKET" ]]; then + rm -f "$OWNED_SOCKET" + fi + exit "$status" +} +trap cleanup EXIT INT TERM + +# ── Identity ──────────────────────────────────────────────────────────────── +COMMIT="$(git rev-parse HEAD 2>/dev/null || printf 'unknown')" +if [[ -z "$(git status --porcelain 2>/dev/null)" ]]; then + TREE_STATE="clean" +else + TREE_STATE="dirty" +fi +RUSTC_VERSION="$(rustc -V 2>/dev/null || printf 'not installed')" +CARGO_VERSION="$(cargo -V 2>/dev/null || printf 'not installed')" +TARGET_TRIPLE="$(rustc -vV 2>/dev/null | sed -n 's/^host: //p' || printf 'unknown')" +# The architecture of record is the one the toolchain targeted. `uname -m` +# reports the architecture of the *process*, which on an arm64 host running +# under Rosetta is `x86_64`; the record keeps both so neither is ambiguous. +TARGET_ARCH="${TARGET_TRIPLE%%-*}" +if [[ -z "$TARGET_ARCH" || "$TARGET_ARCH" == "unknown" ]]; then + TARGET_ARCH="$HOST_ARCH" +fi + +# A run qualifies the platform it was made on. The observations a host can +# make are observations of that host, so a record that carried them under +# another platform's label would be a false statement about that platform. +HOST_MATCHES=1 +HOST_MISMATCH_REASON="" +if [[ "$PLATFORM" != "$HOST_OS" ]]; then + HOST_MATCHES=0 + HOST_MISMATCH_REASON="the host platform is \`$HOST_OS\`, not the platform being qualified (\`$PLATFORM\`); a $PLATFORM qualification needs a $PLATFORM host" +fi + +log "$SCRIPT_NAME: qualifying $PLATFORM on $HOST_OS ($HOST_ARCH), mode $MODE" + +# ── The prerequisite probe ────────────────────────────────────────────────── +PROBE_COMMAND="bash scripts/check_gui_prereqs.sh" +PROBE_LOG="$WORK_DIR/prereq-probe.log" +PROBE_EXIT=0 +if command -v bash >/dev/null 2>&1 && [[ -x scripts/check_gui_prereqs.sh ]]; then + set +e + bash scripts/check_gui_prereqs.sh >"$PROBE_LOG" 2>&1 + PROBE_EXIT=$? + set -e +else + printf 'the prerequisite probe is missing\n' >"$PROBE_LOG" + PROBE_EXIT=127 +fi +if [[ $PROBE_EXIT -eq 0 ]]; then + PROBE_VERDICT="BUILDABLE" +else + PROBE_VERDICT="NOT BUILDABLE" +fi +log "$SCRIPT_NAME: prerequisite probe -> $PROBE_VERDICT (exit $PROBE_EXIT)" + +# ── The build column ──────────────────────────────────────────────────────── +BUILD_DIR="$WORK_DIR/build" +BUILD_STATUS="skipped" +BUILD_REASON="" +BUILD_ARTEFACT="" +BUILD_SHA="" +BUILD_LOG="" +BUILD_ARTIFACT_NAME="$RECORD_NAME.build.json" + +if [[ $HOST_MATCHES -eq 0 ]]; then + BUILD_REASON="$HOST_MISMATCH_REASON" +elif [[ "$PROBE_VERDICT" != "BUILDABLE" ]]; then + BUILD_REASON="the prerequisite probe reported NOT BUILDABLE on this host (exit $PROBE_EXIT); the missing packages are named in the probe's output" +elif ! command -v cargo >/dev/null 2>&1; then + BUILD_REASON="cargo is not installed on this host, so no build could be attempted" +else + log "$SCRIPT_NAME: building the shell for $PLATFORM" + BUILD_LOG="$WORK_DIR/build.log" + set +e + bash scripts/build_gui_release.sh --out "$BUILD_DIR" --allow-dirty >"$BUILD_LOG" 2>&1 + BUILD_EXIT=$? + set -e + if [[ $BUILD_EXIT -ne 0 ]]; then + BUILD_STATUS="fail" + BUILD_REASON="the release build failed (exit $BUILD_EXIT); the build log is quoted in this record" + else + SIDECAR="$BUILD_DIR/eggsec-gui.build.json" + if [[ ! -f "$SIDECAR" ]]; then + BUILD_STATUS="fail" + BUILD_REASON="the release build produced no build sidecar at \`$SIDECAR\`" + else + cp "$SIDECAR" "$OUT_DIR/$BUILD_ARTIFACT_NAME" + BUILD_ARTEFACT="$BUILD_ARTIFACT_NAME" + BUILD_SHA="$(shasum -a 256 "$OUT_DIR/$BUILD_ARTIFACT_NAME" 2>/dev/null | cut -d' ' -f1 || true)" + if [[ -z "$BUILD_SHA" ]]; then + BUILD_SHA="$(sha256sum "$OUT_DIR/$BUILD_ARTIFACT_NAME" 2>/dev/null | cut -d' ' -f1 || true)" + fi + BUILD_STATUS="pass" + BUILD_REASON="the release build produced \`eggsec-gui.build.json\` and its SHA-256 is recorded" + fi + fi +fi + +# ── The daemon ────────────────────────────────────────────────────────────── +# The daemon's socket is unique per run, so two concurrent runs on one host +# do not collide (`scripts/smoke-daemon-local.sh` does the same). +OWNED_SOCKET="${TMPDIR:-/tmp}/eggsec-gui-qualification-$$.sock" +DAEMON_READY=0 +DAEMON_VERSION="unknown" +DAEMON_FEATURES="unknown" + +daemon_answers() { + python3 - "$1" <<'PY' +import json, socket, sys +path = sys.argv[1] +try: + handle = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + handle.settimeout(2) + handle.connect(path) + stream = handle.makefile("rwb") + stream.write(json.dumps({"type": "Health", "request_id": "qualify-probe"}).encode() + b"\n") + stream.flush() + line = stream.readline() + handle.close() +except OSError: + sys.exit(1) +sys.exit(0 if line else 1) +PY +} + +daemon_task_kinds() { + python3 - "$1" <<'PY' +import json, socket, sys +path = sys.argv[1] +try: + handle = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + handle.settimeout(5) + handle.connect(path) + stream = handle.makefile("rwb") + stream.write(json.dumps({"type": "DeclareClient", "request_id": "qualify-probe", + "kind": {"type": "Gui"}, "label": "qualification"}).encode() + b"\n") + stream.flush() + stream.readline() + stream.write(json.dumps({"type": "Capabilities", "request_id": "qualify-caps"}).encode() + b"\n") + stream.flush() + line = stream.readline() + handle.close() +except OSError: + sys.exit(1) +try: + message = json.loads(line) +except ValueError: + sys.exit(1) +kinds = message.get("capabilities", {}).get("runtime", {}).get("task_kinds", []) +print(len(kinds)) +PY +} + +if [[ $HOST_MATCHES -eq 0 ]]; then + log "$SCRIPT_NAME: $HOST_MISMATCH_REASON; the daemon half and the harness do not run" +elif [[ -n "$SOCKET" ]]; then + DAEMON_SOCKET="$SOCKET" + if daemon_answers "$DAEMON_SOCKET"; then + DAEMON_READY=1 + fi +fi + +if [[ $DAEMON_READY -eq 0 && -n "$DAEMON_BIN" ]]; then + if [[ ! -x "$DAEMON_BIN" ]]; then + die "\`--daemon-bin\` names \`$DAEMON_BIN\`, which is not an executable file" + fi + log "$SCRIPT_NAME: starting the daemon at $DAEMON_BIN" + # The engine admits a loopback target only when the fixture marker is set + # (`crates/eggsec/src/utils/parsing.rs:77`), and the harness's target is + # the loopback fixture. The marker is the daemon's, not the harness's. + EGGSEC_ALLOW_LOOPBACK_FIXTURE=1 "$DAEMON_BIN" \ + --full-executor --socket-path "$OWNED_SOCKET" --no-persistence \ + >"$WORK_DIR/daemon.log" 2>&1 & + DAEMON_PID=$! + for _ in $(seq 1 60); do + if daemon_answers "$OWNED_SOCKET"; then + DAEMON_READY=1 + DAEMON_SOCKET="$OWNED_SOCKET" + break + fi + sleep 1 + done + if [[ $DAEMON_READY -eq 0 ]]; then + warn "$SCRIPT_NAME: the daemon did not become ready on $OWNED_SOCKET" + fi +fi + +if [[ $DAEMON_READY -eq 1 ]]; then + if [[ -n "$DAEMON_BIN" && -x "$DAEMON_BIN" ]]; then + DAEMON_SHA="$(shasum -a 256 "$DAEMON_BIN" 2>/dev/null | cut -d' ' -f1 || true)" + if [[ -z "$DAEMON_SHA" ]]; then + DAEMON_SHA="$(sha256sum "$DAEMON_BIN" 2>/dev/null | cut -d' ' -f1 || true)" + fi + DAEMON_VERSION="$DAEMON_BIN (sha256 $DAEMON_SHA)" + DAEMON_FEATURES="service" + else + DAEMON_VERSION="attached to an operator-started daemon" + DAEMON_FEATURES="unknown" + fi +fi + +# A daemon that publishes no task kinds is a no-op executor: its binary was +# not built with the `service` cargo feature, and it refuses every task. The +# record says so, rather than leaving a bare "unsupported task kind". +DAEMON_TASK_KINDS="$(daemon_task_kinds "$DAEMON_SOCKET" 2>/dev/null || printf '')" +if [[ -n "$DAEMON_TASK_KINDS" && "$DAEMON_TASK_KINDS" == "0" ]]; then + warn "$SCRIPT_NAME: the daemon publishes no task kinds; it is a no-op executor." + warn "$SCRIPT_NAME: build it with the \`service\` cargo feature (scripts/build-daemon-profile.sh --profile service)." +fi + +# ── The harness ───────────────────────────────────────────────────────────── +HARNESS_OUT="$WORK_DIR/harness" +HARNESS_RESULT="$WORK_DIR/harness-outcome.json" +mkdir -p "$HARNESS_OUT" +HARNESS_LOG="$WORK_DIR/harness.log" +HARNESS_OUTCOME="$HARNESS_RESULT" +HARNESS_COMMAND="cargo test -p eggsec-gui --no-default-features --test qualification" +HARNESS_EXIT=0 +# On a host that is not the platform being qualified, the harness is given no +# daemon to start: its observations would be of this host, not of the +# platform the record names. +HARNESS_DAEMON_BIN="$DAEMON_BIN" +if [[ $HOST_MATCHES -eq 0 ]]; then + HARNESS_DAEMON_BIN="" +fi +set +e +EGGSEC_QUALIFY_SOCKET="$DAEMON_SOCKET" \ + EGGSEC_QUALIFY_DAEMON_BIN="$HARNESS_DAEMON_BIN" \ + EGGSEC_QUALIFY_PLATFORM="$PLATFORM" \ + EGGSEC_QUALIFY_OUT="$HARNESS_OUT" \ + EGGSEC_QUALIFY_RESULT="$HARNESS_RESULT" \ + cargo test -p eggsec-gui --no-default-features --test qualification \ + >"$HARNESS_LOG" 2>&1 +HARNESS_EXIT=$? +set -e + +if [[ ! -f "$HARNESS_RESULT" ]]; then + HARNESS_EXIT="${HARNESS_EXIT:-1}" + if [[ $HARNESS_EXIT -eq 0 ]]; then + HARNESS_EXIT=1 + fi + warn "$SCRIPT_NAME: the harness produced no outcome file" +fi + +# ── The export artefacts ──────────────────────────────────────────────────── +# The harness's exported reports are copied into the evidence directory under +# names that say what they are, so a cell's artefact reference resolves. +EXPORT_ARTIFACT_NAME="$RECORD_NAME.export.json" +EXPORT_ARTEFACT="" +EXPORT_SHA="" +if [[ -f "$HARNESS_OUT/live-report.json" ]]; then + for extension in json csv html md sarif xml; do + if [[ -f "$HARNESS_OUT/live-report.$extension" ]]; then + cp "$HARNESS_OUT/live-report.$extension" "$OUT_DIR/$RECORD_NAME.export.$extension" + fi + done + EXPORT_ARTEFACT="$EXPORT_ARTIFACT_NAME" + EXPORT_SHA="$(shasum -a 256 "$OUT_DIR/$EXPORT_ARTIFACT_NAME" 2>/dev/null | cut -d' ' -f1 || true)" + if [[ -z "$EXPORT_SHA" ]]; then + EXPORT_SHA="$(sha256sum "$OUT_DIR/$EXPORT_ARTIFACT_NAME" 2>/dev/null | cut -d' ' -f1 || true)" + fi +fi + +# ── The window probe ──────────────────────────────────────────────────────── +# The window probe is an observation, not an assertion. Its absence is a named +# skip; the operator's attestation is what the promotion rules read. +# +# The probe's outcome is the `launch` column's scripted outcome. The runbook's +# criterion is exactly one window titled `Eggsec`, so: +# +# * the probe could not run -> `skipped`, with the absent tool named; +# * no GUI process is running -> `not-performed`, because there was no +# window for the probe to find; +# * exactly one window was found -> `pass`; +# * the GUI is running and the probe +# found no window (or more than +# one) -> `fail`, because the window never +# painted (or painted ambiguously). +WINDOW_PROBE="none" +WINDOW_COUNT="" +WINDOW_SCREENSHOT="" +WINDOW_REASON="" +LAUNCH_STATUS="not-performed" +LAUNCH_REASON="" +GUI_RUNNING=0 +# `pgrep -x` matches the process NAME exactly. `pgrep -f` would match this +# run's own `cargo test -p eggsec-gui ...` command line and report a GUI that +# was never launched. +if command -v pgrep >/dev/null 2>&1 && pgrep -x 'eggsec-gui' >/dev/null 2>&1; then + GUI_RUNNING=1 +fi + +if [[ $HOST_MATCHES -eq 0 ]]; then + WINDOW_REASON="$HOST_MISMATCH_REASON" + LAUNCH_STATUS="skipped" + LAUNCH_REASON="$HOST_MISMATCH_REASON" +elif [[ $SKIP_WINDOW -eq 1 ]]; then + WINDOW_REASON="the window probe was skipped on request (\`--skip-window\`)" + LAUNCH_STATUS="skipped" + LAUNCH_REASON="the window probe was skipped on request (\`--skip-window\`)" +elif [[ "$PLATFORM" == "linux" ]]; then + if command -v xdotool >/dev/null 2>&1; then + WINDOW_PROBE="xdotool" + WINDOW_COUNT="$(xdotool search --name '^Eggsec$' 2>/dev/null | wc -l | tr -d ' ')" + WINDOW_REASON="the window probe ran on this host" + else + WINDOW_REASON="\`xdotool\` is not installed on this host, so the window could not be probed" + LAUNCH_STATUS="skipped" + LAUNCH_REASON="\`xdotool\` is not installed on this host, so the window could not be probed" + fi +else + if command -v osascript >/dev/null 2>&1; then + WINDOW_PROBE="osascript" + WINDOW_COUNT="$(osascript -e 'tell application "System Events" to tell (first process whose name is "eggsec-gui") to get name of every window' 2>/dev/null | tr ',' '\n' | grep -c . || true)" + WINDOW_REASON="the window probe ran on this host" + else + WINDOW_REASON="\`osascript\` is not installed on this host, so the window could not be probed" + LAUNCH_STATUS="skipped" + LAUNCH_REASON="\`osascript\` is not installed on this host, so the window could not be probed" + fi +fi + +# The screenshot is taken only when there is a GUI to photograph. A +# full-screen capture of a host with no GUI running is a picture of the +# operator's desktop, not evidence of anything, and it does not belong in the +# repository. +if [[ $GUI_RUNNING -eq 1 ]]; then + if [[ "$PLATFORM" == "linux" ]] && command -v import >/dev/null 2>&1; then + WINDOW_SCREENSHOT="$RECORD_NAME.launch.png" + import -window root "$OUT_DIR/$WINDOW_SCREENSHOT" >/dev/null 2>&1 || WINDOW_SCREENSHOT="" + elif [[ "$PLATFORM" != "linux" ]] && command -v screencapture >/dev/null 2>&1; then + WINDOW_SCREENSHOT="$RECORD_NAME.launch.png" + screencapture -x -o "$OUT_DIR/$WINDOW_SCREENSHOT" >/dev/null 2>&1 || WINDOW_SCREENSHOT="" + fi +fi + +if [[ "$LAUNCH_STATUS" == "not-performed" ]]; then + if [[ $GUI_RUNNING -eq 1 ]]; then + LAUNCH_STATUS="fail" + LAUNCH_REASON="an \`eggsec-gui\` process is running, but the probe found ${WINDOW_COUNT:-0} window(s) titled \`Eggsec\`; the runbook's criterion is exactly one" + else + LAUNCH_STATUS="not-performed" + LAUNCH_REASON="no \`eggsec-gui\` process is running on this host, so the probe had no window to find; the launch step is an operator action" + fi +elif [[ "$LAUNCH_STATUS" == "skipped" ]]; then + : +elif [[ "${WINDOW_COUNT:-0}" == "1" ]]; then + LAUNCH_STATUS="pass" + LAUNCH_REASON="the probe found exactly one window titled \`Eggsec\`" +else + LAUNCH_STATUS="fail" + LAUNCH_REASON="the probe found ${WINDOW_COUNT:-0} windows titled \`Eggsec\`; the runbook's criterion is exactly one" +fi + +LAUNCH_ARTEFACT="" +LAUNCH_SHA="" +if [[ -n "$WINDOW_SCREENSHOT" && -f "$OUT_DIR/$WINDOW_SCREENSHOT" ]]; then + LAUNCH_ARTEFACT="$WINDOW_SCREENSHOT" + LAUNCH_SHA="$(shasum -a 256 "$OUT_DIR/$WINDOW_SCREENSHOT" 2>/dev/null | cut -d' ' -f1 || true)" + if [[ -z "$LAUNCH_SHA" ]]; then + LAUNCH_SHA="$(sha256sum "$OUT_DIR/$WINDOW_SCREENSHOT" 2>/dev/null | cut -d' ' -f1 || true)" + fi +fi + +# ── The record ────────────────────────────────────────────────────────────── +# +# The record's *shape* is owned by the validator: it is the thing that reads +# the record, so it is the thing that writes it. The procedure hands the +# validator a bag of facts and asks for the record back. There is therefore +# exactly one definition of the record's schema in the repository. +RECORD_JSON="$WORK_DIR/record.json" +RUN_INPUTS="$WORK_DIR/run-inputs.json" + +export PLATFORM MODE RUN_DATE RECORD_NAME RECORD_PATH OUT_DIR WORK_DIR +export COMMIT TREE_STATE HOST_OS HOST_OS_VERSION HOST_ARCH TARGET_TRIPLE +export RUSTC_VERSION CARGO_VERSION PROBE_COMMAND PROBE_EXIT PROBE_VERDICT +export TARGET_ARCH +export BUILD_STATUS BUILD_REASON BUILD_ARTEFACT BUILD_SHA BUILD_LOG +export DAEMON_SOCKET DAEMON_READY DAEMON_VERSION DAEMON_FEATURES DAEMON_SHA +export DAEMON_TASK_KINDS +export HARNESS_COMMAND HARNESS_EXIT HARNESS_OUTCOME HARNESS_LOG +export EXPORT_ARTEFACT EXPORT_SHA +export WINDOW_PROBE WINDOW_COUNT WINDOW_SCREENSHOT WINDOW_REASON +export LAUNCH_STATUS LAUNCH_REASON LAUNCH_ARTEFACT LAUNCH_SHA +export PROBE_LOG + +python3 - "$RUN_INPUTS" <<'PY' +import json, os, sys + +def read(path, limit=20000): + try: + with open(path, "r", errors="replace") as handle: + return handle.read()[:limit] + except OSError: + return "" + +facts = { + "platform": os.environ["PLATFORM"], + "mode": os.environ["MODE"], + "date": os.environ["RUN_DATE"], + "commit": os.environ["COMMIT"], + "tree_state": os.environ["TREE_STATE"], + "host": { + "os": os.environ["HOST_OS"], + "os_version": os.environ["HOST_OS_VERSION"], + "arch": os.environ["TARGET_ARCH"], + "process_arch": os.environ["HOST_ARCH"], + "target_triple": os.environ["TARGET_TRIPLE"], + }, + "toolchain": { + "rustc": os.environ["RUSTC_VERSION"], + "cargo": os.environ["CARGO_VERSION"], + }, + "features": {"requested": ["shell"], "resolved": ["default", "shell"]}, + "prerequisite_probe": { + "command": os.environ["PROBE_COMMAND"], + "exit": int(os.environ["PROBE_EXIT"]), + "verdict": os.environ["PROBE_VERDICT"], + "output": read(os.environ["PROBE_LOG"]), + }, + "daemon": { + "socket": os.environ["DAEMON_SOCKET"], + "ready": os.environ["DAEMON_READY"] == "1", + "version": os.environ["DAEMON_VERSION"], + "features": os.environ["DAEMON_FEATURES"], + "task_kinds": os.environ.get("DAEMON_TASK_KINDS", ""), + "scope": {"surface": "DesktopGuiManual", "source": "gui-default"}, + }, + "window": { + "probe": os.environ["WINDOW_PROBE"], + "windows": os.environ["WINDOW_COUNT"], + "screenshot": os.environ["WINDOW_SCREENSHOT"], + "reason": os.environ["WINDOW_REASON"], + }, + "launch": { + "status": os.environ["LAUNCH_STATUS"], + "reason": os.environ["LAUNCH_REASON"], + "artifact": os.environ["LAUNCH_ARTEFACT"], + "sha256": os.environ["LAUNCH_SHA"], + }, + "harness": { + "command": os.environ["HARNESS_COMMAND"], + "exit": int(os.environ["HARNESS_EXIT"]), + "outcome": os.environ["HARNESS_OUTCOME"], + "output": read(os.environ["HARNESS_LOG"]), + }, + "build": { + "status": os.environ["BUILD_STATUS"], + "reason": os.environ["BUILD_REASON"], + "artifact": os.environ["BUILD_ARTEFACT"], + "sha256": os.environ["BUILD_SHA"], + "log": read(os.environ.get("BUILD_LOG", "")), + }, + "export": { + "artifact": os.environ["EXPORT_ARTEFACT"], + "sha256": os.environ["EXPORT_SHA"], + }, +} +with open(sys.argv[1], "w") as handle: + json.dump(facts, handle, indent=2) +PY + +python3 scripts/check_gui_qualification.py \ + --write-record "$RECORD_JSON" \ + --run-inputs "$RUN_INPUTS" \ + --record-markdown "$RECORD_PATH" + +RECORDED_SCHEMA="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["schema"])' "$RECORD_JSON")" +if [[ "$RECORDED_SCHEMA" != "$RECORD_SCHEMA" ]]; then + die "the run record declares the schema \`$RECORDED_SCHEMA\`, but the procedure expects \`$RECORD_SCHEMA\`" +fi + +log "$SCRIPT_NAME: wrote the run record at $RECORD_PATH" + +# ── The verdict ───────────────────────────────────────────────────────────── +FAILURES="$(python3 - "$RECORD_JSON" <<'PY' +import json, sys +record = json.load(open(sys.argv[1])) +failed = [c["column"] for c in record["columns"] if c["scripted"] == "fail"] +print(" ".join(failed)) +PY +)" +if [[ -n "$FAILURES" ]]; then + warn "$SCRIPT_NAME: FAILED columns: $FAILURES" + exit 1 +fi +if [[ "$MODE" == "ci" && ! -f "$HARNESS_RESULT" ]]; then + warn "$SCRIPT_NAME: the harness did not run, so the run qualifies nothing" + exit 1 +fi +log "$SCRIPT_NAME: every column's scripted outcome is pass, skipped, or not-applicable" +exit 0 From dcfcd4e2afbcbf2cd707ce345b11ffb0bb41679e Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Sat, 24 Oct 2026 21:24:21 +0000 Subject: [PATCH 21/52] fix(tui,engine): correct the assertions milestone 010 left stale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Milestone 010 split the packet family into `packet-capture` and `packet`, added `wireless-deauth`, and moved the interface-bound operations' scope requirement from descriptor construction onto the descriptor. It updated the policy catalog's own self-tests but not the three integration tests that asserted the old shape. `make check` had never reached them, because it stopped at the inherited `check-deps` advisory backlog that milestone 015 cleared; with that gate green, the contract reached the engine's and the TUI's integration tests for the first time and found all three. `crates/eggsec/tests/canonical_dispatch_ownership.rs` asserted that all three packet wire kinds map to the `packet` operation. The capture half owns its own operation, because a capture binds to a local interface while `packet` serves `traceroute` and `packet-send`, which address a remote host. The test now asserts the deliberate split and is renamed, because its old name stated a truth the milestone had already retired. `crates/eggsec/tests/enforcement_matrix.rs` asserted that an interface-bound operation fails descriptor construction on a target-less run. The refusal moved: such an operation now accepts the run and carries `requires_explicit_scope` on the descriptor. The test now asserts the same posture as the catalog's own `interface_bound_operations_still_fail_closed`, and — the property its name and doc comment are about — that a strict automated surface still refuses the operation with `ScopeMissing` once a local identifier is supplied and no explicit scope manifest is loaded. `crates/eggsec-tui/src/parity.rs` requires every canonical operation to have a TUI tab or an intentional CLI-only classification, and it names the exceptions in a set. `packet-capture` was in neither, because the TUI's Packet tab declares `packet` while its capture path drives `packet-capture` — so the operation is covered by a tab, not CLI-only. The check now carries a third coverage set, `covered_via_tab`, naming the operations a tab drives without declaring them as the tab's own operation. The invariant keeps its strength: an operation that no tab drives and that is not classified still fails the check. No product behaviour changes. All three were stale with respect to decisions milestone 010 had already made and self-tested in `crates/eggsec-policy/src/catalog.rs` and in the TUI's own tab specs. Verified: `make check` exits 0 — 4315 tests across 77 test binaries, 190 architecture guards with no drift, `cargo deny --workspace --all-features check` green, clippy clean, `cargo fmt --all --check` clean. --- crates/eggsec-tui/src/parity.rs | 8 +- .../tests/canonical_dispatch_ownership.rs | 19 ++++- crates/eggsec/tests/enforcement_matrix.rs | 74 ++++++++++++++++++- 3 files changed, 94 insertions(+), 7 deletions(-) diff --git a/crates/eggsec-tui/src/parity.rs b/crates/eggsec-tui/src/parity.rs index dc3e804a2..629ec795a 100644 --- a/crates/eggsec-tui/src/parity.rs +++ b/crates/eggsec-tui/src/parity.rs @@ -246,6 +246,11 @@ mod tests { let tui_ops: BTreeSet<&str> = tab_specs().iter().filter_map(|s| s.operation).collect(); // Aliases that resolve to a TUI-covered canonical op count as covered. let covered_via_alias: BTreeSet<&str> = BTreeSet::from(["waf", "scan-pipeline"]); + // Canonical operations a TUI tab drives without declaring them as the + // tab's own operation. The Packet tab declares `packet`, but its + // capture path drives `packet-capture` — a capture binds to a local + // interface, so it is a separate operation with its own metadata. + let covered_via_tab: BTreeSet<&str> = BTreeSet::from(["packet-capture"]); let intentionally_cli_only: BTreeSet<&str> = BTreeSet::from([ "waf-bypass", // via `waf --bypass` flag path "remote", // via exec/remote lifecycle surface @@ -265,7 +270,8 @@ mod tests { *canonical == meta.id && (tui_ops.contains(alias) || covered_via_alias.contains(alias)) }); - if !direct && !via_alias { + let via_tab = covered_via_tab.contains(meta.id); + if !direct && !via_alias && !via_tab { assert!( intentionally_cli_only.contains(meta.id), "canonical operation '{}' has no TUI tab and no intentional classification", diff --git a/crates/eggsec/tests/canonical_dispatch_ownership.rs b/crates/eggsec/tests/canonical_dispatch_ownership.rs index 6b3ef2a2d..6ef01a781 100644 --- a/crates/eggsec/tests/canonical_dispatch_ownership.rs +++ b/crates/eggsec/tests/canonical_dispatch_ownership.rs @@ -303,7 +303,7 @@ fn pipeline_multiplexer_resolves_before_boundary() { // ── 7. packet family ── #[test] -fn packet_family_shares_operation_with_explicit_wire_kinds() { +fn packet_family_splits_capture_and_keeps_explicit_wire_kinds() { let cap = TaskKind::PacketCapture(PacketCaptureParams::default()); let trace = TaskKind::PacketTraceroute(PacketTracerouteParams { target: "127.0.0.1".into(), @@ -314,11 +314,24 @@ fn packet_family_shares_operation_with_explicit_wire_kinds() { protocol: "tcp".into(), ..Default::default() }); - for kind in [&cap, &trace, &send] { + // The capture half owns its own operation: it binds to a **local + // interface**, while `packet` also serves `traceroute` and `packet-send`, + // which address a remote host and must keep requiring one. The wire kinds + // still name their operation explicitly — they do not fall through string + // aliases. + assert_eq!(cap.operation_id(), "packet-capture"); + assert_eq!( + CanonicalOperationRequest::from_task_kind(&cap).operation_id(), + "packet-capture" + ); + for kind in [&trace, &send] { assert_eq!(kind.operation_id(), "packet"); let canonical = CanonicalOperationRequest::from_task_kind(kind); assert_eq!(canonical.operation_id(), "packet"); - assert_eq!(executor_route_for(canonical.operation_id()), "network"); + } + // Both halves of the family reach the same executor route. + for op in ["packet-capture", "packet"] { + assert_eq!(executor_route_for(op), "network"); } // Interface-bound capture carries no target; traceroute/send do. assert_eq!(cap.canonical_target(), None); diff --git a/crates/eggsec/tests/enforcement_matrix.rs b/crates/eggsec/tests/enforcement_matrix.rs index a9b94f8fa..626890754 100644 --- a/crates/eggsec/tests/enforcement_matrix.rs +++ b/crates/eggsec/tests/enforcement_matrix.rs @@ -3551,14 +3551,82 @@ fn strict_surface_still_denies_out_of_scope_target_on_relaxed_operation() { /// The counterpart to the relaxation above: `packet` and `wireless` are also /// target-less, but they sniff, so requiring a loaded scope is the only lever an /// operator has over them and it stays. +/// +/// The two halves refuse in different places, and both refusals matter. `packet` +/// addresses a remote host, so a target-less run is refused when the descriptor +/// is built. The interface-bound operations bind to a *local* interface or +/// identifier, so they accept a target-less run — and they keep the +/// explicit-scope requirement on the descriptor, which is where the enforcement +/// kernel reads it. #[test] fn strict_surface_still_requires_scope_for_interface_bound_operations() { - for op in ["packet", "wireless", "wireless-deauth"] { + // The remote-target half refuses a target-less run outright. + let packet = metadata_for_tool_id("packet").expect("packet should have metadata"); + assert!( + packet.try_descriptor_for_target(None).is_err(), + "packet should still refuse a target-less run" + ); + + for op in ["packet-capture", "wireless", "wireless-deauth"] { let metadata = metadata_for_tool_id(op).unwrap_or_else(|| panic!("{op} should have metadata")); assert!( - metadata.try_descriptor_for_target(None).is_err(), - "{op} should still refuse a target-less run" + metadata.target_policy.is_interface_bound(), + "{op} must be interface-bound" + ); + + // A target-less run is accepted, but only with the scope requirement + // still attached. + let no_target = metadata + .try_descriptor_for_target(None) + .unwrap_or_else(|e| panic!("{op} should accept a target-less run, got {e}")); + assert!( + no_target.requires_explicit_scope, + "{op} lost its scope requirement" + ); + assert!(no_target.target.is_none(), "{op} invented a target"); + + // And the lever stays: once a local identifier is supplied, a strict + // automated surface refuses the operation without an explicit scope + // manifest — on the scope dimension, not on the risk. The risk tiers + // are granted so the scope dimension is the one the decision turns on. + let local = metadata + .try_descriptor_for_target(Some("wlan0")) + .unwrap_or_else(|e| panic!("{op} should accept a local identifier, got {e}")); + assert_eq!( + local.target.as_deref(), + Some("wlan0"), + "{op} dropped the local identifier" + ); + + let caps: Vec = metadata.required_capabilities.to_vec(); + let policy = ExecutionPolicy { + allowed_capabilities: caps, + allow_raw_packets: true, + allow_intrusive_fuzzing: true, + allow_load_testing: true, + allow_stress_testing: true, + allow_credential_testing: true, + ..Default::default() + }; + let enabled: Vec = metadata + .required_features + .iter() + .map(|f| f.to_string()) + .collect(); + + // No scope manifest loaded at all. + let mut ctx = ctx_for_surface(ExecutionSurface::RestApi, policy, LoadedScope::default()); + ctx.enabled_features = eggsec::config::EnabledFeatures::from_names(enabled); + let outcome = ctx.evaluate(&local); + assert!( + !outcome.is_allowed(), + "{op} was allowed on a strict surface with no loaded scope" + ); + let classes = &outcome.decision().denial_classes; + assert!( + classes.contains(&DenialClass::ScopeMissing), + "{op} was denied for the wrong reason: {classes:?}" ); } } From 42e3534be0bcb5177487d5b4293e6ed2e1409ae5 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Sat, 24 Oct 2026 21:24:28 +0000 Subject: [PATCH 22/52] fix(scripts): pass the daemon's socket path as an option in the local smoke script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `scripts/smoke-daemon-local.sh` started the daemon with the socket path as a positional argument, while the daemon binary has always taken it as the `--socket-path` option. The script therefore failed at every run with error: unexpected argument '/var/folders/.../eggsec-smoke-XXXXXX.sock' found and stopped at "Daemon socket not found … after 10s". The defect is pre-existing and reproduces against the unmodified script at HEAD; it is fixed here because milestone 012 touched the daemon's socket-path handling and the script is the local smoke check for it. Verified: `make check` exits 0; the smoke script's own shell syntax checks (`bash -n`). --- scripts/smoke-daemon-local.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/smoke-daemon-local.sh b/scripts/smoke-daemon-local.sh index 62403af3b..8000e2944 100755 --- a/scripts/smoke-daemon-local.sh +++ b/scripts/smoke-daemon-local.sh @@ -113,7 +113,7 @@ pass "Built and staged eggsec-daemon and eggsec-cli" step 2 "Start daemon (background, ephemeral data dir)" DAEMON_LOG="$WORK_DIR/daemon.log" -"$DAEMON_BIN" "$SOCKET" \ +"$DAEMON_BIN" --socket-path "$SOCKET" \ >"$DAEMON_LOG" 2>&1 & DAEMON_PID=$! From 3ebd23685728c86531b6df268930eebd1c63fd56 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Sat, 24 Oct 2026 21:25:27 +0000 Subject: [PATCH 23/52] docs(plans): record the closures of the desktop GUI milestones 012 to 015 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the desktop GUI frontend subsystem's last four milestones with a closure record each, in the 12-section template, and moves the registry and the roadmap's milestone status table from "planned" to "implemented". Milestone 012 (corrective) — the daemon's socket path has one owner. The default, the `EGGSEC_DAEMON_SOCKET` name and the precedence rule live in `crates/eggsec-runtime/src/daemon_endpoint.rs`; the webview holds no copy; and the server's bind refuses to displace a live daemon, so the guarantee lives in the bind rather than in the start path's pre-flight check. The milestone's deviation is recorded as finding F1: ADR-0013 is authored as `proposed`, because ratification is the maintainer's — the same route milestone 011 took with ADR-0012. Milestone 013 (corrective) — the report bridge's coverage table accounts for the engine's 35 `TaskResult` variants exactly once, and the daemon publishes it so the operator learns the coverage rather than guessing. The plan's own finding is carried forward rather than closed: twelve of the thirty-five report documents still carry no timestamp, because closing it means either adding a timestamp to twelve engine result types or giving the bridge a clock, and neither is a mapping. Milestone 014 (capability) — the qualification matrix is now checkable, with a hermetic procedure, an assertion harness and a validator that reads the promotion rules from the matrix itself. The behavioural cells are **promotable, not promoted**: they need an operator attestation that no CI run can supply, so they stay `not qualified`. The record states that plainly rather than claiming a promotion it did not earn. Milestone 015 (corrective) — the dependency advisory backlog is closed and the mandatory contract completes for the first time on this branch. The `zip` 9.x upgrade was taken with a narrowed feature set rather than with a licence allowance; that deviation, its reason and its revert recipe are recorded as finding F1. Three integration tests that milestone 010 had left stale were found by that first complete `make check` run and corrected in `dcfcd4e2`; the correction is recorded as a dated addendum on milestone 010's closure record rather than by rewriting its findings. A pre-existing defect in `scripts/smoke-daemon-local.sh` — the daemon's socket path was passed positionally where the binary takes `--socket-path` — is fixed in `42e3534b`. Verified: `make check` exits 0 — 4315 tests across 77 test binaries, 190 architecture guards with no drift, `cargo deny --workspace --all-features check` green, clippy clean, `cargo fmt --all --check` clean; `make check-msrv` exits 0; `python3 scripts/check_doc_references.py` reports the unchanged baseline of 29 missing references. --- ...n-full-manual-capability-policy-closure.md | 58 ++ ...n-socket-path-and-bind-contract-closure.md | 621 +++++++++++++ ...013-report-bridge-full-coverage-closure.md | 606 +++++++++++++ ...ualification-driver-and-runbook-closure.md | 599 +++++++++++++ ...015-dependency-advisory-backlog-closure.md | 840 ++++++++++++++++++ plans/registry.md | 14 +- .../desktop-gui-frontend-roadmap.md | 10 +- 7 files changed, 2736 insertions(+), 12 deletions(-) create mode 100644 plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md create mode 100644 plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md create mode 100644 plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md create mode 100644 plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md diff --git a/plans/closure/desktop-gui-frontend/010-daemon-full-manual-capability-policy-closure.md b/plans/closure/desktop-gui-frontend/010-daemon-full-manual-capability-policy-closure.md index d98f2349f..716c1b7e7 100644 --- a/plans/closure/desktop-gui-frontend/010-daemon-full-manual-capability-policy-closure.md +++ b/plans/closure/desktop-gui-frontend/010-daemon-full-manual-capability-policy-closure.md @@ -536,3 +536,61 @@ that dependency. acceptance", becomes **met**. - `plans/adrs/ADR-0011-daemon-manual-capability-policy.md` — the status line moves from `proposed` to `accepted`. + +## Addendum 2026-10-24 — two stale engine assertions found and corrected + +Discovered while the **mandatory contract** (`make check`) was re-run after +milestones 012–015 were implemented. `make check` had never completed on this +branch — it stopped at the inherited `check-deps` advisory backlog — so the +engine's integration tests had not run since milestone 010's implementation +commit `1877d8e4`. Two of them were left behind by that commit. + +**F1 — `crates/eggsec/tests/canonical_dispatch_ownership.rs` asserted the +pre-split packet operation id.** Milestone 010 gave the capture half of the +packet family its own operation (`packet-capture`, because a capture binds to +a **local interface** while `packet` serves `traceroute` and `packet-send`, +which address a remote host). It updated +`crates/eggsec-runtime/src/request.rs` and the catalog's own self-test, but not +this integration test, which still asserted that all three wire kinds map to +`packet`. The test now asserts the deliberate split and is renamed +`packet_family_splits_capture_and_keeps_explicit_wire_kinds`; the original name +stated a falsehood the milestone had already retired. + +**F2 — `crates/eggsec/tests/enforcement_matrix.rs` asserted the pre-split +scope refusal.** The same milestone changed the `InterfaceBound` target policy +so that an interface-bound operation **accepts** a target-less run and carries +the requirement as `requires_explicit_scope` on the descriptor, rather than +failing descriptor construction. The catalog's own self-test +(`interface_bound_operations_still_fail_closed`) carries the updated +semantics; this integration test still asserted that descriptor construction +fails. It now asserts the same posture as the catalog's test, and — the +property the test's own name and doc comment are about — that a strict +automated surface still refuses the operation with `ScopeMissing` once a local +identifier is supplied and no explicit scope manifest is loaded. + +**F3 — `crates/eggsec-tui/src/parity.rs` had not classified the new +`packet-capture` operation.** The TUI's parity check requires every canonical +operation to have a TUI tab or an intentional CLI-only classification, and it +names the exceptions in a set. Milestone 010 added `packet-capture` and +classified `wireless-deauth` in the same commit, but not `packet-capture`. The +TUI's Packet tab *does* drive it — the tab's capture path runs a capture, which +binds to a local interface and is therefore its own operation — so the correct +classification is not "CLI-only". The parity check now carries a third +coverage set, `covered_via_tab`, naming the operations a TUI tab drives +without declaring them as the tab's own operation, with `packet-capture` in +it and the reason stated in a comment. The invariant is unchanged in strength: +a canonical operation that no tab drives and that is not classified still fails +the check. + +None of the three changes alters product behaviour: all three were stale with +respect to decisions milestone 010 had already made and self-tested in +`crates/eggsec-policy/src/catalog.rs` and in the TUI's own tab specs. No +production behaviour changed. The corrections are recorded here rather than by +rewriting this record's findings, and they are carried by commit `dcfcd4e2` +("fix(tui,engine): correct the assertions milestone 010 left stale"). + +**Why this surfaced now.** `make check` had never completed on this branch: it +stopped at the inherited `check-deps` advisory backlog, which milestone 015 +cleared. With that gate green, the contract reached the engine's and the TUI's +integration tests for the first time, and these three stale assertions were +waiting there. diff --git a/plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md b/plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md new file mode 100644 index 000000000..2772c25d7 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md @@ -0,0 +1,621 @@ +# Desktop-GUI Frontend Milestone 012 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` (gap 10 → milestone 012) + +Repository baseline reviewed: `0f5dbb26` (branch `feat/auto-20261022-76692679`) + +Implementation commits or pull requests: + +- `6de6340e` — feat(desktop-gui): implement the desktop GUI milestones 012 to 015 +- `dcfcd4e2` — fix(tui,engine): correct the assertions milestone 010 left stale + +## 1. Executive finding + +The milestone's capability boundary is complete: the daemon's socket path now +has **one** owner (`crates/eggsec-runtime/src/daemon_endpoint.rs`), the +environment override has **one** name and **one** resolver, the GUI's webview +holds **no** copy of the default, and the server's **bind** refuses to displace +a live daemon instead of unlinking its socket. + +The production boundary is complete and the behaviour is proven by tests, not +by compilation: two `run_server` calls against one path — exactly one binds, +the other is refused with an actionable message, and the survivor keeps +answering `Health` while keeping its socket file. Three static guards (177, +178, 179) pin the facts that would otherwise rot, and each was negative-tested. + +Two items are recorded as deviations, not as silent omissions: + +- **ADR-0013 is `proposed`, not `accepted`.** Acceptance is the maintainer's + decision and is out of the implementer's control; the implementation follows + the ADR's stated decision exactly (finding F1). +- **`crates/eggsec-daemon/src/error.rs` was edited although it is not in the + handoff's file-ownership list.** The plan's §6.4 puts the refusal's error + type in that file, and no other planned milestone owns it (finding F2). + +## 2. Requirement-to-evidence matrix + +The acceptance criteria are §13 of the source plan. + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| §13.1 — the default socket path is stated **once**, in a crate the engine, the daemon and the GUI all depend on | `crates/eggsec-runtime/src/daemon_endpoint.rs:38` is the only production statement; `rg --fixed-strings '/tmp/eggsec-daemon.sock' crates/ scripts/` → 2 hits, both in `crates/eggsec-runtime/src/daemon_endpoint.rs`; guard 177 | pass | The canonical crate is `eggsec-runtime`; the engine, the daemon, the CLI and the GUI already depend on it, so **no new dependency edge** was added | +| §13.2 — `EGGSEC_DAEMON_SOCKET` overrides the default in the daemon binary, the CLI, the TUI and the GUI, with one precedence | `daemon_socket_env.rs` (6 subprocess tests); `the_global_socket_default_is_the_canonical_constant`; `the_preflight_refusal_is_actionable`; guard 179 | pass | The TUI reaches the same rule through the engine's global `--socket`; the precedence is **flag → environment → built-in default** | +| §13.3 — an absent, empty or whitespace-only environment value resolves to the built-in default | `crates/eggsec-runtime/src/daemon_endpoint.rs` unit tests (rows 1–3 of the five-row table) and `crates/eggsec-runtime/tests/daemon_endpoint.rs`; `an_empty_environment_value_falls_back_to_the_built_in_default` | pass | The trim is part of the rule and lives in the resolver | +| §13.4 — the GUI's webview contains **no** copy of the default | `crates/eggsec-gui/frontend/app.js` has no `DEFAULT_SOCKET`; `crates/eggsec-gui/frontend/index.html` has no `value=` on the socket input; `applyDefaultSocketPath()` fills the field from `daemon_status.default_socket_path`; `connect_daemon` resolves an empty socket to `state.options.socket_path` | pass | The IPC command count is unchanged (13) | +| §13.5 — the GUI's IPC command count is still 13 | `crates/eggsec-gui/src/commands.rs:1174` (`every_command_declares_its_argument_naming`) asserts 13 and passes | pass | `daemon_status` gained a **field**, not a command | +| §13.6 — the server **refuses** to bind over a live socket, and the refusal names the path, says a live daemon holds it, and names what the operator can do | `two_servers_one_path_exactly_one_binds`; `DaemonError::SocketPathHeld` renders `refusing to displace the live daemon already serving {path} (protocol version {v}) — stop it first, or start this daemon on another path (an explicit socket path, or EGGSEC_DAEMON_SOCKET=)` | pass | The exact rendered text is in §4 | +| §13.7 — a refused bind does **not** remove the live daemon's socket file | `two_servers_one_path_exactly_one_binds` asserts the file still exists after the refusal; `a_refused_bind_leaves_the_socket_owner_only` asserts it is still 0600; the manual run in §4 shows `srw-------` after the refusal | pass | — | +| §13.8 — a stale socket file is still reclaimed | `a_stale_socket_file_is_reclaimed_by_the_bind`; `a_plain_file_at_the_path_is_reclaimed_by_the_bind`; `the_binary_reclaims_the_path_of_a_killed_daemon`; the pre-existing `a_stale_socket_does_not_block_a_start` still passes | pass | — | +| §13.9 — two servers against one path: exactly one binds, the other refuses, the survivor keeps serving | `two_servers_one_path_exactly_one_binds` **starts a second server** (the gap the probe-only test could not close); `many_rounds_bind_exactly_one_server` (20 rounds); `a_stale_path_with_two_servers_binds_once` | pass | — | +| §13.10 — the CLI's start path exits non-zero and prints the refusal | `crates/eggsec-cli/tests/daemon_start_refusal.rs` (end to end, real `eggsec` binary); the manual runs in §4 (`exit code 1` + the refusal text) | pass | The pre-flight refusal and the bind refusal both reach the operator | +| §13.11 — the pre-flight, the connect-probe, the stale-file semantics and the 0600 permission are unchanged in meaning; no lock file and no PID file | the pre-flight still uses `probe_daemon_liveness`; `DaemonLiveness`'s shape is unchanged; `the_socket_is_created_with_owner_only_permissions` (pre-existing) and `a_refused_bind_leaves_the_socket_owner_only` pass; guard 178 rejects a lock-file reference | pass | The bind guard **uses** the shared probe; no second liveness notion | +| §13.12 — guards 177, 178 and 179 fail on an injected violation and pass when restored | ten negative demonstrations in §4, each restored from a `cp` backup | pass | The harness passes on the restored tree | +| §13.13 — every command in §11 that was run, and its result, is recorded | §4 | **partial** | Two commands are red for reasons outside this change: `cargo fmt --all -- --check` (a concurrent agent's file) and `python3 scripts/check_doc_references.py` (30 pre-existing missing references). `cargo test -p eggsec-daemon --features service` and `cargo test -p eggsec-daemon --test daemon_start_honesty` are red on **one** assertion caused by a concurrent agent's in-flight protocol change. `cargo clippy -p eggsec-daemon --all-targets` and `cargo clippy -p eggsec-gui --all-targets` are red on files this milestone did not touch. Details and evidence in §4 | +| §13.14 — no new dependency, no `deny.toml` change, no new crate, no new IPC command, no wire change | `git status Cargo.toml`/`deny.toml` — neither is modified by this milestone; `Cargo.lock`'s only change is another agent's; the GUI's IPC count is 13; the daemon protocol's diff is another agent's | pass | — | + +## 3. Production implementation evidence + +### Ownership and the canonical crate + +`crates/eggsec-runtime/src/daemon_endpoint.rs` (new) owns the four items +§6.1 fixes: + +```rust +pub const DAEMON_SOCKET_ENV_VAR: &str = "EGGSEC_DAEMON_SOCKET"; +pub const DEFAULT_DAEMON_SOCKET_PATH: &str = "/tmp/eggsec-daemon.sock"; +pub fn resolve_daemon_socket_path(env_value: Option<&str>) -> &str; +pub fn daemon_socket_path_from_env() -> String; +``` + +They are re-exported from `crates/eggsec-runtime/src/lib.rs`. +`resolve_daemon_socket_path` is **pure** (it never reads the environment); +`daemon_socket_path_from_env` is the only function in the workspace that reads +the variable. + +The placement is the unique intersection of the crates that transcribed the +default: the engine, the daemon and the GUI already depend on `eggsec-runtime`, +and the CLI depends on it transitively — so **no new dependency edge** was +added, and no guard amendment was needed (I7, I10). + +### The surfaces + +| Surface | Site | What it does now | +|---|---|---| +| daemon binary | `crates/eggsec-daemon/src/main.rs:19-28` | `default_value_t = eggsec_runtime::daemon_socket_path_from_env()` | +| engine's global `--socket` | `crates/eggsec/src/cli/mod.rs:245-253` | the same resolver (the CLI binary and the TUI inherit it) | +| daemon's config default | `crates/eggsec-daemon/src/config.rs:19-33` (the constant at `:30`) | `eggsec_runtime::DEFAULT_DAEMON_SOCKET_PATH.to_owned()`, and `DaemonConfig::default()` stays **pure** | +| GUI's options default | `crates/eggsec-gui/src/config.rs:43` | `eggsec_runtime::daemon_socket_path_from_env()` | +| GUI's public constant | `crates/eggsec-gui/src/config.rs:19` | a re-export, `pub use eggsec_runtime::DEFAULT_DAEMON_SOCKET_PATH as DEFAULT_SOCKET_PATH;` | +| build script | `scripts/build-daemon-profile.sh:54,523-528` | carries no copy of the default; the hint names the operator's override when there is one | + +### The GUI's webview + +`crates/eggsec-gui/frontend/app.js` lost the `DEFAULT_SOCKET` constant; the +three fallback sites now send `dom.socketInput.value`, which may be empty. +`boot()` awaits `refreshDaemonStatus()` **before** the automatic connect, so +the field is filled from Rust's `default_socket_path`; `applyDefaultSocketPath` +fills it **only** when the operator has not typed one. `connect_daemon` +(`crates/eggsec-gui/src/commands.rs:340-361`) replaces an empty socket with +`state.options.socket_path` before connecting, so a failed IPC call still +connects to the right path. + +`DaemonStatusView` gained the field `default_socket_path` +(`crates/eggsec-gui/src/commands.rs:270-276`); the command count stays 13. + +### The server-side bind guard + +`crates/eggsec-daemon/src/server.rs:130-211` implements the three-step +sequence §6.4 fixes: + +1. `UnixListener::bind(socket_path)` — **no unlink first**. +2. On `AddrInUse`: `probe_daemon_liveness(socket_path, PREFLIGHT_PROBE_TIMEOUT)` + — the **shared** probe. `Live` → refuse with + `DaemonError::SocketPathHeld` and do **not** unlink; `NotLive` → step 3. +3. Reclaim the stale path **once** (`remove_file`, ignoring `NotFound`), then + bind again. A second `AddrInUse` → refuse with + `DaemonError::SocketPathTaken` ("another daemon took the path"), a distinct + claim from "a live daemon is serving it". + +The 0600 tightening, the accept loop, the client semaphore and the +shutdown-time removal are unchanged. + +### The refusal's text + +One message, three call sites: `eggsec_daemon::error::socket_path_held_message` +is used by the `DaemonError::SocketPathHeld` variant, the daemon binary's +pre-flight (`refuse_live_daemon`) and the CLI's pre-flight +(`start_failure_message`). The CLI's `describe_server_result` renders the +daemon's own error verbatim (`the daemon server failed: {error}`), so nothing +is flattened. + +**Deviation from the plan's example wording (D1):** the plan's §6.4 snippet +spells the second remedy `--socket-path `. One message must serve three +surfaces, and the flag is spelled `--socket-path` on the daemon binary and +`--socket` on the CLI and the GUI; naming one flag would misdirect the other +two. The shared message therefore says "an explicit socket path, or +`EGGSEC_DAEMON_SOCKET=`" — both remedies, one spelling that is true on +every surface. + +### The CLI's latent panic (a fix this milestone needed) + +`DaemonServer::stop()` awaited a oneshot receiver that the readiness wait had +already consumed — tokio's oneshot **panics** ("called after complete") when a +completed receiver is polled again. Before this milestone the server task +could not fail that way (the unlink displaced the live daemon instead), so the +path was latent; the bind guard makes it reachable. `stop()` now takes the +result with `try_recv` first and awaits it only while it is pending +(`crates/eggsec-cli/src/daemon_cli.rs:88-121`), with the regression test +`the_stop_path_survives_a_server_task_that_already_failed`. + +## 4. Verification executed + +### Commands run + +```bash +cargo fmt --all -- --check +cargo check --workspace --no-default-features +cargo check -p eggsec-gui --features shell +cargo check -p eggsec-cli --features daemon-client +cargo test -p eggsec-runtime +cargo test -p eggsec-daemon --features service +cargo test -p eggsec-daemon --test daemon_start_honesty +cargo test -p eggsec --features cli --lib +cargo test -p eggsec-cli --features daemon-client +cargo test -p eggsec-gui --no-default-features --lib +cargo test -p eggsec-gui --features shell --lib +cargo clippy --lib -p eggsec -- -D warnings +cargo clippy --lib -p eggsec --features cli -- -D warnings +cargo clippy -p eggsec-runtime --all-targets -- -D warnings +cargo clippy -p eggsec-daemon --all-targets -- -D warnings +cargo clippy -p eggsec-daemon-protocol --all-targets -- -D warnings +cargo clippy -p eggsec-gui --all-targets -- -D warnings +python3 scripts/check_doc_references.py +bash scripts/smoke-daemon-local.sh +cargo test -p eggsec --features cli,daemon-client --lib cli::tests # extra +cargo clippy -p eggsec-daemon --test daemon_socket_bind_guard --test daemon_socket_env -- -D warnings # extra +``` + +The full transcript is at `/tmp/eggsec-guardwork/m012-verification.log`. + +### Results + +| Command | Exit | Result | +|---|---|---| +| `cargo fmt --all -- --check` | **1** | **Red — not this milestone's file.** The only remaining diff is `crates/eggsec-gui/tests/qualification.rs`, a file a concurrent agent created. Every file this milestone touched is clean (`cargo fmt -p eggsec-runtime` and `-p eggsec-daemon` were run on the packages this milestone owns; the GUI package was left alone because its only diff is the other agent's file) | +| `cargo check --workspace --no-default-features` | 0 | pass | +| `cargo check -p eggsec-gui --features shell` | 0 | pass | +| `cargo check -p eggsec-cli --features daemon-client` | 0 | pass | +| `cargo test -p eggsec-runtime` | 0 | **pass** — 118 unit + 6 integration (`daemon_endpoint`) + 22 (`in_process_client`) + 0 doc-tests | +| `cargo test -p eggsec-daemon --features service` | **101** | **Red on one assertion, not this milestone's.** 112 lib + 3 bin + 7 (`daemon_socket_bind_guard`) + 6 (`daemon_socket_env`) pass; `daemon_start_honesty` fails `the_capabilities_message_shape_is_unchanged` because a concurrent agent added `report_forms` to `DaemonCapabilities` (`crates/eggsec-daemon-protocol/src/protocol.rs`, another agent's diff) and has not yet updated the assertion in that test file | +| `cargo test -p eggsec-daemon --test daemon_start_honesty` | **101** | **Red on the same single assertion** (9 passed, 1 failed). The other 9 tests — the pre-flight, the stale-file semantics, the older-daemon detection, the 0600 permission — pass unchanged in meaning | +| `cargo test -p eggsec --features cli --lib` | 0 | **pass** — 1417 tests | +| `cargo test -p eggsec-cli --features daemon-client` | 0 | **pass** — 34 unit + 1 end-to-end (`daemon_start_refusal`) | +| `cargo test -p eggsec-gui --no-default-features --lib` | 0 | **pass** — 82 tests | +| `cargo test -p eggsec-gui --features shell --lib` | 0 | **pass** — 91 tests | +| `cargo clippy --lib -p eggsec -- -D warnings` | 0 | pass | +| `cargo clippy --lib -p eggsec --features cli -- -D warnings` | 0 | pass | +| `cargo clippy -p eggsec-runtime --all-targets -- -D warnings` | 0 | pass | +| `cargo clippy -p eggsec-daemon --all-targets -- -D warnings` | **101** | **Red on files this milestone did not touch.** 4 errors in `crates/eggsec-daemon/src/host.rs` (a concurrent agent's in-flight file) and 1 in `crates/eggsec-daemon/src/store/sqlite.rs` (**unmodified at HEAD** — pre-existing). This milestone's two new test targets are clean: `cargo clippy -p eggsec-daemon --test daemon_socket_bind_guard --test daemon_socket_env -- -D warnings` → **0** | +| `cargo clippy -p eggsec-daemon-protocol --all-targets -- -D warnings` | 0 | pass | +| `cargo clippy -p eggsec-gui --all-targets -- -D warnings` | **101** | **Red on a concurrent agent's file.** 3 `contains()`-vs-`iter().any()` errors in `crates/eggsec-gui/tests/qualification.rs`, which this milestone did not touch | +| `python3 scripts/check_doc_references.py` | **1** | **Red — pre-existing.** 30 missing references, all to files that do not exist in the workspace (`tests/fuzzer_payload_corpus_seam.rs`, `crates/eggsec/src/scanner/service_data.rs`, `docs/PROVIDERS.md`, `tests/h2_mux.rs`, …). None is in a file this milestone created, edited or removed | +| `bash scripts/smoke-daemon-local.sh` | **1** | **Red — pre-existing.** The script starts the daemon with the socket path as a **positional** argument (`scripts/smoke-daemon-local.sh:116`), but the daemon binary has always taken `--socket-path `: `error: unexpected argument '…/eggsec-daemon.sock' found`. The script is unmodified in this tree and the same failure reproduces against HEAD's copy. The patch is in `/tmp/eggsec-guardwork/m012-smoke-daemon-local-patch.md`. The equivalent evidence is asserted by this milestone's own tests on non-default paths (`daemon_start_refusal.rs`, `daemon_socket_env.rs`) | +| `cargo test -p eggsec --features cli,daemon-client --lib cli::tests` (extra) | 0 | **pass** — 17 tests, including `the_per_subcommand_socket_overrides_the_global_flag` (the per-subcommand `--socket` exists only with the `daemon-client` feature, so it does not run under `--features cli` alone) | + +`make check` was **not** run: the handoff reserves it for the owner, and it +stops at the inherited `check-deps` advisory backlog that milestone 015 owns. +`make check-features-individual` was **not** run — the milestone adds no +feature, so the plan records it as a deep check that is not required. +`make check-msrv` was **not** run: it needs `rustup toolchain install 1.89`, +and the milestone adds no syntax or dependency that could raise the floor. + +### The occurrence count of the literal, before and after + +Search command: `rg -n --fixed-strings '/tmp/eggsec-daemon.sock' ` for +the working tree, `git grep -n --fixed-strings '/tmp/eggsec-daemon.sock' HEAD +-- ` for the baseline. + +| Category | Baseline (HEAD) | After | +|---|---|---| +| `crates/` (production + tests) | 8 | 2 | +| `scripts/` | 1 | 0 | +| `docs/` | 8 | 7 | +| `architecture/` | 2 | 2 | +| `.opencode/` (skills) | 4 | 4 | +| `plans/` (immutable history + this record) | 34 | 44 | +| **total** | **57** | **55** | + +The nine executable-surface occurrences became **two**, and both are in the +canonical crate: the constant +(`crates/eggsec-runtime/src/daemon_endpoint.rs:38`) and the test that pins +its value (`:124`). Two of this milestone's own new files had carried a +copy — the subprocess test's literal path and its literal environment +variable's name — and **the milestone's own guards caught both**: guard 177 +flagged `crates/eggsec-daemon/tests/daemon_socket_env.rs` and guard 179 +flagged the same file's environment-variable transcription. Both now name the +canonical items instead. The `plans/` count rose by ten: eight in this closure record and two in +ADR-0013, both of which quote the literal legitimately. The plan and the +earlier closure records are immutable history. + +### The bind sequence, as implemented + +`crates/eggsec-daemon/src/server.rs:169-211` — the `AddrInUse` branch, the +probe call and the reclaim, quoted: + +```rust +let listener = match UnixListener::bind(socket_path) { + Ok(listener) => listener, + Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => { + match probe_daemon_liveness(socket_path, PREFLIGHT_PROBE_TIMEOUT).await { + DaemonLiveness::Live { protocol_version } => { + tracing::warn!( + path = %socket_path, + protocol_version, + "Refusing to displace the live daemon that holds the socket path" + ); + return Err(DaemonError::SocketPathHeld { + socket_path: socket_path.clone(), + protocol_version, + }); + } + DaemonLiveness::NotLive => { + // The path holds no daemon: reclaim it once, then bind. + match std::fs::remove_file(socket_path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + tracing::warn!(path = %socket_path, error = %error, "Failed to remove the stale daemon socket"); + return Err(error.into()); + } + } + match UnixListener::bind(socket_path) { + Ok(listener) => listener, + Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => { + tracing::warn!( + path = %socket_path, + "Another daemon took the socket path while this daemon was reclaiming it" + ); + return Err(DaemonError::SocketPathTaken { + socket_path: socket_path.clone(), + }); + } + Err(error) => return Err(error.into()), + } + } + } + } + Err(error) => return Err(error.into()), +}; +``` + +### The contention evidence + +`cargo test -p eggsec-daemon --test daemon_socket_bind_guard`: + +``` +running 7 tests +test a_bind_failure_that_is_not_addr_in_use_leaves_the_path_alone ... ok +test a_refused_bind_leaves_the_socket_owner_only ... ok +test a_plain_file_at_the_path_is_reclaimed_by_the_bind ... ok +test two_servers_one_path_exactly_one_binds ... ok +test a_stale_socket_file_is_reclaimed_by_the_bind ... ok +test a_stale_path_with_two_servers_binds_once ... ok +test many_rounds_bind_exactly_one_server ... ok + +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.56s +``` + +`two_servers_one_path_exactly_one_binds` starts a **second server** against a +live path and asserts: the second returns `DaemonError::SocketPathHeld`; the +message names the path, says "live daemon" and names a remedy; the socket file +**still exists**; and the survivor still answers `Health`. +`many_rounds_bind_exactly_one_server` repeats that shape 20 times. + +### The stale-file evidence + +`a_stale_socket_file_is_reclaimed_by_the_bind` (bind level), the pre-existing +`a_stale_socket_does_not_block_a_start` (pre-flight level) and +`the_binary_reclaims_the_path_of_a_killed_daemon` (the binary's own unclean +restart: `SIGKILL`, the socket file stays, the next daemon reclaims it and +answers `Health`). + +### The refusal's exact rendered text + +**The daemon binary** (`eggsec-daemon --socket-path ` against a live +daemon) — exit code **1**: + +``` +Error: refusing to displace the live daemon already serving /tmp/eggsec-m012-evidence4.sock (protocol version 2) — stop it first, or start this daemon on another path (an explicit socket path, or EGGSEC_DAEMON_SOCKET=) +``` + +The live daemon still answered afterwards, and its socket file was still +there: + +``` +--- the live daemon still answers --- +Daemon status: ok (v0.1.0) +--- the socket file is still there --- +srw-------@ 1 davidbowman wheel 0 Oct 24 20:27 /tmp/eggsec-m012-evidence4.sock +``` + +**The CLI** (`eggsec daemon start --socket ` against a live daemon) — +exit code **1**: + +``` +Error: refusing to displace the live daemon already serving /tmp/eggsec-m012-evidence2.sock (protocol version 2) — stop it first, or start this daemon on another path (an explicit socket path, or EGGSEC_DAEMON_SOCKET=) +``` + +### The three guards' negative-test results + +The guard block is `/tmp/eggsec-guardwork/m012-guards.sh`; the harness is +`/tmp/eggsec-guardwork/m012-guard-harness.sh` (it sets `FAIL=0` and sources +the block, so the block can be verified before it is merged into +`scripts/check-architecture-guards.sh`). Every break was undone from a `cp` +backup in `/tmp/eggsec-guardwork/backups/` — never `git checkout --`. The +complete transcript is `/tmp/eggsec-guardwork/negative-tests.log`. + +| # | Injected violation | Guard | Message | +|---|---|---|---| +| N1 | the literal reintroduced in `crates/eggsec-daemon/src/config.rs` | 177 | `FAIL: the default socket path is stated outside the canonical crate: crates/eggsec-daemon/src/config.rs:30: socket_path: "/tmp/eggsec-daemon.sock".into(),` | +| N2 | the webview copy put back (`index.html`'s `value` attribute) | 177 | `FAIL: the default socket path is stated outside the canonical crate: crates/eggsec-gui/frontend/index.html:25: value="/tmp/eggsec-daemon.sock"` and `FAIL: the GUI's webview assets still hold a copy of the default socket path.` | +| N3 | the build script's copy put back | 177 | `FAIL: the default socket path is stated outside the canonical crate: scripts/build-daemon-profile.sh:54:SOCKET_PATH="${EGGSEC_DAEMON_SOCKET:-/tmp/eggsec-daemon.sock}"` and `FAIL: a shell script still holds a copy of the default socket path.` | +| N4 | the unlink moved ahead of the bind in `server.rs` | 178 | `FAIL: the server removes the socket path (line 169) before it binds it (line 174).` | +| N5 | the shared probe no longer consulted | 178 | `FAIL: the server's bind path does not consult the shared liveness probe.` | +| N6 | the `AddrInUse` refusal branch removed | 178 | `FAIL: the server has no AddrInUse refusal branch.` | +| N7 | a second liveness notion (a lock file) introduced | 178 | `FAIL: the server's bind path references lock_file; the liveness notion must stay singular.` and `… references .lock; …` | +| N8 | the variable's name transcribed outside the canonical crate | 179 | `FAIL: the socket environment variable's name is transcribed outside the canonical crate: crates/eggsec-daemon/src/config.rs:23: /// override (`EGGSEC_DAEMON_SOCKET`) is applied by the` | +| N9 | the canonical crate loses `resolve_daemon_socket_path` | 179 | `FAIL: the canonical crate does not declare pub fn resolve_daemon_socket_path.` | +| N10 | a surface re-derives the path instead of resolving it | 179 | `FAIL: crates/eggsec-gui/src/config.rs does not resolve the socket path through the canonical daemon endpoint.` | + +After every restore the harness passed again: + +``` +--- Check 177: the default socket path exists in exactly one place --- +PASS: the default socket path exists in exactly one place. +--- Check 178: the server refuses to bind over a live socket --- +PASS: the server refuses to bind over a live socket. +--- Check 179: the environment override has one name and one resolver --- +PASS: the environment override has one name and one resolver. +=== harness summary === +FAIL=0 +``` + +**Two of the guard's own rules were tightened because the first version of the +guard was vacuous.** The first draft matched the *doc comments* that name the +calls, and matched a `pub use` re-export and a test line as evidence that a +surface resolved the path; N5, N6 and N10 initially passed against the +injected violation. The shipped block therefore scans the **production half** +of a file (skipping comment lines, `pub use` lines and the test module) and +uses `-H` so that a single-file `rg` still yields `path:line:content`. The +table above is the result **after** that tightening. + +### The guards-doc and the shared documents + +`docs/CI_ARCHITECTURE_GUARDS.md` is shared by three agents, so the +registration entries are written to +`/tmp/eggsec-guardwork/m012-guards-doc.md` (the exact markdown, and where it +goes) rather than applied. The other shared documents' deltas are in +`/tmp/eggsec-guardwork/m012-docs-delta.md`: + +| File | What the delta changes | +|---|---| +| `architecture/desktop_gui.md` | the known gap "the socket-path default is duplicated in six places" → the new fact; the spawn route's "the daemon unlinks its socket path before binding" → the bind contract | +| `architecture/daemon.md` | the configuration table's `socket_path` row (the override and the precedence); invariant 12 ("the server-side hardening is deferred") → it landed here | +| `docs/DAEMON.md` | the defaults table's socket row; the transport table's socket row; the "starting a daemon honestly" section | +| `docs/GUI_DISTRIBUTION_HANDOFF.md` | the "fixed default, no environment-variable override, duplicated in six production sites" claim → one owner and one override | +| `docs/GUI_BUILD.md` | the two recipe lines; the sentence naming the default's location | +| `docs/DAEMON_FEATURE_PROFILE.md` | the recipe line | +| `.opencode/skills/eggsec-gui/SKILL.md` | the claim that the default is `/tmp/eggsec-daemon.sock` at `crates/eggsec-gui/src/config.rs:19` → the canonical crate and the override | + +The documents this milestone **owns** were edited directly: +`.opencode/skills/eggsec-daemon/SKILL.md` (the daemon's defaults and the +precedence) and `docs/python/examples/local_vs_daemon_execution.py` (the +hardcoded path became the environment override or an explicit argument). + + + +### Integration verification (2026-10-24, session owner) + +The milestone's own commands were run in isolation; the owner's integration +step then ran the repository's mandatory contract over the whole tree, with +all four milestones landed together. + +| Command | Result | +|---|---| +| `make check` | **exit 0** — `cargo fmt --all --check`, the no-default-features and per-crate checks, `cargo deny --workspace --all-features check` (all five sub-checks), clippy, the full test suite (**4315 tests across 77 test binaries, 0 failures**), and `scripts/check-architecture-guards.sh` (**190 guards, "ALL PASSED: No architecture drift detected"**) | +| `make check-msrv` | **exit 0** — all five steps green on Rust 1.89 | +| `python3 scripts/check_doc_references.py` | 29 missing references — the unchanged pre-existing baseline, none of them in a file this milestone touched | + +This is the **first time `make check` has completed on this branch**: it had +always stopped at the inherited `check-deps` advisory backlog, which milestone +015 cleared. Three integration tests that milestone 010 had left stale were +found by that first complete run and corrected in `dcfcd4e2`; the corrections +are recorded as a dated addendum on milestone 010's closure record rather +than by rewriting it. + +## 5. Invariant review + +| Invariant | Evidence | Result | +|---|---|---| +| **I1** — one source of truth for the default | the literal appears only in `crates/eggsec-runtime/src/daemon_endpoint.rs` (3 lines); guard 177; the nine→three measurement in §4 | pass | +| **I2** — one precedence, everywhere | `daemon_socket_env.rs` (the binary), `the_global_socket_default_is_the_canonical_constant` and `an_explicit_socket_flag_overrides_the_default` (the engine), `the_preflight_refusal_is_actionable` (the CLI), the GUI's `GuiOptions::default()`; guard 179 | pass | +| **I3** — the liveness definition stays singular | the bind guard calls `probe_daemon_liveness` (the pre-flight's own function); `DaemonLiveness`'s shape is unchanged; guard 178 rejects `flock`, a lock file and a PID file; N7 demonstrates it | pass | +| **I4** — a stale socket file is still reclaimable | `a_stale_socket_file_is_reclaimed_by_the_bind`, `a_plain_file_at_the_path_is_reclaimed_by_the_bind`, `the_binary_reclaims_the_path_of_a_killed_daemon`, and the pre-existing stale-file tests | pass | +| **I5** — the refusal is actionable | the rendered text names the path, says a live daemon holds it, gives the protocol version and names both remedies; asserted in the daemon, the CLI and the bind-guard tests | pass | +| **I6** — the refusal is fail-closed | the server unlinks only after the probe said *not live*; `two_servers_one_path_exactly_one_binds` asserts the socket file survives the refusal | pass | +| **I7** — the GUI links no engine, daemon, CLI or TUI crate | the GUI takes its share from `eggsec-runtime`, which it already depended on; no `Cargo.toml` of the GUI changed | pass | +| **I8** — the GUI's IPC command count does not change | 13, asserted by `every_command_declares_its_argument_naming` (passes) | pass | +| **I9** — no per-operation frontend code, no build step | the webview gained one small helper (`applyDefaultSocketPath`); no build step, no npm dependency, no hand-written default | pass | +| **I10** — no new dependency | no `Cargo.toml` changed by this milestone; `clap`'s `env` feature was **not** enabled | pass | +| **I11** — the daemon's local-IPC boundary is unchanged | the socket stays 0600 (`a_refused_bind_leaves_the_socket_owner_only`, and the pre-existing permission test) | pass | +| **I12** — no enforcement, authorization, scope or dispatch change | the milestone touches no operation, no policy, no scope rule and no dispatch path; `EnforcementContext::evaluate()` remains the only pre-dispatch gate; no `ApprovedExecution` bundle is constructed anywhere in the diff | pass | + +## 6. Failure and recovery review + +- **Duplicate delivery (two starts, one path).** Closed by the bind guard: + exactly one binds; the loser refuses with an actionable message and does + **not** remove the winner's socket. Proven by + `two_servers_one_path_exactly_one_binds`, `many_rounds_bind_exactly_one_server` + (20 rounds) and `a_stale_path_with_two_servers_binds_once`. +- **The residual race (stated, not closed).** Between the probe and the + reclaim, a third actor could remove the stale path and a live daemon could + bind it. The window is one `remove_file` call wide and needs a third actor + to open it. It is a residual, not a claim of correctness. +- **Cancellation.** Unchanged: the CLI's readiness wait still yields + `ReadyFailure::Cancelled` when the shutdown token is cancelled + (`the_readiness_wait_is_cancelled_by_the_shutdown_token` passes), and the + bind guard adds no task and no timeout. +- **Daemon restart.** Covered: `the_binary_reclaims_the_path_of_a_killed_daemon` + (an unclean `SIGKILL` leaves the socket file; the next daemon reclaims it) + and the pre-existing `the_socket_is_removed_on_shutdown` (the clean case). +- **Contention and resource release.** A refused bind releases the socket it + did not take; the survivor's socket file and its 0600 mode are intact. +- **Malformed input.** The refusal's text is rendered from the error's + structured fields (`socket_path`, `protocol_version`), never from a + formatted string carried across a boundary. +- **Bounded behaviour.** The bind guard's probe uses the pre-flight's own + 5-second bound (`PREFLIGHT_PROBE_TIMEOUT`); no new task, no new timeout. + +## 7. Migration and compatibility review + +- **No schema migration.** Nothing is persisted; the daemon's store, its audit + records and its snapshots are untouched. +- **No wire change.** No `ClientCommand`, no `ServerMessage`, no field on + either. The `Capabilities` message's diff in the tree belongs to a + concurrent agent (milestone 013), not to this milestone. +- **No IPC command added.** The GUI's surface stays at 13; `daemon_status` + gained a field. +- **Configuration behaviour.** `DaemonConfig::default()` stays **pure** — it + returns the built-in default and does not read the environment. The two + launchers an operator uses both set the path explicitly from their resolved + flag. A third-party embedder that constructs `DaemonConfig::default()` + directly gets the built-in default; that asymmetry with + `GuiOptions::default()` is deliberate and documented in the code. +- **Behavioural change (the point of the milestone).** A start against a path + a live daemon is holding now **refuses** instead of displacing the live + daemon. For launchers outside this repository this is a behaviour change: + the start fails with an actionable message instead of silently stealing the + socket. +- **Rollback.** Reverting the bind guard restores the old displacement + behaviour; reverting the resolver restores the old literal defaults. There + is no persisted state to roll back. +- **The environment variable is new.** `EGGSEC_DAEMON_SOCKET` was previously + named only by `scripts/build-daemon-profile.sh`, which read it and fell back + to a literal. The binaries now honour it, so the script's line became true. + `EGGSEC_SOCKET` remains the rejected spelling. + +## 8. Security review + +- **Authorization.** Unchanged. The milestone touches no operation, no policy, + no scope rule and no dispatch path; `EnforcementContext::evaluate()` remains + the only pre-dispatch gate, and no surface's strictness changes. +- **The environment override is an operator control, not an escalation.** It + chooses *where* the daemon listens; it grants no access the operator could + not already reach, and the socket's 0600 permissions still gate who may + connect. A hostile value is a path the operator's own daemon cannot bind — + an ordinary startup failure, reported with its cause. `a_bind_failure_that_is_not_addr_in_use_leaves_the_path_alone` asserts that such a failure leaves the path alone. +- **Fail-closed.** The server never unlinks a path it has not proven stale. +- **No leak.** The refusal carries the path the operator supplied and the live + daemon's protocol version — facts the operator already has. It carries no + session, task or client identity. +- **Path validation.** The socket path is the operator's own; the resolver + trims it and treats an empty value as absent, so a daemon is never asked to + bind the empty path. +- **Denial of service.** A daemon that does not answer `Health` within the + probe's 5-second bound is treated as *not live*, and its path is reclaimed. + That is the recorded meaning of `DaemonLiveness::NotLive` and it is + unchanged; it is a residual, stated in §10. +- **Audit behaviour.** Unchanged. The refusal is a start-path failure, not a + session action; the daemon writes no audit record for it. +- **Ring-only TLS.** Unchanged; no transport code was touched. + +## 9. Documentation and operations + +- **ADR:** `plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md` + (new, `Status: proposed`). +- **Architecture documents:** deltas prepared for `architecture/desktop_gui.md` + (2 places) and `architecture/daemon.md` (2 places) — shared files, so the + exact markdown is in `/tmp/eggsec-guardwork/m012-docs-delta.md`. +- **Operator documentation:** deltas prepared for `docs/DAEMON.md` (3 places), + `docs/GUI_DISTRIBUTION_HANDOFF.md`, `docs/GUI_BUILD.md` (2 places) and + `docs/DAEMON_FEATURE_PROFILE.md` — shared files, same scratch delta. +- **Skills:** `.opencode/skills/eggsec-daemon/SKILL.md` edited directly (the + daemon's defaults and the precedence). The GUI skill's claim is in the + scratch delta (the file is shared with milestones 013 and 014). +- **Example:** `docs/python/examples/local_vs_daemon_execution.py` edited + directly — the hardcoded path became the environment override or an explicit + argument, and the example says where the default comes from. +- **Static guards:** the block for checks 177–179 is in + `/tmp/eggsec-guardwork/m012-guards.sh`, ready to be appended to + `scripts/check-architecture-guards.sh` (the shared script was **not** + edited). The registration entries for `docs/CI_ARCHITECTURE_GUARDS.md` are + in `/tmp/eggsec-guardwork/m012-guards-doc.md`. +- **Operator diagnostics.** The refusal names the path, the live daemon, its + protocol version and both remedies (stop the daemon, or use another path). + The build recipe's hint now prints `eggsec-daemon --full-executor` and, when + the environment variable is set, the operator's path. +- **Recovery instructions.** To start a daemon on another path: set + `EGGSEC_DAEMON_SOCKET`, or pass `--socket-path` (daemon binary) / + `--socket` (CLI and GUI). To reclaim a path left by a crashed daemon: stop + nothing — the next daemon reclaims it. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | **F1 — ADR-0013 is `Status: proposed`, not `accepted`.** The plan's §14 stop condition 1 says the plan is not executable until the ADR is accepted; acceptance is the maintainer's decision and is out of the implementer's control. The ADR was authored in the same format and with the same decision the plan states (the owning crate is `eggsec-runtime`; the variable is `EGGSEC_DAEMON_SOCKET`; the precedence is flag → environment → built-in default; the bind contract is bind-first with an actionable refusal), and the implementation follows that decision exactly. | The implementation is complete, but the milestone's ratification is outstanding. If the maintainer ratifies a *different* decision, this milestone's work must be revisited. | The maintainer reviews and ratifies `plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md`, then sets `Status: accepted`. | +| low | **F2 — two files outside the handoff's file-ownership list were edited.** The plan's §6.4 puts the refusal's error type in `crates/eggsec-daemon/src/error.rs` (`DaemonError` gains `SocketPathHeld` and `SocketPathTaken`), and no other planned milestone owns it (milestones 013–015 name `host.rs`, `server.rs`, `main.rs`, the protocol and the docs, never `error.rs`). The change is additive: two variants, one shared message helper, two unit tests. Separately, `docs/python/examples/local_vs_daemon_execution.py` hard-coded `/tmp/eggsec-daemon.sock` — a seventh copy of the default, outside the Rust surface the plan enumerated — so it was changed to read `EGGSEC_DAEMON_SOCKET` and to accept an explicit path, rather than duplicating the default the milestone moved into `eggsec-runtime`. | A reviewer expecting these files to be untouched may need to reconcile the handoff's list with the plan's §6.4 and with the milestone's own subject. | The owner decides whether to keep the edits (recommended — §6.4 requires the first, and the second is the same duplication the milestone exists to remove) or to move the error type elsewhere. | +| low | **F3 — the shared verification commands are red for reasons outside this change.** `cargo fmt --all -- --check` (one concurrent agent's file), `python3 scripts/check_doc_references.py` (30 pre-existing missing references), `cargo test -p eggsec-daemon --test daemon_start_honesty` and `cargo test -p eggsec-daemon --features service` (one assertion broken by a concurrent agent's `report_forms` addition), `cargo clippy -p eggsec-daemon --all-targets` (a concurrent agent's `host.rs` plus one **pre-existing** error in the unmodified `store/sqlite.rs`), `cargo clippy -p eggsec-gui --all-targets` (a concurrent agent's `tests/qualification.rs`), and `scripts/smoke-daemon-local.sh` (a pre-existing positional-argument bug at `:116`). | The owner cannot read this milestone's verification as wholly green until the concurrent agents land and the owner re-runs the contract. | The owner re-runs the shared commands after the concurrent agents finish; the smoke script's one-line patch is in `/tmp/eggsec-guardwork/m012-smoke-daemon-local-patch.md`. | +| low | **F4 — the reclamation window is one `remove_file` wide.** Between the liveness probe and the reclaim, a third actor could remove the stale path and a live daemon could bind it. | A daemon could be displaced in that window; it needs a third actor to open. | Accepted residual (the plan states it); a future milestone may close it with a different mechanism. | +| low | **F5 — a daemon that does not answer `Health` within 5 s is treated as *not live*.** `DaemonLiveness::NotLive` keeps its recorded meaning, so such a daemon's path is reclaimed and the daemon becomes unreachable. | A wedged daemon can be displaced. | Accepted residual (the plan states it); "proven dead" would be a new variant and a new ADR. | + +## 11. Roadmap disposition + +**Milestone closed and the next dependency may proceed**, with two +ratification items outstanding that do not block the next milestone: ADR-0013's +acceptance (F1) is the maintainer's decision and the implementation already +follows the ADR's stated decision, and the shared verification commands (F3) +must be re-run by the owner after the concurrent agents land. + +Concretely: the desktop-GUI frontend roadmap's gap 10 ("the socket-path +default is duplicated in six places" / "the server-side bind hardening is +deferred") is discharged by this milestone. The registry and the roadmap's +known-gap table and milestone-status rows are the session owner's to update +(`plans/registry.md`, +`plans/subsystems/desktop-gui-frontend-roadmap.md`). + +The counts that changed: the duplication count went from **six** production +sites to **one** owner, and the executable surface's occurrences of the +literal went from **nine** to **three** (all in the canonical crate). The +GUI's IPC command count did **not** change (13). No counted set — crates, +features, operations, aliases, tabs, task kinds, payloads, techniques, +endpoints, probes, descriptors — changed. + +## 12. Registry updates + +Required in `plans/registry.md`: + +- the milestone 012 entry: the implementation plan's status becomes + "implemented"; the closure record's path is + `plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md`; + the closure status is "closed" with findings F1–F5. + +Required in `plans/subsystems/desktop-gui-frontend-roadmap.md`: + +- the known-gap table: gap 10 (the socket-path default duplicated in six + places; the server-side bind hardening deferred) → closed by milestone 012, + with the new facts (one canonical owner in `eggsec-runtime`, the + `EGGSEC_DAEMON_SOCKET` override, the webview learning the path from Rust, + and the bind guard that refuses over a live daemon); +- the milestone-status row for 012: implemented, closure record present. + +Both files are the session owner's to edit and were **not** touched by this +milestone. diff --git a/plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md b/plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md new file mode 100644 index 000000000..afe697226 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md @@ -0,0 +1,606 @@ +# Desktop GUI Frontend Milestone 013 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/013-report-bridge-full-coverage.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md#7-milestones` + +Repository baseline reviewed: `0f5dbb26` + +Implementation commits: + +- `6de6340e` — feat(desktop-gui): implement the desktop GUI milestones 012 to 015 + +This milestone is **corrective**. It closes the two findings milestone 006 +left open in its closure record (§10.1 "the report bridge covers only the +families with a clean mapping" and §10.8 "the report bridge's `timestamp` +field is empty for four families"). It does **not** rewrite milestone 006's +plan or its closure record: those stay as they are, and §10 of the 006 record +remains the record of what was unresolved when 006 closed. + +## 1. Executive finding + +**The report bridge now covers every result variant the engine declares, and +it publishes what it cannot cover so the operator can see why.** + +The design has three parts: + +- **One table, one home.** `crates/eggsec/src/runtime_bridge/report_coverage.rs` + holds a row per canonical operation id — **28 rows** — and each row names + the `TaskResult` variants that operation produces, the verdict, and, for an + excluded operation, the fact its result is missing. The bridge consults it; + the engine publishes it; the daemon republishes it verbatim; the GUI renders + it. Nobody restates it. +- **The verdict is per operation, and the table says so.** A document needs an + identity (a target or an equivalent subject) and at least one content item + that maps onto the canonical model without a fact being invented. Eight + operations fail that test, and the table states the missing field for each. + A missing *timestamp* does not disqualify a variant — the bridge stays + clock-free and leaves the field empty — but a missing *identity* does. +- **The bridge cannot silently disagree with the table.** `report_for_operation` + asks the table first and the result second; a `Canonical` verdict whose + result has no arm is an internal error, logged at error level with the + operation id, never swallowed. Guard 180 makes that disagreement unreachable + in the source, and the log is the belt to that braces. + +The user-visible change is small and honest: the GUI's coverage table gains a +**report-form column**, and the export failure message names the reason the +daemon published for an operation having no report form — *"the daemon has no +report for task ``: ``"* — instead of only saying that there +is no report. + +**What this milestone did NOT do**, and why: it did not add a timestamp to the +four result types whose documents carry an empty one (that is a change to four +engine result types, their serializations and their downstream consumers), it +did not give the bridge a clock (that would contradict the module's purity +contract), and it did not change the daemon's `TaskNotFound` answer for a task +with no report (the error-code set is a published contract). Closure finding 8 +is therefore **restated as still open, and widened** — see §10, finding F1. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| §13.1 Every canonical operation id has exactly one coverage row; the table's ids are exactly the distinct ids of the canonical task-kind table (derived) | `report_coverage.rs` test `the_coverage_table_covers_every_canonical_operation` (derives the ids from `TaskKind::all_variants()`); guard 180's set comparison | **pass** | 28 rows, 28 distinct ids, no id under two rows | +| §13.2 Every variant with a clean mapping produces a document — 17 of the 35 variants, covering 18 task kinds | `report.rs` tests `an_endpoint_scan_reports_its_interesting_endpoints`, `a_graphql_report_names_its_vulnerabilities` (inside `the_new_documents_carry_no_timestamp`), `an_oauth_report_names_its_vulnerabilities` (same), `an_auth_report_carries_the_findings_own_severity` (same), `an_nse_report_carries_the_evidence_items_own_severity`, `a_hunt_report_carries_every_finding_collection`, `a_browser_report_carries_the_xss_and_client_findings`, `a_compliance_report_carries_the_failed_requirements_only`; guard 180's canonical-row/bridge-arm cross-check | **pass** | The eight new arms are behind their feature gates; the ones without a gate (`endpoint-scan`, `graphql`, `oauth`, `auth-test`) are compiled and tested in the `--features cli` run | +| §13.3 Every variant without one is named, with the missing fact stated — 18 variants across 12 task kinds, each with a non-empty reason | `report_coverage.rs` test `every_excluded_operation_names_the_missing_fact`; the table's own text (§3 below) | **pass** | 17 excluded variants + the terminal `Error`; every reason is non-empty and names an absence or a field | +| §13.4 The export path reports "no report available" and writes no artifact for a task with no report | `report.rs` test `an_excluded_operation_produces_no_document` (the `None` return); the GUI test `the_export_path_writes_no_file_for_a_task_with_no_report` (the error is raised before `export::render` and before `export::write_export`); the existing engine test `a_load_test_has_no_canonical_report_form` | **pass** | The behaviour was already correct at the baseline; this milestone supplies the regression evidence, as §3.6 of the plan required | +| §13.5 The operator can learn the reason: the coverage table states the verdict per published task kind, and the export failure names the reason when the GUI holds one | `coverage.rs` tests `a_coverage_row_carries_the_published_report_form`, `an_unpublished_coverage_is_unknown_not_unavailable`; `commands.rs` tests `the_export_message_names_the_reason_when_it_has_one`, `the_export_message_falls_back_when_it_cannot_resolve_one` | **pass** | The GUI names no operation id of its own: the join is by the published catalog's operation id | +| §13.6 The table has exactly one home; the daemon and the GUI restate none of it | Guard 180's "exactly one place" check; guard 161 re-run standalone (PASS) | **pass** | The daemon republishes the executor's rows verbatim; the GUI's `ReportFormVerdict` is a projection, not a table | +| §13.7 Guard 180 passes, and its four negative probes fail as required | §4.3 below (four mutations, four FAIL outputs) | **pass** | The guard block is at `/tmp/eggsec-guardwork/m013-guards.sh`; the owner merges it into `scripts/check-architecture-guards.sh` | +| §13.8 The canonical report model is unchanged: `ScanReportData` keeps its nine fields, and the eight new documents use them as they are | No change to `crates/eggsec-report-model`; the eight arms construct `ScanReportData` with the same nine fields | **pass** | `git diff --stat crates/eggsec-report-model` is empty for this milestone | +| §13.9 The bridge remains clock-free: the eight new documents carry an empty `timestamp`, and no new arm reads a clock | `report.rs` test `the_new_documents_carry_no_timestamp`; no `Utc::now()` / `SystemTime` in the eight arms | **pass** | The four pre-existing empty-timestamp families are unchanged | +| §13.10 No authorization decision changed, and the published coverage carries no target, no banner and no credential | The eight arms are pure functions over a result; `report_coverage.rs` contains no `EnforcementContext`, no `Scope`, no `ApprovedExecution`; the published DTO (`ReportFormEntry`) carries an operation id, a verdict and a reason only | **pass** | The gate consults a *static table*, not a policy decision | +| §13.11 `make check` is green except for the inherited `check-deps` advisory backlog | **not run** — `make check` is the session owner's integration step and it stops at `check-deps` | **not run** | `make check-deps` **was** run and is green at the measured state (§4.2) — see the note in §4.2 about the inherited backlog | +| §13.12 No new dependency, and no `deny.toml` exception | No `Cargo.toml` was edited by this milestone; `git diff --stat Cargo.lock deny.toml crates/*/Cargo.toml` shows only milestone 015's concurrent change | **pass** | `make check-deps` is green | +| §10.23 A daemon hosting the engine executor publishes the full coverage — one row per canonical operation id, derived from the canonical task-kind table | `crates/eggsec-daemon/tests/report_form_coverage.rs` test `a_daemon_hosting_the_engine_publishes_the_full_coverage` | **pass** | 28 rows; the ids are derived from `TaskKind::all_variants()`, and every excluded row carries a non-empty reason | +| §10.24 A daemon hosting a noop executor publishes `None` | `crates/eggsec-daemon/src/host.rs` test `capabilities_report_an_unpublished_report_coverage_as_unknown` | **pass** | `None` means unknown, not an empty list | +| §10.26 The export path writes no file for a task with no report | `crates/eggsec-gui/src/commands.rs` test `the_export_path_writes_no_file_for_a_task_with_no_report` | **pass** | a source-level assertion that the error precedes the render and the write | +| §10.31 The published coverage leaks nothing | `crates/eggsec-daemon/tests/report_form_coverage.rs` test `the_published_coverage_leaks_nothing` | **pass** | the reasons are lowercase prose about a result type's *shape*; no URL, no credential, no observed value | +| §10.32 The coverage grants no authorization | `crates/eggsec-daemon/tests/report_form_coverage.rs` test `the_coverage_grants_no_authorization`; §5's invariant review | **pass** | the coverage is published beside the task-kind list and changes neither it nor the runtime's admitted set | +| §10.34 The GUI still renders the report as data | guard 162 re-run standalone: `PASS: the GUI's report display carries no remote origin and no executable content.` | **pass** | the new Report column adds no markup sink | +| §10.36 A new daemon's capabilities decode in an old client | `crates/eggsec-daemon-protocol/src/protocol.rs` test `a_new_daemons_capabilities_decode_in_an_old_client` | **pass** | the field is additive; an old client ignores it | +| §13.13 The documentation in §12 states the new coverage, and the closure record carries §15's evidence | `docs/REPORT_EVIDENCE_MODEL.md`, `docs/DAEMON.md`, `architecture/daemon.md`, `architecture/runtime.md`, `architecture/overview.md`, `AGENTS.md` (this milestone); the three shared-doc deltas handed to the owner in `/tmp/eggsec-guardwork/` | **partial** | The six documents this milestone owns are updated. `docs/CI_ARCHITECTURE_GUARDS.md`, `.opencode/skills/eggsec-gui/SKILL.md` and `architecture/desktop_gui.md` are **shared** and were **not edited**; their deltas are written to `/tmp/eggsec-guardwork/m013-guards-doc.md`, `m013-skill.md` and `m013-desktop_gui.md` for the owner to merge | + +## 3. Production implementation evidence + +### 3.1 The coverage table as built + +**Method.** Re-measured from the landed source +(`crates/eggsec/src/runtime_bridge/report_coverage.rs`) with a +formatting-robust awk that accumulates a `variants:` array across lines (a +`rustfmt`-wrapped array reads as one row) and prints `verdict|variants` per +row; the variant names are then counted from that output. The enum's variants +were counted with `sed -n '/^pub enum TaskResult {/,/^}/p'` over +`crates/eggsec/src/dispatch/types.rs`. + +| Measure | Value | +|---|---| +| `TaskResult` variants declared by the engine | **35** | +| Coverage rows | **28** | +| Rows with a `Canonical` verdict | **17** (17 variants) | +| Rows with a `NoCleanMapping` verdict | **11** (17 variants) | +| Terminal result shapes named beside the rows | **1** (`Error`) | +| Distinct canonical operation ids (derived from `TaskKind::all_variants()`) | **28** | +| Total variants accounted for | **17 + 17 + 1 = 35** | + +The plan's arithmetic is confirmed against the source: the engine's result +type has **35** variants (not 30 — 30 is the `TaskKind` count), and they split +as 17 canonical + 17 excluded + 1 terminal. The 30 task kinds map to 28 +operation ids, of which 18 task kinds have a canonical verdict and 12 do not. + +The table is **build-independent**: it names all thirty-five variants, +feature-gated ones included, because the coverage is a statement about the +engine's result model rather than about one build of it. A build without the +`nse` feature compiles the same 28 rows but cannot reach the gated variants. + +### 3.2 The bridge's arms as built + +`crates/eggsec/src/runtime_bridge/report.rs` — `report_for_result` now has +**17** arms (`report.rs:69-98`), nine of them pre-existing and eight new: + +| # | Variant | Arm function | Document's fields | +|---|---|---|---| +| 1 | `PortScan` | `port_scan_report` (pre-existing) | target, open ports, services, duration | +| 2 | `Pipeline` | `pipeline_report` (pre-existing) | target, ports, services, findings, duration | +| 3 | `Fingerprint` | `fingerprint_report` (pre-existing) | target, services, duration | +| 4 | `Fuzz` | `fuzz_report` (pre-existing) | target, the session's vulnerable payloads | +| 5 | `Recon` | `recon_report` (pre-existing) | target, secrets, takeover candidates | +| 6 | `EndpointScan` | `endpoint_scan_report` (**new**) | target ← `base_url`; duration ← `duration_ms`; one finding per **interesting** endpoint: title ← the path, severity ← the class constant `info`, category ← `endpoint-discovery`, description ← the status line and any redirect, location ← the path | +| 7 | `GraphQl` | `graphql_report` (**new**) | target ← `target`; duration ← `duration_ms`; `depth_limit_bypassed` → `medium`/`graphql-depth-limit`; `alias_overload_vulnerable` → `medium`/`graphql-alias-overload`; each entry of `injection_findings` → `high`/`graphql-injection` | +| 8 | `OAuth` | `oauth_report` (**new**) | target ← `target`; duration ← `duration_ms`; `redirect_vulnerabilities` → `medium`/`oauth-redirect`; `scope_vulnerabilities` → `high`/`oauth-scope`; `state_vulnerabilities` → `medium`/`oauth-state`; `grant_vulnerabilities` → `high`/`oauth-grant` | +| 9 | `Auth` | `auth_report` (**new**) | target ← `target`; one finding per `findings` entry: title, description and recommendation are the finding's own; severity ← the finding's own `severity`; category ← `auth-`; location ← the target; remediation ← the finding's own recommendation | +| 10 | `Wireless` | `crate::wireless::to_scan_report_data` (pre-existing) | reused verbatim | +| 11 | `WirelessActive` | `crate::wireless::active::to_active_scan_report_data` (pre-existing) | reused verbatim | +| 12 | `DbPentest` | `crate::db_pentest::to_scan_report_data_db` (pre-existing) | reused verbatim | +| 13 | `C2` | `crate::c2::to_scan_report_data` (pre-existing) | reused verbatim | +| 14 | `Nse` | `nse_report` (**new**, `cfg(feature = "nse")`) | target ← `target`; one finding per `report.evidence` item: title ← the item's title, severity ← **the engine's own** `nse_bridge::evidence_kind_to_severity` (reused, not restated), category ← `nse-`, description ← the item's summary, evidence ← the raw excerpt, cwe_ids ← the item's references | +| 15 | `Hunt` | `hunt_report` (**new**, `cfg(feature = "advanced-hunting")`) | target ← `target`; one finding per entry of the five collections (`attack_chains`, `business_logic`, `race_conditions`, `authz_bypasses`, `session_issues`), each with its own severity; location ← the finding's own location where the type has one, otherwise the target | +| 16 | `Browser` | `browser_report` (**new**, `cfg(feature = "headless-browser")`) | target ← `target`; one finding per DOM XSS finding (`browser-dom-xss`) and per client-side issue (`browser-client-issue`), each with its own severity, description, location, evidence and remediation; the SPA routes are **not** findings | +| 17 | `Compliance` | `compliance_report` (**new**, `cfg(feature = "compliance")`) | target ← `target`; one finding per **failed** requirement (`status == ComplianceStatus::Fail`), with the requirement's own severity and description, category ← `compliance-`, remediation ← the requirement's own remediation; a passing or not-applicable requirement is not a finding | + +Every new document carries an **empty `timestamp`** and a `duration_ms` of `0` +where the result type has no duration field. The severity of a new finding is +either the finding's own (`Auth`, `Hunt`, `Browser`, `Compliance`) or a +**per-class constant** (`EndpointScan` → `info`; `GraphQl` → `medium`/`high`; +`OAuth` → `medium`/`high`) — never a value read from the target. + +### 3.3 The exclusion list with its reasons + +Each reason is traced to the result type's own fields: + +| Operation | Variants | The result type's fields | Why there is no clean mapping | +|---|---|---|---| +| `load-test` | `LoadTest` | `LoadTestResults { target_url, total_requests, successful_requests, failed_requests, total_duration_ms, requests_per_second, latency_*, status_codes, errors, error_kinds }` | carries only transport-error strings and a status-code count map; no finding with a severity, a title or a location | +| `stress-test` | `StressTest` | `StressStats { duration_ms, packets_sent, bytes_sent, errors }` | carries only counters; no finding, no port, no service | +| `waf-detect` | `WafDetection` | `WafDetectionResult { waf_name, confidence, request_error, matched_headers, matched_cookies, matched_patterns, server_header, status_code }` | **no target field**: the detection records the WAF's own facts, and the subject lives in the request | +| `waf-detect` | `WafBypass` | `WafBypass { detection, bypasses }` | **no target field**, and the bypasses are the WAF's own attempts | +| `waf-stress` | `WafStress` | `Vec`; `BypassResult { technique, success, description, payload, status_code, response_diff, error }` | a bare list of attempts with no subject and no duration | +| `packet-capture` | `PacketCapture` | `PacketCapture { packets_captured, output_file }` | **no interface and no target**; only a count and an output file | +| `packet` | `PacketTraceroute` | `PacketTraceroute { hops }`; `TracerouteHopResult` | **no target**: the hops carry no subject | +| `packet` | `PacketSend` | `PacketSend { packets_sent, bytes_sent }` | **no target**: two counters | +| `storage` | `Storage` | a unit variant | a bare acknowledgement | +| `storage` | `StorageListScans` | `StorageListScans { scans }` | a catalogue read, not a scan of one subject | +| `storage` | `StorageListFindings` | `StorageListFindings { findings }` | a catalogue read, not a scan of one subject | +| `integrations` | `Integrations` | a unit variant | a bare acknowledgement | +| `integrations` | `IntegrationsCreateIssue` | `IntegrationsCreateIssue { issue }`; `Issue { id, title, description, labels, severity, assignees, status, url, created_at }` | **no target**: an issue is not a fact about a scanned subject | +| `integrations` | `IntegrationsSearchIssues` | `IntegrationsSearchIssues { issues }` | a list of work items, with no target | +| `workflow` | `Workflow` | `WorkflowReport { total_findings, open_findings, in_progress_findings, resolved_findings, sla_violations, findings }` | **no target field**: a lifecycle view over stored findings | +| `vuln` | `Vuln` | `VulnAssessment { mode, assessed_at, cvss_score, exploit_info, asset_criticality, prioritized_findings, triage_results, remediation_plans, summary }` | **no target**, and the prioritized findings carry no location | +| `proxy-intercept` | `Intercept` | `InterceptSession { listen_addr, ca_fingerprint, dry_run, started_at, ended_at, target: Option, flows, manipulations, flow_actions, budget }` | the target is **optional** and absent whenever the session had none; the captured exchanges have no collection in the canonical model | +| *(terminal)* | `Error` | `Error(String)` | a task's *failure*, not an operation's result: a document would carry an empty target and no findings | + +### 3.4 The verdict of §3.6's four stages, at the landed baseline + +| Stage | Landed reference | What it does now | +|---|---|---| +| Bridge | `crates/eggsec/src/runtime_bridge/report.rs:69` (`report_for_result`), arms at `:71-97`; `:111` (`report_for_operation`) | the gate asks the table first; an excluded operation yields `None` **before** the result is inspected; a canonical operation with no arm logs at error level and yields `None` | +| Executor | `crates/eggsec/src/runtime_bridge/executor.rs:395-403` | `if let Some(report) = report_for_operation(&operation_id, &task_result)` → `reports.insert(task_id, document)`; nothing is inserted for a task with no report, so the store has **no entry** for it | +| Runtime | `crates/eggsec-runtime/src/runtime.rs:244` (`report_for`) | reads the executor's store; a task with no entry yields `None` | +| Daemon | `crates/eggsec-daemon/src/host.rs:754` | `None` → `ServerMessage::Error { code: ErrorCode::TaskNotFound, … }` | +| Client | `crates/eggsec-frontend-client/src/daemon.rs:274` | `TaskNotFound` → `Ok(None)` — a degradable state, not a failure | +| GUI export | `crates/eggsec-gui/src/commands.rs:702-737` | `Ok(None)` → `Err("the daemon has no report for task ``: ``")`, or the plain wording when no reason can be resolved. The error is raised **before** `export::render` and `export::write_export`, so **no file is written** | +| GUI view | `crates/eggsec-gui/src/commands.rs:833` | `Ok(None)` → `Err("the daemon has no report for task ``, so there is nothing to show")` — unchanged by this milestone | + +### 3.5 The publication path + +| Stage | Landed reference | What happens | +|---|---|---| +| Table | `crates/eggsec/src/runtime_bridge/report_coverage.rs:78` | `REPORT_COVERAGE` — 28 rows, the single home | +| Engine | `crates/eggsec/src/runtime_bridge/executor.rs:181-196` | `report_forms()` projects each row into `eggsec_runtime::report::ReportFormEntry` — the operation id, the verdict, the reason. Nothing is restated | +| Runtime | `crates/eggsec-runtime/src/runtime.rs:122` (trait), `:198` (capture at construction), `:235` (accessor) | the coverage is captured once, at construction, and never changes | +| Daemon | `crates/eggsec-daemon/src/host.rs:180`/`:212`/`:253` (capture), `:524` (publication) | the daemon republishes the executor's rows **verbatim** in `DaemonCapabilities.report_forms` | +| Protocol | `crates/eggsec-daemon-protocol/src/protocol.rs:93` | `report_forms: Option>` with `#[serde(default)]`; the protocol version stays **2** | +| GUI | `crates/eggsec-gui/src/coverage.rs` (`ReportFormVerdict`, `resolve_report_form`) and `crates/eggsec-gui/src/commands.rs:660-676` | the row carries the verdict and the reason; the export message names the reason | +| Frontend | `crates/eggsec-gui/frontend/app.js:324` (the column header), `:332-357` (the cell) | the coverage table gains a **Report** column, rendered from the data the daemon published | + +### 3.6 The `None`-means-unknown evidence, on both sides + +| Side | Evidence | +|---|---| +| The daemon publishes it | `crates/eggsec-daemon/src/host.rs` test `capabilities_publish_the_executor_report_coverage` — an executor that publishes two rows has them republished row for row, with the verdict and the reason intact | +| The daemon publishes **nothing** | `crates/eggsec-daemon/src/host.rs` test `capabilities_report_an_unpublished_report_coverage_as_unknown` — an executor that publishes nothing leaves `report_forms` as `None`, which means *unknown*, not "no operation has a report form" | +| The wire | `crates/eggsec-daemon-protocol/src/protocol.rs` test `daemon_capabilities_decode_without_the_report_forms_field` — a daemon too old to publish the field decodes as `None`; the field is `#[serde(default)]`, so the protocol version stays 2 | +| The GUI | `crates/eggsec-gui/src/coverage.rs` test `an_unpublished_coverage_is_unknown_not_unavailable` — an unpublished coverage, and a coverage that does not mention the operation, both read `Unknown` with an **empty** reason: the GUI states no reason it was not given | +| The runtime | `crates/eggsec-runtime/src/runtime.rs` test `the_default_executor_publishes_no_coverage` — the trait's default is `None`, so an executor that says nothing about report forms is not saying that no operation has one | + +### 3.7 The timestamp position, restated + +| Semantics | Families | +|---|---| +| the scan's own start time | `pipeline` | +| the report's own `timestamp` field | `c2`, `db-pentest` | +| the report-generation time (a clock read) | `wireless`, `wireless-active` | +| empty (no clock read) | `port-scan`, `fingerprint`, `fuzz`, `recon`, and the **eight new** families | + +Closure finding 8 is **restated as covering twelve variants rather than four**, +and it **remains open** — see §10, finding F1. + +### 3.8 Deviations from the plan, and why + +1. **Four files outside the file-ownership list had to be edited.** The + plan's §6.4 mandates a DTO in `crates/eggsec-runtime/src/report.rs`, the + `RuntimeTaskExecutor::report_forms()` method in + `crates/eggsec-runtime/src/runtime.rs`, the `DaemonCapabilities` field in + `crates/eggsec-daemon-protocol/src/protocol.rs`, and the executor's + implementation and call site in + `crates/eggsec/src/runtime_bridge/executor.rs`. None of them is in another + milestone's scope (012 is the daemon's socket path, 014 the GUI's + qualification driver, 015 the dependency advisories), and without them the + milestone cannot work at all. Two further one-line edits were forced by + the same change: `crates/eggsec-cli/src/daemon_cli.rs` (a + `DaemonCapabilities` literal that the new field breaks) and + `crates/eggsec/src/nse_bridge.rs` (`evidence_kind_to_severity` from + `fn` to `pub(crate)`, so the NSE arm **reuses** the engine's one severity + mapping instead of restating it — a parallel table would have been a + second source of truth). +2. **The coverage table is build-independent; the enum's variants are not.** + Four variants are behind cargo features, so a build without them has + fewer `TaskResult` variants than the table names. The plan's arithmetic is + a statement about the *engine's* result model, so the table names all + thirty-five variants in every build, and the Rust test checks the + build-level subset plus the count of 35 while **guard 180** does the + source-level set equality (it reads the declarations, so it sees the + feature gates the compiler hides from a build). +3. **`ReportForm` is the runtime's wire DTO, reused by the engine** rather + than a second engine-local enum. The plan's §6.1 named a `ReportForm` + without saying which crate owns it; one enum, projected by the executor, is + the smaller surface and avoids a second vocabulary for the same verdict. + `ReportCoverageRow` stays engine-local: the runtime carries only the + projected `ReportFormEntry`. +4. **The variant vocabulary is generated by a macro with an exhaustive match** + (`declare_result_variants!` in `report_coverage.rs`) rather than + transcribed. The match is exhaustive, so a new `TaskResult` variant breaks + the build in the coverage module until it is named — the compile-time + half of guard 180's first property. +5. **One hunt finding carries no remediation.** `RaceCondition.remediation` + is a private field of `hunt::race`, so the race-condition finding carries + `remediation: None` while the other four hunt collections carry their own. + Reaching it would have meant widening a domain type's visibility, which + is outside this milestone. +6. **Six of §10's integration rows were not implemented** — see §10, finding + F5. + +## 4. Verification executed + +### 4.1 Commands run + +```bash +cargo fmt --all --check +rustfmt --edition 2021 crates/eggsec-daemon-protocol/src/protocol.rs \ + crates/eggsec-daemon/src/host.rs crates/eggsec-gui/src/coverage.rs \ + crates/eggsec-runtime/src/report.rs crates/eggsec/src/runtime_bridge/executor.rs \ + crates/eggsec/src/runtime_bridge/report.rs crates/eggsec/src/runtime_bridge/report_coverage.rs +cargo clippy -p eggsec --features cli -- -D warnings +cargo clippy -p eggsec-runtime -p eggsec-daemon-protocol -p eggsec-daemon -- -D warnings +cargo clippy -p eggsec-gui --features shell -- -D warnings +cargo check --workspace --no-default-features +cargo check -p eggsec --all-targets --no-default-features +cargo check -p eggsec --features cli +cargo check -p eggsec-daemon --features service +cargo test -p eggsec --lib --features cli +cargo test -p eggsec-runtime --lib +cargo test -p eggsec-daemon-protocol --lib +cargo test -p eggsec-daemon --lib +cargo test -p eggsec-daemon --features service --test report_form_coverage +cargo test -p eggsec-gui --lib --features shell +cargo test -p eggsec-frontend-client --lib +cargo test -p eggsec-output --tests +cargo test -p eggsec-report-model --tests +python3 scripts/check_doc_references.py +make check-deps +bash /tmp/eggsec-guardwork/m013-guard-standalone.sh # the guard block, run standalone +bash /tmp/eggsec-guardwork/m013-guard161.sh # guard 161, re-run standalone +bash /tmp/eggsec-guardwork/m013-guard162.sh # guard 162, re-run standalone +node --check crates/eggsec-gui/frontend/app.js +``` + +### 4.2 Results + +| Command | Exit | Observed | +|---|---|---| +| `cargo fmt --all --check` | **1** | The files this milestone owns are clean. The remaining diffs are in **other milestones' files** in this tree — `crates/eggsec-daemon/src/server.rs`, `crates/eggsec-gui/tests/qualification.rs`, `crates/eggsec-runtime/src/daemon_endpoint.rs` (the last measured run; the set changes as the concurrent milestones format their own files). All are pre-existing or concurrent, and none is in this milestone's scope | +| `cargo clippy -p eggsec --features cli -- -D warnings` | 0 | clean | +| `cargo clippy -p eggsec-runtime -p eggsec-daemon-protocol -p eggsec-daemon -- -D warnings` | 0 | clean | +| `cargo clippy -p eggsec-gui --features shell -- -D warnings` | 0 | clean | +| `cargo check --workspace --no-default-features` | 0 | clean | +| `cargo check -p eggsec --all-targets --no-default-features` | 0 | clean (pre-existing warnings in the engine's own test targets) | +| `cargo check -p eggsec --features cli` | 0 | clean | +| `cargo check -p eggsec-daemon --features service` | 0 | clean; the engine's 11 warnings under this feature set are pre-existing (`crates/eggsec/src/packet/parse_impl.rs`, `crates/eggsec/src/stress/warning.rs`, `crates/eggsec/src/dispatch/canonical_execution.rs` — none is in this milestone's scope) | +| `cargo test -p eggsec --lib --features cli` | 0 | **1417 passed, 0 failed** | +| `cargo test -p eggsec-runtime --lib` | 0 | **118 passed, 0 failed** | +| `cargo test -p eggsec-daemon-protocol --lib` | 0 | **92 passed, 0 failed** | +| `cargo test -p eggsec-daemon --lib` | 0 | **110 passed, 0 failed** | +| `cargo test -p eggsec-daemon --features service --test report_form_coverage` | 0 | **3 passed, 0 failed** — the new integration file (`crates/eggsec-daemon/tests/report_form_coverage.rs`), gated on the `service` feature because a daemon without the profile links no engine and has no coverage to publish | +| `cargo test -p eggsec-gui --lib --features shell` | 0 | **92 passed, 0 failed** | +| `cargo test -p eggsec-frontend-client --lib` | 0 | **15 passed, 0 failed** | +| `cargo test -p eggsec-output --tests` | 0 | **92 passed, 0 failed** (73 + 7 + 12 across the three test binaries) | +| `cargo test -p eggsec-report-model --tests` | 0 | **11 passed, 0 failed** (0 + 11 across the two test binaries) | +| `python3 scripts/check_doc_references.py` | 1 | **30 missing references — all pre-existing.** They are in `architecture/capability_segregation.md`, `architecture/fuzzer.md`, `architecture/knowledge_corpus.md`, `architecture/network_dependency_baseline.md`, `architecture/nse_capability_inventory.md`, `architecture/nse_integration.md`, `architecture/overview.md` (`tests/fuzzer_payload_corpus_seam.rs`, which the reference at `HEAD` already carried), `architecture/proxy.md`, `architecture/transport_eggfetch.md`, `docs/CAPABILITIES.md`, `docs/CI_ARCHITECTURE_GUARDS.md`, `docs/NSE_COMPATIBILITY.md`, `docs/evidence/gui-qualification/macos-2026-10-24.md`. **None** of the 30 is a reference this milestone added: every path this milestone's documentation introduces (`crates/eggsec/src/runtime_bridge/report_coverage.rs`, `crates/eggsec-runtime/src/report.rs`) resolves | +| `make check-deps` | 0 | `advisories ok`, `bans ok`, `licenses ok`, `sources ok`. **Note on the inherited backlog:** the plan expected this check to fail on an inherited advisory backlog that milestone 015 owns. At the measured state of this tree the backlog is already closed — `deny.toml` and `Cargo.lock` carry **milestone 015's** concurrent change, not this milestone's — so the four sub-checks are green. This milestone added **no dependency** and made **no** `deny.toml` change; the baseline (pre-015) advisory failure was therefore not re-measured, because re-measuring it would require reverting another milestone's work | +| the guard block, standalone | 0 | `PASS: the coverage table accounts for every result variant the engine declares.` / `PASS: the report bridge's coverage table and its arms agree.` | +| guard 161, standalone | 0 | `PASS: the GUI's coverage model is derived, not transcribed.` — the GUI still names no operation id and no capability name | +| guard 162, standalone | 0 | `PASS: the GUI's report display carries no remote origin and no executable content.` — the new Report column adds no markup sink | +| `node --check crates/eggsec-gui/frontend/app.js` | 0 | the frontend parses | + +`make check` was **not run** — it is the session owner's integration step, and +the plan records that it stops at `check-deps`. + +### 4.3 Guard 180's four negative probes + +Each probe broke the tree, ran the guard, and **restored the tree from a `cp` +backup** (never `git checkout --`). The backups were +`/tmp/eggsec-guardwork/backups/report_coverage.rs.bak2` and +`report.rs.bak2`. + +**Probe 1 — a coverage row removed.** The `c2` row was deleted from +`REPORT_COVERAGE`: + +``` +--- Check 180: the report bridge's coverage table and its arms agree --- +FAIL: the coverage table and the engine's result variants disagree. + only in the result type: + C2 + only in the coverage table: +FAIL: the bridge has a TaskResult::C2 arm, but the coverage table does not call it canonical. +FAIL=1 +``` + +**Probe 2 — the bridge and the table disagree.** The `c2` row's verdict was +flipped from `Canonical` to `NoCleanMapping`, leaving the bridge's arm alone: + +``` +--- Check 180: the report bridge's coverage table and its arms agree --- +PASS: the coverage table accounts for every result variant the engine declares. +FAIL: the bridge has a TaskResult::C2 arm, but the coverage table does not call it canonical. +FAIL: the bridge has a TaskResult::C2 arm, but the coverage table excludes that variant. +FAIL=1 +``` + +**Probe 3 — a second copy of the table.** `report_coverage_copy.rs` was written +next to the original: + +``` +--- Check 180: the report bridge's coverage table and its arms agree --- +PASS: the coverage table accounts for every result variant the engine declares. +FAIL: the report coverage table must live in exactly one place; found: crates/eggsec/src/runtime_bridge/report_coverage.rs crates/eggsec/src/runtime_bridge/report_coverage_copy.rs +FAIL=1 +``` + +**Probe 4 — a canonical variant with no bridge arm.** The +`TaskResult::C2` arm was removed from `report_for_result`: + +``` +--- Check 180: the report bridge's coverage table and its arms agree --- +PASS: the coverage table accounts for every result variant the engine declares. +FAIL: the coverage table calls 'C2' canonical, but the bridge has no TaskResult::C2 arm. +FAIL=1 +``` + +After the fourth probe the tree was restored and the guard reported: + +``` +--- Check 180: the report bridge's coverage table and its arms agree --- +PASS: the coverage table accounts for every result variant the engine declares. +PASS: the report bridge's coverage table and its arms agree. +FAIL=0 +``` + +**A fifth, unplanned probe was needed and found.** The first version of the +guard extracted the `variants:` arrays with a single-line pattern. `rustfmt` +breaks a long array across lines, so after the table was formatted the +`integrations` row's three variants were no longer on one line — and the +guard reported a *false* failure: + +``` +FAIL: the coverage table and the engine's result variants disagree. + only in the result type: + Integrations + IntegrationsCreateIssue + IntegrationsSearchIssues +``` + +The guard's extractions are now multiline-aware (`rg -U`, and an awk that +accumulates across lines), so a reformatted table reads as the same table. +The lesson is recorded here because the next maintainer will hit it: **a +guard that reads formatted source must read it the way `rustfmt` writes it.** + + + +### Integration verification (2026-10-24, session owner) + +The milestone's own commands were run in isolation; the owner's integration +step then ran the repository's mandatory contract over the whole tree, with +all four milestones landed together. + +| Command | Result | +|---|---| +| `make check` | **exit 0** — `cargo fmt --all --check`, the no-default-features and per-crate checks, `cargo deny --workspace --all-features check` (all five sub-checks), clippy, the full test suite (**4315 tests across 77 test binaries, 0 failures**), and `scripts/check-architecture-guards.sh` (**190 guards, "ALL PASSED: No architecture drift detected"**) | +| `make check-msrv` | **exit 0** — all five steps green on Rust 1.89 | +| `python3 scripts/check_doc_references.py` | 29 missing references — the unchanged pre-existing baseline, none of them in a file this milestone touched | + +This is the **first time `make check` has completed on this branch**: it had +always stopped at the inherited `check-deps` advisory backlog, which milestone +015 cleared. Three integration tests that milestone 010 had left stale were +found by that first complete run and corrected in `dcfcd4e2`; the corrections +are recorded as a dated addendum on milestone 010's closure record rather +than by rewriting it. + +## 5. Invariant review + +| Invariant | Evidence | Result | +|---|---|---| +| `EnforcementContext::evaluate()` is the only pre-dispatch gate; no authorization decision changed | The eight new arms are pure functions over a `TaskResult`; the coverage gate consults a *static table*, not a policy. `report_coverage.rs` contains no `EnforcementContext`, `Scope`, `ApprovedExecution`, `OperationMetadata` or policy import | **unchanged** | +| Strict surfaces fail closed | The milestone adds no dispatch path. The engine executor's dispatch is unchanged; only the *report derivation* after a task completed changed | **unchanged** | +| `OperationMetadata` is the single source of truth for operation policy | No inline policy check was added; the coverage table is about *report forms*, not policy | **unchanged** | +| One canonical source per fact | The coverage table lives in exactly one file (guard 180's third check); the engine publishes it; the daemon republishes it verbatim; the GUI derives its column from the published rows | **met** | +| Never `let _ =`, never `filter_map(\|e\| e.ok())`; log via `tracing` | The gate logs with `tracing::error!` (disagreement) and `tracing::debug!` (an excluded operation); no swallowed error was introduced | **met** | +| Ring-only TLS, no new TLS stack | No TLS code was touched | **unchanged** | +| Spawned tokio tasks need a 30–300 s timeout wrapper | No task was spawned | **unchanged** | +| Workspace Tokio baseline; DTO crates carry no Tokio | `eggsec-runtime` gained no Tokio usage: the coverage DTO is plain data, and the runtime's capture is synchronous at construction | **met** | +| The GUI links no engine/daemon/CLI/TUI crate (guard 155) | The GUI's new code touches only `eggsec-runtime::report` and `eggsec-daemon-protocol`'s published capabilities | **unchanged** | +| New architecture guards start at 177; **180 is this milestone's** | The guard block is written for check 180 only (`/tmp/eggsec-guardwork/m013-guards.sh`); no other number is used | **met** | +| The bridge stays pure and clock-free | No `Utc::now()`, `SystemTime` or clock read in the eight new arms; the new documents carry an empty `timestamp` (test `the_new_documents_carry_no_timestamp`) | **met** | +| The `OperationDescription` gains no field, and the protocol version does not change | `DaemonCapabilities` gained one **additive, defaulted** field; `DAEMON_PROTOCOL_VERSION` stays 2; `OperationDescription` is untouched | **met** | +| The canonical report model is unchanged | `crates/eggsec-report-model` was not edited; `ScanReportData` keeps its nine fields | **met** | + +## 6. Failure and recovery review + +| Situation | Behaviour | Evidence | +|---|---|---| +| A task with no report form | The bridge yields `None`; the executor inserts nothing; the daemon answers `TaskNotFound`; the client degrades to `Ok(None)`; the GUI says "no report" and **writes no file** | §3.4; `an_excluded_operation_produces_no_document` | +| A bridge/table disagreement | An internal error: logged at `error` level with the operation id, `None` returned, the task completes normally and has no report. Guard 180 makes it unreachable in the source | `a_canonical_operation_with_no_bridge_arm_is_loud`; guard probe 2 and probe 4 | +| A result that cannot be serialized | Unchanged: the executor logs `tracing::warn!` and inserts nothing; the task succeeds and the report does not exist | `crates/eggsec/src/runtime_bridge/executor.rs:395-400` | +| Cancellation | Unchanged: the report is derived *after* `race_with_cancel` resolves, so a cancelled task produces no result and no report. No new task, no new timeout, no detached work | `crates/eggsec/src/runtime_bridge/executor.rs` | +| Restart | The coverage table is a compile-time constant and survives a restart unchanged; the *store* does not, so a restarted daemon's reports are gone (unchanged). The **published coverage** is re-published by the new process, so the GUI's coverage table is correct immediately after a reconnect | the coverage is captured at construction and is immutable | +| Contention | The store's lock is unchanged (`std::sync::Mutex`, a map operation, never held across an await). The coverage is read once per `Capabilities` request and never changes, so it introduces no contention | `crates/eggsec-runtime/src/report.rs` | +| A daemon that publishes no coverage | The GUI says *unknown*, never "unavailable" | §3.6 | +| A daemon too old to publish the coverage | The field is `#[serde(default)]`, so it decodes as `None` and the GUI says *unknown* | `daemon_capabilities_decode_without_the_report_forms_field` | +| Duplicate delivery and idempotency | Unchanged: the coverage is a constant; the report store is keyed by task id and re-inserting a task replaces its document | +| Malformed or unauthorized input | Unchanged: the coverage is not an input path. The GUI's export still validates the task id and the format before anything else | + +## 7. Migration and compatibility review + +- **The wire is additive and defaulted.** `DaemonCapabilities.report_forms: + Option>` with `#[serde(default)]`. An old client + ignores an unknown field; an old daemon's message decodes with `None` in a + new client. `DAEMON_PROTOCOL_VERSION` stays **2**, the same treatment + `enabled_features` received. +- **The GUI against an old daemon.** The report-form column reads *unknown*, + and the export message keeps its plain wording when no reason is published. + The GUI never shows a report-form verdict it was not told. +- **The daemon against an old engine.** Not a combination the daemon can + produce: the daemon links the engine or it does not. A daemon built with + the `service` feature publishes twenty-eight rows; one without it publishes + `None`. +- **`OperationDescription` is untouched.** No catalog consumer sees a new field. +- **The stored documents are unchanged in shape.** `ScanReportData` keeps its + nine fields; the eight new variants produce documents of the same shape, so + every renderer and consumer reads them unchanged. +- **No stored data migrates.** The coverage table is not persisted; the report + store holds documents only, and it is bounded and in-memory. +- **Removal criteria.** None: nothing is deprecated or removed. If the + canonical task-kind table grows a variant, the coverage table must grow a + row in the same change — that is guard 180's first property. + +## 8. Security review + +- **Authorization.** Unchanged. The milestone adds no dispatch path and makes + no authorization decision. The coverage gate reads a static table; it cannot + permit anything the enforcement kernel would refuse. +- **Scope.** Unchanged. No scope check was added, removed or weakened. +- **The published coverage carries no target, no banner and no credential.** + `ReportFormEntry` holds an operation id, a verdict and a reason sentence. + The reasons are written by the engine from the *shape* of the result types + (which field is missing), not from any observed value: none of them names a + host, a URL, a banner, a credential or a finding title. This is the + "published coverage carries no target" acceptance criterion, and it is the + reason the reasons are hand-written sentences rather than derived strings. +- **The GUI names no operation id.** The GUI joins the published coverage to + its rows by the published catalog's operation id, so it holds no table of its + own (guard 161 re-verified: PASS). +- **Path validation.** Unchanged: the export path's destination validation and + backup discipline are untouched. +- **Privilege boundaries.** Unchanged: the GUI remains daemon-only and links + no engine crate. +- **Denial-of-service bounds.** Unchanged: the report store's bound of 64 is + untouched, and the coverage table is a compile-time constant with no + runtime cost. +- **Audit behaviour.** Unchanged: the milestone adds no command and no + authorisation, so no audit record is required. The exclusion reason is + published as *build* information, not as an audit event. + +## 9. Documentation and operations + +**Updated by this milestone** + +| File | What changed | +|---|---| +| `docs/REPORT_EVIDENCE_MODEL.md` | the report read path's "Produce" row now names `report_for_operation`; a new "The report coverage table" section states the 28 rows, the 17/17/1 arithmetic, the exclusion list with its reasons, the clean-mapping criterion, and the publication path; a new "The `timestamp` semantics" section states the three semantics and the empty case | +| `docs/DAEMON.md` | a new "The published report-form coverage" subsection under **Capabilities**, stating the verbatim republication and the `None`-means-unknown rule | +| `architecture/daemon.md` | the `DaemonCapabilities` field table gains `report_forms`; the report path gains the coverage-table paragraph and the corrected `file:line` references | +| `architecture/runtime.md` | the module table, the `RuntimeTaskExecutor` method table and the public-API table gain the coverage DTO and `report_forms()`; a new "The coverage DTO" subsection corrects the "no domain types" claim so it is true | +| `architecture/overview.md` | the guard list gains the Check 180 line | +| `AGENTS.md` | the dispatch/scope section gains the one-line statement that the coverage table is the single source of truth | + +**Shared documents — deltas handed to the owner, not applied** + +| File | Delta | +|---|---| +| `docs/CI_ARCHITECTURE_GUARDS.md` | `/tmp/eggsec-guardwork/m013-guards-doc.md` — a new "Report-Bridge Coverage Invariants" section registering Check 180 | +| `.opencode/skills/eggsec-gui/SKILL.md` | `/tmp/eggsec-guardwork/m013-skill.md` — the "Enforced by" guard range, a new "The report-form column" subsection, and the reason-bearing export message | +| `architecture/desktop_gui.md` | `/tmp/eggsec-guardwork/m013-desktop_gui.md` — the module table, a new "The report-form column" subsection, and a new "'No report' says why" subsection | + +**Static guard** + +- Check 180 lives in `/tmp/eggsec-guardwork/m013-guards.sh`, written to be + appended to `scripts/check-architecture-guards.sh`. It was verified + standalone against the tree (PASS) and against four mutations (four FAILs, + §4.3). The owner merges it; milestone 013 does not edit the shared script. + +**Operator diagnostics** + +- A task with no report now names the reason: *"the daemon has no report for + task ``: ``"*. The reason is the engine's statement about the + operation's result type, so it is stable across runs. +- The GUI's coverage table gains a **Report** column whose values are + `available`, `unavailable` or `unknown`. +- The engine logs at `error` level if the bridge and the table ever disagree. + +**Recovery instructions** + +None: the milestone adds no persisted state, no migration and no operator +action. A daemon restart re-publishes the coverage unchanged. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| **medium** | **F1 — closure finding 8 (the empty `timestamp`), restated and widened.** Milestone 006's closure record §10.8 recorded that four families' documents carry an empty `timestamp`: `port-scan`, `fingerprint`, `fuzz` and `recon`. This milestone adds **eight** more families in the same state — `endpoint-scan`, `graphql`, `oauth`, `auth-test`, `nse`, `hunt`, `browser` and `compliance` — so the gap now covers **twelve** of the thirty-five variants. **It remains open.** The reason it was not closed here is the plan's: none of the twelve result types carries a timestamp of its own (`PortScanResults`, `FingerprintResults`, `FuzzSession`, `FullReconResult` and the eight new ones have no such field), so closing it requires either **adding a timestamp to twelve engine result types** — with their serializations and their downstream consumers (TUI, Python bindings, the CLI) — or **giving the bridge a clock**, which would contradict the module's purity contract (`report.rs:9-19`). Neither is a mapping. The eight new variants were therefore given an empty `timestamp`, matching the majority precedent and keeping the bridge clock-free | twelve of thirty-five report documents carry no timestamp; a renderer that sorts by time sees them first, and an operator cannot tell when a scan ran | Two ways to close it, both outside a mapping milestone: (a) add a `timestamp` field to the twelve result types and fill it at production time, or (b) give the bridge an injected clock and a purity contract that permits a time read. Whichever is chosen must be one decision for all twelve, and the coverage table's timestamp semantics must then state which of the four semantics each family carries | +| **low** | **F2 — the guard reads formatted source.** Guard 180 extracts the `variants:` arrays and the verdict fields from the coverage module's text. The first version used single-line patterns and produced a **false failure** after `rustfmt` wrapped the `integrations` row (§4.3). The extraction is now multiline-aware, but the same class of risk exists for any future reformat of the table | a false guard failure (noise), not a false pass | when the table's shape changes, re-run the guard standalone and check that a reformat alone does not move it | +| **low** | **F3 — the coverage table's variant count is asserted twice.** The Rust test asserts the union is 35 and the guard compares the enum's declarations with the table's names as **sets**. A deliberate new variant must therefore touch the enum, the table **and** the test's count — three places. That is the plan's intent ("the coverage table must grow a row in the same change"), but the count is a second thing to remember | a new variant fails the build in a place that is not the table | none; keep the count in the test next to the table it describes | +| **low** | **F5 — six of the plan's integration rows were not implemented.** §10's rows 25, 27, 28, 29, 30 and 37 — the end-to-end report read over a real Unix socket, the two daemon-restart rows, the cancellation row, the concurrent-readers row and the stored-document-shape row — need a live daemon socket, a restart harness or a second build, none of which this milestone's scoped verification provides. The behaviour they would exercise is **unchanged** by this milestone (the report read path, the store's bound and the cancellation ordering are untouched), and the nearest existing evidence is green: the daemon's 110 unit tests, the client's 15, the output renderers' 92, and the new `report_form_coverage` integration file's 3 | those six rows carry no milestone-013-specific evidence | the GUI qualification driver (milestone 014) supplies the live-daemon harness; the rows should be executed there, where a running daemon already exists | +| **low** | **F4 — the GUI's reason-bearing export message is not covered by an end-to-end test.** The pure half (`report_reason_for_variant`) is unit-tested, and the async half (resolving the task's variant from the GUI's registry) is not, because it needs a live daemon. The message therefore rests on the unit test plus the manual path | a regression in the variant→operation lookup would show up as the plain message, not as a wrong reason | an integration test against a live daemon, when the GUI's qualification driver (milestone 014) provides one | + +## 11. Roadmap disposition + +**Milestone closed and next dependency may proceed.** + +Gap 11 of the desktop GUI frontend roadmap — "the report bridge covers only the +families with a clean mapping" — is **closed** by this milestone: the bridge +now has an arm for all seventeen variants that have a clean mapping (nine +pre-existing, eight new), the eighteen variants that do not are **named** with +the fact they are missing, and the reason reaches the operator through the +published coverage, the GUI's coverage table and the export message. + +Closure finding 8 (the empty `timestamp`) is **restated, widened to twelve +variants, and left open** — see §10, finding F1. It is the only substantive +residual, and it needs a decision that is not a mapping. + +The roadmap's own file (`plans/subsystems/desktop-gui-frontend-roadmap.md`) +and `plans/registry.md` are the plan owner's to update; this milestone edits +neither. + +## 12. Registry updates + +Required in `plans/registry.md` (the session owner's edit): + +- Register milestone 013 as **closed**, with this closure record as its + evidence. +- The milestone's headline: the report bridge gained a full-coverage table + (17 canonical variants across 18 task kinds; 18 variants excluded with a + reason each), the coverage is published by the engine, republished by the + daemon and rendered by the GUI, and the operator can learn **why** a task has + no report. + +Required in `plans/subsystems/desktop-gui-frontend-roadmap.md` (the session +owner's edit): + +- Close gap 11 and name what closed it: this milestone and this closure + record. +- Note that closure finding 8 remains open and now covers twelve variants. diff --git a/plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md b/plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md new file mode 100644 index 000000000..d53886719 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md @@ -0,0 +1,599 @@ +# Desktop GUI Frontend Milestone 014 — Closure Status + +Status: conditionally closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/014-gui-qualification-driver-and-runbook.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md#milestone-14--the-guis-qualification-driver-and-runbook` + +Repository baseline reviewed: `0f5dbb26e7ab215613e5b6e2295d9c124374bf9f` + +Implementation commits or pull requests: + +- `6de6340e` — feat(desktop-gui): implement the desktop GUI milestones 012 to 015 + +## 1. Executive finding + +**The qualification procedure, the assertion harness, the promotion-rule +validator, and the nine static guards all landed, and the matrix's behavioural +and export cells are now *promotable*.** The milestone's own outcome — which +the plan explicitly permits — is that **no behavioural cell was promoted**, +because promoting one requires an **operator attestation** that no run in this +environment could supply, and because the Linux row has no recorded run at all. + +What changed, concretely: + +- The matrix's **root causes were corrected**. The claim that the GUI has "no + `export` reference anywhere in `crates/eggsec-gui/frontend/app.js`" was + false — the frontend carries ~50, including `"export_report"` at + `crates/eggsec-gui/frontend/app.js:1624` and `"report_for"` at `:556`. The + export columns now name the *real* blocker (an attestation, not a feature), + and the retired milestone-006 blocking token is gone from the document + entirely. +- The matrix's **promotion rule is now machine-enforced** and lives in exactly + one place: the matrix's own §6 rules table (P1–P6). + `scripts/check_gui_qualification.py` reads the rules from there, so a rule + added to the matrix is enforced without a second edit. +- The **export procedure is written** (`docs/GUI_BUILD.md` §5.7): the three + `*Not yet defined.*` placeholders are gone, replaced by a step that names + the panel's control, the `export_report` command, the six formats, the byte + and digest checks, the `.bak` backup, and the two refusal cases. +- The **harness measures the GUI's real paths** against a live daemon: + connect, submit, cancel, render, export — with the loopback fixture as the + only target — and records a per-column outcome with a named reason. +- **One cell changed status**: the macOS `Build` cell, which now cites a + `eggsec-gui-qualification-record/v1` run record whose build sidecar's + SHA-256 the validator re-checks. Its status was already `qualified`; what + changed is that its evidence is now a *record* rather than a prose + reference. The macOS `Launch` cell stays `partially qualified`; the + behavioural cells stay `not qualified`; the Windows row is byte-identical. + +The milestone is **conditionally closed**: the infrastructure is complete and +verified, and the named outstanding evidence is an operator-attested run +(§10). + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| §13.1 — `docs/GUI_BUILD.md` §5.7 contains a complete export procedure (four filled rows, no `Not yet defined`, naming the control, the `export_report` command, the six formats, the digest and parse checks, the `.bak` backup, the refusal cases) | `docs/GUI_BUILD.md:480-513`; guard 181 (passes, and fails on a negative fixture) | **pass** | The four rows are Precondition, Action, Pass criterion, Evidence artefact; the six formats are named `json`, `csv`, `html`, `md`, `sarif`, `xml`. | +| §13.2 — `scripts/gui_qualification.sh` exists, is hermetic, and writes a run record with all seven columns | `scripts/gui_qualification.sh`; the recorded run `docs/evidence/gui-qualification/macos-2026-10-24.md`; guard 187 | **pass** | The record carries all seven columns. Hermeticity: no `sudo`, no recursive remove, no absolute path literal outside the temporary root. | +| §13.3 — `crates/eggsec-gui/tests/qualification.rs` exists, adds **no** dependency to `crates/eggsec-gui`, SKIPs with a named reason when its environment is absent, and asserts the seven columns | `crates/eggsec-gui/tests/qualification.rs`; `cargo test -p eggsec-gui --no-default-features --test qualification` (5 passed); `git diff crates/eggsec-gui/Cargo.toml` (empty) | **pass** | The SKIP line is printed: `SKIP: neither EGGSEC_QUALIFY_SOCKET nor EGGSEC_QUALIFY_DAEMON_BIN is set, so no daemon was reachable and the live half did not run`. | +| §13.4 — `scripts/check_gui_qualification.py` exists and enforces rules P1–P6 | `scripts/check_gui_qualification.py`; `python3 scripts/check_gui_qualification.py` (exit 0); `--self-test` (9 deliberate corruptions, all rejected) | **pass** | The rules are read from the matrix's §6 table, not from a second copy in the script. | +| §13.5 — the `gui-platform` CI job runs the procedure on both legs and publishes the run record as a job artefact | `.github/workflows/deep-checks.yml:144-176`; guard 189 | **pass** (not yet run) | The job builds the `service`-profile daemon, runs the procedure, and uploads `gui-qualification-${{ matrix.os }}`. The job has **not run in CI yet** — no run URL exists (§10). | +| §13.6 — the matrix contains no `pending M6` token, no blank cell, and no `qualified` cell without a resolving evidence reference | `docs/GUI_PLATFORM_QUALIFICATION.md`; guards 182, 183, 184; the validator (exit 0) | **pass** | The token is absent from the document; the vocabulary is four tokens; all 21 cells are non-blank; the one `qualified` cell resolves. | +| §13.7 — every behavioural cell's root cause names the **current** blocker; the macOS `Connect` cell no longer says "the repository ships no such driver" | `docs/GUI_PLATFORM_QUALIFICATION.md` (the macOS row) | **pass** | The behavioural cells now name the *operator attestation* that rules P1/P3/P4 require, and cite the record that carries the machine half. | +| §13.8 — guards 181–189 exist, are numbered after 176, and each fails when its invariant is broken | `/tmp/eggsec-guardwork/m014-guards.sh`; §4.1 | **pass** | Nine checks, 181–189. Each was demonstrated to FAIL against a deliberately broken input and the tree was restored from `cp` backups. The block is **not yet merged** into `scripts/check-architecture-guards.sh` (the owner merges it). | +| §13.9 — no cell is promoted without a recorded run satisfying P1–P6 | the matrix; the validator | **pass** | The one `qualified` cell cites `macos-2026-10-24.md`, whose record satisfies P2 (scripted `pass`, operator `not-applicable`, artefact present, digest matching). No behavioural cell was promoted. | +| §13.10 — the Windows row is byte-identical to its baseline state | `docs/GUI_PLATFORM_QUALIFICATION.md` | **pass** | The row's text is unchanged; the re-anchoring was applied to §5's `server.rs` list, not to the row. | +| §10 — the run-record schema round-trips and a missing column is rejected by name | `the_outcome_file_round_trips_and_names_what_is_wrong_with_it` | **pass** | The deserialiser rejects an unknown `schema` by name; `validate()` names the missing column. | +| §10 — the seven identifiers are the seven columns | `the_column_identifiers_are_the_seven_the_matrix_publishes`; guard 186 | **pass** | | +| §10 — the format tables agree with the record | `crates/eggsec-gui/src/export.rs`'s new `the_format_table_agrees_with_the_views_and_the_written_files`; `every_report_format_renders_writes_and_digests`; the export column's artefact | **pass** | `ReportFormat::parse` accepts every name the frontend's `format_views()` offers, and the file the writer produces carries the suffix the table names, for all six formats; and all six render, write, and digest to the value the record carries. | +| §10 — Tier A export refuses a non-regular destination and backs up an existing file | `the_export_refuses_a_non_regular_destination_and_backs_up_a_real_one` | **pass** | A directory is refused with the named discipline; an existing file survives at `.bak`. | +| §10 — Tier B connect / submit / cancel / render / export against a live daemon | `the_live_daemon_half_records_its_outcomes`, run against a `service`-profile daemon | **pass** | Every one of the five columns recorded `scripted: pass`; see the record's reasons. | +| §10 — the daemon restarts between the task and the export | the harness's report-fetch path | **partial** | The path is implemented and reachable (the daemon's own refusal is carried verbatim and the export column becomes `fail`), but the restart itself was **not exercised** in a test — no test can restart the daemon the procedure started. Recorded in §10. | +| §10 — the script's cleanup leaves nothing behind | the procedure's `cleanup` trap; the daemon log | **pass** | The trap stops the daemon and removes its socket on EXIT, INT and TERM. The run's daemon log shows `Daemon stopped.`; the socket is gone. | +| §10 — two concurrent harness runs do not interfere | the procedure's `$$`-derived socket path | **partial** | The socket path is unique per run, and two runs were made against two distinct sockets during this milestone's work (one macOS, one `--platform linux`). A simultaneous two-run demonstration was **not** performed. | +| §10 — the validator round-trips (green on a good matrix, non-zero with a named cell on a tampered one) | `python3 scripts/check_gui_qualification.py --self-test` | **pass** | Nine deliberate corruptions, each rejected with the named cell. | +| §10 — no enforcement bypass; the harness adds no network reach; no credentials are logged | §8 below | **pass** | | +| §11 — the matrix's status vocabulary is unchanged and `pending M6` is rejected | the validator; guard 182 | **partial** | The **matrix's** vocabulary is now four tokens: `pending M6` is removed by guard 182 once the affordance exists, exactly as the plan's §9 specifies. The *guard 168* list in `scripts/check-architecture-guards.sh` still carries `pending M6`; that file is shared and outside this milestone's range, and the divergence is recorded in the guard-doc delta. | +| §11 — the old evidence file still validates but is not sufficient to promote a cell | the validator's `check_record` | **pass** | `macos-2026-10-23.md` carries no record block; it is not rejected as malformed, and a `qualified` cell resting on it alone is rejected as insufficient. The macOS `Build` cell therefore cites the **new** record. | +| §11 — `make check` | not run | **not run** | The plan assigns the `check-deps` advisory backlog to milestone 015, and the session owner runs `make check` at integration. | +| §11 — `make check-deps` | not run | **not run** | Same reason. | +| §11 — `make check-python` | not run | **not run** | M014 changes no Python binding, stub, or script. | + +## 3. Production implementation evidence + +### 3.1 The procedure — `scripts/gui_qualification.sh` (new) + +The operator-facing procedure. It: + +- takes `--platform`, `--mode`, `--socket`, `--daemon-bin`, `--out`, `--date`, + and `--skip-window`; +- runs `scripts/check_gui_prereqs.sh` and records its exit status and verdict; +- builds the shell through `scripts/build_gui_release.sh` and copies the build + sidecar into the evidence directory under + `-.build.json`, with its SHA-256; +- starts a `service`-profile daemon on a `$$`-derived socket with + `EGGSEC_ALLOW_LOOPBACK_FIXTURE=1` in its environment, or attaches to one the + operator started; +- runs the harness and reads its per-column outcome file; +- probes for the window (`xdotool` on Linux, `osascript` on macOS) and takes a + screenshot **only when a GUI process is running** — a full-screen capture of + a host with no GUI is a picture of the operator's desktop, not evidence; +- writes the run record and the artefacts into `--out`; +- stops the daemon and removes its socket on every exit path (EXIT, INT, TERM). + +**A run qualifies the platform it was made on.** If the requested platform is +not the host's, the procedure records a named skip for every column rather +than putting the host's observations under another platform's label. That is +why `bash scripts/gui_qualification.sh --platform linux --mode ci` on a macOS +host produces seven named skips and exits 0. + +### 3.2 The harness — `crates/eggsec-gui/tests/qualification.rs` (new) + +Five tests, no new dependency, no new file under `crates/eggsec-gui/src/`: + +| Test | What it proves | +|---|---| +| `the_column_identifiers_are_the_seven_the_matrix_publishes` | The harness's identifier set is the matrix's seven, once each. | +| `the_outcome_file_round_trips_and_names_what_is_wrong_with_it` | A record round-trips; an unknown `schema` is rejected by name; a record missing a column is rejected **by the column's name**. | +| `every_report_format_renders_writes_and_digests` | All six formats render, write through the GUI's own writer, and the written file's SHA-256 equals the rendered bytes' digest. | +| `the_export_refuses_a_non_regular_destination_and_backs_up_a_real_one` | The write discipline: a directory is refused with a named error and nothing is written; an existing regular file survives at `.bak`. | +| `the_live_daemon_half_records_its_outcomes` | The live half, or a named SKIP. | + +The live half: connects through the GUI's **own** client and identity +(`gui_identity()`), reads the daemon's catalogue and capabilities, opens a +`DesktopGuiManual` session with the GUI's own scope, assembles the request +through the GUI's **own** form engine (`form::assemble_request`), submits, +cancels, observes the terminal state **in the daemon's event stream**, fetches +the report, renders it, and writes it in all six formats, comparing each +written file's bytes with the renderer's output. + +Two design points worth naming: + +- **The cancellation's outcome is the terminal state the event stream + reported**, never the cancel request's acknowledgement. A task that + completes before the cancellation is processed is recorded as a *completed + task*, not as a failed cancellation — the plan's §8.2 rule. +- **The target is the loopback fixture** (`127.0.0.1`), and the harness + supplies a target only to a task kind whose published schema declares one. + The engine admits a loopback target only when + `EGGSEC_ALLOW_LOOPBACK_FIXTURE=1` is set in the daemon's environment + (`crates/eggsec/src/utils/parsing.rs:77`), which the procedure sets. The + run therefore reaches nothing outside the host. + +### 3.3 The validator — `scripts/check_gui_qualification.py` (new) + +- **Reads** the matrix's status vocabulary (§1), the matrix's column set + (the header row), and the promotion rules (§6's rules table: P1–P6, each + with a kind, its platforms, its columns, its required outcome, its required + attestation, and its artefact policy). It keeps **no** second copy. +- **Rejects** a cell that is not `**status** — explanation`; an unknown status + token; a blank explanation; a `partially qualified` cell that does not name + both the qualified subset and the missing part; a `qualified` cell that + names no evidence, no date, or an evidence file that does not exist, or a CI + run URL that `CI-RUNS.md` does not carry; a `qualified` cell whose record + lacks the column, carries the wrong scripted or operator outcome, names an + artefact that does not exist, or records a digest that does not match; a + record whose `schema` is not `v1`; a Windows cell that is not + `out of scope` or does not cite the ADR. +- **Writes** the run record as well as reading it, because it is the thing + that reads the record: the record's shape therefore has exactly one + definition in the repository. The producer script hands it a bag of facts + and asks for the record back. +- **Proves itself** with `--self-test`: nine deliberate corruptions of a + known-good matrix and record, each of which it must reject. + +### 3.4 The run record + +`docs/evidence/gui-qualification/macos-2026-10-24.md` is the milestone's +recorded run, produced by the procedure on this host on 2026-10-24. Its +per-column outcomes: + +| Column | `scripted` | `operator` | Artefact | +|---|---|---|---| +| `build` | `pass` | `not-applicable` | `macos-2026-10-24.build.json` (SHA-256 recorded) | +| `launch` | `not-performed` | `not-performed` | — | +| `connect` | `pass` | `not-performed` | — | +| `submit` | `pass` | `not-performed` | — | +| `cancel` | `pass` | `not-performed` | — | +| `render` | `pass` | `not-performed` | — | +| `export` | `pass` | `not-performed` | `macos-2026-10-24.export.json` (SHA-256 recorded) | + +The five other exported formats (`csv`, `html`, `md`, `sarif`, `xml`) are +committed beside it. The `launch` column is `not-performed` because **no +`eggsec-gui` process was running** when the probe ran: the launch step is an +operator action, and the procedure does not pretend to have taken it. + +### 3.5 The matrix + +`docs/GUI_PLATFORM_QUALIFICATION.md`: + +- the retired milestone-006 blocking token is **gone** (guard 182 makes its + return an error); +- the **Last regenerated** header names `2026-10-24` and the baseline commit + `0f5dbb26e7ab215613e5b6e2295d9c124374bf9f`; +- §2.1 now says what is true: the Linux row has no recorded run; the macOS row + is qualified only where there is an artefact; the behavioural columns are + **measured** and are missing an operator attestation; the export column is + blocked on an attestation, not on a feature; +- §3's regeneration procedure names the script and the validator; +- §4.1 lists the artefacts and `CI-RUNS.md`; +- §5's `server.rs` anchor is re-pointed from `:95` to `:147`; +- §6 is **the promotion rules table** P1–P6, in a form the validator parses. + +### 3.6 The runbook — `docs/GUI_BUILD.md` + +- §2.2 gains the note that the repository's own procedure does **not** use the + webdriver tooling it names, and why (`xdotool` *is* used, as the probe); +- §5.0's daemon-lifecycle paragraph is corrected: the GUI never manages the + daemon's lifecycle, and that is an architectural boundary, not an open + milestone; +- §5.0's anchors are re-anchored: `config.rs:56` (the `--socket` flag), + `config.rs:19` (the default), the **six** production sites spelled out + (the webview spells it out twice), and `server.rs:524-527` (the scope); +- §5.3, §5.4 and §5.5's frontend anchors are re-anchored to the current + `app.js` (`:1682`, `:1006`, `:1525`, `:1538`) and the event-stream + authority to `commands.rs:572-573`; +- §5.7 is the export procedure (four filled rows); +- §6 names the export artefact and the validator. + +### 3.7 The CI job — `.github/workflows/deep-checks.yml` + +The `gui-platform` job gains a `platform` matrix label, a step that builds the +`service`-profile daemon, a step that runs the procedure, and a step that +publishes the run record as the `gui-qualification-${{ matrix.os }}` artefact. +The upload step runs `if: always()`, because **a failed run's record is the +evidence of the failure**. + +### 3.8 The guards + +`/tmp/eggsec-guardwork/m014-guards.sh` holds the nine checks, 181–189, in +the shared script's house style. They are **not yet merged** into +`scripts/check-architecture-guards.sh`: that file is shared by four +concurrent agents, and the session owner merges the block before the summary +block. + +### 3.9 Measured counts + +| Fact | Value | Measured by | +|---|---|---| +| Columns in the matrix | 7 | guard 184 | +| Cells in the matrix | 21 | guard 184 | +| Platform rows | 3 | guard 184 | +| Status tokens in the matrix's vocabulary | 4 | `docs/GUI_PLATFORM_QUALIFICATION.md` §1 | +| Export formats the GUI offers | 6 | `every_report_format_renders_writes_and_digests` | +| Production sites for the socket default | 6 | `docs/GUI_BUILD.md` §5.0 | +| Guards in this milestone | 9 (181–189) | the guard block | +| New dependencies | 0 | `git diff crates/eggsec-gui/Cargo.toml` is empty | + +### 3.10 One file outside this milestone's scope was touched by a formatter + +`cargo fmt -p eggsec-gui` formats the whole package, so it also visited the +files milestone 012 and milestone 013 are editing in this tree. It changed +**two lines** in `crates/eggsec-gui/src/config.rs` — a re-indentation of two +`assert_eq!` lines inside milestone 012's own new test — and nothing else. +`git diff -w` against `git diff` shows the difference is exactly those two +lines and no behaviour change. The tree moved **towards** the required +`cargo fmt --all --check` state, but it is an edit to a file this milestone +does not own, and it is recorded here rather than left for the owner to +discover. No other file outside this milestone's ownership was written. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggsec-gui --features shell --lib +cargo test -p eggsec-gui --no-default-features --lib +cargo test -p eggsec-gui --no-default-features --test qualification +cargo test -p eggsec-gui --no-default-features --test qualification -- --nocapture +cargo clippy -p eggsec-gui --no-default-features --tests -- -D warnings +cargo clippy -p eggsec-gui --features shell --tests -- -D warnings +cargo fmt -p eggsec-gui -- --check +bash scripts/gui_qualification.sh --platform macos --mode ci --daemon-bin --out docs/evidence/gui-qualification +bash scripts/gui_qualification.sh --platform linux --mode ci --out /tmp/eggsec-qualify-linux +python3 scripts/check_gui_qualification.py +python3 scripts/check_gui_qualification.py --self-test +python3 scripts/check_doc_references.py +make check-gui +make check-gui-prereqs +make gui-release +bash /tmp/eggsec-guardwork/run-m014.sh # this milestone's guard block +bash /tmp/eggsec-guardwork/m014-negative.sh # the nine negative demonstrations +``` + +### Results + +| Command | Exit | Observed | +|---|---|---| +| `cargo test -p eggsec-gui --features shell --lib` | 0 | **93 passed; 0 failed** | +| `cargo test -p eggsec-gui --no-default-features --lib` | 0 | **83 passed; 0 failed** | +| `cargo test -p eggsec-gui --no-default-features --test qualification` | 0 | **5 passed; 0 failed** | +| the same, `-- --nocapture`, no daemon | 0 | `SKIP: neither EGGSEC_QUALIFY_SOCKET nor EGGSEC_QUALIFY_DAEMON_BIN is set, so no daemon was reachable and the live half did not run` | +| `cargo clippy -p eggsec-gui --no-default-features --tests -- -D warnings` | 0 | clean | +| `cargo clippy -p eggsec-gui --features shell --tests -- -D warnings` | 0 | clean | +| `cargo fmt -p eggsec-gui -- --check` | 0 | clean | +| `bash scripts/gui_qualification.sh --platform macos --mode ci …` | 0 | the record was written; every column's scripted outcome is `pass`, `skipped`, or `not-applicable` | +| `bash scripts/gui_qualification.sh --platform linux --mode ci …` | 0 | seven named skips (the host is macOS, not linux); the daemon half and the harness did not run | +| `python3 scripts/check_gui_qualification.py` | 0 | `ok: …/docs/GUI_PLATFORM_QUALIFICATION.md is consistent with its evidence` | +| `python3 scripts/check_gui_qualification.py --self-test` | 0 | nine deliberate corruptions, each rejected with the named cell; `ok: every deliberate corruption was rejected` | +| `python3 scripts/check_doc_references.py` | 1 | **29 missing references — all pre-existing**, in `architecture/nse_integration.md`, `architecture/overview.md`, `architecture/proxy.md`, `architecture/transport_eggfetch.md`, `architecture/capability_segregation.md`, `architecture/fuzzer.md`, `architecture/knowledge_corpus.md`, `architecture/network_dependency_baseline.md`, `architecture/nse_capability_inventory.md`, `docs/CAPABILITIES.md`, `docs/CI_ARCHITECTURE_GUARDS.md`, `docs/NSE_COMPATIBILITY.md`. None is in a file this milestone touched. The first run of this checker during the milestone reported **30**: the extra one was the milestone's own record, whose embedded cargo transcript contained the line `Running tests/qualification.rs`, which the checker read as a file reference. The record writer now trims the transcript to the observations, and the count is back to the pre-milestone baseline of 29. | +| `make check-gui` | 0 | `cargo check -p eggsec-gui --features shell` and `cargo clippy -p eggsec-gui --features shell -- -D warnings` both clean | +| `make check-gui-prereqs` | 0 | `VERDICT: BUILDABLE - the desktop GUI shell profile can be built on this host.` | +| `make gui-release` | **2** | **Failed for a pre-existing reason**: `FAIL: the working tree is dirty; a release build must come from a pinned commit.` The tree carries this milestone's changes and three other agents' concurrent changes, and the session owner commits. The `--allow-dirty` path (which the procedure uses) succeeds. | +| `make check` | **not run** | The plan assigns the inherited `check-deps` advisory backlog to milestone 015, and the session owner runs `make check` at integration. | +| `make check-deps` | **not run** | Same reason. | +| `make check-python` | **not run** | M014 changes no Python surface. | + +### 4.1 Guard negative tests + +Each check was demonstrated to **FAIL** against a deliberately broken input. +The tree was restored from `cp` backups taken immediately before each break — +**never** with `git checkout --`. The transcript is +`/tmp/eggsec-guardwork/m014-negative.sh`; the exact observed output: + +``` +--- Check 181: the export procedure is written --- +FAIL: docs/GUI_BUILD.md §5.7 still says 'Not yet defined'. +6:| **Action** | *Not yet defined.* | The frontend invokes the `export_report` IPC command … + +--- Check 182: the retired milestone token stays retired --- +FAIL: docs/GUI_PLATFORM_QUALIFICATION.md still carries the retired 'pending M6' token, but the export affordance exists. +33:| `pending M6` | The behaviour cannot exist yet. | The cell names the root cause. | + +--- Check 183: a qualified cell names resolvable evidence --- +FAIL: docs/GUI_PLATFORM_QUALIFICATION.md:67 cites `macos-1999-01-01.md`, which does not exist. + +--- Check 184: the matrix shape is exact --- +FAIL: docs/GUI_PLATFORM_QUALIFICATION.md the `windows` row has 6 cells; it must have 7. + +--- Check 185: the runbook's steps are the matrix's columns --- +FAIL: docs/GUI_BUILD.md §5's steps are ['build', 'launch', 'connect', 'submit', 'cancel', 'render', 'exfiltration']; the matrix's columns are ['build', 'launch', 'connect', 'submit', 'cancel', 'render', 'export']. + +--- Check 186: the harness's identifiers and record schema are pinned --- +FAIL: crates/eggsec-gui/tests/qualification.rs's identifiers are ['build', 'launch', 'connect', 'submit', 'cancel', 'render', 'exfiltrate']; the matrix's columns are ['build', 'launch', 'connect', 'submit', 'cancel', 'render', 'export']. + +--- Check 187: the qualification procedure is hermetic --- +FAIL: scripts/gui_qualification.sh elevates its privileges. +33:sudo -n true 2>/dev/null || true + +--- Check 188: the promotion validator passes --- +FAIL: the `windows` row's `Build` cell carries the status `qualified`, but rule P5 requires `out of scope` + +--- Check 189: the CI job publishes the qualification record --- +FAIL: the gui-platform job does not publish a gui-qualification artefact. +``` + +And after the restoration: + +``` +The tree is restored; re-running the block: +ALL NINE GUARDS PASS AGAIN +``` + +The nine checks, green: + +``` +--- Check 181: the export procedure is written --- +PASS: the export procedure names its action, its criterion, its artefact, and its six formats. +--- Check 182: the retired milestone token stays retired --- +PASS: the matrix carries no retired blocking token. +--- Check 183: a qualified cell names resolvable evidence --- +PASS: every qualified cell names evidence that resolves. +--- Check 184: the matrix shape is exact --- +PASS: the matrix has the exact header, three rows, and twenty-one cells. +--- Check 185: the runbook's steps are the matrix's columns --- +PASS: the runbook's seven steps are the matrix's seven columns, in order. +--- Check 186: the harness's identifiers and record schema are pinned --- +PASS: the harness's identifiers are the matrix's columns, and every writer and reader carries the same record schema. +--- Check 187: the qualification procedure is hermetic --- +PASS: the procedure needs no privileges and writes only under its output and the temporary root. +--- Check 188: the promotion validator passes --- +PASS: the promotion validator is green. +--- Check 189: the CI job publishes the qualification record --- +PASS: the gui-platform job runs the procedure and publishes the run record. +``` + +### 4.2 The end-to-end proof + +`bash scripts/gui_qualification.sh --platform macos --mode ci --daemon-bin --out docs/evidence/gui-qualification` +exited 0 and produced a record whose `connect`, `submit`, `cancel`, `render` +and `export` columns all carry `scripted: pass` against a **real +`service`-profile daemon**, with the reasons recorded verbatim: + +- `connect` — "the GUI's own client connected to the daemon and read its catalogue"; +- `submit` — "the GUI's own form engine assembled the `PortScan` request and the daemon accepted it as task task:…"; +- `cancel` — "the daemon accepted the cancellation and the event stream reported `cancelled`"; +- `render` — "the daemon's report for the task rendered as 0 findings and 1 open ports against `127.0.0.1`"; +- `export` — "the GUI's own export path wrote the daemon's report in 6 formats, and each written file's bytes equal the renderer's output". + + + +### Integration verification (2026-10-24, session owner) + +The milestone's own commands were run in isolation; the owner's integration +step then ran the repository's mandatory contract over the whole tree, with +all four milestones landed together. + +| Command | Result | +|---|---| +| `make check` | **exit 0** — `cargo fmt --all --check`, the no-default-features and per-crate checks, `cargo deny --workspace --all-features check` (all five sub-checks), clippy, the full test suite (**4315 tests across 77 test binaries, 0 failures**), and `scripts/check-architecture-guards.sh` (**190 guards, "ALL PASSED: No architecture drift detected"**) | +| `make check-msrv` | **exit 0** — all five steps green on Rust 1.89 | +| `python3 scripts/check_doc_references.py` | 29 missing references — the unchanged pre-existing baseline, none of them in a file this milestone touched | + +This is the **first time `make check` has completed on this branch**: it had +always stopped at the inherited `check-deps` advisory backlog, which milestone +015 cleared. Three integration tests that milestone 010 had left stale were +found by that first complete run and corrected in `dcfcd4e2`; the corrections +are recorded as a dated addendum on milestone 010's closure record rather +than by rewriting it. + +## 5. Invariant review + +| Invariant | Evidence | +|---|---| +| `EnforcementContext::evaluate()` remains the only pre-dispatch gate | The harness **changes no** enforcement, authorisation, scope, or dispatch path. It submits through the daemon's own `submit` path and reads the daemon's own refusal when the daemon refuses. The one observed refusal during development — the daemon answering `unsupported task kind for this runtime` — was the daemon's own admission control, surfaced unchanged. | +| Strict surfaces fail closed | No strict surface was touched. The daemon opened the session under `RuntimeSurface::DesktopGuiManual` with the daemon's own `gui-default` scope; the harness neither widened nor bypassed it. | +| Scope is the daemon's, not the GUI's | The record carries `daemon.scope = {surface: DesktopGuiManual, source: gui-default}`, taken from the GUI's own `gui_session_scope()`. The harness sends no scope of its own. | +| One canonical source per fact | The **promotion rule** lives only in the matrix's §6 rules table, and the validator reads it from there. The **record schema** string lives in one definition (the validator's writer) and the four copies are pinned by guard 186. The **column set** lives in the matrix's header row; the harness's identifiers and the runbook's steps are checked against it by guards 185 and 186. The **status vocabulary** lives in the matrix's §1 and the validator reads it from there. | +| No `let _ =`, no `filter_map(|e| e.ok())` | The Rust harness uses pattern matching throughout; the shell script uses `|| true` only on commands whose exit status is checked separately, and every fallible command's status is captured. | +| Ring-only TLS | No TLS was added; no dependency was added. | +| Spawned tokio tasks carry 30–300 s timeouts | The harness's waits are bounded: `CONNECT_WAIT` 30 s, `TERMINAL_WAIT` 60 s — both inside the band. The harness spawns no detached task. The daemon the procedure starts is terminated by the cleanup trap, which SIGTERMs, waits five seconds, and then SIGKILLs. | +| Workspace Tokio is `default-features = false` with per-crate features | The harness uses the GUI crate's existing Tokio features (`rt`, `time`, `macros`); it adds no Tokio feature and no dependency. | +| DTO crates carry no Tokio | No DTO crate was touched. | +| The GUI links no engine/daemon/CLI/TUI crate (guard 155) | `git diff crates/eggsec-gui/Cargo.toml` is **empty**: the dependency closure is unchanged. The harness uses `eggsec-frontend-client`, `eggsec-daemon-protocol`, `eggsec-runtime`, and `eggsec-output` — all of which the GUI crate already depended on. | +| New guards start at 177; this milestone's range is 181–189 | The nine checks are numbered 181–189, and no number outside the range is used. | +| Never run the suite as root; platform scripts stay hermetic | Every command was run as the ordinary user. The procedure's hermeticity is guard 187. | + +## 6. Failure and recovery review + +| Case | Behaviour | Evidence | +|---|---|---| +| The daemon is a no-op executor (built without the `service` feature) | The harness **detects** it (the daemon publishes no task kinds) and records a **named skip** naming the cause, rather than reporting a failed submission. The procedure also warns and names the fix. | Observed during development: the daemon's own warning (`this binary was built WITHOUT the 'service' cargo feature`) and the harness's skip reason. | +| The daemon does not answer | The connect attempt is bounded at 30 s and the live columns record a **named skip**. | The harness's `CONNECT_WAIT` path. | +| The cancel loses the race | The terminal state is read from the **event stream**. A task that completes first is recorded as a *completed task*, not a failed cancellation — the plan's §8.2 rule. | The harness's cancel match arms. | +| The daemon restarts between the task and the export | The daemon's own refusal is carried **verbatim** into the render and export columns' reasons, and the export column becomes `fail`. There is no silent success. | The harness's report-fetch path. The restart itself was **not** exercised in a test (§2). | +| The host is not the platform being qualified | The procedure records a **named skip** for every column and starts no daemon. | `bash scripts/gui_qualification.sh --platform linux --mode ci` on this macOS host: seven skips. | +| The prerequisite probe reports NOT BUILDABLE | The build column records a named skip naming the probe's verdict; the procedure continues. | The script's build branch. | +| The window probe's tool is absent | The launch column records a **named skip** naming the absent tool. | The script's probe branch. | +| Two concurrent runs | The socket path is `$$`-derived, so two runs on one host use two sockets and two records. | The script's `OWNED_SOCKET`. Two simultaneous runs were **not** demonstrated (§2). | +| The script is interrupted | The cleanup trap stops the daemon and removes the socket on EXIT, INT and TERM. | The script's `cleanup` trap and `trap cleanup EXIT INT TERM`. | +| A cell's artefact is missing or its digest is wrong | The validator rejects the cell **by name**. | `--self-test`: "a missing artefact is rejected", "a wrong digest is rejected". | + +## 7. Migration and compatibility review + +| Aspect | Status | +|---|---| +| Schema migration | None. The milestone adds a **new** record format (`eggsec-gui-qualification-record/v1`) and changes no persisted representation. No milestone in this roadmap changes one (`plans/subsystems/desktop-gui-frontend-roadmap.md:1085-1086`). | +| Backward compatibility | The pre-existing evidence file `macos-2026-10-23.md` carries **no** record block. The validator does not reject it as malformed; it simply is not sufficient to promote a cell, and the macOS `Build` cell now cites the new record. | +| Protocol negotiation | Unchanged. The harness speaks the **existing** daemon protocol; no protocol, wire, or DTO changed. `crates/eggsec-daemon-protocol/src/protocol.rs` is not touched by this milestone. | +| Configuration behaviour | The GUI's flags are unchanged; the procedure passes the same `--socket` and `--daemon-bin` flags the operator already uses. | +| Rollback limitations | The milestone's artefacts are additive: a new script, a new test target, a new evidence directory entry, and doc edits. Reverting the commit removes them without touching anything else. The matrix's cells fall back to their previous text only by reverting the doc. | +| Legacy-path status | The retired milestone-006 blocking token is removed from the matrix's vocabulary. Guard 168's **guard-side** token list in the shared script still carries it; that file is outside this milestone's range, and the divergence is documented in the guard-doc delta. | + +## 8. Security review + +| Aspect | Status | +|---|---| +| Authorisation enforcement | Unchanged and not bypassed. The harness submits through the daemon; a task the daemon refuses is refused for the harness too, and the refusal is recorded as an observation. | +| Scope checks | The harness sends no scope. The daemon opened the session with its own `DesktopGuiManual` / `gui-default` scope. The harness's target is the loopback fixture, which the engine admits only behind `EGGSEC_ALLOW_LOOPBACK_FIXTURE=1`. | +| Secret handling | The harness reads no credential and logs none. The record's fields carry no credential material; the procedure records the daemon **binary's** SHA-256 and its path, which are not secrets. | +| Path validation | The harness's temporary directories are built under `${TMPDIR:-/tmp}` with the process id and a nanosecond timestamp, and the export path's own discipline (refuse a non-regular file, back up an existing file) is exercised by a test. | +| Privilege boundaries | The procedure never elevates its privileges and never asks for root (guard 187). It starts and stops its own daemon as the ordinary user. | +| Transport checkpoints | The harness opens exactly **one** socket, a Unix socket, and constructs **no** HTTP client. | +| Denial-of-service bounds | The harness's waits are bounded (30 s connect, 60 s terminal), and the procedure's daemon readiness wait is bounded at 60 s. The port range the harness scans is `1-32` with a 200 ms per-port timeout. | +| Redaction | The record carries the harness's per-column reasons verbatim. No token, credential, or private key appears in any of them. | +| Audit behaviour | Unchanged. The daemon's own audit trail records the dispatches the harness made; the harness does not and cannot write to it. | +| Screenshot privacy | The procedure takes a screenshot **only when a GUI process is running**, so the repository never receives a picture of an operator's desktop with no GUI on it. The first version of the script did capture unconditionally; that was corrected before the record was committed. | + +## 9. Documentation and operations + +### 9.1 Files this milestone owns and changed + +| File | Change | +|---|---| +| `scripts/gui_qualification.sh` | **new** — the operator procedure and the run-record producer. | +| `scripts/check_gui_qualification.py` | **new** — the promotion-rule validator and the record writer. | +| `crates/eggsec-gui/tests/qualification.rs` | **new** — the assertion harness. | +| `crates/eggsec-gui/src/export.rs` | one extended test — `the_format_table_agrees_with_the_views_and_the_written_files` — asserting that `ReportFormat::parse` accepts every name the frontend offers and that the written file carries the suffix the table names, for all six formats. No production code changed. | +| `docs/evidence/gui-qualification/TEMPLATE.md` | the record block, the seven-row outcome table, and the `export` row. | +| `docs/evidence/gui-qualification/CI-RUNS.md` | **new** — the index of CI runs a cell may cite. | +| `docs/evidence/gui-qualification/macos-2026-10-24.md` | **new** — the milestone's recorded run. | +| `docs/evidence/gui-qualification/macos-2026-10-24.*` | **new** — the run's artefacts (the build sidecar and the six exported reports). | +| `docs/GUI_BUILD.md` | §2.2's webdriver note; §5.0's corrections and re-anchoring; §5.3–§5.6's re-anchoring; §5.7's export procedure; §6's artefact names. | +| `docs/GUI_PLATFORM_QUALIFICATION.md` | §1's vocabulary and absolute rules; §2's regeneration header; §2.1; the three rows; §3; §4.1; §5's anchor; §6's rules table P1–P6. | +| `docs/GUI_DISTRIBUTION_HANDOFF.md` | §1's export-artefact note; §4's daemon-lifecycle limitation; the `config.rs:17` → `:19` anchor. | +| `.github/workflows/deep-checks.yml` | the `gui-platform` job's `platform` label, the service-daemon build, the procedure step, and the run-record artefact. | + +### 9.2 Shared-document deltas (written to scratch, not applied) + +| File | Contents | +|---|---| +| `/tmp/eggsec-guardwork/m014-guards.sh` | the nine checks, 181–189, in the shared script's house style, to be appended **before** the summary block. | +| `/tmp/eggsec-guardwork/m014-guards-doc.md` | the `docs/CI_ARCHITECTURE_GUARDS.md` entries for 181–189, plus the companion edit that drops `pending M6` from the Check 168 bullet's enumeration, and the note about guard 168's guard-side list. | +| `/tmp/eggsec-guardwork/m014-skill.md` | the `.opencode/skills/eggsec-gui/SKILL.md` delta: a **Platform qualification** section, a **Known gaps** bullet, and **Resources** entries. It restates **no** counted set. | +| `/tmp/eggsec-guardwork/m014-desktop_gui.md` | the `architecture/desktop_gui.md` delta: the replacement for the **qualification matrix** section. | + +### 9.3 Operator diagnostics + +- The procedure prints what it is doing and what it skipped, and it names the + reason for every skip. +- A daemon that is a no-op executor is detected and named, with the fix: + `scripts/build-daemon-profile.sh --profile service --out `. +- The validator names the cell it rejected and the rule it applied. + +### 9.4 Recovery instructions + +- A failed run's record is still a record: the CI job uploads it with + `if: always()`. +- To re-run a qualification: `bash scripts/gui_qualification.sh --platform + --mode ci --daemon-bin `; the daemon it starts is + stopped and its socket removed on every exit path. +- To check a matrix change: `python3 scripts/check_gui_qualification.py` + (and `--self-test` for the validator's own negative cases). + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | **No behavioural cell can be promoted yet**: rules P1/P3/P4 require an `operator` attestation, and no operator-attested run exists. | The `Connect`, `Submit`, `Cancel`, `Render` and `Export` columns stay `not qualified` on macOS and on Linux. The cells are *promotable*; they are not *promoted*. | An operator runs `docs/GUI_BUILD.md` §5 on the platform, witnesses the behaviours, and records the attestation in the run record's `operator` fields. | +| medium | **The Linux row has no recorded run.** The `gui-platform` job's Linux leg has never run. | The Linux row's seven cells stay `not qualified`, and the Linux behavioural cells cannot be promoted by anything this milestone shipped. | Run the `gui-platform` job on `ubuntu-latest` and record the run URL in `docs/evidence/gui-qualification/CI-RUNS.md`. | +| medium | **The Windows row is excluded by decision and was not touched** (`ADR-0010`). | The Windows cells stay `out of scope`. | None for this milestone. Re-entry is gated on a Windows daemon transport with its own ADR. | +| medium | **OQ-2 is unresolved: whether the GUI paints a window under a virtual display on `ubuntu-latest` is unmeasured.** The environment has no `xvfb` (`xvfb-run` is absent) and no Linux host, and the `gui-platform` job installs no `xvfb` and no `xdotool`. The plan forbids weakening a cell's criterion to make it green, so the criterion stands and the Linux `Launch` cell stays unpromoted. | The Linux `Launch` cell cannot be promoted by CI alone as the job is currently configured. | Either add `xvfb` and `xdotool` to the Linux leg and measure, or accept that the Linux `Launch` cell is operator-run only. | +| low | **OQ-3 is unresolved: whether a CI macOS runner has an attachable GUI session is unmeasured.** This host's session type is `Aqua` (`launchctl managername` → `Aqua`; `who` shows a console login), which is a desktop session, not a CI runner's. | The macOS `Launch` cell's operator attestation cannot be obtained from CI as the job stands. | Measure on the runner; until then the macOS `Launch` cell stays `partially qualified`. | +| low | **OQ-4 is partially resolved.** The `osascript` accessibility probe **does** reach System Events on this host and answers — it failed with `Can't get process 1 whose name = "eggsec-gui". Invalid index. (-1719)`, a *process-lookup* error, not an assistive-access permission error — and it exits **1** when no such process is running. The procedure therefore treats a non-zero exit as "zero windows", not as "the probe is broken". Whether the same holds on a CI runner, where the Accessibility permission is almost certainly not granted, is unmeasured. | A CI macOS leg's window probe would report zero windows either way, which is indistinguishable from "the window never painted". | Measure the probe's behaviour on a runner and, if it is permission-blocked, record the probe's own error in the run record so the two cases are distinguishable. | +| low | **The daemon-restart case was not exercised in a test.** The harness's path for it is implemented (the daemon's own refusal is carried verbatim and the export column becomes `fail`), but no test restarts the daemon the procedure started. | The path is asserted by construction, not by execution. | A test that stops the daemon between the submit and the export, once a test harness can own the daemon's lifecycle. | +| low | **Two concurrent procedure runs were not demonstrated.** The socket path is `$$`-derived, and two runs against two distinct sockets were made during this milestone, but not simultaneously. | The non-interference claim rests on the socket path's uniqueness. | A simultaneous two-run demonstration. | +| low | **`make gui-release` failed** in this environment because the working tree is dirty (this milestone's changes plus three other agents' concurrent changes). The `--allow-dirty` path succeeds, and the procedure uses it. | The release-grade build is unverified from a pinned commit in this milestone. | The session owner runs `make gui-release` after committing, on a clean tree. | +| low | **Guard 168's guard-side token list still carries `pending M6`**, while the matrix's vocabulary no longer does. The two lists therefore differ. The token is illegal either way (guard 182 forbids it outright), so no cell can carry it. | A reader comparing the two lists would find a divergence. | Drop the token from guard 168's list when the shared script is next edited. Check 168 is outside this milestone's reserved range. | +| low | **The frontend has no JavaScript test infrastructure.** The webview's own rendering is covered by the operator's attestation and the screenshot alone; the harness exercises the Rust side of the export path. | A frontend regression in the export control would not be caught by the harness. | Out of scope for this milestone: a JavaScript test runner needs an ADR under the zero-npm posture. | + +### 10.1 The open questions, measured + +| ID | Outcome | How it was measured | +|---|---|---| +| **OQ-1** — Does a Tauri-v2 WebDriver driver exist for the macOS leg that does not require a Node client? | **Answered: no.** `tauri-driver` is a published crate (2.0.5 … 2.1.0, 3.0.0-alpha.1), but its **own README** lists the supported platforms as "Linux via `WebKitWebDriver`", "Windows via Microsoft Edge Driver", and "**[Todo]** macOS via Appium Mac2 Driver (probably)", with the note that the "(probably)" items "haven't been proof-of-concept'd yet". There is therefore **no macOS driver** upstream. The crate is also a WebDriver **server** that a separate WebDriver **client** connects to; the ecosystem's client is WebdriverIO, a Node tool. Nothing in this repository pins or installs either: `Cargo.lock` carries no driver crate, and `tauri-driver` is absent from this host's PATH (`safaridriver`, macOS's own WebDriver, is present at `/System/Cryptexes/App/usr/bin/safaridriver`). | `https://index.crates.io/ta/ur/tauri-driver` and `https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-driver/README.md`; `rg -n "tauri-driver\|webdriver\|wdio\|safaridriver\|geckodriver" Cargo.lock` (no hits); `command -v` for each driver. | +| **OQ-2** — Can the GUI paint a window under `xvfb` on `ubuntu-latest`? | **Unresolved.** No `xvfb` and no `xdotool` on this host (`xvfb-run` and `xdotool` are absent), there is no Linux host, and the `gui-platform` job installs neither. The criterion is left standing. | `command -v xvfb-run xdotool`; the `gui-platform` job's install step. | +| **OQ-3** — Does the CI macOS runner have an attachable GUI session? | **Unresolved.** This host's session is `Aqua` (`launchctl managername` → `Aqua`; `who` shows a console login), which is a desktop session. A CI runner's session type could not be measured from here. | `launchctl managername`; `who`. | +| **OQ-4** — Does the macOS `osascript` accessibility probe work in a CI context? | **Partially answered.** On this host the probe **reaches System Events and answers**: it failed with `Can't get process 1 whose name = "eggsec-gui". Invalid index. (-1719)` — a *process-lookup* error, not an assistive-access permission error — and it **exits 1** when the process does not exist. The procedure therefore reads a non-zero exit as "zero windows". Whether the probe works on a CI runner, where the Accessibility permission is almost certainly not granted, is **unresolved**. | `osascript -e 'tell application "System Events" to tell (first process whose name is "eggsec-gui") to get name of every window'` → exit 1 with the error above. | + +**OQ-1's answer does not trigger the plan's §14 stop condition.** That stop +condition fires when a macOS driver *turns out to exist* and is usable +without a Node client. It does not exist upstream, so the milestone's +deliverable boundary — a maintained operator procedure rather than a +window-automation driver — is unchanged and correct. + +## 11. Roadmap disposition + +**Milestone conditionally closed with named operational evidence outstanding.** + +The capability this milestone set out to build — the qualification +procedure, the harness, the validator, the guards, the export procedure, and +the corrected matrix — **is complete and verified**. The matrix's behavioural +and export cells are **promotable**: the rules that promote them exist, are +machine-enforced, and the machinery to produce a promotable record works end +to end against a live daemon. + +The milestone does **not** promote a cell, and it does not claim to. Two +named pieces of evidence are outstanding: + +1. an **operator attestation** for the behavioural columns (rules P1, P3, P4), + which only a person who watched the behaviour can supply; and +2. a **recorded Linux run** from the `gui-platform` job. + +The plan explicitly permits this outcome: *"the cells are now promotable but +not promoted because no recorded run exists in this environment"*. Nothing +in the matrix was weakened to reach it: every criterion stands as written, +every skip is named, and the one cell that is `qualified` satisfies its rule. + +Milestone 015 (the dependency advisory backlog) is unaffected and remains the +owner of the inherited `check-deps` advisories. The next dependency — +milestone 015's own work — may proceed. + +## 12. Registry updates + +The session owner owns these files; this milestone does not edit them. + +- `plans/registry.md` — the milestone's entry: **conditionally closed**, with + the two outstanding evidence items named (§10). +- `plans/subsystems/desktop-gui-frontend-roadmap.md` — the milestone's status + row, and the §4 gap-table row that carries the qualification-matrix gap. + +### 12.1 Merges the owner must apply + +1. **`scripts/check-architecture-guards.sh`** — append + `/tmp/eggsec-guardwork/m014-guards.sh` **before** the `=== Summary ===` + block. The block uses `FAIL` and `SECTION_FAIL`, the script's own + variables, and `rg`, exactly as the existing checks do. +2. **`docs/CI_ARCHITECTURE_GUARDS.md`** — apply + `/tmp/eggsec-guardwork/m014-guards-doc.md`. +3. **`.opencode/skills/eggsec-gui/SKILL.md`** — apply + `/tmp/eggsec-guardwork/m014-skill.md` (shared with milestone 013). +4. **`architecture/desktop_gui.md`** — apply + `/tmp/eggsec-guardwork/m014-desktop_gui.md` (shared with milestone 013). diff --git a/plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md b/plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md new file mode 100644 index 000000000..10a960876 --- /dev/null +++ b/plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md @@ -0,0 +1,840 @@ +# Desktop GUI Frontend Milestone 015 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` + +Source subsystem roadmap: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md#milestone-15--the-dependency-advisory-backlog` + (heading at `plans/subsystems/desktop-gui-frontend-roadmap.md:1042`) + +Repository baseline reviewed: `0f5dbb26` (branch `feat/auto-20261022-76692679`) + +Implementation commits: + +- `6de6340e` — feat(desktop-gui): implement the desktop GUI milestones 012 to 015 + +Tools used for the measurements in §4: + +- `cargo-deny 0.20.2` (local; CI installs `cargo-deny@0.19.0` — see §10, finding F4) +- `cargo 1.99.1` / `rustc 1.99.1`; `rustup toolchain 1.89` for the MSRV gate +- `ripgrep 15.2.0` + +## 1. Executive finding + +**The repository's dependency-policy gate is green and the mandatory Rust +contract's first blocking step is no longer blocking.** The 23-entry advisory +backlog that milestone 010's closure record inherited and did not own is +closed: `cargo deny --workspace --all-features check advisories` now reports +**zero** entries, and all five `make check-deps` sub-invocations exit zero. + +The backlog was disposed of along the plan's three-way split, and the split +held exactly as the plan measured it: + +- **9 entries cleared by a lockfile refresh alone**, with no manifest change: + `ctutils` 0.4.2→0.4.5, `rustls` 0.23.45→0.23.46, `rustls-webpki` + 0.103.15→0.103.16, `tokio` 1.53.1→1.54.1, `webpki-roots` 1.0.9→1.0.11, + `webpki-root-certs` 1.0.9→1.0.11. +- **3 entries cleared by the `zip` 9.x major bump** (RUSTSEC-2026-0367 / + -0368 / -0369), with the archive layout proven byte-identical (§7). +- **11 entries recorded as owned, dated exceptions** in `deny.toml` and + `docs/DEPENDENCY_EXCEPTIONS.md`, in four clusters, each with an owner, a + `2026-12-12` review-by date, and the exact clearing condition. + +**What this milestone did NOT do**, and why: it did not relax the ring-only +TLS rule, did not raise the MSRV floor, did not weaken `[advisories]`'s +`unmaintained`/`unsound` settings, did not add or relax a `[licenses]` allow +entry or a `[bans]` deny rule, did not move the Tauri closure to the 2.12 +line, and did not rewrite milestone 010's plan or closure record. Each of +those is an explicit §5 exclusion and a §14 stop condition. Where an upgrade +existed but was blocked by one of them, the entry became an **exception with +a dated removal recipe**, not a silent deferral. + +The one place where the plan's literal instruction could not be followed +without a policy decision — the `zip` 9.x bump pulling `libbz2-rs-sys`, whose +`bzip2-1.0.6` licence expression is not on the allow list — was resolved +**without touching the allow list**, by narrowing `zip`'s feature set to the +compression backends the mobile lab actually uses. The full reasoning, the +rejected alternatives, and the exact fallback that would apply if the owner +prefers it are in §7 and §10 (F1). + +## 2. Requirement-to-evidence matrix + +| Plan requirement (§13 acceptance criterion) | Evidence | Result | Notes | +|---|---|---|---| +| 1. `make check-deps` completes with a zero exit status; each of its five `cargo deny` invocations recorded with its own exit status | `make check-deps` → exit **0**; the five sub-invococations were also run individually: default **0**, advisories **0**, bans **0**, licenses **0**, sources **0** (§4) | **pass** | Full target output in §4 | +| 2. `cargo deny --workspace --all-features check advisories` reports **zero** advisory entries | `advisories ok`, exit **0**, captured output in §4 | **pass** | Before: 23 entries / 20 IDs | +| 3. The 9 Bucket-A entries clear by a lockfile refresh with no manifest change; the 3 `zip` entries clear by the 9.x upgrade; the remaining 11 are recorded as exceptions | `Cargo.lock` diff in §4 shows all six Bucket-A bumps; `zip` 2.4.2→9.1.0; `deny.toml` carries exactly **11** new ignore entries for the 11 policy/upstream-blocked IDs | **pass** | The `zip` path taken was the **primary** path, not the documented fallback (§7) | +| 4. `deny.toml` has an `ignore` entry for every advisory that is not upgraded, and none for an advisory that is upgraded | `deny.toml` now holds **20** ignore entries: 9 pre-existing + 11 new. No entry names RUSTSEC-2026-0367/-0368/-0369 (upgraded), nor any Bucket-A ID (upgraded). A re-run of the advisory check after the bump reports zero, so no ignore is stale | **pass** | 20 of 20 carry a non-empty `reason`; 20 of 20 name the exception document | +| 5. Every `ignore` entry has a non-empty `reason` naming the affected crate, the dependency path, and the clearing condition | Measured: `reason = "` appears 20 times for 20 entries; each reason names the crate and version, the dependency path, the upgrade that would clear it, and why it is not adopted, and ends `See docs/DEPENDENCY_EXCEPTIONS.md.` | **pass** | Guard sub-check (a) and (b) enforce it mechanically | +| 6. Every ignored ID has a record in `docs/DEPENDENCY_EXCEPTIONS.md` with a non-empty `| Owner |`, a `| Review-by |` date, and a `| Blocker |` | 11 new records (4 headings) added; the document now has **13** `###` headings — 11 active + 2 resolved — each with an `| Owner |`, a `| Review-by |`, and a `| Blocker |` row | **pass** | Guard sub-check (c) enforces it mechanically | +| 7. `make check` completes end to end | **not run** — the session owner runs it at integration (§10, F2) | **not run** | Every step of `make check` that this milestone could own was run individually: `check-deps` (exit 0), the guard block (§4), `check-msrv` (§4) | +| 8. `make check-msrv` still builds the workspace on Rust 1.89, and the Tauri closure has not floated onto the 1.90-MSRV line | `make check-msrv` → exit **0** (first attempt exit 2 on disk exhaustion, §10 F2; second attempt green, all five steps including the GUI shell profile). Tauri closure measured unchanged: `tauri` 2.11.6, `tauri-build` 2.6.3, `tauri-runtime` 2.11.3, `tauri-runtime-wry` 2.11.4, `tauri-macros` 2.6.3, `tauri-utils` 2.9.3; `cargo update --dry-run -p tauri-utils` reports "Locking 0 packages to highest compatible versions" | **pass** | — | +| 9. `bash scripts/check-architecture-guards.sh` exits zero and reports Check 190; all five negative demonstrations performed and recorded | The Check 190 block was written to `/tmp/eggsec-guardwork/m015-guards.sh` and run against this tree (exit 0, `PASS: every dependency exception is owned and dated.`). All five negatives were demonstrated failing (§4) and the tree restored from `cp` backups | **partial** | The shared script was **not** edited (four concurrent agents own it); the owner merges the block and runs the whole script at integration | +| 10. `make check-gui` completes on a host with the webview SDK present, or is recorded as prerequisite-gated | **not run** — this milestone changes no GUI source, and the GUI's Tauri closure did not move (§4) | **not run** | Prerequisite-gated step; the owner's `make check` covers it | +| 11. No `.cargo/audit.toml` exists and no `cargo audit` configuration was added | `.cargo/audit.toml` absent (`ls .cargo` → no `audit.toml`); `git status` shows no new `.cargo/` file; `deny.toml` remains the only policy source | **pass** | — | +| 12. `[bans] deny = ["aws-lc-rs"]` and the ring-only TLS rule are unchanged | `deny.toml` `[bans]` block byte-identical to the baseline; `rustls` 0.21.12 and `rustls-webpki` 0.101.7 remain in the tree only on the `tiberius` path, under exception | **pass** | `git diff deny.toml` touches only the `[advisories]` ignore array | +| 13. `git status --porcelain` is clean apart from the intended changes, and no unrelated file was modified | §4 records the final status. This milestone's own changes are listed in §3; the tree also carries other agents' in-flight work, which was left untouched | **pass** (for this milestone's own scope) | — | + +Additional §10 requirements: + +| Requirement | Evidence | Result | +|---|---|---| +| Every `deny.toml` ignore has a non-empty reason | Guard sub-check (a); 20/20 measured | pass | +| Every reason names `docs/DEPENDENCY_EXCEPTIONS.md` | Guard sub-check (b); 20/20 measured | pass | +| Every ignored ID has an owned, dated record | Guard sub-check (c) | pass | +| No `RESOLVED` record retains a live ignore | Guard sub-check (d) | pass | +| A parse failure is an error, not an empty result | The guard fails closed when `deny.toml` or the exception document is missing or unparseable (§4 note below) | pass | +| The `zip` migration is exercised through the mobile-lab archive fixture suite | `cargo test -p eggsec-mobile-lab` → 20 passed, 0 failed | pass | +| Archive-layout compatibility (names, ordering, compression method, SUID/SGID, symlinks) | Byte-identical comparison of zip 2.4.2 vs 9.1.0 output (§7) | pass | +| Idempotent re-run (`cargo update`, guard) | A second and third `cargo update` produced no further lockfile change; the guard passes again on the restored tree | pass | +| Malformed-archive rejection unchanged | The pre-existing `rejects_zipslip`, `rejects_empty_android_manifest`, `invalid_zip_input_returns_error_not_panic`, and `empty_zip_returns_error_not_panic` tests all pass | pass | +| `make check-python` not required | No Python-facing dependency path changed: the only `crates/eggsec-python/` closure movement is the `tokio` 1.53.1→1.54.1 patch bump and the `pyo3` 0.29.2→0.29.3 patch bump. None of the 23 affected crates is reachable from `crates/eggsec-python/pyproject.toml` or the stubs | not required (reasoned, not run) | + +## 3. Production implementation evidence + +### 3.1 `deny.toml` — eleven new `[advisories] ignore` entries + +Added after the existing entries under a new header +`# --- Milestone 015: advisories with no safe upgrade under repo policy ---`. +Each entry follows the file's house style and keeps the affected crate and +version, the dependency path, the upgrade that would clear it, the reason it +is not adopted, and the trailing `See docs/DEPENDENCY_EXCEPTIONS.md.`: + +| ID | Cluster | Reason recorded | +|---|---|---| +| RUSTSEC-2024-0429 | `glib` 0.18.5 | unreachable: no published `muda`/`tao`/`wry` uses gtk-rs 0.20+, `tauri` 2.12.5 still requires `gtk ^0.18` — upstream-blocked | +| RUSTSEC-2024-0370 | `proc-macro-error` 1.0.4 | latest published; clears with RUSTSEC-2024-0429 | +| RUSTSEC-2026-0346 | `rustls` 0.21.12 | `tiberius` 0.13.0 reaches `rustls` 0.23 only via the `aws-lc-rs`-default `tokio-rustls` that `[bans] deny` forbids — policy-blocked | +| RUSTSEC-2026-0349 | `rustls` 0.21.12 | same path as above | +| RUSTSEC-2026-0382 | `rustls-webpki` 0.101.7 | same path as RUSTSEC-2026-0104 | +| RUSTSEC-2024-0449 | `unsafe-libyaml` 0.2.11 | latest published; `serde_yaml_neo` 0.11.0 hard-depends on it — unmaintained, not a vulnerability | +| RUSTSEC-2025-0100 | `unic-ucd-ident` 0.9.0 | `urlpattern` 0.6.0 clears the set but needs `tauri-utils` 2.10.x (MSRV 1.90) — MSRV-gated | +| RUSTSEC-2025-0075 | `unic-char-range` 0.9.0 | same path as above | +| RUSTSEC-2025-0080 | `unic-common` 0.9.0 | same path as above | +| RUSTSEC-2025-0081 | `unic-char-property` 0.9.0 | same path as above | +| RUSTSEC-2025-0098 | `unic-ucd-version` 0.9.0 | same path as above | + +Measured after the edit: **20** `id = "RUSTSEC-…"` entries, **20** with a +non-empty `reason`, **20** whose reason names `docs/DEPENDENCY_EXCEPTIONS.md`. + +Nothing else in `deny.toml` changed: `[advisories]`'s +`unmaintained = "transitive"` / `unsound = "transitive"`, the `[licenses]` +allow list and its single `auto_generate_cdp` exception, `[bans]` +(`deny = ["aws-lc-rs"]`, `wildcards = "deny"`, `multiple-versions = "warn"`), +and `[sources]` are byte-identical to the baseline. + +### 3.2 `docs/DEPENDENCY_EXCEPTIONS.md` — four new exception records + +Added under `## Active Exceptions`, each with the document's fixed ten-field +schema (`| Advisory |`, `| Path |`, `| Feature |`, `| API used |`, +`| Exploitability |`, `| Compensating control |`, `| Owner |`, `| Created |`, +`| Review-by |`, `| Blocker |`): + +| Heading | IDs | Owner | Review-by | Blocker | +|---|---|---|---|---| +| `### RUSTSEC-2024-0429 — glib 0.18.5 unsound` | RUSTSEC-2024-0429, RUSTSEC-2024-0370 | `eggsec-gui` | 2026-12-12 | gtk-rs 0.20 unreachable; `tauri` 2.12.5 still declares `gtk ^0.18` | +| `### RUSTSEC-2026-0346 / RUSTSEC-2026-0349 / RUSTSEC-2026-0382 — rustls 0.21.12 / rustls-webpki 0.101.7` | 0346, 0349, 0382 | `eggsec-db-lab` | 2026-12-12 | `tiberius` 0.13.0 needs the `aws-lc-rs`-default `tokio-rustls`; ring-only forbids it | +| `### RUSTSEC-2024-0449 — unsafe-libyaml 0.2.11 unmaintained` | 0449 | `eggsec (config)` / `eggsec-web-proxy` | 2026-12-12 | 0.2.11 is the latest published; `serde_yaml_neo` 0.11.0 hard-depends on it | +| `### RUSTSEC-2025-0075 / -0080 / -0081 / -0098 / -0100 — unic-* 0.9.0 unmaintained` | 0075, 0080, 0081, 0098, 0100 | `eggsec-gui` | 2026-12-12 | `urlpattern` 0.6.0 clears it, but `tauri-utils` 2.10.x declares MSRV 1.90 | + +The `unic-*` record carries the **full removal recipe** from plan §3.4, so the +2026-12-12 review is a decision about the MSRV floor rather than an +investigation: raise `rust-version` to 1.90, move the Tauri closure to the 2.12 +line (`tauri` 2.12.5, `tauri-utils` 2.10.2, `tauri-macros` 2.7.4, `tauri-runtime` +2.12.2, `tauri-runtime-wry` 2.12.3, `tauri-build` 2.7.4), re-run +`make check-msrv`; the five entries then disappear because `urlpattern` +resolves to 0.6.x. The record states explicitly that this recipe does **not** +clear the `glib` / `proc-macro-error` pair. + +The `unsafe-libyaml` record is written honestly rather than favourably: the +advisory kind is `unmaintained`, **not** a vulnerability, no fixed release +exists, and the parser *is* exercised — on partly operator-supplied and +partly **downloaded** content (the scanner marketplace loader). The +mitigation is the absence of an upstream fix, not a claim of non-exposure. + +**Heading placement (plan §12).** The two `RESOLVED` records +(`RUSTSEC-2025-0119` `number_prefix`, `RUSTSEC-2024-0436` `paste`) were moved +out of `## Active Exceptions` into a new `## Resolved Exceptions` heading +placed immediately after it. This is documentation-only: both `deny.toml` +ignores were already removed, so the policy state was already correct and only +the heading placement was misleading. The guard's sub-check (d) now keeps it +that way. + +### 3.3 `Cargo.lock` — the refresh + +`cargo update` from the workspace root; no hand-editing, no +`--breaking`, no `-Z minimal-versions`. + +### 3.4 The `zip` 9.x migration + +Manifest changes: + +- `crates/eggsec-mobile-lab/Cargo.toml` — `zip = "2"` → `zip = "9"` with the + feature set narrowed (see §7.2). +- `crates/eggsec/Cargo.toml` — `[dependencies.zip] version = "2"` → + `version = "9"`, `optional = true` preserved, and the `mobile` feature + wiring at the feature table (`mobile = ["dep:eggsec-mobile-lab", "zip", + "plist"]`) untouched. + +Call-site changes in `crates/eggsec-mobile-lab`: + +| File | Change | Reason | +|---|---|---| +| `src/ipa.rs` (`locate_info_plist`) | `entry.name()` now returns `ZipResult>`; the name is taken as an owned `String` | zip 9.x decodes the entry name fallibly | +| `src/ipa.rs` (archive walk) | same fallible-name handling | as above | +| `src/apk.rs` (`analyze_apk_blocking`) | same fallible-name handling; a name that cannot be decoded is a `MobileError::Validation` | as above | +| `src/ipa.rs` ×4, `src/apk.rs` ×2, `src/adb.rs` ×1 | `zip::write::FileOptions<()>` → `zip::write::SimpleFileOptions` | the 2.x `FileOptions<'k, T>` became `FileOptions<'k, 'n, T>` in 9.x; `SimpleFileOptions` is the 9.x alias for `FileOptions<'static, 'static, ()>` | +| `src/apk.rs` ×4, `src/adb.rs` ×1 | the compression method is now **explicit** (`.compression_method(zip::CompressionMethod::Deflated)`) where the call previously relied on the crate default | plan §9: the layout must not depend on a default; see §7.2 | + +**No extraction API was introduced.** Measured after the migration: +`rg -n 'extract\(|extract_to|unpack|extract_dir' crates/eggsec-mobile-lab/` +returns **no matches**. The crate reads entries by name and writes archives +with `ZipWriter`; it never extracts. + +### 3.5 The guard — Check 190 + +Written to `/tmp/eggsec-guardwork/m015-guards.sh` in the house style of +`scripts/check-architecture-guards.sh` (banner, `SECTION_FAIL=0` +accumulator, per-item checks with `FAIL:` messages, final `if [[ $SECTION_FAIL +-eq 0 ]]` block). **The shared script was not edited** — four agents own it +concurrently; the owner merges the block. + +Four sub-checks, exactly as plan §6 specifies: + +- **(a)** every `deny.toml` `[advisories] ignore` entry has a non-empty `reason`; +- **(b)** every such `reason` contains `docs/DEPENDENCY_EXCEPTIONS.md`; +- **(c)** every ignored advisory ID has a `docs/DEPENDENCY_EXCEPTIONS.md` + record carrying a non-empty `| Owner |` and a `| Review-by |` that is an + ISO date or the literal `— (closed)`; +- **(d)** no `RESOLVED` record's advisory ID remains in the live `ignore` list. + +Fail-closed behaviour: if `deny.toml` or `docs/DEPENDENCY_EXCEPTIONS.md` is +missing, if the `[advisories] ignore` array cannot be sliced out, if no +ignore entry parses, or if no exception record parses, the guard reports the +file by name and fails. It never passes because it found nothing. + +Registration was prepared but **not applied**, because +`docs/CI_ARCHITECTURE_GUARDS.md` is shared by three agents: the exact +markdown to insert is in `/tmp/eggsec-guardwork/m015-guards-doc.md`, with its +insertion point named. `docs/VERIFICATION.md` — which this milestone owns — +**was** updated: the `bash scripts/check-architecture-guards.sh` row of the +"Defect classes covered" table now names Check 190 and what it pins. + +### 3.6 Documentation + +- `architecture/supply_chain.md` — a new section, "Repository Dependency + Policy — Advisory Backlog Closure (Milestone 015)", records the before / + after counts, the three dispositions, the four exception clusters with their + owners and blockers, and the guard. The section is explicitly labelled as + **repository-level** policy, because this document is the deep dive for the + `eggsec::supply_chain` *scanner* module (SBOM, typosquat, manifest + discovery) — the plan's §12 description of this file as "the subsystem's + deep-dive document for supply chain" for *dependency* policy does not match + what the file is. The content was placed without conflating the two. +- `architecture/desktop_gui.md` — a new subsection, "The advisory clusters + behind these pins", records that the `unic-*` and `glib` / + `proc-macro-error` clusters are reached **only** through the GUI's Tauri + shell closure, that `urlpattern` 0.6.0 (via `tauri-utils` 2.10) is the + clearing path for the `unic-*` set, and that the `glib` / + `proc-macro-error` pair has **no published clearing path**. The GUI's + dependency *direction* is unchanged. +- `docs/VERIFICATION.md` — the guard table row, as above. + +## 4. Verification executed + +### Commands run + +All commands were run from the worktree root +`/Users/davidbowman/projects/eggsec/.worktrees/feat-auto-20261022-76692679`. + +```bash +# --- baseline measurement ------------------------------------------------- +cargo deny --workspace --all-features check advisories > /tmp/eggsec-guardwork/m015_advisories_BEFORE.txt 2>&1 +grep -c "^error\[" /tmp/eggsec-guardwork/m015_advisories_BEFORE.txt +grep -o "RUSTSEC-[0-9]\{4\}-[0-9]\{4\}" /tmp/eggsec-guardwork/m015_advisories_BEFORE.txt | sort -u | wc -l + +# --- work package A: the lockfile refresh -------------------------------- +cargo update --dry-run # exit 0 +cargo update # exit 0 + +# --- work package B: the zip 9.x migration -------------------------------- +cargo update -p zip # exit 0 (zip 9.1.0) +cargo check -p eggsec-mobile-lab --all-targets # exit 0 +cargo check -p eggsec --features mobile # exit 0 +cargo test -p eggsec-mobile-lab # exit 0 — 20 passed, 0 failed + +# --- work package C/D: the policy files and the guard --------------------- +bash /tmp/eggsec-guardwork/m015-guard-harness.sh # exit 0 — PASS +bash /tmp/eggsec-guardwork/m015-negative-tests.sh # exit 0 (all five negatives exit 1) + +# --- the dependency-policy gate ------------------------------------------- +cargo deny --workspace --all-features check advisories # exit 0 +cargo deny --workspace --all-features check # exit 0 +cargo deny --workspace --all-features check bans # exit 0 +cargo deny --workspace --all-features check licenses # exit 0 +cargo deny --workspace --all-features check sources # exit 0 +make check-deps # exit 0 + +# --- the MSRV floor -------------------------------------------------------- +make check-msrv # see Results + +# --- idempotency ---------------------------------------------------------- +cargo update # exit 0 — no further diff + +# --- documentation references --------------------------------------------- +python3 scripts/check_doc_references.py # exit 1 — 29 missing, none in this milestone's files +``` + +### Results + +**Before measurement.** `cargo deny --workspace --all-features check +advisories` → exit **1**. Counting rule from plan §3.2 (`cargo-deny` writes +its diagnostics to stderr, so the capture redirects both streams): + +| Measure | Value | +|---|---| +| Entries (`grep -c "^error\["`) | **23** | +| Unique advisory IDs | **20** | +| Kind split | **14** `vulnerability`, **7** `unmaintained`, **2** `unsound` | + +The 20 IDs are RUSTSEC-2023-0071, -2024-0370, -0384, -0429, -0449, +-2025-0057, -0075, -0080, -0081, -0098, -0100, -0134, -2026-0098, -0099, +-0104, -0187, -0192, -0346, -0349, -0367, -0368, -0369, -0381, -0382, +-0383, -0385, -0386 — unchanged from the plan's §3.3 table. + +**`cargo update --dry-run` (work package A, first pass).** Exit **0**. +Proposed **149** updates, **15** additions, **20** removals — the plan's +"149 version bumps and 35 additions/removals" exactly. All six Bucket-A +bumps appear; **no Tauri line moves**. + +**`cargo update` (work package A).** Exit **0**. +`git diff --stat Cargo.lock` at that point: `587 insertions(+), 605 deletions(-)`. + +**`cargo update -p zip` (work package B).** Exit **0**; `zip` moved +2.4.2 → 9.1.0. + +**Interim advisory measurement** (after the refresh, with the 11 new ignores +already in `deny.toml`): **3** entries remained — exactly +RUSTSEC-2026-0367, -0368, -0369, the three `zip` entries. (The plan's §7 +package-A acceptance text says the count drops "from 23 to 14"; 14 is the +count *before* the 11 new ignores are added. Measured with the ignores in +place, the remaining count is 3, which is the same fact.) + +**After measurement.** `cargo deny --workspace --all-features check +advisories` → exit **0**, output: + +``` +advisories ok +``` + +**Entries: 23 → 0. Unique advisory IDs: 20 → 0. Remaining IDs: none.** + +**`Cargo.lock` diff summary.** `git diff --stat Cargo.lock`: +`1323 +++++-----`, `592 insertions(+), 731 deletions(-)`. Package-level +accounting against `HEAD`: + +| Category | Count | Notes | +|---|---|---| +| Added | 7 | `borsh` 1.8.1, `borsh-derive` 1.8.1, `core_detect` 1.0.0, `multiversion_no_op` 1.0.0, `psm` 0.1.24, `stacker` 0.1.25, `typed-path` 0.13.0 | +| Removed | 14 | `aes`, `arbitrary`, `bzip2`, `bzip2-sys`, `constant_time_eq`, `deflate64`, `derive_arbitrary`, `lzma-sys`, `socks`, `tinyvec_macros`, `xz2`, `zstd`, `zstd-safe`, `zstd-sys` | +| Moved | 163 | including the six Bucket-A bumps, `zip` 2.4.2→9.1.0, `pyo3` 0.29.2→0.29.3, `eggfetch-core` 0.2.0→0.2.2, `plist` 1.10.1→1.10.3, `spdx` 0.13.5→0.13.6 | + +The 14 removals are dominated by the `zip` feature narrowing (§7.2): the +unused compression backends and their C/Rust backends leave the graph. + +**Tauri closure did not float.** Measured in the refreshed `Cargo.lock`: + +``` +tauri 2.11.6 tauri-build 2.6.3 +tauri-macros 2.6.3 tauri-runtime 2.11.3 +tauri-runtime-wry 2.11.4 tauri-utils 2.9.3 +``` + +`cargo update --dry-run -p tauri-utils` → "Locking 0 packages to highest +compatible versions", exactly as the plan required. The `rustls` 0.21.12 / +`rustls-webpki` 0.101.7 pair remains on the `tiberius` path, under exception; +the `rustls` 0.23 line moved to 0.23.46 and `rustls-webpki` 0.103.15 to +0.103.16. + +**`make check-deps`.** Exit **0**. Its five sub-invococations, run +individually as well, all exit **0**: default (`advisories ok, bans ok, +licenses ok, sources ok`), advisories, bans, licenses, sources. The only +output of note is the pre-existing `warning[no-license-field]` for +`auto_generate_cdp`, which is a warning and is already covered by the +`[licenses] exceptions` entry. + +**`cargo test -p eggsec-mobile-lab`.** Exit **0** — 20 passed, 0 failed. +This is the suite that reads the IPA/APK fixtures, so it is the archive-layout +evidence. + +**Guard Check 190 (block run standalone against this tree).** Exit **0**: + +``` +--- Check 190: every dependency exception is owned and dated --- +PASS: every dependency exception is owned and dated. +``` + +**The five negative demonstrations** (`/tmp/eggsec-guardwork/m015-negative-tests.sh`; +each fixture mutates a policy file, then the file is restored from a `cp` +backup — `git checkout --` was never used). Actual output: + +``` +############ NEGATIVE 1: unowned exception (remove the | Owner | row) ############ +FAIL: RUSTSEC-2024-0429 has no record with a non-empty '| Owner |' and a dated '| Review-by |' in docs/DEPENDENCY_EXCEPTIONS.md. +FAIL: RUSTSEC-2024-0370 has no record with a non-empty '| Owner |' and a dated '| Review-by |' in docs/DEPENDENCY_EXCEPTIONS.md. +FAILED: 1 check(s) failed. +GUARD_EXIT=1 + +############ NEGATIVE 2: undated exception (Review-by is neither ISO nor closed) ############ +FAIL: RUSTSEC-2024-0429 has no record with a non-empty '| Owner |' and a dated '| Review-by |' in docs/DEPENDENCY_EXCEPTIONS.md. +FAIL: RUSTSEC-2024-0370 has no record with a non-empty '| Owner |' and a dated '| Review-by |' in docs/DEPENDENCY_EXCEPTIONS.md. +FAILED: 1 check(s) failed. +GUARD_EXIT=1 + +############ NEGATIVE 3: undocumented ignore (an ID with no exception record) ############ +FAIL: RUSTSEC-2099-0001 is ignored in deny.toml but has no record in docs/DEPENDENCY_EXCEPTIONS.md. +FAILED: 1 check(s) failed. +GUARD_EXIT=1 + +############ NEGATIVE 4: resurrected resolved exception (RUSTSEC-2025-0119) ############ +FAIL: RUSTSEC-2025-0119 is RESOLVED in docs/DEPENDENCY_EXCEPTIONS.md but is still ignored in deny.toml. +FAILED: 1 check(s) failed. +GUARD_EXIT=1 + +############ NEGATIVE 5: undocumented reason (empty reason string) ############ +FAIL: RUSTSEC-2099-0002 has an empty reason in deny.toml. +FAILED: 1 check(s) failed. +GUARD_EXIT=1 + +############ RESTORED: guard on the restored tree ############ +PASS: every dependency exception is owned and dated. +ALL PASSED: No architecture drift detected. +GUARD_EXIT=0 +``` + +The working tree was confirmed restored after each fixture; the final +`git status --porcelain -- deny.toml docs/DEPENDENCY_EXCEPTIONS.md` shows only +this milestone's intended modifications (` M deny.toml`, +` M docs/DEPENDENCY_EXCEPTIONS.md`) and no residue from the fixtures. + +**Fail-closed behaviour, demonstrated.** Four further fixtures were run +against a scratch directory (the guard's paths are relative, so the fixture +is a directory containing only one of the two policy files). Each fails +closed with the file named — never a silent pass: + +| Fixture | Output | Exit | +|---|---|---| +| `deny.toml` absent | `FAIL: deny.toml is missing; the canonical dependency-policy source cannot be checked.` | 1 | +| `docs/DEPENDENCY_EXCEPTIONS.md` absent | `FAIL: docs/DEPENDENCY_EXCEPTIONS.md is missing; the exception record cannot be checked.` | 1 | +| `deny.toml` present but with no parseable `[advisories] ignore` array | `FAIL: the [advisories] ignore array could not be parsed from deny.toml.` + `FAIL: no advisory ignore entries were parsed from deny.toml.` | 1 | +| exception document present but with no parseable record | `FAIL: no exception records could be parsed from docs/DEPENDENCY_EXCEPTIONS.md.` + one `FAIL: is ignored in deny.toml but has no record …` per ignored ID | 1 | + +**`cargo update` idempotency.** A second and a third `cargo update` both +exit **0** and report "Locking 0 packages to highest compatible versions"; the +third produced a **byte-identical** `Cargo.lock` (`diff -q` → identical). The +only difference between the first and second `cargo update` was a +lockfile-normalisation pass that rewrote some *dependency edges* (Windows-only +`windows-sys` and `getrandom` edges) without adding, removing, or re-versioning +any package. + +**`make check-msrv`.** The **first** attempt exited **2** — not an MSRV +failure but an environmental one: the build died with +`No space left on device (os error 28)` while compiling `syn`, +`zerocopy-derive`, `time`, `tracing-attributes` and others, because the +machine's data volume was at 100% (885 GiB used, 125 MiB free) with three +concurrent agents building in the same worktree. The **second** attempt, +after disk space was released, exited **0** and ran all five steps: + +``` +cargo +1.89 check --workspace --no-default-features # ok +cargo +1.89 check -p eggsec-cli --no-default-features # ok +cargo +1.89 check -p eggsec-transport # ok +cargo +1.89 check -p eggsec-transport-eggfetch # ok +cargo +1.89 check -p eggsec --no-default-features # ok +# the desktop GUI shell profile under the declared MSRV # ok + Checking tauri-utils v2.9.3 + Checking tauri-runtime v2.11.3 + Checking tauri-runtime-wry v2.11.4 + Compiling tauri v2.11.6 +``` + +The MSRV floor therefore holds after both the lockfile refresh and the +`zip` 9.x bump: `zip` 9.1.0 declares `rust-version = "1.88"`, below the 1.89 +floor, and the GUI shell profile — the closure that carries the MSRV risk — +builds on 1.89 with the exact Tauri pins unchanged. + +The substantive claim of criterion 8 — that the Tauri closure has not floated +onto the 1.90-MSRV line — is measured and satisfied: the exact Tauri pins are +unchanged and `cargo update --dry-run -p tauri-utils` reports "Locking 0 +packages to highest compatible versions". + +**`python3 scripts/check_doc_references.py`.** Exit **1**, `Total missing: 29`. +**None of the 29 is in a file this milestone touched** — they are in +`architecture/capability_segregation.md`, `architecture/fuzzer.md`, +`architecture/knowledge_corpus.md`, `architecture/network_dependency_baseline.md`, +`architecture/nse_capability_inventory.md`, `architecture/nse_integration.md`, +`architecture/overview.md`, `architecture/proxy.md`, +`architecture/transport_eggfetch.md`, `docs/CAPABILITIES.md`, +`docs/CI_ARCHITECTURE_GUARDS.md`, and `docs/NSE_COMPATIBILITY.md` — all +pre-existing drift owned by other milestones. This milestone's own +documentation edits introduce no missing reference. + +**Formatting and lint on the milestone's own Rust changes.** +`cargo fmt --all --check` exits **1**, but **none of the 12 files with a +formatting diff is a file this milestone touched** — they are +`crates/eggsec-daemon-protocol/src/protocol.rs`, +`crates/eggsec-daemon/src/{host,server}.rs`, +`crates/eggsec-daemon/tests/daemon_socket_env.rs`, +`crates/eggsec-gui/src/coverage.rs`, +`crates/eggsec-gui/tests/qualification.rs`, +`crates/eggsec-runtime/src/{daemon_endpoint,report}.rs`, +`crates/eggsec-runtime/tests/daemon_endpoint.rs`, and +`crates/eggsec/src/runtime_bridge/{executor,report,report_coverage}.rs` — +all other agents' in-flight work. The three `eggsec-mobile-lab` source files +this milestone edited are rustfmt-clean. +`cargo clippy -p eggsec-mobile-lab --all-targets` exits **0** with three +warnings, all pre-existing at `HEAD`: the unused `use std::io::Cursor;` in +`invalid_zip_input_returns_error_not_panic` (`apk.rs:1233`) and two +`contains()`-vs-`iter().any()` suggestions in pre-existing test assertions +(`apk.rs:1164-1165`). `make clippy` does not lint this crate. + +**`make check` was deliberately NOT run** — the session owner runs it at +integration, per the milestone brief. + + + +### Integration verification (2026-10-24, session owner) + +The milestone's own commands were run in isolation; the owner's integration +step then ran the repository's mandatory contract over the whole tree, with +all four milestones landed together. + +| Command | Result | +|---|---| +| `make check` | **exit 0** — `cargo fmt --all --check`, the no-default-features and per-crate checks, `cargo deny --workspace --all-features check` (all five sub-checks), clippy, the full test suite (**4315 tests across 77 test binaries, 0 failures**), and `scripts/check-architecture-guards.sh` (**190 guards, "ALL PASSED: No architecture drift detected"**) | +| `make check-msrv` | **exit 0** — all five steps green on Rust 1.89 | +| `python3 scripts/check_doc_references.py` | 29 missing references — the unchanged pre-existing baseline, none of them in a file this milestone touched | + +This is the **first time `make check` has completed on this branch**: it had +always stopped at the inherited `check-deps` advisory backlog, which milestone +015 cleared. Three integration tests that milestone 010 had left stale were +found by that first complete run and corrected in `dcfcd4e2`; the corrections +are recorded as a dated addendum on milestone 010's closure record rather +than by rewriting it. + +## 5. Invariant review + +| Invariant (plan §4) | Evidence | +|---|---| +| `deny.toml` is the canonical dependency-policy source; `.cargo/audit.toml` must not exist; no `cargo audit` config may be reintroduced | No `.cargo/audit.toml` exists; `git status` shows no `.cargo/` change; `deny.toml` is the only policy file edited | +| Every retained dependency exception carries an owner, a review-by date, and a record in `docs/DEPENDENCY_EXCEPTIONS.md` | 20 ignore entries ↔ 13 records (11 active + 2 resolved), each with `| Owner |` and `| Review-by |`; guard sub-checks (c) and (d) enforce it mechanically | +| TLS is ring-only everywhere; `[bans] deny = ["aws-lc-rs"]` stands | `git diff deny.toml` touches only the `[advisories]` ignore array; the `[bans]` block is unchanged; `rustls` 0.21.12 stays only on the `tiberius` path under exception; `tokio-rustls` 0.24.1 is unchanged (0.26.5→0.26.6 is the 0.23-line `aws-lc-rs`-free copy) | +| MSRV 1.89; no upgrade may raise it | `Cargo.toml:39` unchanged; `zip` 9.1.0 declares `rust-version = "1.88"` (below the floor); the Tauri closure is unchanged | +| No new dependency without an explicit `deny.toml` decision | `cargo deny check bans` and `check licenses` both exit 0 after the bump; the 7 added and 14 removed packages are all covered by the existing allow list and the `multiple-versions = "warn"` policy; **no** `[licenses]` allow entry and **no** `[bans]` rule was added or relaxed | +| `make check-deps` fails closed when `cargo-deny` is absent | `Makefile:153` is untouched; the new guard reads the two policy files with plain text tools and does **not** depend on `cargo-deny` being installed | +| The desktop GUI is daemon-only and links no engine/daemon/CLI/TUI crate (guard 155) | Untouched: no GUI source or manifest was modified; the GUI's closure only changed through `cargo update`'s version bumps, which do not change dependency *direction* | +| `EnforcementContext::evaluate()` remains the mandatory pre-dispatch gate; strict surfaces remain fail-closed | **This milestone changed no dispatch, authorization, scope, or protocol code.** No file under `crates/eggsec/src/dispatch/`, `crates/eggsec/src/config/`, `crates/eggsec-policy/`, or the daemon protocol was edited. The only Rust edits are the `zip` call sites inside `crates/eggsec-mobile-lab` | +| Never `let _ =`; never `filter_map(|e| e.ok())`; log via `tracing` | The `zip` migration introduces no `let _ =` and no `filter_map(... .ok())`. The new fallible-name handling uses `match`/`?`-style propagation into `MobileError`, and the existing `tracing::warn!` call in the APK manifest parser is untouched | +| No full-suite run as root | Every command was run as the normal user | +| Workspace Tokio is `default-features = false` with per-crate `features = [...]` | No manifest feature policy changed. The `tokio` bump is 1.53.1 → 1.54.1 within the same major; the feature set is unchanged (no `test-util` anywhere) | +| New architecture guards start at 177; **this milestone's reserved number is 190** | The block is written as `--- Check 190: ... ---`; no other number was used | + +## 6. Failure and recovery review + +This milestone has no runtime, task, or session semantics; the relevant +failure semantics are those of the tooling and of the dependency graph. + +- **`cargo update` fails (network unavailable).** The lockfile is not + written; `cargo deny` re-reads the existing lockfile and re-reports the + same set. The committed lockfile was regenerated in this environment with + live crates.io and a live advisory database. +- **Advisory database moves between the local run and CI's run.** The + advisory database is fetched live from `https://github.com/rustsec/advisory-db` + (`deny.toml:16-17`). A new advisory published against a crate in this + workspace would fail CI's `check-deps` even though the local run is green. + This is the intended fail-closed posture; §10 records it as a standing + residual. +- **Local tool version differs from CI's.** Local `cargo-deny` is 0.20.2; CI + installs `cargo-deny@0.19.0` (`.github/workflows/ci.yml:67`). The advisory + database and the `deny.toml` semantics are the same, but *reporting* may + differ across a version boundary. **A local green is not proof of a CI + green**; the CI job is the authority. +- **Contention.** Three other agents ran cargo against the same worktree and + target directory during this milestone. Cargo serialises on its own lock; + no lock-wait failure was observed that needed a retry, and no + `cargo update` was killed. One `make check-msrv` attempt failed on disk + exhaustion (§10, F2) rather than on contention. +- **Restart and recovery.** There is no long-lived state. `Cargo.lock` is + rewritten atomically by cargo; an interrupted refresh leaves the previous + lockfile intact and re-running it is idempotent — demonstrated: a second + and third `cargo update` produced no further change. +- **Duplicate delivery.** Re-running the lockfile refresh on an + already-refreshed lockfile is a no-op (measured). Re-running the exception + recording is a no-op provided the guard's sub-checks hold (measured). The + one non-idempotent step is the negative-fixture demonstration, which + mutates a policy file; it was performed with `cp` backups and the tree was + confirmed restored afterwards. +- **Cancellation.** No tokio task is spawned by this milestone, so + `eggsec-runtime::race_with_cancel` is not involved and no timeout wrapper + is required. + +## 7. Migration and compatibility review + +### 7.1 Backward compatibility + +No wire, protocol, DTO, or persisted-format compatibility surface was +touched. The daemon protocol remains additive-only; the GUI re-attaches after +a restart rather than restoring its own state. + +### 7.2 The `zip` 2.x → 9.x migration — path taken, and why + +**Path taken: the primary path (the 9.x upgrade), with `zip`'s feature set +narrowed to the compression backends the mobile lab actually uses.** The +plan's documented fallback (recording the three `zip` entries as exceptions +and reverting to 2.x) was **not** taken. + +The narrowing was forced by a real, measured gate failure, not by +preference. `zip` 9.1.0's default `bzip2` feature pulls `bzip2` 0.6, which +defaults to `libbz2-rs-sys` 0.2.5; that crate declares +`license = "bzip2-1.0.6"`, which is **not** on the `[licenses]` allow list +(`deny.toml:39-56`). Measured result with the default feature set: + +``` +error[rejected]: failed to satisfy license requirements + ┌─ …/libbz2-rs-sys-0.2.5/Cargo.toml:27:12 +27 │ license = "bzip2-1.0.6" + │ rejected: license is not explicitly allowed + ├ libbz2-rs-sys v0.2.5 + └── bzip2 v0.6.1 + └── zip v9.1.0 +``` + +That is plan §14's stop condition — "a new transitive dependency introduced +by the `zip` bump is not covered by the `[licenses]` allow list" — and the +plan's remedy is explicit: *adding a licence is a policy decision and is out +of scope*. Adding `bzip2-1.0.6` was therefore **not** an option. + +The alternatives considered, in order: + +1. **Add the licence to the allow list.** Rejected: §5 exclusion, §14 stop + condition, and the milestone brief's hard rule. +2. **Take the documented fallback** (three `zip` exceptions, revert to 2.x). + Rejected as the *first* choice because it leaves three real + vulnerabilities live and merely suppresses them — the opposite of the + milestone's objective, and the plan's §5 "Deliverable boundary" is + "every advisory with a safe upgrade is upgraded". It remains available and + is fully specified in §10 (F1) if the owner prefers it. +3. **Narrow `zip`'s features** to `["deflate", "time"]`. **Chosen.** The + mobile lab reads and writes only `Stored` and `Deflated` entries — those + are the only two methods any APK or IPA uses in practice — so the `bzip2`, + `lzma`, `xz`, `zstd`, `ppmd`, `deflate64` and `aes-crypto` backends are + unused. Dropping them removes the offending crate entirely, keeps the + `zip` 9.1.0 security fix, and **changes no policy surface**: no licence + was added, no ban relaxed, no TLS rule touched, no MSRV moved. It is also + this repository's own convention — `Cargo.toml:88` does the same for + `schemars` ("`default-features = false` keeps them out of the graph"), and + `hickory-resolver` and `reqwest` are trimmed the same way. + +`time` is kept deliberately: it is what makes the writer stamp "now" rather +than 1980-01-01, so the archive timestamps are unchanged. `deflate` is kept +because it provides both `Deflated` writing and `Deflated` *reading*, and +because `_deflate-any` is what makes `CompressionMethod::default()` resolve +to `Deflated` — exactly as in 2.4.2. + +**Net effect on the dependency graph** (measured): 14 packages left the tree +(`aes`, `bzip2`, `bzip2-sys`, `constant_time_eq`, `deflate64`, `lzma-sys`, +`xz2`, `zstd`, `zstd-safe`, `zstd-sys`, `socks`, `arbitrary`, +`derive_arbitrary`, `tinyvec_macros`). The graph is *smaller* than the +baseline. + +**Archive-layout compatibility evidence.** The synthetic fixtures the +mobile-lab tests build were reproduced under `zip = "=2.4.2"` and +`zip = "=9.1.0"` (default-features off, `features = ["deflate", "time"]` — +the exact configuration now in the repository) in a scratch project outside +the tree, with the modification timestamp pinned on both sides so the +comparison isolates the layout from the wall clock. The two writers produced +**byte-identical archives**: + +``` +=== fixture: stored === +zip2 bytes = 354 +zip9 bytes = 354 +identical = true +--- zip2 listing --- + name=AndroidManifest.xml method=Stored size=42 compressed=42 unix_mode=Some(33188) + name=res/values/secrets.xml method=Stored size=56 compressed=56 unix_mode=Some(33188) +--- zip9 listing --- + name=AndroidManifest.xml method=Stored size=42 compressed=42 unix_mode=Some(33188) + name=res/values/secrets.xml method=Stored size=56 compressed=56 unix_mode=Some(33188) +--- listing identical = true + +=== fixture: default === +zip2 bytes = 139 +zip9 bytes = 139 +identical = true +--- zip2 listing --- + name=../../evil.xml method=Deflated size=11 compressed=13 unix_mode=Some(33188) +--- zip9 listing --- + name=../../evil.xml method=Deflated size=11 compressed=13 unix_mode=Some(33188) +--- listing identical = true +``` + +That covers plan §9's list, item by item: + +| §9 requirement | Measured | +|---|---| +| entry names and ordering unchanged | identical (`AndroidManifest.xml`, then `res/values/secrets.xml`; and the single `../../evil.xml` fixture) | +| compression method per entry unchanged | `Stored` where 2.x wrote `Stored`; `Deflated` where 2.x wrote `Deflated` (the default) — identical | +| no entry gains SUID/SGID bits or a symlink | `unix_mode=Some(33188)` = `0o100644` on both sides — a regular file with no setuid/setgid bit and no symlink bit | +| the reader still rejects a malformed archive the same way | `rejects_zipslip`, `rejects_empty_android_manifest`, `invalid_zip_input_returns_error_not_panic`, `empty_zip_returns_error_not_panic` all pass; the "ZipSlip"/"traversal" and "empty AndroidManifest" assertions are unchanged | +| no extraction step introduced | `rg 'extract\(|extract_to|unpack|extract_dir' crates/eggsec-mobile-lab/` → **no matches** | + +**The compression method was made explicit** at the five call sites that +previously relied on the crate default (`apk.rs` ×4, `adb.rs` ×1). Plan §9 +requires: "If the 9.x writer's default compression differs from 2.x's, the +implementer must set it explicitly rather than accept the new default." It +does *not* differ in the 9.1.0 + `deflate` configuration — both resolve the +default to `Deflated`, which is why the byte comparison above is identical — +but the explicit form removes the dependency of the archive layout on a +default that a future feature change could move. + +### 7.3 The `Cargo.lock` refresh + +A lockfile bump is a normal supply-chain event. It changes no public API of +the workspace. It may change the behaviour of transitive crates that moved by +a minor or patch version, which is why the mobile-lab suite and the full +`cargo-deny` sweep were re-run after it — both are green. + +### 7.4 Removal criteria for the legacy paths + +The `zip` 2.x requirement is gone from both manifests; no +`zip = ">=2, <9"`-style range was introduced to keep both alive. The +`rustls` 0.21 / `tokio-rustls` 0.24 path is **not** removed: it is retained +under exception and stays live until either the ring-only rule changes or +`tiberius` exposes a ring-only path. + +## 8. Security review + +- **Authorization, scope, and dispatch.** Unchanged. This milestone touched + no enforcement, scope, dispatch, or protocol code. `EnforcementContext::evaluate()` + remains the sole pre-dispatch gate; strict surfaces remain fail-closed. +- **The `zip` advisory cluster** concerns archive **extraction** (SUID/SGID + preservation, symlink targets escaping the destination, Unix permissions + applied through symlinks). The mobile lab never extracts: it reads + individual entries by name and writes archives with `ZipWriter`. Measured + after the migration: no `extract()`, `extract_to`, `unpack`, or + `extract_dir` call site exists in `crates/eggsec-mobile-lab`. The + compensating control is therefore void-free, and the advisory is in any + case **fixed** rather than suppressed. +- **The `rustls` 0.21-line cluster** sits behind lab-only, + operator-initiated, scope-enforced MSSQL connections, matching the + pre-existing record at `docs/DEPENDENCY_EXCEPTIONS.md`. The upgrade stays + blocked by the ring-only rule and the cluster's blast radius does not grow. +- **The `unsafe-libyaml` cluster** parses YAML that is partly + operator-supplied and partly downloaded (the scanner marketplace loader). + The record says so plainly: the advisory kind is `unmaintained`, no fixed + release exists, and the parser is exercised — the mitigation is the absence + of an upstream fix, not a claim of non-exposure. +- **The `unic-*` cluster** is reached only through the GUI's Tauri shell + closure; the crates are pure data tables with no unsafe code and no I/O. +- **TLS.** The ring-only rule is unchanged. `rustls` 0.23 (the `reqwest` path) + moved to 0.23.46, which is the patched line; `rustls` 0.21.12 stays only on + the `tiberius` path, under exception. `aws-lc-rs` remains denied. +- **Supply-chain posture.** The graph got *smaller* (14 packages removed) and + the advisory count went to zero. No new direct dependency was added to any + workspace crate. +- **No secret handling, path validation, or privilege boundary** was touched. + The mobile lab's own ZipSlip guard (`is_safe_entry_name`, plus the APK + path-traversal rejection) is unchanged and still exercised by + `rejects_zipslip`. + +## 9. Documentation and operations + +| Artifact | Change | Owner of the file | +|---|---|---| +| `deny.toml` | 11 new `[advisories] ignore` entries | this milestone | +| `docs/DEPENDENCY_EXCEPTIONS.md` | 4 new exception records; 2 `RESOLVED` records moved under a new `## Resolved Exceptions` heading; header review date updated | this milestone | +| `docs/VERIFICATION.md` | the `bash scripts/check-architecture-guards.sh` row of the "Defect classes covered" table now names Check 190 and what it pins | this milestone | +| `architecture/supply_chain.md` | new section "Repository Dependency Policy — Advisory Backlog Closure (Milestone 015)" | this milestone | +| `architecture/desktop_gui.md` | new subsection "The advisory clusters behind these pins" | this milestone | +| `scripts/check-architecture-guards.sh` | **not edited** — the Check 190 block is delivered at `/tmp/eggsec-guardwork/m015-guards.sh` for the owner to merge | shared (four agents) | +| `docs/CI_ARCHITECTURE_GUARDS.md` | **not edited** — the registration entry is delivered at `/tmp/eggsec-guardwork/m015-guards-doc.md`, with its insertion point named | shared (three agents) | +| `plans/registry.md`, `plans/subsystems/desktop-gui-frontend-roadmap.md` | **not edited** — the session owner updates both | session owner | +| `plans/closure/desktop-gui-frontend/010-…-closure.md` | **not modified**, per `plans/implementation/README.md:179` | immutable history | + +**Operator diagnostics.** `make check-deps` is now the supply-chain gate that +passes; an operator who needs to know *why* an advisory is tolerated reads +`docs/DEPENDENCY_EXCEPTIONS.md`, where every entry now carries an owner, a +review date, the dependency path, the API-use assessment, and the exact +condition that would clear it. `cargo deny` reports `advisories ok`. + +**Recovery instructions.** If a dependency upgrade lands later, the recipe is +in each record's `| Blocker |` row. For the `unic-*` cluster it is the +MSRV-1.90 + Tauri-2.12 recipe; for `glib` / `proc-macro-error` it is the +upstream gtk-rs 0.20 move; for the `rustls` 0.21 line it is either a +ring-only `tiberius` path or an ADR that relaxes the ring-only rule. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| **medium** | **F1 — the `zip` 9.x upgrade was taken with a narrowed feature set, not verbatim as plan §7 B wrote it.** Plan §7 B specifies `zip = "9"` with the default feature set; the default feature set fails `cargo deny check licenses` because `zip` 9's `bzip2` feature pulls `libbz2-rs-sys` (`license = "bzip2-1.0.6"`, not on the allow list), and adding a licence is a §5 exclusion and a §14 stop condition. The feature set was therefore narrowed to `["deflate", "time"]` (§7.2). | The three `zip` advisories are **fixed** rather than suppressed, and no policy surface moved — but the manifest no longer matches the plan's literal text, and `zip` can no longer read `bzip2`/`lzma`/`xz`/`zstd`/`ppmd`/AES entries (none of which an APK or IPA uses). | The owner should confirm the narrowing. If the maintainer prefers the plan's fallback instead: revert `crates/eggsec-mobile-lab/Cargo.toml` and `crates/eggsec/Cargo.toml` to `zip = "2"`, revert the four `crates/eggsec-mobile-lab/src/*` call sites, re-run `cargo update`, and record RUSTSEC-2026-0367 / -0368 / -0369 as three exceptions with owner `eggsec-mobile-lab`, review-by `2026-12-12`, and the "no `extract()` call site" compensating control. The archive-layout evidence in §7.2 would then no longer apply. | +| **low** | **F2 — the first `make check-msrv` attempt failed on disk exhaustion** (exit 2, `No space left on device (os error 28)`) because the machine's data volume was at 100% with three concurrent agents building in the same worktree. **The second attempt exited 0** and all five MSRV steps are green (§4). | None to the milestone's outcome — the MSRV floor holds. The environmental condition is real, though: the worktree's `target/` is ~28 GB and the machine's data volume reached 100% during this session. | Nothing for the milestone. The owner should check free disk space before the integration `make check`; concurrent builds in the same worktree are the cause. | +| **medium** | **F3 — `make check` was not run.** It is the session owner's integration step. | The end-to-end contract is not proven by this record. Every step this milestone owns was run individually: `make check-deps` (exit 0), `make check-msrv` (exit 0 on the second attempt), the Check 190 block (exit 0, plus five negative demonstrations), `cargo test -p eggsec-mobile-lab` (exit 0), and all five `cargo deny` sub-checks (exit 0). | The owner runs `make check` at integration. | +| **low** | **F4 — local `cargo-deny` is 0.20.2; CI installs `cargo-deny@0.19.0`** (`.github/workflows/ci.yml:67`). | Reporting may differ across the version boundary (ordering, extra diagnostics, and in principle whether an advisory is surfaced at all). A local green is not proof of a CI green. | The `dependency-policy` CI job is the authority. If CI reports an advisory this run did not, treat it as a new entry under plan §14's "the advisory set moves" condition. | +| **low** | **F5 — `python3 scripts/check_doc_references.py` exits 1 with 29 missing references.** None is in a file this milestone touched. | Pre-existing documentation drift; it does not affect the dependency gate, but it does make that script non-green. | Owned by the milestones that own those documents (the corpus-seam and NSE document refreshes). Not this milestone's scope. | +| **low** | **F6 — a pre-existing `unused_imports` warning in `crates/eggsec-mobile-lab/src/apk.rs`** (`use std::io::Cursor;` inside `invalid_zip_input_returns_error_not_panic`) is present at `HEAD` too. `make clippy` does not lint this crate, so the contract is unaffected. | Cosmetic. | Left untouched deliberately — it is pre-existing and unrelated to the migration. | + +**No residual advisory backlog.** Every entry that existed at the baseline is +either upgraded away or recorded with an owner, a review-by date, and a +blocking condition. `cargo deny --workspace --all-features check advisories` +reports **zero** entries, and the residual list is empty: there is no +advisory entry that remains unrecorded or un-upgraded. + +## 11. Roadmap disposition + +**Milestone closed, and the next dependency may proceed.** The roadmap's M15 +exit conditions — "`make check-deps` is green; every retained exception is +recorded with an owner and a review-by date; and `make check` completes" — +are met for the first two, and the third is the owner's integration step +(F3). The MSRV floor holds after both the refresh and the `zip` bump +(`make check-msrv` exit 0). + +**Roadmap consistency check** (plan §12, against the amendment already applied +at `plans/subsystems/desktop-gui-frontend-roadmap.md:1060-1071`): + +| The amended roadmap paragraph says | Measured | Agrees? | +|---|---|---| +| 23 entries across 20 advisory IDs (14 `vulnerability`, 7 `unmaintained`, 2 `unsound`) | 23 entries / 20 IDs, same kind split | yes | +| the patch-level lockfile refreshes clear 9 of 23 — a plurality, not a majority | exactly 6 Bucket-A bumps in the lockfile diff, satisfying all 9 advisory minimums | yes | +| 7 have an upgrade this repository's policy blocks | the 3 `rustls`/`rustls-webpki` entries (ring-only) and the `glib` entry (Tauri pin + MSRV) — 4 policy-blocked; the 3 `zip` entries were **upgraded**, not blocked | **the "7 policy-blocked" figure is superseded**: 3 of those 7 had a safe upgrade after all (the `zip` bump), and were upgraded rather than excepted | +| the remaining 7 have no safe upgrade at all | the 7 are `proc-macro-error`, `unsafe-libyaml`, and the five `unic-*` — all recorded as exceptions | yes | +| `glib` 0.18.5 is held by "the exact `tauri` pin and the MSRV floor" | **extended**: the entry is *additionally* upstream-blocked — no published `muda`/`tao`/`wry` uses gtk-rs 0.20+, and `tauri` 2.12.5 itself still declares `gtk ^0.18`. Moving the Tauri line would not clear it | the refinement required by plan §0.4 / §12 is recorded in the exception record, in `architecture/desktop_gui.md`, and in `architecture/supply_chain.md` | + +The roadmap's milestone entry, class, dependencies, deliverable boundary and +deferred-work statement were **not** rewritten — they belong to the session +owner. + +## 12. Registry updates + +Required in `plans/registry.md` (the session owner applies these): + +- Record milestone 015's implementation date and this closure record + alongside `plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md`. +- Note that the plan's `planned 2026-10-24` entry for + `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` + is now implemented, and that the 9 / 3 / 11 split held as measured. +- Note the narrowed `zip` feature set (F1) and the `make check` step still + outstanding (F3). + +Required in `plans/subsystems/desktop-gui-frontend-roadmap.md` (the session +owner applies these): + +- Move the M15 entry from planned to implemented/closed. +- Optionally carry the §11 refinement that 3 of the "7 policy-blocked" + entries were in fact upgradable (`zip`), so the amended arithmetic reads + 9 refreshed + 3 upgraded + 11 excepted = 23. diff --git a/plans/registry.md b/plans/registry.md index 66a2bcabb..9c31d48ae 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -35,7 +35,7 @@ Flat-era files (2026-07 – 2026-09) are grandfathered at the `plans/` top level | security-knowledge-corpus | **closed** | `plans/subsystems/security-knowledge-corpus-roadmap.md`; `plans/adrs/ADR-0005-knowledge-corpus-crate-ownership.md`; `plans/adrs/ADR-0006-knowledge-corpus-publication.md` | **All five milestones closed 2026-10-05.** 001 redaction deleted (guard 147); 002 `eggsec-service-db` (guards 114/148); 003 `eggsec-secrets` (guards 148/149); 004 `eggsec-payloads` (guards 148/150 + `fuzzer_payload_corpus_seam`); 005 **publication deferred** by ADR-0006. Three internal `publish = false` leaf crates with permanent engine facades, zero consumer diffs, and no regression in the corpus test contracts (verified 2026-10-06: payloads 252 / service-db 21 / secrets 11 / udp-scan 23 — all four crates are wired into `make check`) | | network-transport-egress | closed | `plans/network-dependency-hardening-roadmap-2026-09-11.md`; `plans/eggress-1.0.8-adoption-roadmap-2026-09-22.md` | Eggress 1.0.10 adoption + metadata closure (2026-09-25, implementation `fe5ec2d2`); ADR-0001, ADR-0002 controlling | | frontend-runtime-tui | active | `plans/frontend-runtime-convergence-roadmap-2026-09-10.md`; `plans/tui-terminal-ownership-corrective-roadmap-2026-09-19.md` | Reopened for `plans/implementation/frontend-runtime-tui/001-pipeline-session-registry-and-resume-picker.md` (scan session store + TUI resume picker) | -| desktop-gui-frontend | **active** | `plans/subsystems/desktop-gui-frontend-roadmap.md`; `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` (accepted); `plans/adrs/ADR-0008-operation-parameter-schema-publication.md` (accepted); `plans/adrs/ADR-0009-gui-shell-technology-selection.md` (**accepted 2026-10-23**); `plans/adrs/ADR-0010-gui-supported-platform-scope.md` (**accepted 2026-10-23**) | A desktop GUI is authorized as a **new frontend surface**, not a second product: a leaf application crate that reaches the engine only through the daemon protocol, leaving the engine, the daemon's existing message shapes, and the runtime DTOs unchanged in substance. Foundation milestones **M1–M3 are closed (2026-10-23)**: the operation-parameter schema is published over a read-only `DescribeOperations` daemon command, the frontend-client contract now lives in the frontend-neutral `eggsec-frontend-client` crate, and `DesktopGuiManual` is a first-class manual surface with GUI-attributable audit records. **`ADR-0009` was ratified on 2026-10-23** — Tauri v2 pinned to the 2.11.x line, egui pre-sanctioned as the fallback — and **M4 and M5 are now implemented (2026-10-23)**: the `crates/eggsec-gui` crate exists (**workspace: 25 crates**), and `ADR-0009`'s deferred JavaScript-dependency-policy question is discharged because the frontend ships an empty dependency set. **M6 is now implemented (2026-10-24)** — full operation coverage (a derived coverage model over every published task kind, with the daemon's enabled-feature set published additively), report export through `eggsec-output`, and an opt-in daemon spawn-and-supervise lifecycle. **M6 also fixed three defects it found**: the `DesktopGuiManual` surface was missing from the engine's permissive set, so every GUI task was denied; the daemon answered an unknown command with an empty request id, so a client waited out its timeout instead of learning the command was refused; and the GUI's Content Security Policy forbids embedding the engine's HTML document, so the report view renders structured content and the HTML format is export-only. **M7, M8, and M9 are now implemented (2026-10-23)**: **M8 defines the daemon's `service` feature profile and its reproducible build recipe**, with a machine-checked conformance test, which M6's coverage value depends on; **M9 makes the daemon obtainable and stops `eggsec daemon start` from advertising capabilities it cannot execute**; **M7 records the platform qualification matrix, the reproducible GUI build recipe, and the distribution handoff artifact**. **`ADR-0010` was accepted on 2026-10-23**: the desktop GUI's supported platforms are **Linux and macOS**, and **Windows is out of scope** because its only transport — the daemon's Unix domain socket — is unavailable there; the engine, CLI, TUI, and Python surfaces are unaffected. Binary distribution, signing, and packaging are **out of scope — handled separately** **M10 and M11 are implemented (2026-10-24)**: the daemon publishes and admits every canonical capability kind for manual execution, and it can now **hold** an operation at its confirmation point, expose the decision, and take the operator's answer — the answer being bounded by the confirmation classes the policy kernel demanded, with a strict surface never holding a decision at all. **M12–M15 are planned (2026-10-24) and their implementation plans were authored on 2026-10-24**: the daemon's socket-path default and bind contract (corrective, guards 177–179), the report bridge's full coverage (corrective, guard 180), the GUI's qualification driver and runbook (capability, guards 181–189), and the dependency advisory backlog (corrective, guard 190). The four plans reserve **disjoint guard ranges** in milestone order, following milestone 007's precedent, so an implementer taking them out of order re-derives the numbers rather than colliding. | +| desktop-gui-frontend | **active** | `plans/subsystems/desktop-gui-frontend-roadmap.md`; `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` (accepted); `plans/adrs/ADR-0008-operation-parameter-schema-publication.md` (accepted); `plans/adrs/ADR-0009-gui-shell-technology-selection.md` (**accepted 2026-10-23**); `plans/adrs/ADR-0010-gui-supported-platform-scope.md` (**accepted 2026-10-23**) | A desktop GUI is authorized as a **new frontend surface**, not a second product: a leaf application crate that reaches the engine only through the daemon protocol, leaving the engine, the daemon's existing message shapes, and the runtime DTOs unchanged in substance. Foundation milestones **M1–M3 are closed (2026-10-23)**: the operation-parameter schema is published over a read-only `DescribeOperations` daemon command, the frontend-client contract now lives in the frontend-neutral `eggsec-frontend-client` crate, and `DesktopGuiManual` is a first-class manual surface with GUI-attributable audit records. **`ADR-0009` was ratified on 2026-10-23** — Tauri v2 pinned to the 2.11.x line, egui pre-sanctioned as the fallback — and **M4 and M5 are now implemented (2026-10-23)**: the `crates/eggsec-gui` crate exists (**workspace: 25 crates**), and `ADR-0009`'s deferred JavaScript-dependency-policy question is discharged because the frontend ships an empty dependency set. **M6 is now implemented (2026-10-24)** — full operation coverage (a derived coverage model over every published task kind, with the daemon's enabled-feature set published additively), report export through `eggsec-output`, and an opt-in daemon spawn-and-supervise lifecycle. **M6 also fixed three defects it found**: the `DesktopGuiManual` surface was missing from the engine's permissive set, so every GUI task was denied; the daemon answered an unknown command with an empty request id, so a client waited out its timeout instead of learning the command was refused; and the GUI's Content Security Policy forbids embedding the engine's HTML document, so the report view renders structured content and the HTML format is export-only. **M7, M8, and M9 are now implemented (2026-10-23)**: **M8 defines the daemon's `service` feature profile and its reproducible build recipe**, with a machine-checked conformance test, which M6's coverage value depends on; **M9 makes the daemon obtainable and stops `eggsec daemon start` from advertising capabilities it cannot execute**; **M7 records the platform qualification matrix, the reproducible GUI build recipe, and the distribution handoff artifact**. **`ADR-0010` was accepted on 2026-10-23**: the desktop GUI's supported platforms are **Linux and macOS**, and **Windows is out of scope** because its only transport — the daemon's Unix domain socket — is unavailable there; the engine, CLI, TUI, and Python surfaces are unaffected. Binary distribution, signing, and packaging are **out of scope — handled separately** **M10 and M11 are implemented (2026-10-24)**: the daemon publishes and admits every canonical capability kind for manual execution, and it can now **hold** an operation at its confirmation point, expose the decision, and take the operator's answer — the answer being bounded by the confirmation classes the policy kernel demanded, with a strict surface never holding a decision at all. **M12–M15 are implemented (2026-10-24)**: the daemon's socket-path default and bind contract (corrective, guards 177–179) — the default, the `EGGSEC_DAEMON_SOCKET` name and the precedence rule now live in one place, `crates/eggsec-runtime/src/daemon_endpoint.rs`, and the server's **bind** refuses to displace a live daemon rather than the start path merely checking first; the report bridge's full coverage (corrective, guard 180) — the engine's 35 `TaskResult` variants are accounted for exactly once in a single coverage table, published by the daemon and rendered by the GUI; the GUI's qualification driver and runbook (capability, guards 181–189) — the qualification matrix is now checkable, with a hermetic procedure, an assertion harness and a validator that reads the promotion rules from the matrix itself, though the behavioural cells stay `not qualified` until an operator attests to them; and the dependency advisory backlog (corrective, guard 190) — the 23 inherited advisories are cleared, so **`make check` now runs past `check-deps` for the first time on this branch**. The four plans reserved **disjoint guard ranges** in milestone order, following milestone 007's precedent. | | python-programmability | closed | `plans/python-library-roadmap.md`; `plans/python-api-completion-roadmap.md`; `plans/python-api-high-value-roadmap.md`; `plans/python-api-release-5-roadmap.md` | Release 5 phase F compatibility/performance/release closure | | ci-verification-release | closed | `plans/ci-verification-release-simplification-roadmap.md`; `plans/ci-release-simplification-corrective-closure-index.md` | Phase K evidence-toolchain polish | | performance-resource-efficiency | closed | `plans/performance-resource-efficiency-roadmap-2026-09-21.md` | Phase F + closure-polish corrective pass | @@ -169,7 +169,7 @@ compiled with its full original test suite passing (payload corpus 233, secret d - `plans/implementation/security-knowledge-corpus/003-secret-detection-extraction.md` — **closed 2026-10-05**; closure `plans/closure/security-knowledge-corpus/003-closure.md`. `recon/secrets.rs` moved into `crates/eggsec-secrets` with a **one-line** body diff (the `Severity` import); 11 tests green, `eggsec-core` the only workspace edge, and **zero** consumer diffs — so `eggsec-python`'s exhaustive 30-arm `SecretType` match compiles untouched. Check 149 pins the owner, the facade, and freezes the AWS-scoped entropy gate at `3.5`. - `plans/implementation/security-knowledge-corpus/005-publication-qualification.md` — **closed 2026-10-05 (deferral)**; closure `plans/closure/security-knowledge-corpus/005-closure.md`, decision in `plans/adrs/ADR-0006-knowledge-corpus-publication.md` (accepted). Publication **deferred**: corpora still evolving (14 commits since 2026-06-01, `+550 payloads`), release qualification proven expensive (NSE M007C, 74-function break), `eggsec-core` would need publishing on a shared version line, **no external consumer identified**, and `eggsec-payloads` would ship a `get_payloads` that panics for 6 of 40 variants. Reopening requires all four ADR conditions. No code changed. -### desktop-gui-frontend (M1–M3 closed 2026-10-23; M4–M5 implemented 2026-10-23; M6 implemented 2026-10-24; M7 conditionally closed 2026-10-23; M8–M9 closed 2026-10-23; M10–M11 implemented 2026-10-24; M12–M15 planned 2026-10-24, implementation plans authored 2026-10-24) +### desktop-gui-frontend (M1–M3 closed 2026-10-23; M4–M5 implemented 2026-10-23; M6 implemented 2026-10-24; M7 conditionally closed 2026-10-23; M8–M9 closed 2026-10-23; M10–M11 implemented 2026-10-24; M12–M15 implemented 2026-10-24) Governed by `plans/subsystems/desktop-gui-frontend-roadmap.md` with `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md` (accepted), @@ -223,10 +223,10 @@ side effect. - `plans/implementation/desktop-gui-frontend/008-daemon-feature-profile-and-build-recipe.md` — **closed 2026-10-23**; closure `plans/closure/desktop-gui-frontend/008-daemon-feature-profile-and-build-recipe-closure.md`; `Primary class: capability`. **This milestone exists because a measurement falsified the assumption milestone 006 was built on.** `eggsec-daemon`'s `full-executor` cargo feature enables `eggsec/cli`, and the engine's `cli` feature enables only `clap` — so a `--full-executor` daemon links the engine with **none** of the engine's 28-member `full` aggregate. Milestone 006's stated user value ("the GUI reaches the engine's full feature set — the maintainer's stated requirement") is therefore unreachable with a stock daemon build. The milestone defines a **daemon feature profile** — an explicit, documented list of engine features — as a cargo feature on `crates/eggsec-daemon`, with a per-feature inclusion rationale, the system prerequisites the profile implies, a reproducible build recipe, and a **machine-checked conformance test** so the documented list cannot drift from the build. The engine's `crates/eggsec/src/config/feature_registry.rs` (50 features, a 28-member `full` aggregate, and a list of features excluded from `full` **with machine-checked reasons**) is the source of truth the profile derives from. The plan selects **Option A**, one `service` profile of 20 engine features, with `full-executor` becoming a deprecated alias. **Three corrections the plan makes to the briefing-level assumptions, each verified against source:** (a) the profile **must** enable the engine's `cli` feature — `runtime_bridge`, `commands`, and `dispatch` are all `#[cfg(feature = "cli")]` (`crates/eggsec/src/lib.rs:88-91`, `:104-105`, `:136-137`), so `cli` is a **host gate**, not a CLI surface; the negative test is scoped to the serving surfaces (`rest-api`, `grpc-api`, `ws-api`) instead; (b) `packet-inspection` needs **no** libpcap — it is pure Rust (`pnet`, `pnet_packet`, `libc`), and `nse` **vendors** OpenSSL, so it needs a C toolchain rather than system `libssl-dev` — the prose in `docs/PLATFORM.md`, `docs/FEATURE_MATRIX.md`, and `crates/eggsec/src/platform/prereqs.rs` is **stale** on both counts and must be corrected; (c) the engine's `full` aggregate does **not** include `grpc-api` (it is excluded with the reason "serving-surface"), so the profile is neither `full` nor a subset of it. Two further consequences are recorded: `deny.toml:8-12` sets `[graph] all-features = true`, so the profile narrows the **shipped binary** only and cannot remove advisory entries from `make check-deps`; and **guard 104 pins the literal** `full-executor = ["dep:eggsec", "eggsec/cli"]` (`scripts/check-architecture-guards.sh:2677-2680`), so the guard must be updated with the profile. **Boundary:** M006 owns the *runtime publication* of the enabled-feature set; M009 owns the *obtainability* path; M008 owns neither. **Implemented (closed 2026-10-23).** The profile contract landed in the engine at `crates/eggsec/src/config/daemon_profile.rs` — `DAEMON_SERVICE_PROFILE` (20 features), `DAEMON_SERVICE_EXCLUDED` (the other 30), `DAEMON_SERVICE_FORBIDDEN`, a **derived** `required_profile_features()` that reads the policy catalog rather than transcribing it, and a **pure**, fail-closed `profile_violations()`. The daemon's `service` cargo feature enables those 20 engine features and `full-executor = ["service"]` is the deprecated alias, so every existing invocation keeps working. The build recipe is `scripts/build-daemon-profile.sh` plus `make build-daemon-profile`: it pins `cargo build --release --locked -p eggsec-daemon --features service --target `, refuses a dirty tree without `--allow-dirty`, and writes a sidecar recording the commit SHA, the dirty flag, `rustc -Vv`, the toolchain, the MSRV floor, the target triple, the resolved feature set, the `Cargo.lock` hash, the size, and the SHA-256 — with **no** signing, bundling, packaging, or npm step. Conformance is machine-checked on both sides: the static half runs in every `make check` (`cargo test -p eggsec --features cli --test feature_matrix`, **43 passed**) and the runtime half compares the **compiled** feature set to the documented list (`cargo test -p eggsec-daemon --features service --test feature_profile`, **20 passed**); guard 163 pins the manifest to the engine's contract by set equality, and guard 104 was strengthened from a literal string match to a `tomllib` parse. **A separately-owned blocking fix was required first:** the `websocket` engine feature had **never compiled** — `WebSocketFuzzer::url` was `pub(crate)` inside the `eggsec-payloads` corpus crate, so the engine could not read the target it must dial (`E0616`). The defect was invisible because `websocket` is not in the engine's default feature set, so `make check` never compiled it, and it **blocked the profile's build outright**. It was landed as its own commit `7332baea`, adding a `pub fn url(&self) -> &str` accessor rather than a public field, so the corpus crate keeps control of the struct's shape. - `plans/implementation/desktop-gui-frontend/009-daemon-obtainability-and-start-honesty.md` — **closed 2026-10-23**; closure `plans/closure/desktop-gui-frontend/009-daemon-obtainability-and-start-honesty-closure.md`; `Primary class: capability`. Two defects that block the GUI and, independently, mislead CLI users today. **First, `eggsec daemon start` advertises capabilities it cannot execute**: it hosts `DaemonHost::new(config, NoopExecutor, noop_store())` (`crates/eggsec-cli/src/daemon_cli.rs:45-53`), so the daemon serves the **20**-capability conservative set while rejecting every task — and its own doc comment claims the command "delegates to the daemon binary logic" (`crates/eggsec-cli/src/daemon_cli.rs:579-584`), which the code does not do. It also prints "Daemon started" after a **fixed 100 ms** sleep whether or not the socket bound, and `run_server` unlinks the socket path before binding (`crates/eggsec-daemon/src/server.rs:89-95`), so a second daemon silently steals a live socket. **Second, nothing installs the daemon binary — and the CLI's daemon commands are not even compiled into the default install**: `crates/eggsec-cli/Cargo.toml:39` declares `default = ["tui"]`, and the `daemon`/`session`/`task` subcommands are gated behind the non-default `daemon-client` feature (`crates/eggsec/src/cli/mod.rs:463-469`), so `cargo install --path crates/eggsec-cli` yields a binary with **no `daemon` subcommand at all**. No `PATH`, sidecar, or `current_exe` convention exists anywhere in the workspace either — which is why milestone 006's daemon-lifecycle work must take an **operator-supplied** executable path. A third finding sharpens the first: the daemon's *runtime*-enforced capability set is `full_lab()` (**29** kinds, `crates/eggsec-runtime/src/runtime_config.rs:32`), not the 20 the conservative set advertises, and **both** hand-written lists omit the 30th canonical name `resume` — so three distinct sets are in play and the GUI must not assume the advertised list is either the enforced one or the canonical one. The CLI also already links the **real** engine executor at no extra dependency cost (`eggsec::runtime_bridge::EggsecRuntimeExecutor` is `#[cfg(feature = "cli")]`), which is what makes the plan's selected option cheap. The milestone delivers a documented obtainability path for the daemon binary, a decision on `eggsec daemon start`'s honesty, a real readiness wait in place of the fixed sleep, a pre-flight liveness check that refuses to displace a live daemon, and the corrected doc comment. **Boundary:** M008 owns the feature profile and M006 owns the protocol; M009 owns neither, and its code surface is outside the GUI crate. **Implemented (closed 2026-10-23).** The capability lie is now unrepresentable: `RuntimeTaskExecutor` gained one **defaulted** `supported_task_kinds()` method (its default is the conservative set, so every existing implementor keeps publishing what it published), `DaemonHost` derives its published list at construction from the executor's declaration **intersected with** the daemon's conservative policy, and the hand-set `executor_is_noop` flag was removed because the property is now computed. A rejecting executor declares the empty set, so it publishes nothing. The CLI's rejecting `NoopExecutor` was **deleted** — `eggsec daemon start` now hosts the real engine executor — and the start path was rewritten around a typed outcome (*ready* / *refused* / *failed*): it waits for a **real readiness signal** (connect + `Health` + `Capabilities` on a bounded 60 s loop, never stdout scraping), observes the spawned server task's own `Result`, reports the socket path, the protocol version, and the advertised task-kind count, and reports success **only** from the *ready* outcome. Both start paths — the CLI's and the daemon binary's — now **refuse to displace a live daemon**: the pre-flight probe connects rather than `stat`s the socket, so a stale path left by a crashed daemon does not block a start while a live one does. The obtainability path is closed by documentation: `docs/DAEMON.md` carries the exact `cargo install` recipe for the daemon binary and the CLI, states that the `--full-executor` **runtime** flag is a different mechanism from the `service` **cargo** feature, and corrects the false persistence claim. `make check` gained `cargo check` and `cargo test -p eggsec-cli --features daemon-client` — the `daemon`/`session`/`task` subcommands sit behind that non-default feature and were previously outside the merge gate entirely. **31 new tests** were added (CLI 11 · daemon host 6 · daemon integration 10 · daemon binary 1 · runtime 3), and guards 164–167 pin the honesty invariants, each negative-tested. **Two deviations are recorded in the closure:** the plan's "8 of the 20 advertised capabilities are feature-gated off" is now true only of the **CLI-hosted** daemon (the `service` profile enables all 20), and the plan's "the `full-executor` build links the engine with the `cli` feature only" was false at the baseline and was deliberately not printed as written. -- `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md` — **planned 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M12: the daemon's socket path and bind contract. **Corrective against milestone 009's deferral and milestone 004's explicit deferral of the duplication.** The plan's central measurement is that **half the milestone's exit condition is already met**: both start paths — the CLI's (`crates/eggsec-cli/src/daemon_cli.rs:141-157`) and the daemon binary's (`crates/eggsec-daemon/src/main.rs:226-233`) — run a pre-flight liveness probe that **refuses** to displace a live daemon, and the probe connects rather than `stat`s the socket, so a stale path left by a crashed daemon does not block a start. What remains open is the **server-side bind**: `run_server` still unlinks the socket path before binding (`crates/eggsec-daemon/src/server.rs:141-147`), so the refusal is *raced*, and milestone 009's own closure record names that as the deferred server-side hardening. The plan therefore moves the guarantee from "the start path checks first" to "the bind itself refuses", which closes the race by construction rather than narrowing it. The second open half is the **canonical default**: the literal `/tmp/eggsec-daemon.sock` is transcribed in six production sites, and `scripts/build-daemon-profile.sh:45` already reads an `EGGSEC_DAEMON_SOCKET` override that no Rust code honours. The plan puts the canonical constant in **`eggsec-runtime`** — measured as the unique dependency intersection of the engine, the daemon, and the GUI — in a new `daemon_endpoint.rs`, keeps the repository's existing `EGGSEC_DAEMON_SOCKET` name, and applies one precedence everywhere. Three new guards (**177–179**) pin it. -- `plans/implementation/desktop-gui-frontend/013-report-bridge-full-coverage.md` — **planned 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M13: the report bridge's full coverage. **Corrective against milestone 006.** The plan measures the engine's result type at **35** `TaskResult` variants against the bridge's **9** arms — five unconditional and four behind cargo features (`wireless`, `wireless-advanced`, `db-pentest`, `c2`) — so **26** variants fall through to `None` and a completed task leaves no store entry at all. The milestone's third exit condition is **already met** and becomes a preservation obligation: the GUI reports "the daemon has no report for task `{task_id}`, so there is nothing to export" rather than writing an empty artifact (`crates/eggsec-gui/src/commands.rs:689-691`). The plan's work is the coverage half: a 35-row table naming each variant's verdict and the missing fact where no clean mapping exists, eight new bridge arms for the families that have one, and a coverage table with exactly one home — pinned by guard **180**, which fails when a variant is neither mapped nor named. The canonical report model is unchanged, the bridge stays clock-free, and no authorisation decision changes. -- `plans/implementation/desktop-gui-frontend/014-gui-qualification-driver-and-runbook.md` — **planned 2026-10-24**; `Primary class: capability`. Covers the roadmap's M14: the GUI's qualification driver and runbook — **the first capability-class milestone in this series**, and the one that closes milestone 007's conditional close, whose `Export` column still reads `pending M006`. The plan measures the qualification matrix at **21 cells** (3 platforms × 7 behaviours) and finds that **eight** — Connect, Submit, Cancel, Render on Linux and macOS — are blocked on the absence of a driver, while the two export cells are blocked on a procedure that was never written. It also finds the matrix **stale**: it claims the GUI has "no `export` reference anywhere in `crates/eggsec-gui/frontend/app.js`" (the frontend has 50, including `export_report` at `app.js:1624`), and it cites `crates/eggsec-daemon/src/server.rs:95` for the bind, which moved to `:147`. The plan chooses the **operator-procedure** route over a headless driver — a GitHub-hosted runner has no display server, and the matrix's own promotion rule (`docs/GUI_PLATFORM_QUALIFICATION.md:232-237`) already routes the behavioural columns through the runbook steps in `docs/GUI_BUILD.md` §5 — and adds a hermetic in-crate harness, the missing export procedure, and nine new guards (**181–189**). -- `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` — **planned 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M15: the dependency advisory backlog — the last thing stopping the repository's mandatory contract from completing. **Corrective against the inherited backlog** that milestone 010's closure recorded but did not own. The backlog is measured at **23 entries across 20 advisory IDs** (14 `vulnerability`, 7 `unmaintained`, 2 `unsound`) and splits three ways: **9** cleared by a lockfile refresh alone (verified with `cargo update --dry-run`, which proposes `ctutils` 0.4.5, `rustls` 0.23.46, `rustls-webpki` 0.103.16, `tokio` 1.54.1, `webpki-roots` 1.0.11, `webpki-root-certs` 1.0.11); **7** with an upgrade this repository's policy blocks — the `rustls` 0.21 line and `rustls-webpki` 0.101.7 are reachable only through `tiberius`, whose upgrade pulls `tokio-rustls` with default features and so enables the `aws-lc-rs` provider the ring-only rule forbids, and `glib` 0.18.5 is held by the exact `tauri` pin and the MSRV 1.89 floor; and **7** with no safe upgrade at all. The plan records that the roadmap's "a majority" claim is a **plurality** (9 of 23), corrects the roadmap, and requires every retained exception to carry an owner and a review-by date in `docs/DEPENDENCY_EXCEPTIONS.md`, pinned by guard **190**. +- `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md` — **implemented 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M12: the daemon's socket path and bind contract. **Corrective against milestone 009's deferral and milestone 004's explicit deferral of the duplication.** The plan's central measurement is that **half the milestone's exit condition is already met**: both start paths — the CLI's (`crates/eggsec-cli/src/daemon_cli.rs:141-157`) and the daemon binary's (`crates/eggsec-daemon/src/main.rs:226-233`) — run a pre-flight liveness probe that **refuses** to displace a live daemon, and the probe connects rather than `stat`s the socket, so a stale path left by a crashed daemon does not block a start. What remains open is the **server-side bind**: `run_server` still unlinks the socket path before binding (`crates/eggsec-daemon/src/server.rs:141-147`), so the refusal is *raced*, and milestone 009's own closure record names that as the deferred server-side hardening. The plan therefore moves the guarantee from "the start path checks first" to "the bind itself refuses", which closes the race by construction rather than narrowing it. The second open half is the **canonical default**: the literal `/tmp/eggsec-daemon.sock` is transcribed in six production sites, and `scripts/build-daemon-profile.sh:45` already reads an `EGGSEC_DAEMON_SOCKET` override that no Rust code honours. The plan puts the canonical constant in **`eggsec-runtime`** — measured as the unique dependency intersection of the engine, the daemon, and the GUI — in a new `daemon_endpoint.rs`, keeps the repository's existing `EGGSEC_DAEMON_SOCKET` name, and applies one precedence everywhere. Three new guards (**177–179**) pin it. Closure record: `plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md`. +- `plans/implementation/desktop-gui-frontend/013-report-bridge-full-coverage.md` — **implemented 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M13: the report bridge's full coverage. **Corrective against milestone 006.** The plan measures the engine's result type at **35** `TaskResult` variants against the bridge's **9** arms — five unconditional and four behind cargo features (`wireless`, `wireless-advanced`, `db-pentest`, `c2`) — so **26** variants fall through to `None` and a completed task leaves no store entry at all. The milestone's third exit condition is **already met** and becomes a preservation obligation: the GUI reports "the daemon has no report for task `{task_id}`, so there is nothing to export" rather than writing an empty artifact (`crates/eggsec-gui/src/commands.rs:689-691`). The plan's work is the coverage half: a 35-row table naming each variant's verdict and the missing fact where no clean mapping exists, eight new bridge arms for the families that have one, and a coverage table with exactly one home — pinned by guard **180**, which fails when a variant is neither mapped nor named. The canonical report model is unchanged, the bridge stays clock-free, and no authorisation decision changes. Closure record: `plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md`. +- `plans/implementation/desktop-gui-frontend/014-gui-qualification-driver-and-runbook.md` — **implemented 2026-10-24**; `Primary class: capability`. Covers the roadmap's M14: the GUI's qualification driver and runbook — **the first capability-class milestone in this series**, and the one that closes milestone 007's conditional close, whose `Export` column still reads `pending M006`. The plan measures the qualification matrix at **21 cells** (3 platforms × 7 behaviours) and finds that **eight** — Connect, Submit, Cancel, Render on Linux and macOS — are blocked on the absence of a driver, while the two export cells are blocked on a procedure that was never written. It also finds the matrix **stale**: it claims the GUI has "no `export` reference anywhere in `crates/eggsec-gui/frontend/app.js`" (the frontend has 50, including `export_report` at `app.js:1624`), and it cites `crates/eggsec-daemon/src/server.rs:95` for the bind, which moved to `:147`. The plan chooses the **operator-procedure** route over a headless driver — a GitHub-hosted runner has no display server, and the matrix's own promotion rule (`docs/GUI_PLATFORM_QUALIFICATION.md:232-237`) already routes the behavioural columns through the runbook steps in `docs/GUI_BUILD.md` §5 — and adds a hermetic in-crate harness, the missing export procedure, and nine new guards (**181–189**). Closure record: `plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md`. **The cells are promotable, not promoted**: the behavioural columns need an operator attestation that no CI run can supply, so they stay `not qualified`. +- `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` — **implemented 2026-10-24**; `Primary class: corrective`. Covers the roadmap's M15: the dependency advisory backlog — the last thing stopping the repository's mandatory contract from completing. **Corrective against the inherited backlog** that milestone 010's closure recorded but did not own. The backlog is measured at **23 entries across 20 advisory IDs** (14 `vulnerability`, 7 `unmaintained`, 2 `unsound`) and splits three ways: **9** cleared by a lockfile refresh alone (verified with `cargo update --dry-run`, which proposes `ctutils` 0.4.5, `rustls` 0.23.46, `rustls-webpki` 0.103.16, `tokio` 1.54.1, `webpki-roots` 1.0.11, `webpki-root-certs` 1.0.11); **7** with an upgrade this repository's policy blocks — the `rustls` 0.21 line and `rustls-webpki` 0.101.7 are reachable only through `tiberius`, whose upgrade pulls `tokio-rustls` with default features and so enables the `aws-lc-rs` provider the ring-only rule forbids, and `glib` 0.18.5 is held by the exact `tauri` pin and the MSRV 1.89 floor; and **7** with no safe upgrade at all. The plan records that the roadmap's "a majority" claim is a **plurality** (9 of 23), corrects the roadmap, and requires every retained exception to carry an owner and a review-by date in `docs/DEPENDENCY_EXCEPTIONS.md`, pinned by guard **190**. Closure record: `plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md`. **The backlog is closed**: `cargo deny --workspace --all-features check` is green, so `make check` now runs past `check-deps` for the first time on this branch. **One workspace-wide dependency issue is open, and it is partly attributable to this subsystem:** `make check-deps` reports `advisories FAILED`. Recording an exception needs an owner and a review-by date, so it is a maintainer decision. The engine-side entries are the `rustls 0.21.12` family (via `tokio-rustls 0.24.1` → `tiberius 0.12.3` → `eggsec`), `zip 2.4.2` (three advisories: RUSTSEC-2026-0367, -0368, -0369), `rustls 0.23.45` / `rustls-webpki 0.103.15`, `ctutils`, `unsafe-libyaml`, `webpki-roots`, `tokio`, and `webpki-root-certs`. **Seven further advisory entries are reachable only through the GUI's Tauri closure and are therefore attributable to `crates/eggsec-gui`**: `glib 0.18.5` (RUSTSEC-2024-0429, unsound) and `glib-macros 0.18.5` → `proc-macro-error 1.0.4` (RUSTSEC-2024-0370, unmaintained), both via `tauri` → `gtk` → `atk`; and the five `unic-*` crates — `unic-char-property`, `unic-char-range`, `unic-common`, `unic-ucd-ident`, `unic-ucd-version` (RUSTSEC-2025-0081, -0075, -0080, -0100, -0098) — via `tauri-utils` → `urlpattern` → `unic-ucd-ident`. This was verified against the dependency graph rather than inferred: the engine's tree contains **no** `glib`, `glib-macros`, `urlpattern`, or `unic-*` crate on either the host or the Linux target, while the GUI's tree contains all of them. @@ -269,7 +269,7 @@ All closure evidence for flat-era work lives inline in the files above (appended | Crate boundaries | crate-boundary Phase D; `architecture/overview.md` dependency map | | Transport/egress | Eggress 1.0.10 closure; ADR-0001, ADR-0002; `architecture/transport_eggfetch.md`, `architecture/network_dependency_closure.md` | | Frontend/runtime | frontend-runtime Phase 3 + TUI terminal-ownership Phase B; `architecture/tui.md`, `architecture/runtime_bridge.md` | -| Desktop GUI frontend | `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md`; `plans/adrs/ADR-0008-operation-parameter-schema-publication.md`; `plans/adrs/ADR-0009-gui-shell-technology-selection.md` (**accepted 2026-10-23**); `plans/adrs/ADR-0010-gui-supported-platform-scope.md` (**accepted 2026-10-23**); `plans/subsystems/desktop-gui-frontend-roadmap.md`; `plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md`, `-002-frontend-client-contract-extraction-closure.md`, `-003-desktop-gui-surface-parity-closure.md` (M1–M3 closed 2026-10-23), `-004-gui-shell-skeleton-closure.md`, `-005-schema-driven-forms-and-task-dashboard-closure.md` (M4–M5 implemented 2026-10-23), `-007-packaging-and-platform-qualification-closure.md` (M7 conditionally closed 2026-10-23), `-008-daemon-feature-profile-and-build-recipe-closure.md`, `-009-daemon-obtainability-and-start-honesty-closure.md` (M8–M9 closed 2026-10-23), `-006-full-operation-coverage-and-report-export-closure.md`, `-010-daemon-full-manual-capability-policy-closure.md`, `-011-daemon-mediated-policy-approval-closure.md` (M6, M10, M11 implemented 2026-10-24); `plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md`, `-005-schema-driven-forms-and-task-dashboard.md` (both implemented 2026-10-23), `-007-packaging-and-platform-qualification.md`, `-008-daemon-feature-profile-and-build-recipe.md`, `-009-daemon-obtainability-and-start-honesty.md` (implemented 2026-10-23), `-006-full-operation-coverage-and-report-export.md`, `-010-daemon-full-manual-capability-policy.md`, `-011-daemon-mediated-policy-approval.md` (implemented 2026-10-24); `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md`, `-013-report-bridge-full-coverage.md`, `-014-gui-qualification-driver-and-runbook.md`, `-015-dependency-advisory-backlog.md` (planned 2026-10-24) | +| Desktop GUI frontend | `plans/adrs/ADR-0007-desktop-gui-frontend-boundary.md`; `plans/adrs/ADR-0008-operation-parameter-schema-publication.md`; `plans/adrs/ADR-0009-gui-shell-technology-selection.md` (**accepted 2026-10-23**); `plans/adrs/ADR-0010-gui-supported-platform-scope.md` (**accepted 2026-10-23**); `plans/subsystems/desktop-gui-frontend-roadmap.md`; `plans/closure/desktop-gui-frontend/001-operation-parameter-schema-publication-closure.md`, `-002-frontend-client-contract-extraction-closure.md`, `-003-desktop-gui-surface-parity-closure.md` (M1–M3 closed 2026-10-23), `-004-gui-shell-skeleton-closure.md`, `-005-schema-driven-forms-and-task-dashboard-closure.md` (M4–M5 implemented 2026-10-23), `-007-packaging-and-platform-qualification-closure.md` (M7 conditionally closed 2026-10-23), `-008-daemon-feature-profile-and-build-recipe-closure.md`, `-009-daemon-obtainability-and-start-honesty-closure.md` (M8–M9 closed 2026-10-23), `-006-full-operation-coverage-and-report-export-closure.md`, `-010-daemon-full-manual-capability-policy-closure.md`, `-011-daemon-mediated-policy-approval-closure.md` (M6, M10, M11 implemented 2026-10-24), `-012-daemon-socket-path-and-bind-contract-closure.md`, `-013-report-bridge-full-coverage-closure.md`, `-014-gui-qualification-driver-and-runbook-closure.md`, `-015-dependency-advisory-backlog-closure.md` (M12–M15 implemented 2026-10-24); `plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md` (**proposed 2026-10-24** — M12's decision; acceptance is the maintainer's); `plans/implementation/desktop-gui-frontend/004-gui-shell-skeleton.md`, `-005-schema-driven-forms-and-task-dashboard.md` (both implemented 2026-10-23), `-007-packaging-and-platform-qualification.md`, `-008-daemon-feature-profile-and-build-recipe.md`, `-009-daemon-obtainability-and-start-honesty.md` (implemented 2026-10-23), `-006-full-operation-coverage-and-report-export.md`, `-010-daemon-full-manual-capability-policy.md`, `-011-daemon-mediated-policy-approval.md` (implemented 2026-10-24); `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md`, `-013-report-bridge-full-coverage.md`, `-014-gui-qualification-driver-and-runbook.md`, `-015-dependency-advisory-backlog.md` (implemented 2026-10-24) | | Python API | Release 5 phase F; `architecture/python_api.md` | | CI/release | Phase K; `docs/VERIFICATION.md` | | Performance | Phase F + polish corrective; `architecture/performance.md` | diff --git a/plans/subsystems/desktop-gui-frontend-roadmap.md b/plans/subsystems/desktop-gui-frontend-roadmap.md index 3517d6ae1..1500a01e2 100644 --- a/plans/subsystems/desktop-gui-frontend-roadmap.md +++ b/plans/subsystems/desktop-gui-frontend-roadmap.md @@ -1,6 +1,6 @@ # Desktop GUI Frontend Roadmap -Status: active (M1–M3 closed 2026-10-23; ADR-0009 ratified 2026-10-23; M4 and M5 implemented 2026-10-23; M7 conditionally closed 2026-10-23; M8 and M9 closed 2026-10-23; M6 implemented 2026-10-24; M10 and M11 implemented 2026-10-24; M12–M15 planned 2026-10-24, implementation plans authored 2026-10-24) +Status: active (M1–M3 closed 2026-10-23; ADR-0009 ratified 2026-10-23; M4 and M5 implemented 2026-10-23; M7 conditionally closed 2026-10-23; M8 and M9 closed 2026-10-23; M6 implemented 2026-10-24; M10 and M11 implemented 2026-10-24; M12–M15 implemented 2026-10-24) Long-term references: @@ -1251,7 +1251,7 @@ This roadmap is closed when: | 9 — Daemon obtainability and start honesty | **closed 2026-10-23** | `plans/implementation/desktop-gui-frontend/009-daemon-obtainability-and-start-honesty.md` | `plans/closure/desktop-gui-frontend/009-daemon-obtainability-and-start-honesty-closure.md` | — (M8 met: closed 2026-10-23) | | 10 — The daemon's full manual capability policy | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/010-daemon-full-manual-capability-policy.md` | `plans/closure/desktop-gui-frontend/010-daemon-full-manual-capability-policy-closure.md` | `ADR-0011` (**met** — accepted 2026-10-24); M9 (met — closed 2026-10-23) | | 11 — Daemon-mediated policy approval | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/011-daemon-mediated-policy-approval.md` | `plans/closure/desktop-gui-frontend/011-daemon-mediated-policy-approval-closure.md` | M10 (met — implemented 2026-10-24); `ADR-0012` (implemented as written; acceptance is the maintainer's) | -| 12 — The daemon's socket path and bind contract | **planned 2026-10-24** | `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md` | — | M9 (met — closed 2026-10-23; the start-path refusal and the liveness probe already exist, so the open half is the server-side bind and the canonical default) | -| 13 — The report bridge's full coverage | **planned 2026-10-24** | `plans/implementation/desktop-gui-frontend/013-report-bridge-full-coverage.md` | — | M6 (met — implemented 2026-10-24) | -| 14 — The GUI's qualification driver and runbook | **planned 2026-10-24** | `plans/implementation/desktop-gui-frontend/014-gui-qualification-driver-and-runbook.md` | — | M7 (met — conditionally closed 2026-10-23); M6 (met) | -| 15 — The dependency advisory backlog | **planned 2026-10-24** | `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` | — | — | +| 12 — The daemon's socket path and bind contract | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract.md` | `plans/closure/desktop-gui-frontend/012-daemon-socket-path-and-bind-contract-closure.md` | M9 (met — closed 2026-10-23); `ADR-0013` (implemented as written; acceptance is the maintainer's) | +| 13 — The report bridge's full coverage | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/013-report-bridge-full-coverage.md` | `plans/closure/desktop-gui-frontend/013-report-bridge-full-coverage-closure.md` | M6 (met — implemented 2026-10-24) | +| 14 — The GUI's qualification driver and runbook | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/014-gui-qualification-driver-and-runbook.md` | `plans/closure/desktop-gui-frontend/014-gui-qualification-driver-and-runbook-closure.md` | M7 (met — conditionally closed 2026-10-23); M6 (met). **The cells are promotable, not promoted** — the behavioural columns need an operator attestation no CI run can supply, so they stay `not qualified` | +| 15 — The dependency advisory backlog | **implemented 2026-10-24** | `plans/implementation/desktop-gui-frontend/015-dependency-advisory-backlog.md` | `plans/closure/desktop-gui-frontend/015-dependency-advisory-backlog-closure.md` | — (`cargo deny --workspace --all-features check` is green; `make check` now runs past `check-deps` for the first time on this branch) | From cf3aa450f91cd62bba2a2996f3389ae51d5cc2bb Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Sat, 24 Oct 2026 22:38:16 +0000 Subject: [PATCH 24/52] feat(qualification): add the operator-attestation path to the GUI qualification The desktop GUI's platform-qualification matrix promotes the behavioural columns on rule P1, which requires both a scripted outcome of `pass` and an operator outcome of `pass`. Nothing could write that second value: the harness emitted `not-performed` at every one of its sites, and the only documented route to a promotion was a hand edit of the record's json block -- which a later run silently overwrites. That is a promotion with no tooling behind it. This adds the missing machinery rather than weakening the rule. An operator writes an attestation file of their own (schema `eggsec-gui-operator-attestation/v1`) naming who observed the behaviours, when, on which platform, against which commit, and what they saw for each column. The procedure merges it into the record in the same write that produces the record, so the record has one writer and a later run cannot erase the attestation. The validator refuses an unattributed `pass`, an attestation that names another platform or another commit, and an attestation that claims a column passed whose scripted outcome was not `pass`. `--run-label` lets a day with two runs keep two records rather than one overwriting the other. Guard 191 pins the three facts that make the machinery real and the two that keep it honest: the procedure accepts an attestation and passes it to the record writer, the validator knows the schema and refuses an unattributed pass, no code path defaults an operator outcome to `pass`, the harness never self-attests, and the matrix's own rule P1 still requires the operator's `pass`. It was negative-tested against five injected violations -- the procedure losing the flag, the flag not reaching the writer, P1 weakened to `not-applicable`, the harness emitting a pass, and the validator defaulting an outcome to `pass` -- and it caught every one of them. Verified: `python3 scripts/check_gui_qualification.py --self-test` (17 cases), `python3 scripts/check_gui_qualification.py` (the existing CI-mode record stays valid), `bash scripts/check-architecture-guards.sh` (191 guards). --- docs/CI_ARCHITECTURE_GUARDS.md | 5 +- docs/GUI_BUILD.md | 61 ++- docs/GUI_PLATFORM_QUALIFICATION.md | 19 +- docs/evidence/gui-qualification/TEMPLATE.md | 89 ++- scripts/check-architecture-guards.sh | 138 +++++ scripts/check_gui_qualification.py | 572 +++++++++++++++++++- scripts/gui_qualification.sh | 79 ++- 7 files changed, 940 insertions(+), 23 deletions(-) diff --git a/docs/CI_ARCHITECTURE_GUARDS.md b/docs/CI_ARCHITECTURE_GUARDS.md index e73d27218..bdedc5c26 100644 --- a/docs/CI_ARCHITECTURE_GUARDS.md +++ b/docs/CI_ARCHITECTURE_GUARDS.md @@ -285,9 +285,9 @@ Milestone 013 gave the report bridge a **coverage table**: the single source of - The coverage table and the bridge's arms **agree** (Check 180): the guard reads the `TaskResult` variants from `crates/eggsec/src/dispatch/types.rs` and the variant lists from `crates/eggsec/src/runtime_bridge/report_coverage.rs` and asserts that the two sets are equal, so a new result variant that no row names fails the check rather than silently producing no report. It also asserts that every variant the table calls *canonical* has a `TaskResult::` arm in `crates/eggsec/src/runtime_bridge/report.rs`, that every bridge arm is a canonical row, that an excluded variant has no arm, and that the table exists in exactly one place — a second copy would be a second hand-maintained catalog. The names are read from their owners, never transcribed in the guard. -### Desktop-GUI Platform-Qualification Invariants (2026-10-24, guards Check 181–189) +### Desktop-GUI Platform-Qualification Invariants (2026-10-24, guards Check 181–189 and Check 191) -Milestone 014 made the desktop GUI's qualification matrix **checkable**. The matrix's behavioural columns were unpromotable because nothing produced the evidence they claim and nothing checked the claims that existed. The procedure (`scripts/gui_qualification.sh`), the harness (`crates/eggsec-gui/tests/qualification.rs`), and the validator (`scripts/check_gui_qualification.py`) close that loop, and nine checks pin it: +Milestone 014 made the desktop GUI's qualification matrix **checkable**. The matrix's behavioural columns were unpromotable because nothing produced the evidence they claim and nothing checked the claims that existed. The procedure (`scripts/gui_qualification.sh`), the harness (`crates/eggsec-gui/tests/qualification.rs`), and the validator (`scripts/check_gui_qualification.py`) close that loop, and the checks below pin it: - The **export procedure is written** (Check 181): `docs/GUI_BUILD.md` §5.7 must contain no `Not yet defined`, must have a non-empty Action row, a non-empty Pass criterion row, and a non-empty Evidence artefact row, must name the `export_report` command, and must name all six formats (`json`, `csv`, `html`, `md`, `sarif`, `xml`). A column with no procedure is a column nobody can run. - The **retired milestone token stays retired** (Check 182): if `crates/eggsec-gui/frontend/app.js` contains `export_report`, then `docs/GUI_PLATFORM_QUALIFICATION.md` contains no `pending M6`. The token described a block that no longer exists; a token that can outlive its cause is a token that lies. @@ -298,6 +298,7 @@ Milestone 014 made the desktop GUI's qualification matrix **checkable**. The mat - The **procedure is hermetic** (Check 187): `scripts/gui_qualification.sh` must not name `sudo`, must not remove anything recursively, and must name no absolute path outside the temporary root. The procedure runs on a developer's machine and on a CI runner; it must never need privileges the operator has to go and find. - The **promotion validator is green** (Check 188): `python3 scripts/check_gui_qualification.py` must exit 0. The matrix's rules are enforced by a program, not by a reader's diligence. - The **CI job publishes the qualification record** (Check 189): the `gui-platform` job in `.github/workflows/deep-checks.yml` must run `scripts/gui_qualification.sh` and must publish the run record as a job artefact named `gui-qualification-${{ matrix.os }}`. A CI run nobody can read is not evidence. +- An **operator attestation is attributed, and never defaulted** (Check 191): the qualification procedure must accept an `--attestation` file and must pass it to the record writer; the validator must declare the `eggsec-gui-operator-attestation/v1` schema, must refuse an operator outcome of `pass` that no named human signed, and must refuse one that carries no observation; **no code path may default an operator outcome to `pass`** — the only writer of a `pass` is the merge of a signed attestation; the harness must never emit an operator `pass`, because the machine cannot attest for a human; and the matrix's own rule **P1** must still require the operator outcome `pass` for the behavioural columns. Before this machinery existed the only documented route to a promotion was a hand edit of the record's json block, which a later run silently overwrites — a promotion with no tooling behind it. ### NSE Subsystem Invariants - The standalone [eggsec-nse CI](https://github.com/eggstack/eggsec-nse/actions) owns runtime-internal checks: resolver-only script/module loading, per-run `NseRunReport.libraries`, profile/executor construction, library registry consistency, capability wrappers, and runtime corpus assertions. diff --git a/docs/GUI_BUILD.md b/docs/GUI_BUILD.md index a89fa1cc7..7f01d5977 100644 --- a/docs/GUI_BUILD.md +++ b/docs/GUI_BUILD.md @@ -512,7 +512,66 @@ rule P4 needs, but rule P4 also needs the operator's attestation. Until an operator-attested run exists, the cell says what the harness measured and what is still missing. -### 5.8 The repeatability contract +### 5.8 The operator's attestation + +The seven steps above have two halves. The **scripted** half is what the +machine measured: the harness drives the GUI's own client, form engine and +export path against a live daemon, and the record carries the outcome. The +**operator** half is what a person saw. The matrix's rules read both, and the +behavioural columns (Connect, Submit, Cancel, Render, Export) are promoted on +the pair — a cell is not promoted on the scripted half alone. + +The attestation is a file of its own, written by the operator once the +behaviours have been observed, and it is merged into the record in the same +write that produces the record: + +``` +docs/evidence/gui-qualification/-.attestation.json +``` + +```json +{ + "schema": "eggsec-gui-operator-attestation/v1", + "attested_by": "the operator's name", + "attested_at": "YYYY-MM-DD", + "platform": "macos", + "commit": "the commit the behaviours were observed against", + "columns": { + "connect": { + "outcome": "pass", + "observed": "what the operator saw" + } + } +} +``` + +Then re-run the procedure with it: + +``` +bash scripts/gui_qualification.sh --platform macos --mode operator \ + --attestation docs/evidence/gui-qualification/macos-2026-10-24-operator.attestation.json +``` + +**What the validator refuses.** An attestation is refused when it names no +human (`attested_by` empty), when its date is malformed, when it names a +platform the run was not made on, when it names a commit the run was not made +at, or when it claims a column passed whose scripted outcome was not `pass` — +an operator cannot attest to a behaviour the run did not observe. And a +record that carries an operator outcome of `pass` with **no** attestation +block, an empty attester, or no observation is rejected outright: a `pass` +that nobody signed is not an attestation. + +**Why it is a file and not a hand edit.** The attestation is merged by the +procedure that writes the record, so the record has one writer. A hand edit +of the record's json block would be overwritten by the next run — a promotion +that a later run silently erases is not a promotion. + +**A CI run cannot attest.** `--mode ci` accepts an attestation and merges it +as given, but the attestation is still the human's record, not the job's: the +`gui-platform` job has nobody to observe with, so every column it produces +carries `operator: not-performed`. + +### 5.9 The repeatability contract The same steps, on the same platform, with the same daemon, produce the same observable outcomes. diff --git a/docs/GUI_PLATFORM_QUALIFICATION.md b/docs/GUI_PLATFORM_QUALIFICATION.md index 993867ccb..9f4d26f18 100644 --- a/docs/GUI_PLATFORM_QUALIFICATION.md +++ b/docs/GUI_PLATFORM_QUALIFICATION.md @@ -157,7 +157,10 @@ docs/evidence/gui-qualification/ macos-2026-10-24.export.json # the exported report ``` -One file per run, named `-.md`. The filename is part of +One file per run, named `-.md`. A second run on the same +day adds a label: `--run-label operator` names it +`--