diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a96d1922f..fe8c9043e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,10 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable with: components: rustfmt, clippy @@ -43,9 +47,15 @@ jobs: - name: Install cargo-deny (SHA-pinned) 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 + # 0.20.2, the version the local contract runs: two versions of the + # tool must not decide the same policy differently (milestone 015's + # finding F4 -- a local green must be proof of a CI green). + tool: cargo-deny@0.20.2 + # 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 @@ -56,12 +66,19 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - name: Install cargo-deny (SHA-pinned) uses: taiki-e/install-action@c02248eec042a8a90b2335f60bb37dc287b54068 # cargo-deny with: - tool: cargo-deny@0.19.0 + # 0.20.2, the version the local contract runs: two versions of the + # tool must not decide the same policy differently (milestone 015's + # finding F4 -- a local green must be proof of a CI green). + tool: cargo-deny@0.20.2 - name: Advisory/license/source policy over full workspace closure run: make check-deps @@ -74,6 +91,10 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - name: Dependency review (vulnerabilities, moderate+ fails) uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 with: @@ -85,6 +106,10 @@ jobs: # maintain a separate license allowlist, so no deny-licenses is # set here — contradictory allowlists are a Phase F violation. fail-on-severity: moderate + # This is the GTK 0.18 advisory already reviewed and documented in + # deny.toml and docs/DEPENDENCY_EXCEPTIONS.md. Tauri currently pins + # this Linux shell dependency closure upstream. + allow-ghsas: GHSA-wrw7-89jp-8q8g python: name: Python @@ -93,6 +118,10 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 diff --git a/.github/workflows/deep-checks.yml b/.github/workflows/deep-checks.yml index b30c3d364..93ff7468e 100644 --- a/.github/workflows/deep-checks.yml +++ b/.github/workflows/deep-checks.yml @@ -21,14 +21,24 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + # 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: - tool: cargo-deny@0.19.0 + # 0.20.2, the version the local contract runs: two versions of the + # tool must not decide the same policy differently (milestone 015's + # finding F4 -- a local green must be proof of a CI green). + tool: cargo-deny@0.20.2 - name: Optional broad validation run: make check-full - name: Exhaustive per-feature compilation sweep @@ -41,19 +51,22 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@02cb101ec7c40f2c49e1d9714d64511d8e1b74de # master (toolchain input pins 1.89) with: toolchain: "1.89" - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 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 }}) @@ -66,6 +79,10 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: @@ -73,6 +90,112 @@ jobs: - name: Check compilation run: cargo check -p eggsec + # The desktop GUI's platform qualification (milestone 007). + # + # WINDOWS IS EXCLUDED BY DECISION (ADR-0010), not by oversight: the desktop + # GUI's supported platforms are Linux and macOS. The measured reason is that + # the GUI's UNCONDITIONAL dependency `eggsec-frontend-client` imports the + # Unix-domain-socket transport without a cfg(unix) gate + # (crates/eggsec-frontend-client/src/daemon.rs:9 and :56), so + # `cargo check -p eggsec-frontend-client --target x86_64-pc-windows-msvc` + # fails with E0432/E0433/E0599 and the GUI does not compile for Windows at + # all. A Windows leg here would be permanently red rather than informative. + # Adding it is gated on the daemon-transport milestone ADR-0010 names: a + # Windows daemon transport (named pipes or equivalent local IPC) changes the + # KIND of transport rather than adding a read path, so it requires an ADR. + gui-platform: + name: GUI platform (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + # The platform label the qualification procedure records. It is the + # matrix's own fact, not the runner's name. + include: + - os: ubuntu-latest + platform: linux + - os: macos-latest + platform: macos + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + key: gui-platform-${{ matrix.os }} + # The Linux webview SDK. The package list is the workspace's own subset + # (the GitHub-hosted image pre-installs the build toolchain and + # libssl-dev, which is why `build-essential`, `curl`, `wget`, `file`, + # `libxdo-dev`, and `libssl-dev` are absent from it). The full Tauri + # list, and what the omission costs on a bare distribution, is in + # docs/GUI_BUILD.md. + - name: Install the Linux webview prerequisites + if: runner.os == 'Linux' + 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 + # The probe reports BUILDABLE or NOT BUILDABLE; it never says "skipped", + # because a qualification cell needs an answer, not an absence of one. + - name: Probe the GUI shell prerequisites + run: bash scripts/check_gui_prereqs.sh + # The UNGATED check, not the gated `make check` line: on Linux the gated + # line skips when the webview SDK is absent, and this job's whole point + # is to prove the SDK is present AND the shell compiles. + - name: Desktop GUI shell profile (ungated) + run: make check-gui + # Both test profiles: the `shell` feature gates commands.rs and shell.rs, + # so the non-shell path has to be exercised too. The GUI's tests are + # headless-safe (no socket, no window, no subprocess), so they run + # unattended with no display. + - name: GUI test suite (shell profile) + run: cargo test -p eggsec-gui --features shell --lib + - name: GUI test suite (no-shell profile) + run: cargo test -p eggsec-gui --no-default-features --lib + - name: Build the release binary and its metadata sidecar + run: make gui-release + # The sidecar and the checksum are what let a matrix cell cite a CI run + # URL instead of a claim. + - name: Upload the build metadata and checksum + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: gui-release-${{ matrix.os }} + path: | + dist/gui/eggsec-gui.build.json + dist/gui/SHA256SUMS + if-no-files-found: error + # The GUI reaches the engine only through a daemon that carries the + # engine executor, so the harness needs a `service`-profile daemon. The + # profile is heavy (it links the engine), which is why this job lives in + # the scheduled deep-checks workflow rather than in per-PR CI. + - name: Build the service-profile daemon + run: bash scripts/build-daemon-profile.sh --profile service --out "$RUNNER_TEMP/eggsec-daemon" + # The qualification procedure: the build, the daemon, the harness, the + # window probe, and the run record. A named skip does not fail the job; + # a failed column does. + - name: Run the GUI qualification procedure + run: | + bash scripts/gui_qualification.sh \ + --platform "${{ matrix.platform }}" \ + --mode ci \ + --daemon-bin "$RUNNER_TEMP/eggsec-daemon/eggsec-daemon" \ + --out "$RUNNER_TEMP/gui-qualification" + # The run record is the evidence a matrix cell cites. It is published + # even when the procedure failed, because a failed run's record is the + # evidence of the failure. + - name: Upload the qualification run record + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: gui-qualification-${{ matrix.os }} + path: | + ${{ runner.temp }}/gui-qualification/*.md + ${{ runner.temp }}/gui-qualification/*.json + if-no-files-found: error + # Phase F: platform integration maturity (scheduled/manual only, never PR CI). # Fixture layer always runs (no root/hardware). Live layers report SKIP with # the named prerequisite when caps/devices are absent — never red, never @@ -84,6 +207,10 @@ jobs: contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The full history: the guards decide commit ancestry, and a shallow + # checkout cannot answer that question. + with: + fetch-depth: 0 - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: diff --git a/.gitignore b/.gitignore index 385499a22..811701737 100755 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,16 @@ 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/ + +# Desktop GUI release output (the binary plus its build-metadata sidecar). +# scripts/build_gui_release.sh writes here by default; the artefacts are +# build products, never source. +/dist/ + # Pre-built binaries /eggsec eggsec.exe diff --git a/.opencode/skills/eggsec-cli/SKILL.md b/.opencode/skills/eggsec-cli/SKILL.md index f7199aac0..95c6b6871 100644 --- a/.opencode/skills/eggsec-cli/SKILL.md +++ b/.opencode/skills/eggsec-cli/SKILL.md @@ -263,7 +263,7 @@ Current `evaluate_and_enforce_operation` behavior for ManualPermissive `RequireC | Command | Source | Purpose | |---------|--------|---------| -| `daemon start/status/stop` | `crates/eggsec-cli/src/daemon_cli.rs` | Daemon lifecycle management | +| `daemon start/status/stop` | `crates/eggsec-cli/src/daemon_cli.rs` | Daemon lifecycle management. `daemon start` requires the non-default `daemon-client` feature and hosts the **engine** executor (the daemon binary is the persistent one); it refuses to displace a live daemon and reports success only after the daemon answers `Health` | | `daemon history` | `crates/eggsec-cli/src/daemon_cli.rs` | List persisted sessions | | `daemon show ` | `crates/eggsec-cli/src/daemon_cli.rs` | Show persisted snapshot | | `session list/create/snapshot` | `crates/eggsec-cli/src/daemon_cli.rs` | Session introspection | 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..0d54c6970 100644 --- a/.opencode/skills/eggsec-daemon/SKILL.md +++ b/.opencode/skills/eggsec-daemon/SKILL.md @@ -25,14 +25,105 @@ 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 a +daemon built with the engine executor **compiled in**: `--full-executor` is a +*runtime* flag over the daemon's `service` *cargo* feature (its deprecated +`full-executor` alias selects the same profile), so a binary built without the +cargo feature accepts the flag and falls back to a **no-op executor** that +publishes an **empty** task-kind list and rejects every task. The GUI reports +that condition as "the daemon advertises no task kinds" rather than presenting +a submit button that cannot work. + +`eggsec daemon start` is no longer in that state: the CLI's start path hosts +the **engine** executor, so a CLI-hosted daemon advertises and can execute the +conservative task kinds. It does **not** persist sessions — the daemon binary +is the persistent one. + +## Obtaining the daemon + +```bash +# The daemon binary, with the engine executor compiled in. +cargo install --path crates/eggsec-daemon --features service --locked + +# The CLI, with the `daemon`, `session`, and `task` subcommands. +cargo install --path crates/eggsec-cli --features daemon-client --locked +``` + +`full-executor` is a deprecated alias for `service`; `service` is the canonical +spelling. The resulting daemon defaults to the socket path +`/tmp/eggsec-daemon.sock` — the built-in default, stated once in +`crates/eggsec-runtime/src/daemon_endpoint.rs` — and honours the +`EGGSEC_DAEMON_SOCKET` environment variable when it is set. The precedence is +**explicit `--socket-path` flag → `EGGSEC_DAEMON_SOCKET` → built-in default**, +and it is applied by the same resolver in the daemon binary, the CLI, the TUI +and the GUI. The daemon also defaults to the data directory +`$HOME/.local/share/eggsec/daemon`, 10 max clients, and the `info` log level. +The recipe does not produce a packaged, signed, or auto-updating artefact, and +it does not cover Windows (`ADR-0010`: the daemon's transport is a Unix domain +socket). See `docs/DAEMON.md` for the full recipe and its limits. + +## Capability honesty + +The published task-kind list is **derived**, never declared beside the +executor: it is the canonical capability list — derived from the task-kind +set — intersected with the executor's declared support +(`RuntimeTaskExecutor::supported_task_kinds()`), computed once at construction. +The host hands that same list to the runtime as its enforced set, so +**publication and admission are the same object**: the daemon never +advertises a capability it will refuse. A daemon that cannot execute anything +therefore publishes **nothing**; an executor that rejects everything must +declare the empty set explicitly, because the trait's default is the +canonical list. + +Two refusals are different facts and must not be conflated: a *published* +kind whose engine feature is off is denied with `FeatureMissing`, and a +*published* kind the operator's execution policy refuses is denied with the +risk-policy refusal naming the risk tier. Neither is `UnsupportedTaskKind`. + +## Starting a daemon honestly + +- **Pre-flight**: before binding, a start path connects to the socket path and + asks for `Health`. A daemon that answers owns the path: the start is + refused, the socket is left untouched, and the command exits non-zero. An + unreachable socket (a stale file left by a crashed daemon) is *not* live. + The check is a **connection**, never a `stat`. +- **Readiness**: the wait polls `Health` (and `Capabilities`) until the daemon + answers, bounded by a named timeout. Nothing depends on the daemon's log + line — a log format is not a contract. The success message names the socket + path, the protocol version, and the advertised task-kind count; it never + claims that every advertised capability is executable. + ## 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 +5. On strict-surface sessions only the Owner can approve policies; `ApprovePolicy` resolves the runtime's pending decision, and an answer for a task with nothing pending is `ErrorCode::InvalidState`. A strict surface never holds a decision, so there is nothing to answer 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) keep the literal `"daemon"`. An approval is audited under the action `approve-policy` with the answering client, the session, that session's surface, and the outcome (`allow`, `deny`, `rejected`) + +## 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 +157,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..d033c35e5 --- /dev/null +++ b/.opencode/skills/eggsec-frontend-client/SKILL.md @@ -0,0 +1,162 @@ +--- +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`, `approve_task`, `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 method set gained `approve_task` in milestone 011 +(`ADR-0012`): it answers a policy decision the runtime is holding for a task. +The answer names *yes* or *no*; it never names the authorisation. + +## 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..45c35e3c3 --- /dev/null +++ b/.opencode/skills/eggsec-gui/SKILL.md @@ -0,0 +1,613 @@ +--- +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`, `eggsec-output` only (`crates/eggsec-gui/Cargo.toml:38-47`) | +| 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–192 (no engine edge, framework confinement, no second TLS stack, CSP forbids remote origins, no per-operation form code, bounded event retention, derived coverage model, remote-origin-free report display, the daemon's derived capability list, the daemon endpoint's single default and bind contract, the report bridge's single coverage table, the platform qualification's procedure and promotion rules, the operator attestation's attribution, and a CI checkout that carries the history the validator decides the attestation's binding against) | + +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, --daemon-bin) and the default socket path +│ ├── connection.rs# The daemon connection, the GUI's identity, the diagnostics +│ ├── coverage.rs # The derived reachability table for every published task kind +│ ├── availability.rs # The denial ledger: what a live refusal taught the GUI +│ ├── export.rs # The six report formats, the write discipline, the report view +│ ├── daemon.rs # The opt-in daemon lifecycle: probe, spawn, supervise, stop +│ ├── 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 `service` feature + (its deprecated `full-executor` alias) 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, or — opt-in, with + `--daemon-bin` — starts a daemon binary the operator names, without linking + the daemon crate. +- **No outbound HTTP.** The GUI enables neither `tauri`'s `rustls-tls` nor + `native-tls` (`crates/eggsec-gui/Cargo.toml:70`), 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 GUI names no operation id and no capability name.** Its coverage table + is derived from what the daemon publishes; guard 161 enforces it. + +## 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:83-86`). +`tauri-utils` is also a build-dependency so the no-shell build stays off the +1.90 line (`crates/eggsec-gui/Cargo.toml:92`). + +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 thirteen narrow commands, registered in +`crates/eggsec-gui/src/shell.rs:33-47`: + +| Command | Source | +|---|---| +| `connect_daemon(socket)` | `crates/eggsec-gui/src/commands.rs` | +| `list_operations()` | `crates/eggsec-gui/src/commands.rs` | +| `list_task_kinds()` | `crates/eggsec-gui/src/commands.rs` | +| `form_for(variant)` | `crates/eggsec-gui/src/commands.rs` | +| `submit_task(variant, values)` | `crates/eggsec-gui/src/commands.rs` | +| `cancel_task(task_id)` | `crates/eggsec-gui/src/commands.rs` | +| `cancel_active()` | `crates/eggsec-gui/src/commands.rs` | +| `approve_task(task_id, approved, reason)` | `crates/eggsec-gui/src/commands.rs` | +| `task_snapshot()` | `crates/eggsec-gui/src/commands.rs` | +| `coverage()` | `crates/eggsec-gui/src/commands.rs` | +| `export_report(task_id, format, path)` | `crates/eggsec-gui/src/commands.rs` | +| `report_for(task_id, format)` | `crates/eggsec-gui/src/commands.rs` | +| `daemon_status()` | `crates/eggsec-gui/src/commands.rs` | + +`report_for` and `export_report` are separate on purpose: the first delivers +the report's structured content to the webview, the second writes a file to a +path the operator chose. + +The command set is pinned in **three** places, and they must move together: +`declared_command_set_is_exact` (`crates/eggsec-gui/src/commands.rs:993`), +`every_command_declares_its_argument_naming` +(`crates/eggsec-gui/src/commands.rs:1024`), and the Tauri handler +registration (`crates/eggsec-gui/src/shell.rs:33-46`). + +**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:35`), carrying `task_upsert`, `logs`, or +`counters` (`crates/eggsec-gui/src/commands.rs:291-313`). + +## The coverage model: derived, never transcribed + +`crates/eggsec-gui/src/coverage.rs` answers, per published task kind, whether +this GUI can run it. Every input arrives as an argument — the daemon's +catalog, its advertised capability list, its published enabled-feature set — +so a task kind published tomorrow is covered with no GUI change +(`crates/eggsec-gui/src/coverage.rs:85-98`). One row per published task kind. + +The GUI names **no operation id and no capability name** in its production +sources or its frontend. Guard 161 reads those names from their owners +(`crates/eggsec-policy/src/catalog.rs` and +`crates/eggsec-runtime/src/capabilities.rs`) and fails if the GUI names any of +them. + +| Verdict | What produces it | +|---|---| +| `available` | Exposed on the manual surface, capability advertised, required features enabled. | +| `not_exposed` | The catalog does not expose the operation on the manual surface. | +| `not_advertised` | The daemon does not advertise the capability. | +| `feature_disabled` | Advertised, but a required feature is not enabled. | +| `unverified` | The enabled-feature set is **unknown** (the daemon published none). | +| `blocked` | A live denial proved it unavailable in this session. | + +- **An unknown feature set is not an empty one.** `None` means unknown, so a + task kind whose requirements cannot be confirmed is `unverified` — never + `feature_disabled`, never dropped. +- **"Withholds the capability" is not "lacks the feature."** The reason text + distinguishes them. +- A **`required_features` list is a requirement, not a state report.** It says + what the operation needs; the daemon's published enabled-feature set says what + the daemon has. Never read one as the other. +- A **learned denial wins** over every static verdict + (`crates/eggsec-gui/src/coverage.rs:106-133`). The ledger holds one entry per + published task kind, so it is bounded by the catalog's size. + +### The report-form column + +The coverage table carries a second, independent verdict: **does this task +kind's operation produce a report document?** It comes from the daemon's +published `report_forms` coverage — the engine's own table, republished +verbatim — and is joined by the published catalog's operation id, so the GUI +names no operation id of its own. + +| Verdict | What produces it | +|---|---| +| `available` | The daemon published the operation as canonical: it produces a report document. | +| `unavailable` | The daemon published the operation as having no clean mapping, and the row carries the reason. | +| `unknown` | The daemon published no coverage, or none for this operation. | + +- **An unpublished coverage is not an empty one.** `None` means unknown, so + the column reads `unknown` — never `unavailable`. The GUI must never render + a report-form verdict it was not told. +- The reason text comes from the daemon verbatim. The GUI never writes one. + +### The availability resolver + +`crates/eggsec-gui/src/availability.rs` turns a live failure into a fact the +coverage table can use. `denial_from_message` reads the engine's own +`FeatureMissing` denial out of a daemon error message +(`crates/eggsec-gui/src/availability.rs:68-77`): the policy layer phrases it +as `required feature '' is not enabled` +(`crates/eggsec-policy/src/decision.rs:926`) and the dispatch layer as +`requires feature '' which is not compiled in` +(`crates/eggsec/src/dispatch/canonical_execution.rs:626`). Both markers are +recognised (`crates/eggsec-gui/src/availability.rs:59-60`); every other message +yields `Denial::Other`, carried verbatim. A denial is never guessed. + +The `DenialLedger` holds **one entry per task-kind variant** +(`crates/eggsec-gui/src/availability.rs:102-113`), so it is bounded by the +catalog's size, and the most recent denial for a variant replaces the earlier +one. The GUI records the denial against the failed task's variant +(`crates/eggsec-gui/src/commands.rs:927-960`). + +## 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:827`). + +## Policy decisions: the GUI answers, it never decides + +A task waiting on a policy decision shows **the policy's own prompt** — the +wording comes from the daemon, not from the GUI — with **Approve** and +**Reject** buttons (`crates/eggsec-gui/frontend/app.js`). + +- The answer goes to the daemon as *yes* or *no*. **It never names the + authorisation.** +- What the answer permits is computed by the policy kernel on the daemon's + executor side, bounded by exactly the confirmation classes the kernel + demanded. The GUI cannot widen it. +- **The GUI never auto-approves.** An auto-approval would be the GUI settling + an authorisation question that only the daemon's enforcement layer may + settle. +- A task with nothing pending is an error the operator sees, not a silent + no-op: the daemon refuses the answer because there is no decision to + resolve. + +See `plans/adrs/ADR-0012-daemon-mediated-policy-approval.md`. + +## 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:418-421`). + +`supports_rich_tui` describes the **TUI's** capability +(`crates/eggsec-ui-model/src/renderer_registry.rs:18`). 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:146-153`). +- Exposure comes from `OperationDescription::manual_exposable` + (`crates/eggsec-gui/src/commands.rs:442-444`). The GUI is a **manual** surface. +- `unavailable_reason` states why a task kind cannot be submitted + (`crates/eggsec-gui/src/commands.rs:458`). +- The full per-task-kind reachability verdict — exposure, advertisement, the + enabled-feature set and any learned denial — is the **coverage** table, not + this list. See [The coverage model](#the-coverage-model-derived-never-transcribed). + +## The daemon expectation + +The GUI requires an `eggsec-daemon` with the engine executor **compiled in**. +By default the daemon is one the **operator** started: the GUI connects to a +running daemon and starts no process at all. + +The **opt-in** exception is `--daemon-bin `: the GUI starts that +executable itself and owns its lifetime +(`crates/eggsec-gui/src/daemon.rs`). There is no `PATH` lookup and no sidecar +convention — an unnamed executable is never found. The option lives on +`GuiOptions.daemon_bin` and defaults to `None` +(`crates/eggsec-gui/src/config.rs:26-31`). + +- The pre-flight liveness check is a **connection attempt**, never a `stat`: + the daemon unlinks its socket path before binding it, so only a connection + tells a live daemon from a stale socket file + (`crates/eggsec-gui/src/daemon.rs:96-109`). A stale socket file does not + block the spawn; a live daemon is detected so the GUI does not steal it. +- The child is started from an **argv vector**, never a shell string: + `[daemon_bin, "--full-executor", "--socket-path", socket_path]` + (`crates/eggsec-gui/src/daemon.rs:80-87`). +- Readiness is a **protocol handshake**, never the daemon's "Daemon + listening on ..." log line. The wait is bounded by `READINESS_TIMEOUT` + (60 s) and retried every `READINESS_POLL_INTERVAL` (1 s); each probe is + bounded by `PROBE_TIMEOUT` (2 s) + (`crates/eggsec-gui/src/daemon.rs:49-62`). A child that exits during the + wait is reported as a failure with its exit status + (`crates/eggsec-gui/src/daemon.rs:199-213`). +- Teardown is **SIGTERM first**, escalating to an unconditional kill after the + `TERMINATION_GRACE` (5 s) expires (`crates/eggsec-gui/src/daemon.rs:298-332`). + SIGHUP is never sent. +- A readiness timeout **terminates the child** before the error is returned: + a failed start leaves no orphan (`crates/eggsec-gui/src/daemon.rs:153-166`). +- A shutdown watcher stops the supervised child when the window closes, so a + killed GUI does not leave the daemon it started running + (`crates/eggsec-gui/src/shell.rs:61-77`). +- The GUI reports a dead daemon; it never silently respawns one. + +`--full-executor` is a *runtime* flag over the daemon's `service` *cargo* +feature (its deprecated `full-executor` alias selects the same profile), so +the binary must be **built** with that feature: + +```bash +cargo install --path crates/eggsec-daemon --features service --locked +``` + +A binary built without the cargo feature accepts the flag and falls back to a +**no-op executor** that publishes an **empty** task-kind list, so the GUI's +diagnostic names the exact start command +(`crates/eggsec-gui/src/connection.rs:58`) and the GUI reports the +no-op-executor condition — the daemon advertises no task kinds +(`crates/eggsec-gui/src/connection.rs:180`) — rather than offering a submit +button that cannot work. + +`eggsec daemon start` is no longer in that state: the CLI's start path hosts +the **engine** executor, so a CLI-hosted daemon advertises and can execute +the conservative task kinds. It does **not** persist sessions — the daemon +binary is the persistent one. See `docs/DAEMON.md` for the obtainability +recipe and its limits. + +## Platform prerequisites and build profiles + +- Supported platforms: **Linux and macOS**. **Windows is out of scope** — + `plans/adrs/ADR-0010-gui-supported-platform-scope.md` decides it, and the + measured reason is that the GUI's unconditional `eggsec-frontend-client` + dependency imports the Unix-domain-socket transport without a `cfg(unix)` + gate, so the GUI does not compile for Windows. Re-entry needs a Windows + daemon transport, which is a daemon-subsystem change with its own ADR. +- macOS uses 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:71-74`). +- `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`). +- **What was actually built and exercised** per platform, per behaviour, is + recorded in `docs/GUI_PLATFORM_QUALIFICATION.md`, with one evidence file per + run under `docs/evidence/gui-qualification/`. That matrix — not a claim — + is the authoritative statement of platform support; the `gui-platform` CI + job is what promotes a cell. +- `bundle.active` stays `false`. Installers, signing, and notarization belong + to the separate distribution workstream; the handoff artefact and its + known limitations are in `docs/GUI_DISTRIBUTION_HANDOFF.md`. +- The daemon the GUI connects to has its own engine-feature profile and build + recipe, documented in `docs/DAEMON_FEATURE_PROFILE.md`. The GUI's + prerequisites and the daemon's are deliberately kept apart. + +## 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 `/`--socket=` and +`--daemon-bin `/`--daemon-bin=`; the default socket path is +`/tmp/eggsec-daemon.sock`, stated once in +`crates/eggsec-runtime/src/daemon_endpoint.rs` and re-exported by +`crates/eggsec-gui/src/config.rs`. The precedence is **explicit `--socket` +flag → `EGGSEC_DAEMON_SOCKET` → built-in default**. The webview holds no copy +of the default: it learns the path from Rust through `daemon_status`, and an +empty socket field is resolved by the Rust side of `connect_daemon`. + +## Report export and display + +`crates/eggsec-gui/src/export.rs` writes the **same artifacts the CLI writes**, +through the same `eggsec-output` renderers. There is no GUI-specific report +format and no second renderer. + +| Format | Extension | Export rendering | Display rendering | +|---|---|---|---| +| `Json` | `.json` | `convert_to_json` | inert text | +| `Csv` | `.csv` | `convert_to_csv` | inert text | +| `Html` | `.html` | `convert_to_html` | **none — export-only** | +| `Sarif` | `.sarif` | `convert_to_sarif` | inert text | +| `Junit` | `.xml` | `convert_to_junit` | inert text | +| `Markdown` | `.md` | `convert_to_markdown` | inert text | + +The extension map is `crates/eggsec-gui/src/export.rs:92-100`; JUnit's +extension is `.xml` and Markdown's is `.md`, while the wire name stays +`junit` and `markdown` (`crates/eggsec-gui/src/export.rs:123-129`). + +- **The write discipline is the TUI's, unchanged.** A destination that is not a + regular file is **refused**, an existing regular file is **backed up** to + `.bak` before it is replaced, and every failure is an `Err` rather than + a silent overwrite (`crates/eggsec-gui/src/export.rs:349-363`). +- **The GUI does not render the engine's HTML document.** That document carries + an inline ` - - +{}
@@ -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-payloads/src/websocket.rs b/crates/eggsec-payloads/src/websocket.rs index 69ca11d72..2a710e1c0 100755 --- a/crates/eggsec-payloads/src/websocket.rs +++ b/crates/eggsec-payloads/src/websocket.rs @@ -39,8 +39,7 @@ pub struct WebSocketTestResult { } pub struct WebSocketFuzzer { - #[allow(dead_code)] - pub(crate) url: String, + url: String, subprotocols: Vec, } @@ -52,6 +51,16 @@ impl WebSocketFuzzer { } } + /// The target URL this fuzzer was constructed with. + /// + /// Exposed as an accessor rather than a public field so the corpus crate + /// keeps control of the struct's shape while the engine's + /// `AdvancedFuzzer` implementation can still read the target it must + /// dial. + pub fn url(&self) -> &str { + &self.url + } + pub fn with_subprotocols(mut self, protocols: Vec) -> Self { self.subprotocols = protocols; self diff --git a/crates/eggsec-policy/src/catalog.rs b/crates/eggsec-policy/src/catalog.rs index aec5b5590..f09aea4b8 100644 --- a/crates/eggsec-policy/src/catalog.rs +++ b/crates/eggsec-policy/src/catalog.rs @@ -77,6 +77,7 @@ impl OperationMetadata { TargetPolicyKind::ExplicitScopeRequired | TargetPolicyKind::PrivateOrLocalRequired ), required_capabilities: self.required_capabilities.to_vec(), + target_policy: self.target_policy, } } @@ -165,6 +166,39 @@ impl OperationMetadata { | TargetPolicyKind::PrivateOrLocalRequired ), required_capabilities: self.required_capabilities.to_vec(), + target_policy: self.target_policy, + }) + } + TargetPolicyKind::InterfaceBound => { + // The local identifier is optional: an interface-bound + // operation takes no network target. When one is supplied it + // is carried into the descriptor (and from there into the + // audit record) so it is never silently dropped, and it is + // NOT normalized as a network target -- the enforcement + // kernel reads `target_policy` and does not match a local + // identifier against the scope's remote target rules. + let t = target.filter(|s| !s.is_empty()); + Ok(OperationDescriptor { + operation: self.id.to_string(), + mode: self.mode, + risk: self.risk, + intended_uses: self.intended_uses.to_vec(), + target: t.map(|s| s.to_string()), + normalized_target: OperationTarget::None, + required_features: self + .required_features + .iter() + .map(|s| s.to_string()) + .collect(), + required_policy_flags: self + .required_policy_flags + .iter() + .map(|s| s.to_string()) + .collect(), + requires_private_or_local_target: false, + requires_explicit_scope: true, + required_capabilities: self.required_capabilities.to_vec(), + target_policy: self.target_policy, }) } TargetPolicyKind::TargetRequired @@ -204,6 +238,7 @@ impl OperationMetadata { | TargetPolicyKind::PrivateOrLocalRequired ), required_capabilities: self.required_capabilities.to_vec(), + target_policy: self.target_policy, }) } } @@ -476,6 +511,30 @@ pub static ALL_OPERATION_METADATA: &[OperationMetadata] = &[ agent_exposable: true, grpc_exposable: true, }, + OperationMetadata { + // The capture half of the `packet` family. It is split out from + // `packet` because a capture binds to a **local interface**, not to a + // network target: `packet` also serves `traceroute` and `packet-send`, + // which do address a remote host and must keep requiring one. The + // risk tier and the capability are identical to `packet`'s, so the + // split relaxes nothing -- it only stops the capture from inheriting + // a remote-target requirement it can never satisfy. + id: "packet-capture", + display_name: "Packet Capture", + mode: OperationMode::StandardAssessment, + risk: OperationRisk::RawPacket, + intended_uses: &[IntendedUse::WebAssessment], + required_features: &["packet-inspection"], + required_policy_flags: &[], + required_capabilities: &[Capability::RawPacketProbe], + target_policy: TargetPolicyKind::InterfaceBound, + manual_exposable: true, + tui_exposable: true, + mcp_exposable: true, + rest_exposable: true, + agent_exposable: true, + grpc_exposable: true, + }, OperationMetadata { id: "graphql", display_name: "GraphQL Fuzzing", @@ -608,7 +667,9 @@ pub static ALL_OPERATION_METADATA: &[OperationMetadata] = &[ required_features: &["wireless"], required_policy_flags: &[], required_capabilities: &[Capability::PassiveFingerprint], - target_policy: TargetPolicyKind::ExplicitScopeRequired, + // A passive scan binds to a **local interface**, not to a network + // target: there is no host to be in scope for. + target_policy: TargetPolicyKind::InterfaceBound, manual_exposable: true, tui_exposable: true, mcp_exposable: true, @@ -625,7 +686,10 @@ pub static ALL_OPERATION_METADATA: &[OperationMetadata] = &[ required_features: &["wireless-advanced"], required_policy_flags: &[], required_capabilities: &[Capability::RawPacketProbe], - target_policy: TargetPolicyKind::ExplicitScopeRequired, + // A deauth binds to a **local interface** and a BSSID, not to a + // network target. The risk tier and the capability are unchanged: + // the split relaxes the *target*, never the authorisation. + target_policy: TargetPolicyKind::InterfaceBound, manual_exposable: true, tui_exposable: true, mcp_exposable: false, @@ -1358,35 +1422,101 @@ mod operation_metadata_tests { } } - /// Interface-bound sniffing keeps its fail-closed posture. + /// The interface-bound family keeps its fail-closed posture. + /// + /// `packet` stays `ExplicitScopeRequired`: it addresses a remote host + /// (`traceroute`, `packet-send`) and must keep refusing a target-less + /// run. /// - /// `packet` and `wireless` stay `ExplicitScopeRequired`: they have no target - /// to scope against, and unlike the relaxed set they *are* sensitive - /// sniffing operations, so requiring a loaded scope is the only lever an - /// operator has over them. + /// The interface-bound operations (`packet-capture`, `wireless`, + /// `wireless-deauth`) bind to a **local** interface or identifier, so they + /// accept a target-less run -- but they keep requiring an explicit scope, + /// and the local identifier is carried rather than dropped. #[test] fn interface_bound_operations_still_fail_closed() { - for op in ["packet", "wireless", "wireless-deauth"] { + // The remote-target half of the packet family is unchanged. + let packet = metadata_for_tool_id("packet").unwrap_or_else(|| panic!("packet missing")); + let err = packet + .try_descriptor_for_target(None) + .err() + .unwrap_or_else(|| panic!("packet should still refuse a target-less run")); + assert!( + matches!(err, DescriptorError::MissingTarget { .. }), + "packet failed for the wrong reason: {err}" + ); + let desc = packet + .try_descriptor_for_target(Some("10.0.0.5")) + .unwrap_or_else(|e| panic!("packet should accept a target, got {e}")); + assert!( + desc.requires_explicit_scope, + "packet lost its scope requirement" + ); + assert!( + !desc.target_policy.is_interface_bound(), + "packet must not become interface-bound" + ); + + // The interface-bound half accepts no target, and accepts a local + // identifier without turning it into a network target. + for op in ["packet-capture", "wireless", "wireless-deauth"] { let metadata = metadata_for_tool_id(op).unwrap_or_else(|| panic!("{op} missing")); - let err = metadata + assert!( + metadata.target_policy.is_interface_bound(), + "{op} should be interface-bound" + ); + + let no_target = metadata .try_descriptor_for_target(None) - .err() - .unwrap_or_else(|| panic!("{op} should still refuse a target-less run")); + .unwrap_or_else(|e| panic!("{op} should accept no target, got {e}")); assert!( - matches!(err, DescriptorError::MissingTarget { .. }), - "{op} failed for the wrong reason: {err}" + no_target.requires_explicit_scope, + "{op} lost its scope requirement" ); - // And a supplied target is still accepted and scope-checkable. - let desc = metadata - .try_descriptor_for_target(Some("10.0.0.5")) - .unwrap_or_else(|e| panic!("{op} should accept a target, got {e}")); assert!( - desc.requires_explicit_scope, + !no_target.requires_private_or_local_target, + "{op} must not demand a private-range target" + ); + assert!(no_target.target.is_none(), "{op} invented a target"); + + 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" + ); + assert_eq!( + local.normalized_target, + OperationTarget::None, + "{op} normalized a local identifier as a network target" + ); + assert!( + local.requires_explicit_scope, "{op} lost its scope requirement" ); } } + /// Every interface-bound operation is in the target-less set. + /// + /// The catalog's own consistency checks rely on it: an agent- or + /// MCP-exposable operation with a target policy other than `NoTarget` is + /// required to be either scope-required or target-less by nature. + #[test] + fn interface_bound_operations_are_target_less_by_nature() { + for metadata in ALL_OPERATION_METADATA { + if !metadata.target_policy.is_interface_bound() { + continue; + } + assert!( + TARGET_LESS_OPERATIONS.contains(&metadata.id), + "{} is interface-bound but is not in TARGET_LESS_OPERATIONS", + metadata.id + ); + } + } + /// Every operation whose target policy demands a scope must actually be /// able to receive one. /// @@ -1411,9 +1541,21 @@ mod operation_metadata_tests { } } - /// The set of operations that are target-less by nature. + /// The set of operations that have no **network** target by nature. /// /// Deliberately explicit rather than derived: an operation joining this list /// loses a fail-closed guard, so it should be a visible edit. - const TARGET_LESS_OPERATIONS: &[&str] = &["storage", "integrations", "workflow"]; + /// + /// The interface-bound operations belong here for the same reason: they + /// bind to a local interface or a local identifier, so there is no + /// remote target to require. They still require an explicit scope -- the + /// requirement is about the operator's consent, not about a target. + const TARGET_LESS_OPERATIONS: &[&str] = &[ + "storage", + "integrations", + "workflow", + "packet-capture", + "wireless", + "wireless-deauth", + ]; } diff --git a/crates/eggsec-policy/src/decision.rs b/crates/eggsec-policy/src/decision.rs index dd8bfa5de..7fc4fdc68 100644 --- a/crates/eggsec-policy/src/decision.rs +++ b/crates/eggsec-policy/src/decision.rs @@ -339,6 +339,23 @@ impl EnforcementError { Self::SurfaceProfileMismatch { .. } => None, } } + + /// The concrete reasons the decision refused the operation. + /// + /// The `Display` form is deliberately terse ("operation denied by + /// policy"), because a denial summary is read in a log line. A caller + /// that has to report *why* -- a CLI, a GUI, an audit record -- needs + /// the decision's own reasons, which name the risk tier, the missing + /// feature, or the out-of-scope target. This renders them, and falls + /// back to the summary when the decision carries none. + pub fn reasons(&self) -> Vec { + match self.decision() { + Some(decision) if !decision.denied_reasons.is_empty() => { + decision.denied_reasons.clone() + } + _ => vec![self.to_string()], + } + } } /// Categories of conditions that trigger `RequireConfirmation` under `ManualPermissive`. @@ -410,6 +427,58 @@ impl ManualOverride { ConfirmationClass::NonBaselineCapability => self.allow_nonbaseline_capability, } } + + /// Builds the override that permits the given confirmation classes. + /// + /// This is the single place a confirmation class is mapped onto the + /// override field that permits it. It is the inverse of + /// [`ManualOverride::permits`]: for every class in `classes`, the returned + /// override permits it. Callers that need to grant exactly what the + /// enforcement kernel demanded use this rather than restating the table. + /// + /// Three properties are deliberate: + /// + /// - `assume_yes` is never set. An approval is not prompt suppression: it + /// grants the classes that were demanded, not "yes" to everything. + /// - `allow_db_pentest` is never set. `allow_high_risk` is the precise + /// field for [`ConfirmationClass::HighRisk`]; the database-pentest flag + /// is an alternative grant for the same class, not a wider one. + /// - `OutOfScope` and `TargetExpansion` share `allow_out_of_scope`, so + /// permitting either permits both. The two cannot be separated without + /// changing the override's shape, which the CLI's flag set already + /// fixes. + /// + /// `reason` is left unset; a caller that records why the override was + /// granted sets it. + pub fn permitting_classes(classes: &[ConfirmationClass]) -> Self { + let mut granted = Self::default(); + for class in classes { + match class { + ConfirmationClass::OutOfScope | ConfirmationClass::TargetExpansion => { + granted.allow_out_of_scope = true; + } + ConfirmationClass::ExplicitExclusion => { + granted.allow_explicit_exclusion = true; + } + ConfirmationClass::HighRisk => { + granted.allow_high_risk = true; + } + ConfirmationClass::NonBaselineCapability => { + granted.allow_nonbaseline_capability = true; + } + ConfirmationClass::PrivateResolution => { + granted.allow_private_resolution = true; + } + ConfirmationClass::CrossHostRedirect => { + granted.allow_cross_host_redirect = true; + } + ConfirmationClass::TrafficInterception => { + granted.allow_web_proxy = true; + } + } + } + granted + } } /// Reusable enforcement context that bundles execution profile, policy, scope, @@ -933,7 +1002,34 @@ pub fn evaluate_operation_policy( // the caller-resolved addresses; when absent for a target-bearing // descriptor, hostname-pattern matching over an empty fact record decides // (equivalent to the historical unresolvable-host path). - if let Some(ref target) = descriptor.target { + // + // An **interface-bound** operation is the exception: its target is a + // *local identifier* (an interface name, a BSSID), not a remote host. + // The identifier stays in the decision record for audit, but it is never + // matched against the scope's remote target rules -- the scope model has + // no local-host subject to match it against, and matching a local name + // as a hostname would deny every interface-bound operation. The + // operator's explicit-scope requirement is NOT relaxed: a missing scope + // still denies. + if descriptor.target_policy.is_interface_bound() { + if scope.is_none() { + if descriptor.requires_explicit_scope { + decision.push_denial_class( + DenialClass::ScopeMissing, + "scope file required but not provided", + ); + decision.allowed = false; + } + } else { + // The scope is configured. It does not name the local binding, + // but it is present, which is what the explicit-scope + // requirement asks for. Recording a matched rule keeps the + // strict profiles' "ambiguous scope" check satisfied. + decision + .matched_scope_rules + .push("interface-bound local target".to_string()); + } + } else if let Some(ref target) = descriptor.target { if let Some(scope) = scope { // Populate resolved addresses in the decision record if let Some(ts) = target_facts { @@ -1688,3 +1784,89 @@ mod pure_evaluation_tests { assert!(matches!(outcome, EnforcementOutcome::Warn(_))); } } + +#[cfg(test)] +mod manual_override_mapping_tests { + use super::*; + + /// Every confirmation class the kernel can demand. + /// + /// Kept as an explicit list so that adding a class to + /// [`ConfirmationClass`] fails this test until the mapping accounts for + /// it. + const ALL_CLASSES: [ConfirmationClass; 8] = [ + ConfirmationClass::OutOfScope, + ConfirmationClass::ExplicitExclusion, + ConfirmationClass::HighRisk, + ConfirmationClass::NonBaselineCapability, + ConfirmationClass::PrivateResolution, + ConfirmationClass::CrossHostRedirect, + ConfirmationClass::TargetExpansion, + ConfirmationClass::TrafficInterception, + ]; + + #[test] + fn every_class_is_permitted_by_its_own_mapping() { + for class in ALL_CLASSES { + let granted = ManualOverride::permitting_classes(&[class]); + assert!( + granted.permits(class), + "permitting_classes must permit {class:?}" + ); + } + } + + #[test] + fn a_mapping_permits_every_class_it_names() { + for class in ALL_CLASSES { + let granted = ManualOverride::permitting_classes(&[class]); + for other in ALL_CLASSES { + let permitted = granted.permits(other); + let expected = other == class + // `OutOfScope` and `TargetExpansion` share one override + // field, so permitting either permits both. The two + // cannot be separated without changing the override's + // shape, which the CLI's flag set already fixes. + || matches!( + (class, other), + ( + ConfirmationClass::OutOfScope | ConfirmationClass::TargetExpansion, + ConfirmationClass::OutOfScope | ConfirmationClass::TargetExpansion + ) + ); + assert_eq!( + permitted, expected, + "permitting {class:?} must permit {other:?} == {expected}" + ); + } + } + } + + #[test] + fn an_empty_mapping_grants_nothing() { + let granted = ManualOverride::permitting_classes(&[]); + for class in ALL_CLASSES { + assert!( + !granted.permits(class), + "an empty mapping must not permit {class:?}" + ); + } + } + + #[test] + fn a_mapping_never_sets_broad_prompt_suppression() { + // An approval is not prompt suppression. `assume_yes` would let the + // grant silently cover classes the kernel never demanded. + let granted = ManualOverride::permitting_classes(&ALL_CLASSES); + assert!(!granted.assume_yes); + // The database-pentest flag is an alternative grant for the same + // high-risk class, not a wider one. + assert!(!granted.allow_db_pentest); + } + + #[test] + fn a_mapping_leaves_the_reason_to_the_caller() { + let granted = ManualOverride::permitting_classes(&ALL_CLASSES); + assert_eq!(granted.reason, None); + } +} diff --git a/crates/eggsec-policy/src/policy.rs b/crates/eggsec-policy/src/policy.rs index 177446398..c80a0148d 100644 --- a/crates/eggsec-policy/src/policy.rs +++ b/crates/eggsec-policy/src/policy.rs @@ -310,6 +310,19 @@ pub struct OperationDescriptor { /// Capabilities required by this operation (e.g. "active-probe", "crawl"). #[serde(default)] pub required_capabilities: Vec, + /// The operation's target policy. + /// + /// This is the fact the enforcement kernel needs to know whether the + /// descriptor's `target` is a **remote host** or a **local identifier**. + /// Only [`TargetPolicyKind::InterfaceBound`] changes the kernel's + /// behaviour: an interface-bound target is carried into the decision + /// record for audit but is never matched against the scope's remote + /// target rules. + /// + /// `#[serde(default)]` keeps a legacy payload readable; the default is + /// behaviour-preserving because only the interface-bound value branches. + #[serde(default)] + pub target_policy: TargetPolicyKind, } impl OperationDescriptor { @@ -347,8 +360,25 @@ impl OperationDescriptor { requires_private_or_local_target, requires_explicit_scope, required_capabilities, + // This constructor does not know the operation's catalog entry, so + // it cannot know the target policy. The default is the neutral + // one: only `InterfaceBound` changes the kernel's behaviour, so + // the default is behaviour-preserving. Callers that build a + // descriptor for a catalog operation should use + // `OperationMetadata::try_descriptor_for_target`, which sets it + // from the catalog. + target_policy: TargetPolicyKind::default(), } } + + /// Set the descriptor's target policy. + /// + /// Used by callers that construct a descriptor directly rather than + /// through [`OperationMetadata::try_descriptor_for_target`]. + pub fn with_target_policy(mut self, target_policy: TargetPolicyKind) -> Self { + self.target_policy = target_policy; + self + } } /// Origin of an execution request. @@ -368,6 +398,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 +420,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 +436,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 +457,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 +476,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 +493,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 +959,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 +970,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 +983,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 +1047,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 +1072,7 @@ mod tests { ExecutionSurface::TuiManual, ExecutionSurface::CliManualStrict, ExecutionSurface::TuiManualStrict, + ExecutionSurface::DesktopGuiManual, ExecutionSurface::McpServer, ExecutionSurface::SecurityAgent, ExecutionSurface::Ci, @@ -996,6 +1083,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-policy/src/target.rs b/crates/eggsec-policy/src/target.rs index 70d5b52a8..6a43d2f91 100644 --- a/crates/eggsec-policy/src/target.rs +++ b/crates/eggsec-policy/src/target.rs @@ -169,13 +169,48 @@ fn normalize_url(raw: &str) -> OperationTarget { } /// Target policy requirement for operation metadata. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum TargetPolicyKind { NoTarget, OptionalTarget, TargetRequired, ExplicitScopeRequired, PrivateOrLocalRequired, + /// The operation binds to a **local** interface or local identifier — an + /// interface name, a BSSID, a checkpoint path — rather than to a network + /// target. + /// + /// The contract: + /// + /// 1. It accepts a `None` target: the operation takes no network target. + /// 2. It accepts an optional **local identifier** as the descriptor's + /// target. The identifier is carried into the descriptor and the audit + /// record, so it is never silently dropped. + /// 3. `requires_explicit_scope` stays `true`: the operator's explicit + /// scope requirement is **not** relaxed. + /// 4. `requires_private_or_local_target` stays `false`: the local binding + /// is not a network target to be matched against a private-range rule. + /// 5. The local identifier is **not** matched against the scope's remote + /// target rules, because it is not a remote target. + /// + /// The scope model has no first-class local-host subject, so the scope + /// semantics of this value are exactly: *the operator's explicit scope is + /// still required, and the local binding is not a remote target.* This is + /// deliberately **not** "the scope check applies to the local host" — + /// the model cannot say that. + InterfaceBound, +} + +impl Default for TargetPolicyKind { + /// The neutral default for a descriptor deserialized without the field. + /// + /// Only [`Self::InterfaceBound`] changes the kernel's behaviour, so any + /// non-interface-bound default is behaviour-preserving for a legacy + /// payload. + fn default() -> Self { + Self::OptionalTarget + } } impl std::fmt::Display for TargetPolicyKind { @@ -186,10 +221,19 @@ impl std::fmt::Display for TargetPolicyKind { Self::TargetRequired => write!(f, "target-required"), Self::ExplicitScopeRequired => write!(f, "explicit-scope-required"), Self::PrivateOrLocalRequired => write!(f, "private-or-local-required"), + Self::InterfaceBound => write!(f, "interface-bound"), } } } +impl TargetPolicyKind { + /// Whether this policy binds the operation to a local identifier rather + /// than to a network target. + pub fn is_interface_bound(&self) -> bool { + matches!(self, Self::InterfaceBound) + } +} + /// Error returned by [`OperationMetadata::try_descriptor_for_target`] when the /// supplied target violates the operation's target policy. #[derive(Debug, Clone, thiserror::Error)] 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..9c3a3f5b5 100644 --- a/crates/eggsec-python/src/daemon.rs +++ b/crates/eggsec-python/src/daemon.rs @@ -248,6 +248,27 @@ 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, + }, + ServerMessage::TaskReport { + request_id, report, .. + } => DaemonResponsePy { + ok: true, + request_id, + message: format!("report ({} bytes)", report.to_string().len()), + error_code: None, + }, } } @@ -344,13 +365,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-python/src/operation_metadata.rs b/crates/eggsec-python/src/operation_metadata.rs index 2ff179aec..a823c6f80 100644 --- a/crates/eggsec-python/src/operation_metadata.rs +++ b/crates/eggsec-python/src/operation_metadata.rs @@ -580,6 +580,7 @@ impl TargetPolicyKindPy { eggsec::config::TargetPolicyKind::TargetRequired => "target-required", eggsec::config::TargetPolicyKind::ExplicitScopeRequired => "explicit-scope-required", eggsec::config::TargetPolicyKind::PrivateOrLocalRequired => "private-or-local-required", + eggsec::config::TargetPolicyKind::InterfaceBound => "interface-bound", } .to_string() } diff --git a/crates/eggsec-python/src/tool_descriptor.rs b/crates/eggsec-python/src/tool_descriptor.rs index 9491163c4..496cb26b8 100644 --- a/crates/eggsec-python/src/tool_descriptor.rs +++ b/crates/eggsec-python/src/tool_descriptor.rs @@ -199,6 +199,7 @@ fn target_policy_for_stable(tool_id: &str) -> &'static str { eggsec::config::TargetPolicyKind::PrivateOrLocalRequired => { "private-or-local-required" } + eggsec::config::TargetPolicyKind::InterfaceBound => "interface-bound", }; } } @@ -352,6 +353,7 @@ impl ToolDescriptorPy { eggsec::config::TargetPolicyKind::TargetRequired => "target-required", eggsec::config::TargetPolicyKind::ExplicitScopeRequired => "explicit-scope-required", eggsec::config::TargetPolicyKind::PrivateOrLocalRequired => "private-or-local-required", + eggsec::config::TargetPolicyKind::InterfaceBound => "interface-bound", } .to_string(); let supported_surfaces = compute_surfaces( 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/approval.rs b/crates/eggsec-runtime/src/approval.rs new file mode 100644 index 000000000..cc309a01e --- /dev/null +++ b/crates/eggsec-runtime/src/approval.rs @@ -0,0 +1,466 @@ +//! The runtime's pending-approval registry. +//! +//! A manual operation whose policy demands a confirmation is **held** at that +//! point: the task does not proceed, and the decision is exposed to clients so +//! an operator can answer it. The runtime owns the hold, because the runtime +//! owns task lifecycle — the daemon owns the process, and `eggsec-policy` owns +//! authorisation semantics. +//! +//! # What the runtime stores, and what it does not +//! +//! The registry stores a [`PolicyPrompt`] — a message, a confirmation-class +//! *label*, and a flag. It does **not** store a `ConfirmationClass`, an +//! `EnforcementDecision`, or any other policy vocabulary: the runtime crate +//! stays policy-neutral and never depends on `eggsec-policy`. +//! +//! The gate returns an [`ApprovalAnswer`] — "approved" or "denied", with an +//! optional reason. It does not interpret what an approval permits. Only the +//! policy kernel decides that, and it does so on the caller's side of the +//! gate, by re-running the authorisation path with an override bounded by the +//! classes the kernel itself demanded. +//! +//! # Ordering +//! +//! A pending decision is registered **before** the prompt is announced. A +//! client that answers the instant it sees the prompt therefore never races +//! the registration. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +use tokio::sync::oneshot; +use tokio_util::sync::CancellationToken; + +use crate::error::RuntimeError; +use crate::event::PolicyPrompt; +use crate::ids::{SessionId, TaskId}; +use crate::runtime_sink::RuntimeEventSink; + +/// The operator's answer to a pending policy decision. +/// +/// The answer names *yes* or *no*. It never names the authorisation: the +/// classes that are permitted are computed by the policy kernel, not by the +/// client. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApprovalAnswer { + /// The operator approved the pending decision. + Approved { reason: Option }, + /// The operator declined the pending decision. + Denied { reason: Option }, +} + +impl ApprovalAnswer { + /// Builds an answer from the wire-shaped pair of flag and reason. + pub fn from_parts(approved: bool, reason: Option) -> Self { + if approved { + Self::Approved { reason } + } else { + Self::Denied { reason } + } + } + + /// Whether the operator approved. + pub fn is_approved(&self) -> bool { + matches!(self, Self::Approved { .. }) + } +} + +/// A decision awaiting an answer. +#[derive(Debug)] +struct PendingApproval { + /// Identifies this registration, so a dropped waiter removes only its own + /// entry and never a later one registered for the same task. + id: u64, + prompt: PolicyPrompt, + answer_tx: oneshot::Sender, +} + +/// The runtime's registry of pending policy decisions. +#[derive(Debug, Default)] +pub struct ApprovalRegistry { + pending: Mutex, +} + +#[derive(Debug, Default)] +struct RegistryInner { + entries: HashMap<(SessionId, TaskId), PendingApproval>, + next_id: u64, +} + +impl ApprovalRegistry { + /// Registers a pending decision and returns its identifier. + fn register( + &self, + key: (SessionId, TaskId), + prompt: PolicyPrompt, + answer_tx: oneshot::Sender, + ) -> u64 { + let mut inner = self.lock(); + let id = inner.next_id; + inner.next_id = inner.next_id.wrapping_add(1); + inner.entries.insert( + key, + PendingApproval { + id, + prompt, + answer_tx, + }, + ); + id + } + + /// Removes the entry for `key`, but only if it is the registration `id`. + /// + /// A waiter that is dropped (because its task was cancelled) removes its + /// own entry here. The identifier check keeps a late drop from removing a + /// decision that was registered afterwards. + fn remove(&self, key: (SessionId, TaskId), id: u64) -> Option { + let mut inner = self.lock(); + match inner.entries.get(&key) { + Some(entry) if entry.id == id => inner.entries.remove(&key), + _ => None, + } + } + + /// Removes and returns the entry for `key`, whatever its identifier. + fn take(&self, key: (SessionId, TaskId)) -> Option { + let mut inner = self.lock(); + inner.entries.remove(&key) + } + + /// The prompt registered for `key`, if any. + fn prompt_for(&self, key: (SessionId, TaskId)) -> Option { + let inner = self.lock(); + inner.entries.get(&key).map(|entry| entry.prompt.clone()) + } + + /// The number of pending decisions. + #[cfg(test)] + fn len(&self) -> usize { + self.lock().entries.len() + } + + /// Locks the registry, recovering from a poisoned mutex. + /// + /// A panic in a holder must not make the registry permanently unusable: a + /// pending decision is a coordination record, not authority. + fn lock(&self) -> MutexGuard<'_, RegistryInner> { + self.pending + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +/// Removes a registration when the waiter that owns it goes away. +struct RegistrationGuard { + registry: Arc, + key: (SessionId, TaskId), + id: u64, +} + +impl Drop for RegistrationGuard { + fn drop(&mut self) { + if self.registry.remove(self.key, self.id).is_some() { + tracing::debug!( + session_id = %self.key.0, + task_id = %self.key.1, + "pending policy decision dropped with its waiter" + ); + } + } +} + +/// A handle to the runtime's approval registry. +/// +/// The handle is cheap to clone and is carried in the execution context, so an +/// executor can hold an operation at its confirmation point without knowing +/// anything about the daemon, the protocol, or the policy crate. +#[derive(Debug, Clone, Default)] +pub struct ApprovalGate { + registry: Arc, +} + +impl ApprovalGate { + /// Creates a gate over a fresh registry. + pub fn new() -> Self { + Self::default() + } + + /// Registers a pending decision, announces it, and awaits the answer. + /// + /// The decision is registered **before** the prompt is announced, so a + /// client that answers immediately never finds nothing pending. + /// + /// The wait is bounded by the caller's cancellation token: a cancelled + /// task drops its pending decision rather than leaving it behind. + pub async fn request( + &self, + sink: &RuntimeEventSink, + task_id: TaskId, + prompt: PolicyPrompt, + cancel: CancellationToken, + ) -> Result { + let session_id = sink.session_id(); + let key = (session_id, task_id); + let (answer_tx, answer_rx) = oneshot::channel(); + let id = self.registry.register(key, prompt.clone(), answer_tx); + + // The guard removes the registration if this future is dropped before + // the answer arrives — which is how a cancelled task stops holding a + // decision. + let _guard = RegistrationGuard { + registry: Arc::clone(&self.registry), + key, + id, + }; + + sink.policy_decision_required(prompt); + + if cancel.is_cancelled() { + return Err(RuntimeError::DispatchFailed( + "task cancelled before its policy decision was answered".into(), + )); + } + + tokio::select! { + answer = answer_rx => answer.map_err(|_| { + RuntimeError::DispatchFailed( + "the pending policy decision was dropped before it was answered".into(), + ) + }), + _ = cancel.cancelled() => Err(RuntimeError::DispatchFailed( + "task cancelled while awaiting a policy decision".into(), + )), + } + } + + /// Answers a pending decision. + /// + /// Returns `Err` when nothing is pending for that task: a task that never + /// asked, a decision that was already answered, or a decision whose holder + /// was cancelled. A strict surface never registers a decision, so an + /// answer for one lands here too. + pub fn resolve( + &self, + session_id: SessionId, + task_id: TaskId, + answer: ApprovalAnswer, + ) -> Result<(), RuntimeError> { + let key = (session_id, task_id); + let pending = self + .registry + .take(key) + .ok_or_else(|| RuntimeError::NoPendingApproval(task_id.to_string()))?; + if pending.answer_tx.send(answer).is_err() { + // The holder went away between the removal and the send. The + // decision no longer matters, so this is not an error for the + // answerer — but it is worth recording. + tracing::debug!( + session_id = %session_id, + task_id = %task_id, + "policy decision answered after its holder was gone" + ); + } + Ok(()) + } + + /// The prompt registered for a task, if one is pending. + pub fn pending(&self, session_id: SessionId, task_id: TaskId) -> Option { + self.registry.prompt_for((session_id, task_id)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::event::RuntimeEvent; + use tokio::sync::broadcast; + + /// A sink for a task, and the receiver that observes its events. + /// + /// The sink is built for the same task the request names, exactly as the + /// runtime builds it — the announced prompt names the sink's own task. + fn sink_and_receiver( + task_id: TaskId, + session_id: SessionId, + ) -> (RuntimeEventSink, broadcast::Receiver) { + let (tx, rx) = broadcast::channel(16); + let sink = RuntimeEventSink::new(task_id, session_id, tx); + (sink, rx) + } + + fn prompt() -> PolicyPrompt { + PolicyPrompt { + message: "the target is outside the configured scope".into(), + confirmation_class: Some("out-of-scope".into()), + requires_explicit_approval: true, + } + } + + #[tokio::test] + async fn a_registered_prompt_is_observable_and_the_answer_reaches_the_waiter() { + let gate = ApprovalGate::new(); + let session_id = SessionId::new(); + let task_id = TaskId::new(); + let (sink, mut rx) = sink_and_receiver(task_id, session_id); + let cancel = CancellationToken::new(); + + let waiter = { + let gate = gate.clone(); + let sink = sink.clone(); + let cancel = cancel.clone(); + tokio::spawn(async move { gate.request(&sink, task_id, prompt(), cancel).await }) + }; + + // The prompt is announced, and it is announced after registration. + let announced = rx.recv().await.expect("the prompt must be announced"); + match announced { + RuntimeEvent::PolicyDecisionRequired { + session_id: announced_session, + task_id: announced_task, + prompt: announced_prompt, + } => { + assert_eq!(announced_session, session_id); + assert_eq!(announced_task, Some(task_id)); + assert_eq!(announced_prompt.message, prompt().message); + } + other => panic!("expected a policy decision event, got {other:?}"), + } + + assert_eq!( + gate.pending(session_id, task_id).map(|p| p.message), + Some(prompt().message) + ); + + gate.resolve( + session_id, + task_id, + ApprovalAnswer::Approved { + reason: Some("confirmed by the operator".into()), + }, + ) + .expect("the pending decision must resolve"); + + let answer = waiter.await.expect("the waiter must not panic"); + assert_eq!( + answer.expect("the answer must be delivered"), + ApprovalAnswer::Approved { + reason: Some("confirmed by the operator".into()) + } + ); + assert!(gate.pending(session_id, task_id).is_none()); + } + + #[tokio::test] + async fn a_second_answer_for_the_same_task_is_refused() { + let gate = ApprovalGate::new(); + let session_id = SessionId::new(); + let task_id = TaskId::new(); + let (sink, mut rx) = sink_and_receiver(task_id, session_id); + + let waiter = { + let gate = gate.clone(); + let sink = sink.clone(); + tokio::spawn(async move { + gate.request(&sink, task_id, prompt(), CancellationToken::new()) + .await + }) + }; + let _ = rx.recv().await; + + gate.resolve(session_id, task_id, ApprovalAnswer::Denied { reason: None }) + .expect("the first answer resolves"); + let second = gate.resolve( + session_id, + task_id, + ApprovalAnswer::Approved { reason: None }, + ); + assert!( + matches!(second, Err(RuntimeError::NoPendingApproval(_))), + "a second answer must be refused, got {second:?}" + ); + + let answer = waiter.await.expect("the waiter must not panic"); + assert_eq!( + answer.expect("the answer must be delivered"), + ApprovalAnswer::Denied { reason: None } + ); + } + + #[tokio::test] + async fn answering_a_task_that_never_asked_is_refused() { + let gate = ApprovalGate::new(); + let result = gate.resolve( + SessionId::new(), + TaskId::new(), + ApprovalAnswer::Approved { reason: None }, + ); + assert!(matches!(result, Err(RuntimeError::NoPendingApproval(_)))); + } + + #[tokio::test] + async fn a_cancelled_waiter_drops_its_pending_decision() { + let gate = ApprovalGate::new(); + let session_id = SessionId::new(); + let task_id = TaskId::new(); + let (sink, mut rx) = sink_and_receiver(task_id, session_id); + let cancel = CancellationToken::new(); + + let waiter = { + let gate = gate.clone(); + let sink = sink.clone(); + let cancel = cancel.clone(); + tokio::spawn(async move { gate.request(&sink, task_id, prompt(), cancel).await }) + }; + let _ = rx.recv().await; + assert!(gate.pending(session_id, task_id).is_some()); + + cancel.cancel(); + let outcome = waiter.await.expect("the waiter must not panic"); + assert!(matches!(outcome, Err(RuntimeError::DispatchFailed(_)))); + + // The decision does not outlive its holder. + assert!(gate.pending(session_id, task_id).is_none()); + assert_eq!(gate.registry.len(), 0); + } + + #[tokio::test] + async fn a_dropped_waiter_drops_its_pending_decision() { + let gate = ApprovalGate::new(); + let session_id = SessionId::new(); + let task_id = TaskId::new(); + let (sink, mut rx) = sink_and_receiver(task_id, session_id); + + { + let holder = gate.clone(); + let sink = sink.clone(); + let waiter = tokio::spawn(async move { + holder + .request(&sink, task_id, prompt(), CancellationToken::new()) + .await + }); + let _ = rx.recv().await; + assert!(gate.pending(session_id, task_id).is_some()); + // Abort drops the future, which drops the registration. + waiter.abort(); + let _ = waiter.await; + } + + // Give the aborted task a chance to be dropped. + tokio::task::yield_now().await; + assert!(gate.pending(session_id, task_id).is_none()); + assert_eq!(gate.registry.len(), 0); + } + + #[test] + fn an_answer_reports_whether_it_was_approved() { + assert!(ApprovalAnswer::from_parts(true, None).is_approved()); + assert!(!ApprovalAnswer::from_parts(false, None).is_approved()); + assert_eq!( + ApprovalAnswer::from_parts(false, Some("no".into())), + ApprovalAnswer::Denied { + reason: Some("no".into()) + } + ); + } +} diff --git a/crates/eggsec-runtime/src/capabilities.rs b/crates/eggsec-runtime/src/capabilities.rs index 6778d0796..7bdd5456f 100644 --- a/crates/eggsec-runtime/src/capabilities.rs +++ b/crates/eggsec-runtime/src/capabilities.rs @@ -28,85 +28,47 @@ pub struct RuntimeCapabilities { pub supports_multiple_active_tasks: bool, } -/// Default capabilities are conservative (daemon safe subset). -/// Use `full_lab()` for all task kinds. +/// The default capability set is the **canonical** one: every capability name +/// the task-kind set defines, derived rather than transcribed. +/// +/// The capability set is an *advertisement and admission* concern, not an +/// authorisation one. Whether a given operation may run is decided by the +/// enforcement layer from the operation's risk, the operator's execution +/// policy, the loaded scope, and the enabled features. Publishing a hazard +/// family here therefore does not permit it — it only stops the runtime from +/// refusing the submission as an unknown kind. impl Default for RuntimeCapabilities { fn default() -> Self { - Self::daemon_conservative() + Self::canonical() } } impl RuntimeCapabilities { - /// Create conservative capabilities suitable for the daemon. + /// The canonical capability list, derived from the task-kind set. /// - /// Includes only safe, non-hazardous task kinds. Excludes stress testing, - /// packet manipulation, wireless active attacks, database pentest, traffic - /// interception, and C2 simulation. - pub fn daemon_conservative() -> Self { - Self { - task_kinds: vec![ - TaskCapability::new("port-scan", "Port scanning"), - TaskCapability::new("endpoint-scan", "Endpoint discovery"), - TaskCapability::new("fingerprint", "Service fingerprinting"), - TaskCapability::new("waf", "WAF detection"), - TaskCapability::new("pipeline", "Security assessment pipeline"), - TaskCapability::new("recon", "Reconnaissance"), - TaskCapability::new("load-test", "HTTP load testing"), - TaskCapability::new("fuzz", "Fuzzing"), - TaskCapability::new("waf-stress", "WAF stress testing"), - TaskCapability::new("nse", "NSE script execution"), - TaskCapability::new("hunt", "Vulnerability hunting"), - TaskCapability::new("browser", "Headless browser testing"), - TaskCapability::new("graphql", "GraphQL testing"), - TaskCapability::new("oauth", "OAuth testing"), - TaskCapability::new("auth-test", "Authentication testing"), - TaskCapability::new("compliance", "Compliance checking"), - TaskCapability::new("vuln", "Vulnerability scanning"), - TaskCapability::new("storage", "Storage operations"), - TaskCapability::new("integration", "External integrations"), - TaskCapability::new("workflow", "Workflow execution"), - ], - transports: vec!["in-process".into()], - supports_cancellation: true, - supports_multiple_sessions: true, - supports_multiple_active_tasks: false, - } + /// Every canonical capability name appears exactly once — `resume` + /// included — because the list is generated from + /// [`TaskKind::all_variants`] rather than transcribed. The published + /// descriptions come from the canonical description table, which is keyed + /// by capability name and covers exactly this name set. + pub fn canonical() -> Self { + let task_kinds = TaskKind::all_variants() + .iter() + .map(|kind| TaskCapability::new(kind.capability_name(), kind.capability_description())) + .collect(); + Self::with_task_kinds(task_kinds) } - /// Create capabilities listing all task kinds including hazardous/lab families. - pub fn full_lab() -> Self { + /// A capability set carrying exactly the given task kinds. + /// + /// The transports and the session/task flags are the standard ones; only + /// the task-kind list varies. This is how a host makes its **published** + /// set and the runtime's **enforced** set the same object: the published + /// list is computed first, then handed to the runtime as its enforced + /// set. + pub fn with_task_kinds(task_kinds: Vec) -> Self { Self { - task_kinds: vec![ - TaskCapability::new("load-test", "HTTP load testing"), - TaskCapability::new("stress-test", "Network stress testing"), - TaskCapability::new("port-scan", "Port scanning"), - TaskCapability::new("endpoint-scan", "Endpoint discovery"), - TaskCapability::new("fingerprint", "Service fingerprinting"), - TaskCapability::new("fuzz", "Fuzzing"), - TaskCapability::new("waf", "WAF detection"), - TaskCapability::new("waf-stress", "WAF stress testing"), - TaskCapability::new("pipeline", "Security assessment pipeline"), - TaskCapability::new("recon", "Reconnaissance"), - TaskCapability::new("packet-capture", "Packet capture"), - TaskCapability::new("traceroute", "Packet traceroute"), - TaskCapability::new("packet-send", "Packet sending"), - TaskCapability::new("graphql", "GraphQL testing"), - TaskCapability::new("oauth", "OAuth testing"), - TaskCapability::new("auth-test", "Authentication testing"), - TaskCapability::new("nse", "NSE script execution"), - TaskCapability::new("hunt", "Vulnerability hunting"), - TaskCapability::new("browser", "Headless browser testing"), - TaskCapability::new("compliance", "Compliance checking"), - TaskCapability::new("storage", "Storage operations"), - TaskCapability::new("integration", "External integrations"), - TaskCapability::new("workflow", "Workflow execution"), - TaskCapability::new("vuln", "Vulnerability scanning"), - TaskCapability::new("wireless", "WiFi reconnaissance"), - TaskCapability::new("wireless-active", "WiFi active attacks"), - TaskCapability::new("db-pentest", "Database security testing"), - TaskCapability::new("intercept", "Traffic interception"), - TaskCapability::new("c2", "C2 simulation"), - ], + task_kinds, transports: vec!["in-process".into()], supports_cancellation: true, supports_multiple_sessions: true, @@ -114,80 +76,51 @@ impl RuntimeCapabilities { } } - /// Deprecated: use `full_lab()` instead. - #[deprecated(note = "renamed to full_lab(); use full_lab() for all task kinds")] - pub fn full() -> Self { - Self::full_lab() - } - /// Create capabilities for a no-op executor (no task kinds). pub fn noop() -> Self { - Self { - task_kinds: vec![], - transports: vec!["in-process".into()], - supports_cancellation: true, - supports_multiple_sessions: true, - supports_multiple_active_tasks: false, - } + Self::with_task_kinds(Vec::new()) } /// Check if a task kind is supported by these capabilities. + /// + /// The name lookup delegates to [`TaskKind::capability_name`], the single + /// canonical name table — there is no second copy to drift. pub fn supports_task_kind(&self, kind: &TaskKind) -> bool { - let name = task_kind_name(kind); + let name = kind.capability_name(); self.task_kinds.iter().any(|c| c.name == name) } } -/// Map a `TaskKind` variant to its capability name string. -fn task_kind_name(kind: &TaskKind) -> &'static str { - match kind { - TaskKind::LoadTest(_) => "load-test", - TaskKind::StressTest(_) => "stress-test", - TaskKind::PortScan(_) => "port-scan", - TaskKind::EndpointScan(_) => "endpoint-scan", - TaskKind::Fingerprint(_) => "fingerprint", - TaskKind::Fuzz(_) => "fuzz", - TaskKind::Waf(_) => "waf", - TaskKind::WafStress(_) => "waf-stress", - TaskKind::Pipeline(_) => "pipeline", - TaskKind::Resume(_) => "resume", - TaskKind::Recon(_) => "recon", - TaskKind::PacketCapture(_) => "packet-capture", - TaskKind::PacketTraceroute(_) => "traceroute", - TaskKind::PacketSend(_) => "packet-send", - TaskKind::GraphQl(_) => "graphql", - TaskKind::OAuth(_) => "oauth", - TaskKind::AuthTest(_) => "auth-test", - TaskKind::Nse(_) => "nse", - TaskKind::Hunt(_) => "hunt", - TaskKind::Browser(_) => "browser", - TaskKind::Compliance(_) => "compliance", - TaskKind::Storage(_) => "storage", - TaskKind::Integrations(_) => "integration", - TaskKind::Workflow(_) => "workflow", - TaskKind::Vuln(_) => "vuln", - TaskKind::Wireless(_) => "wireless", - TaskKind::WirelessActive(_) => "wireless-active", - TaskKind::DbPentest(_) => "db-pentest", - TaskKind::Intercept(_) => "intercept", - TaskKind::C2(_) => "c2", - } -} - #[cfg(test)] mod tests { use super::*; - use crate::request::*; + use crate::request::{CAPABILITY_DESCRIPTIONS, *}; + + fn canonical_names() -> Vec { + RuntimeCapabilities::canonical() + .task_kinds + .iter() + .map(|c| c.name.clone()) + .collect() + } #[test] fn capabilities_roundtrip() { - let caps = RuntimeCapabilities::daemon_conservative(); + let caps = RuntimeCapabilities::canonical(); let json = serde_json::to_string(&caps).unwrap(); let deserialized: RuntimeCapabilities = serde_json::from_str(&json).unwrap(); assert_eq!(caps.task_kinds.len(), deserialized.task_kinds.len()); assert!(deserialized.supports_cancellation); } + #[test] + fn default_capabilities_are_the_canonical_set() { + assert_eq!( + RuntimeCapabilities::default().task_kinds.len(), + RuntimeCapabilities::canonical().task_kinds.len() + ); + } + #[test] fn default_capabilities_have_task_kinds() { let caps = RuntimeCapabilities::default(); @@ -215,44 +148,53 @@ mod tests { assert!(caps.supports_multiple_sessions); } + /// The derived list must cover every canonical capability name. The + /// enumeration is generated from the canonical task-kind table, so this + /// holds by construction — the test is the machine-checked backstop for + /// the guard that pins the derivation. #[test] - fn daemon_conservative_includes_safe_kinds() { - let caps = RuntimeCapabilities::daemon_conservative(); - let names: Vec<_> = caps.task_kinds.iter().map(|c| c.name.as_str()).collect(); - for expected in &[ - "port-scan", - "endpoint-scan", - "fingerprint", - "waf", - "pipeline", - "recon", - "load-test", - "fuzz", - "waf-stress", - "nse", - "hunt", - "browser", - "graphql", - "oauth", - "auth-test", - "compliance", - "vuln", - "storage", - "integration", - "workflow", - ] { + fn canonical_covers_every_task_kind() { + let caps = RuntimeCapabilities::canonical(); + let variants = TaskKind::all_variants(); + assert_eq!( + caps.task_kinds.len(), + variants.len(), + "the derived list must have one entry per task kind" + ); + for kind in &variants { assert!( - names.contains(expected), - "Missing safe task kind: {expected}" + caps.supports_task_kind(kind), + "canonical list is missing {:?}", + kind.capability_name() ); } } #[test] - fn daemon_conservative_excludes_hazardous_kinds() { - let caps = RuntimeCapabilities::daemon_conservative(); - let names: Vec<_> = caps.task_kinds.iter().map(|c| c.name.as_str()).collect(); - for excluded in &[ + fn canonical_names_are_unique() { + let names = canonical_names(); + let mut unique = names.clone(); + unique.sort(); + unique.dedup(); + assert_eq!(unique.len(), names.len(), "duplicate capability names"); + } + + #[test] + fn canonical_includes_resume() { + let names = canonical_names(); + assert!( + names.contains(&"resume".to_string()), + "resume must be advertised like every other canonical kind" + ); + } + + /// The hazard families are *offered*, not *permitted*: publishing them + /// stops the runtime refusing the submission as an unknown kind. The + /// operator's execution policy still decides whether they may run. + #[test] + fn canonical_includes_the_hazard_families() { + let names = canonical_names(); + for expected in &[ "stress-test", "packet-send", "wireless", @@ -264,54 +206,65 @@ mod tests { "traceroute", ] { assert!( - !names.contains(excluded), - "Hazardous kind should not be in conservative: {excluded}" + names.contains(&expected.to_string()), + "hazard family should be advertised: {expected}" ); } } + /// The description table is data, not identity: it is keyed by capability + /// name and must cover exactly the derived name set — no more, no fewer. #[test] - fn full_lab_has_all_task_kinds() { - let caps = RuntimeCapabilities::full_lab(); - let names: Vec<_> = caps.task_kinds.iter().map(|c| c.name.as_str()).collect(); - for expected in &[ - "load-test", - "stress-test", - "port-scan", - "endpoint-scan", - "fingerprint", - "fuzz", - "waf", - "waf-stress", - "pipeline", - "recon", - "packet-capture", - "traceroute", - "packet-send", - "graphql", - "oauth", - "auth-test", - "nse", - "hunt", - "browser", - "compliance", - "storage", - "integration", - "workflow", - "vuln", - "wireless", - "wireless-active", - "db-pentest", - "intercept", - "c2", - ] { - assert!(names.contains(expected), "Missing task kind: {expected}"); + fn description_table_covers_exactly_the_canonical_names() { + let derived: Vec = canonical_names(); + let derived: Vec<&str> = derived.iter().map(|n| n.as_str()).collect(); + let described: Vec<&str> = CAPABILITY_DESCRIPTIONS.iter().map(|(k, _)| *k).collect(); + assert_eq!( + derived.len(), + described.len(), + "description table must cover exactly the derived name set" + ); + for name in &derived { + assert!( + described.contains(name), + "description table is missing {name}" + ); + } + for name in &described { + assert!( + derived.contains(name), + "description table has an extra name {name}" + ); + } + } + + #[test] + fn every_canonical_entry_has_a_description() { + for capability in &RuntimeCapabilities::canonical().task_kinds { + assert!( + !capability.description.trim().is_empty(), + "capability {} has no description", + capability.name + ); + } + } + + /// The name lookup and the canonical name table must not diverge. + #[test] + fn supports_task_kind_agrees_with_capability_name() { + let caps = RuntimeCapabilities::canonical(); + for kind in TaskKind::all_variants() { + let name = kind.capability_name(); + assert!( + caps.task_kinds.iter().any(|c| c.name == name), + "{name} is not in the canonical list" + ); } } #[test] fn supports_task_kind_positive() { - let caps = RuntimeCapabilities::daemon_conservative(); + let caps = RuntimeCapabilities::canonical(); assert!(caps.supports_task_kind(&TaskKind::PortScan(PortScanParams { target: "10.0.0.1".into(), ports: None, @@ -326,11 +279,32 @@ mod tests { }))); } + /// A runtime configured with a narrower set still refuses the kinds + /// outside it. The canonical list is the default, not the only option. #[test] - fn supports_task_kind_negative() { - let caps = RuntimeCapabilities::daemon_conservative(); + fn a_narrow_set_rejects_the_kinds_outside_it() { + let narrow = RuntimeCapabilities { + task_kinds: vec![ + TaskCapability::new("port-scan", "Port scanning"), + TaskCapability::new("load-test", "HTTP load testing"), + ], + transports: vec!["in-process".into()], + supports_cancellation: true, + supports_multiple_sessions: true, + supports_multiple_active_tasks: false, + }; + assert!( + narrow.supports_task_kind(&TaskKind::PortScan(PortScanParams { + target: "10.0.0.1".into(), + ports: None, + scan_type: None, + timeout_ms: None, + concurrency: None, + udp: None, + })) + ); assert!( - !caps.supports_task_kind(&TaskKind::StressTest(StressTestParams { + !narrow.supports_task_kind(&TaskKind::StressTest(StressTestParams { target: "10.0.0.1".into(), flood_type: "syn".into(), duration_secs: None, @@ -339,10 +313,26 @@ mod tests { })) ); assert!( - !caps.supports_task_kind(&TaskKind::Wireless(WirelessParams { + !narrow.supports_task_kind(&TaskKind::Wireless(WirelessParams { interface: None, duration_secs: None, })) ); } + + #[test] + fn noop_capabilities_are_empty() { + let caps = RuntimeCapabilities::noop(); + assert!(caps.task_kinds.is_empty()); + assert!( + !caps.supports_task_kind(&TaskKind::PortScan(PortScanParams { + target: "10.0.0.1".into(), + ports: None, + scan_type: None, + timeout_ms: None, + concurrency: None, + udp: None, + })) + ); + } } diff --git a/crates/eggsec-runtime/src/daemon_endpoint.rs b/crates/eggsec-runtime/src/daemon_endpoint.rs new file mode 100644 index 000000000..9a696a0a8 --- /dev/null +++ b/crates/eggsec-runtime/src/daemon_endpoint.rs @@ -0,0 +1,131 @@ +//! The daemon's endpoint: one default, one environment override, one rule. +//! +//! The daemon listens on a Unix socket. Which path it listens on is a +//! *deployment* fact, and this module is the single place in the workspace +//! that states it: +//! +//! - [`DEFAULT_DAEMON_SOCKET_PATH`] is the built-in default. +//! - [`DAEMON_SOCKET_ENV_VAR`] is the environment variable that overrides it. +//! - [`resolve_daemon_socket_path`] is the precedence rule, as a pure +//! function. +//! - [`daemon_socket_path_from_env`] is the only function in the workspace +//! that reads the environment. +//! +//! The precedence is **explicit flag → environment → built-in default**, and it +//! is applied here rather than at the call sites, so that the daemon binary, +//! the CLI, the TUI and the GUI cannot disagree about the path. +//! +//! The resolver is deliberately pure: it takes the raw environment value and +//! returns the resolved one, and never reads the process environment. That is +//! what makes the precedence testable without mutating a process-global, and +//! it is why [`daemon_socket_path_from_env`] — the only reader — is a separate +//! function. + +/// The environment variable that overrides the daemon's default socket path. +/// +/// The name is the one the repository already used in +/// `scripts/build-daemon-profile.sh`, so adopting it turns that script's line +/// from a promise the binaries did not keep into a fact. It is **not** +/// `EGGSEC_SOCKET`, which is named and rejected in +/// `docs/GUI_DISTRIBUTION_HANDOFF.md`. +pub const DAEMON_SOCKET_ENV_VAR: &str = "EGGSEC_DAEMON_SOCKET"; + +/// The daemon's built-in default socket path. +/// +/// This is the one place in the workspace's executable surface that states the +/// literal. Every surface resolves to it through +/// [`resolve_daemon_socket_path`]. +pub const DEFAULT_DAEMON_SOCKET_PATH: &str = "/tmp/eggsec-daemon.sock"; + +/// Resolve a raw environment value into the socket path to use. +/// +/// The rule, in one place: +/// +/// | Input | Output | +/// |---|---| +/// | `None` (the variable is unset) | [`DEFAULT_DAEMON_SOCKET_PATH`] | +/// | `Some("")` (set but empty) | [`DEFAULT_DAEMON_SOCKET_PATH`] | +/// | `Some(" ")` (whitespace only) | [`DEFAULT_DAEMON_SOCKET_PATH`] | +/// | `Some("/run/user/1000/eggsec.sock")` | that value, verbatim | +/// | `Some(" /run/user/1000/eggsec.sock ")` | the **trimmed** value | +/// +/// An empty or whitespace-only value is **absent**, not an empty path: a +/// daemon must never be asked to bind the empty path. The trim is part of the +/// rule, so it lives here and not at the call sites. +/// +/// This function is pure — it never reads the process environment. +pub fn resolve_daemon_socket_path(env_value: Option<&str>) -> &str { + match env_value { + Some(raw) => { + let trimmed = raw.trim(); + if trimmed.is_empty() { + DEFAULT_DAEMON_SOCKET_PATH + } else { + trimmed + } + } + None => DEFAULT_DAEMON_SOCKET_PATH, + } +} + +/// Resolve the daemon's socket path from the process environment. +/// +/// This is the only function in the workspace that reads +/// [`DAEMON_SOCKET_ENV_VAR`]. The surfaces call it; they do not read the +/// environment themselves. +pub fn daemon_socket_path_from_env() -> String { + resolve_daemon_socket_path(std::env::var(DAEMON_SOCKET_ENV_VAR).ok().as_deref()).to_owned() +} + +#[cfg(test)] +mod tests { + use super::{resolve_daemon_socket_path, DAEMON_SOCKET_ENV_VAR, DEFAULT_DAEMON_SOCKET_PATH}; + + #[test] + fn an_absent_variable_resolves_to_the_built_in_default() { + assert_eq!(resolve_daemon_socket_path(None), DEFAULT_DAEMON_SOCKET_PATH); + } + + #[test] + fn an_empty_value_resolves_to_the_built_in_default() { + assert_eq!( + resolve_daemon_socket_path(Some("")), + DEFAULT_DAEMON_SOCKET_PATH + ); + } + + #[test] + fn a_whitespace_only_value_resolves_to_the_built_in_default() { + assert_eq!( + resolve_daemon_socket_path(Some(" \t ")), + DEFAULT_DAEMON_SOCKET_PATH + ); + } + + #[test] + fn an_explicit_value_resolves_verbatim() { + assert_eq!( + resolve_daemon_socket_path(Some("/run/user/1000/eggsec.sock")), + "/run/user/1000/eggsec.sock" + ); + } + + #[test] + fn an_explicit_value_is_trimmed() { + assert_eq!( + resolve_daemon_socket_path(Some(" /run/user/1000/eggsec.sock ")), + "/run/user/1000/eggsec.sock" + ); + } + + #[test] + fn the_default_path_value_is_pinned() { + // The one place in the workspace that may state the literal. + assert_eq!(DEFAULT_DAEMON_SOCKET_PATH, "/tmp/eggsec-daemon.sock"); + } + + #[test] + fn the_environment_variable_name_is_pinned() { + assert_eq!(DAEMON_SOCKET_ENV_VAR, "EGGSEC_DAEMON_SOCKET"); + } +} diff --git a/crates/eggsec-runtime/src/error.rs b/crates/eggsec-runtime/src/error.rs index d2ea4f8e5..f8a49fa41 100644 --- a/crates/eggsec-runtime/src/error.rs +++ b/crates/eggsec-runtime/src/error.rs @@ -44,6 +44,14 @@ pub enum RuntimeError { #[error("scope unavailable: {0}")] ScopeUnavailable(String), + /// No policy decision is pending for the task. + /// + /// This covers every way an answer can find nothing to answer: the task + /// never asked, the decision was already answered, the holder was + /// cancelled, or the surface never held a decision at all. + #[error("no pending policy decision for task {0}")] + NoPendingApproval(String), + #[error("cancelled")] Cancelled, } diff --git a/crates/eggsec-runtime/src/lib.rs b/crates/eggsec-runtime/src/lib.rs index 4c9152889..e11d7ebca 100644 --- a/crates/eggsec-runtime/src/lib.rs +++ b/crates/eggsec-runtime/src/lib.rs @@ -1,23 +1,34 @@ +pub mod approval; pub mod cancel; pub mod capabilities; +pub mod daemon_endpoint; 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; pub mod runtime_sink; +#[cfg(feature = "schema")] +pub mod schema; pub mod session; +pub use approval::{ApprovalAnswer, ApprovalGate, ApprovalRegistry}; pub use cancel::race_with_cancel; pub use capabilities::{RuntimeCapabilities, TaskCapability}; +pub use daemon_endpoint::{ + daemon_socket_path_from_env, resolve_daemon_socket_path, DAEMON_SOCKET_ENV_VAR, + DEFAULT_DAEMON_SOCKET_PATH, +}; pub use error::RuntimeError; pub use event::{ ArtifactRef, LogLevel, PolicyPrompt, RuntimeAuditEvent, RuntimeErrorInfo, RuntimeEvent, 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..0ee988c25 --- /dev/null +++ b/crates/eggsec-runtime/src/report.rs @@ -0,0 +1,288 @@ +//! 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. +//! +//! finding text and no credential. The engine owns the verdict; the runtime +//! carries it; the daemon republishes it; the GUI renders it. The runtime +//! crate still holds no report-model type and no domain type. +//! +//! 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 serde::{Deserialize, Serialize}; + +use crate::ids::TaskId; + +/// Whether an operation's result has a clean report mapping. +/// +/// This is the engine's verdict about one canonical operation, published so a +/// client can say *why* a completed task has no report rather than only that +/// it has none. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReportForm { + /// The operation's result maps onto the canonical report model. + Canonical, + /// The operation's result carries no clean report mapping. + NoCleanMapping, +} + +/// One operation's report-form verdict. +/// +/// The row names the canonical operation and, when the operation has no clean +/// mapping, the fact its result is missing. The reason is empty for a +/// canonical operation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReportFormEntry { + /// The canonical operation id. + pub operation_id: String, + /// The operation's verdict. + pub form: ReportForm, + /// Why the operation has no report form; empty for a canonical one. + pub reason: String, +} + +/// 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()); + } + + #[test] + fn the_coverage_dto_round_trips() { + let entries = vec![ + ReportFormEntry { + operation_id: "scan-ports".to_owned(), + form: ReportForm::Canonical, + reason: String::new(), + }, + ReportFormEntry { + operation_id: "waf-detect".to_owned(), + form: ReportForm::NoCleanMapping, + reason: "the result carries no target field".to_owned(), + }, + ]; + + let encoded = serde_json::to_string(&entries).expect("the coverage encodes"); + let decoded: Vec = + serde_json::from_str(&encoded).expect("the coverage decodes"); + + assert_eq!(decoded, entries); + assert_eq!(decoded[0].form, ReportForm::Canonical); + assert!( + decoded[0].reason.is_empty(), + "a canonical operation carries no reason" + ); + assert_eq!(decoded[1].form, ReportForm::NoCleanMapping); + assert!(decoded[1].reason.contains("no target")); + } + + #[test] + fn the_coverage_form_is_named_on_the_wire() { + let encoded = serde_json::to_string(&ReportForm::NoCleanMapping).expect("the form encodes"); + assert_eq!(encoded, "\"no_clean_mapping\""); + let decoded: ReportForm = serde_json::from_str(&encoded).expect("the form decodes"); + assert_eq!(decoded, ReportForm::NoCleanMapping); + } +} diff --git a/crates/eggsec-runtime/src/request.rs b/crates/eggsec-runtime/src/request.rs index 47240f14c..6df7f0292 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", @@ -55,43 +62,114 @@ impl RuntimeSurface { } } -/// Frontend-neutral task kind enum covering all TUI task categories. +/// The canonical task-kind table. /// -/// Each variant represents a distinct tool or operation that can be submitted -/// to the runtime. Payload structs are serializable and TUI-free. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "params")] -pub enum TaskKind { - 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), +/// This is the **single source of truth** for the task-kind set: it declares +/// the variants, their wire capability names, and their published +/// descriptions. The runtime's canonical capability list, the admission +/// check's name lookup, and the published capability list are all generated +/// from it, so a new variant cannot be added without the derived list +/// noticing -- adding one is a compile error until the table covers it. +/// +/// The macro is deliberate. The list is transcribed exactly once, and the +/// generated matches are exhaustive by construction (no wildcard arm), which +/// is the compile-time guarantee the workspace's single-table rule asks for. +macro_rules! define_task_kinds { + ( + $( + $(#[$meta:meta])* + $variant:ident($params:ty) => $name:literal, $description:literal; + )* + ) => { + /// Frontend-neutral task kind enum covering all TUI task categories. + /// + /// Each variant represents a distinct tool or operation that can be submitted + /// 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 { + $( + $(#[$meta])* + $variant($params), + )* + } + + impl TaskKind { + /// Wire capability name for this task kind variant. + /// + /// This name must match the entries in + /// [`crate::capabilities::RuntimeCapabilities::task_kinds`] for the + /// task to be supported by a given runtime configuration. It is + /// transport metadata, not the canonical operation identity (see + /// [`Self::operation_id`]). + pub fn capability_name(&self) -> &'static str { + match self { + $( TaskKind::$variant(_) => $name, )* + } + } + + /// Every task-kind variant, in declaration order. + /// + /// The payloads are defaults: this enumerates the *kinds*, not + /// runnable requests. Generated from the canonical table, so it + /// covers every variant by construction -- adding a variant to the + /// table adds it here, and there is no hand-maintained list to + /// fall out of step. + pub fn all_variants() -> Vec { + vec![ $( TaskKind::$variant(<$params>::default()), )* ] + } + + /// The published description of this variant's capability. + pub fn capability_description(&self) -> &'static str { + match self { + $( TaskKind::$variant(_) => $description, )* + } + } + } + + /// Curated published descriptions, keyed by capability name. + /// + /// Data, not identity: the *names* are derived from the task-kind set + /// above, while these strings are the wording the daemon publishes. + /// The key set is exactly the canonical name set, by construction. + pub const CAPABILITY_DESCRIPTIONS: &[(&str, &str)] = &[ + $( ($name, $description), )* + ]; + }; +} + +define_task_kinds! { + LoadTest(LoadTestParams) => "load-test", "HTTP load testing"; + StressTest(StressTestParams) => "stress-test", "Network stress testing"; + PortScan(PortScanParams) => "port-scan", "Port scanning"; + EndpointScan(EndpointScanParams) => "endpoint-scan", "Endpoint discovery"; + Fingerprint(FingerprintParams) => "fingerprint", "Service fingerprinting"; + Fuzz(FuzzParams) => "fuzz", "Fuzzing"; + Waf(WafParams) => "waf", "WAF detection"; + WafStress(WafStressParams) => "waf-stress", "WAF stress testing"; + Pipeline(PipelineParams) => "pipeline", "Security assessment pipeline"; + Resume(ResumeParams) => "resume", "Resume a saved scan checkpoint"; + Recon(ReconParams) => "recon", "Reconnaissance"; + PacketCapture(PacketCaptureParams) => "packet-capture", "Packet capture"; + PacketTraceroute(PacketTracerouteParams) => "traceroute", "Packet traceroute"; + PacketSend(PacketSendParams) => "packet-send", "Packet sending"; + GraphQl(GraphQlParams) => "graphql", "GraphQL testing"; + OAuth(OAuthParams) => "oauth", "OAuth testing"; + AuthTest(AuthTestParams) => "auth-test", "Authentication testing"; + Nse(NseParams) => "nse", "NSE script execution"; + Hunt(HuntParams) => "hunt", "Vulnerability hunting"; + Browser(BrowserParams) => "browser", "Headless browser testing"; + Compliance(ComplianceParams) => "compliance", "Compliance checking"; + Storage(StorageParams) => "storage", "Storage operations"; + Integrations(IntegrationsParams) => "integration", "External integrations"; + Workflow(WorkflowParams) => "workflow", "Workflow execution"; + Vuln(VulnParams) => "vuln", "Vulnerability scanning"; + Wireless(WirelessParams) => "wireless", "WiFi reconnaissance"; + WirelessActive(WirelessActiveParams) => "wireless-active", "WiFi active attacks"; + DbPentest(DbPentestParams) => "db-pentest", "Database security testing"; + Intercept(InterceptParams) => "intercept", "Traffic interception"; + C2(C2Params) => "c2", "C2 simulation"; } /// A runtime request to execute a task. @@ -107,6 +185,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 +204,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 +215,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 +230,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 +251,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 +261,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 +283,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 +292,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, @@ -214,7 +300,8 @@ pub struct WafStressParams { } /// Pipeline parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct PipelineParams { pub target: String, pub profile: Option, @@ -239,13 +326,15 @@ 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)] +#[derive(Default, 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)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ReconParams { pub target: String, pub modules: Option>, @@ -253,6 +342,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, @@ -262,7 +352,8 @@ pub struct PacketCaptureParams { } /// Packet traceroute parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, 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 +361,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 +373,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 +386,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 +402,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, @@ -319,7 +414,8 @@ pub struct AuthTestParams { } /// NSE script parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct NseParams { pub target: String, pub script: String, @@ -342,21 +438,24 @@ pub struct NseParams { } /// Vulnerability hunt parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct HuntParams { pub target: String, pub hunt_type: Option, } /// Browser testing parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct BrowserParams { pub target: String, pub headless: Option, } /// Compliance check parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct ComplianceParams { pub target: String, pub framework: Option, @@ -364,6 +463,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, @@ -393,28 +493,32 @@ pub struct StorageParams { } /// Integration parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct IntegrationsParams { pub integration_type: String, pub config: Option, } /// Workflow parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct WorkflowParams { pub workflow_id: Option, pub steps: Option>, } /// Vulnerability parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub struct VulnParams { pub target: String, pub vuln_type: Option, } /// Wireless recon parameters. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Default, 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 +552,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 +590,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 +604,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 +615,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, @@ -515,50 +623,6 @@ pub struct C2Params { } impl TaskKind { - /// Wire capability name for this task kind variant. - /// - /// This name must match the entries in [`RuntimeCapabilities::task_kinds`] - /// for the task to be supported by a given runtime configuration. It is - /// transport metadata, not the canonical operation identity (see - /// [`Self::operation_id`]). - pub fn capability_name(&self) -> &'static str { - match self { - TaskKind::LoadTest(_) => "load-test", - TaskKind::StressTest(_) => "stress-test", - TaskKind::PortScan(_) => "port-scan", - TaskKind::EndpointScan(_) => "endpoint-scan", - TaskKind::Fingerprint(_) => "fingerprint", - TaskKind::Fuzz(_) => "fuzz", - TaskKind::Waf(_) => "waf", - TaskKind::WafStress(_) => "waf-stress", - TaskKind::Pipeline(_) => "pipeline", - // Resume is a distinct wire kind with its own capability name, so a - // runtime can advertise pipeline support without also advertising - // resume — the daemon conservative set deliberately omits it. - TaskKind::Resume(_) => "resume", - TaskKind::Recon(_) => "recon", - TaskKind::PacketCapture(_) => "packet-capture", - TaskKind::PacketTraceroute(_) => "traceroute", - TaskKind::PacketSend(_) => "packet-send", - TaskKind::GraphQl(_) => "graphql", - TaskKind::OAuth(_) => "oauth", - TaskKind::AuthTest(_) => "auth-test", - TaskKind::Nse(_) => "nse", - TaskKind::Hunt(_) => "hunt", - TaskKind::Browser(_) => "browser", - TaskKind::Compliance(_) => "compliance", - TaskKind::Storage(_) => "storage", - TaskKind::Integrations(_) => "integration", - TaskKind::Workflow(_) => "workflow", - TaskKind::Vuln(_) => "vuln", - TaskKind::Wireless(_) => "wireless", - TaskKind::WirelessActive(_) => "wireless-active", - TaskKind::DbPentest(_) => "db-pentest", - TaskKind::Intercept(_) => "intercept", - TaskKind::C2(_) => "c2", - } - } - /// Canonical engine operation ID for this task kind (wire-compat accessor). /// /// This is the single wire-side match for operation identity. Engine @@ -597,7 +661,11 @@ impl TaskKind { // enforcement the same way. TaskKind::Resume(_) => "pipeline", TaskKind::Recon(_) => "recon", - TaskKind::PacketCapture(_) => "packet", + // The capture half of the packet family owns its own operation: + // a capture binds to a **local interface**, while `packet` also + // serves `traceroute` and `packet-send`, which address a remote + // host and must keep requiring one. + TaskKind::PacketCapture(_) => "packet-capture", TaskKind::PacketTraceroute(_) => "packet", TaskKind::PacketSend(_) => "packet", TaskKind::GraphQl(_) => "graphql", @@ -612,15 +680,26 @@ impl TaskKind { TaskKind::Workflow(_) => "workflow", TaskKind::Vuln(_) => "vuln", TaskKind::Wireless(_) => "wireless", - TaskKind::WirelessActive(_) => "wireless", + // An active wireless request performs a deauth/disassoc, which is + // the `wireless-deauth` operation -- risk `Intrusive`, capability + // `RawPacketProbe`, feature `wireless-advanced`. It must NOT be + // authorised under the passive `wireless` operation's risk level: + // the CLI already resolves its deauth command against + // `wireless-deauth`, so the daemon and the CLI have to agree. + TaskKind::WirelessActive(_) => "wireless-deauth", TaskKind::DbPentest(_) => "db-pentest", TaskKind::Intercept(_) => "proxy-intercept", TaskKind::C2(_) => "c2", } } - /// Canonical target for this task kind (`None` for `NoTarget` or - /// interface-bound operations). Wire-compat accessor; engine adapters + /// Canonical target for this task kind. + /// + /// `None` for a `NoTarget` operation. For an **interface-bound** + /// operation the value is the *local identifier* -- an interface name, a + /// BSSID -- not a remote host: the enforcement kernel carries it into the + /// descriptor and the audit record without matching it against the + /// scope's remote target rules. Wire-compat accessor; engine adapters /// delegate to this method (see [`Self::operation_id`]). /// /// Exhaustive for the same compile-failure guarantee as @@ -643,7 +722,11 @@ impl TaskKind { // target from the selected session in their own descriptor path. TaskKind::Resume(_) => None, TaskKind::Recon(p) => Some(p.target.clone()), - TaskKind::PacketCapture(_) => None, + // The local identifier, not a remote host. It is carried into + // the descriptor and the audit record, and the enforcement + // kernel does not match it against the scope's remote target + // rules. + TaskKind::PacketCapture(p) => p.interface.clone(), TaskKind::PacketTraceroute(p) => Some(p.target.clone()), TaskKind::PacketSend(p) => Some(p.target.clone()), TaskKind::GraphQl(p) => Some(p.target.clone()), @@ -657,8 +740,11 @@ impl TaskKind { TaskKind::Integrations(_) => None, TaskKind::Workflow(_) => None, TaskKind::Vuln(p) => Some(p.target.clone()), - TaskKind::Wireless(_) => None, - TaskKind::WirelessActive(_) => None, + TaskKind::Wireless(p) => p.interface.clone(), + // The deauth's local identifier is the BSSID it targets, with + // the interface as the fallback. The CLI passes the BSSID as the + // target for the same operation, so the two agree. + TaskKind::WirelessActive(p) => p.target_bssid.clone().or_else(|| p.interface.clone()), TaskKind::DbPentest(p) => Some(p.target.clone()), TaskKind::Intercept(p) => p.target.clone(), TaskKind::C2(p) => p.target.clone(), diff --git a/crates/eggsec-runtime/src/runtime.rs b/crates/eggsec-runtime/src/runtime.rs index d50cc1a14..e29368c05 100644 --- a/crates/eggsec-runtime/src/runtime.rs +++ b/crates/eggsec-runtime/src/runtime.rs @@ -4,8 +4,10 @@ use std::sync::Arc; use tokio::sync::{broadcast, Mutex}; use tokio_util::sync::CancellationToken; +use crate::capabilities::{RuntimeCapabilities, TaskCapability}; use crate::event::{RuntimeErrorInfo, RuntimeEvent, TaskOutcome, TaskStatus}; use crate::ids::{ClientId, SessionId, TaskId}; +use crate::report::ReportFormEntry; use crate::request::{RunRequest, RuntimeSurface}; use crate::session::{ RuntimeExecutionContext, RuntimeSession, SessionScope, SessionSnapshot, SessionSummary, @@ -54,6 +56,72 @@ pub trait RuntimeTaskExecutor: Send + Sync + 'static { ) -> std::pin::Pin< Box> + Send + 'static>, >; + + /// The task kinds this executor can execute. + /// + /// The default is the **canonical** list: every capability name the + /// task-kind set defines, derived rather than transcribed. An executor + /// that says nothing is therefore treated as able to run every canonical + /// kind, which is the same statement the derived list makes everywhere + /// else in the workspace. + /// + /// An executor that rejects every task MUST declare the empty set + /// instead -- otherwise a host would advertise capabilities the executor + /// cannot execute, which is the one state this declaration exists to make + /// unrepresentable. + fn supported_task_kinds(&self) -> Vec { + RuntimeCapabilities::canonical().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 + } + + /// The report-form coverage this executor's build publishes. + /// + /// This is another *build* fact, like [`Self::enabled_features`]: it says + /// which canonical operations produce a report document and which do + /// not. A host publishes it so a client can tell an operator **why** a + /// completed task has no report, rather than only that it has none. + /// + /// `None` means **unknown**: the executor links no engine, or does not + /// publish the fact — the same distinction [`Self::enabled_features`] + /// draws. `Some(vec![])` means the executor published an empty coverage, + /// which is a different, knowable fact. + /// + /// The default is `None` so every existing implementor keeps its current + /// behaviour and no host has to change to compile. + fn report_forms(&self) -> Option> { + None + } } struct RuntimeState { @@ -75,22 +143,169 @@ struct RuntimeState { /// lifecycle state. pub struct Runtime { state: Arc>, + /// The executor's declared support, captured at construction. + /// + /// It lives outside the state mutex so a host can read it synchronously + /// 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's published report-form coverage, 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 `enabled_features` does: a host reads it synchronously + /// while building its own published capability list. The coverage is + /// immutable for the life of the process, so every concurrent reader + /// observes the same rows. + report_forms: Option>, + /// The runtime's enforced capability set, captured at construction. + /// + /// This is the configured set every session carries, and therefore the + /// set a submission is admitted against. It lives outside the state mutex + /// for the same reason `supported_task_kinds` does: a host reads it + /// synchronously while building its published capability list, so that the + /// published set and the enforced set can be made the same object. + enforced_task_kinds: Vec, + /// 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, + /// The runtime's pending-approval registry. + /// + /// A manual operation whose policy demands a confirmation is held here + /// until an operator answers. It lives outside the state mutex so that + /// answering a pending decision never waits behind a task-lifecycle + /// lock, and so the handle can be cloned into an execution context + /// cheaply. + approvals: crate::approval::ApprovalGate, } impl Runtime { /// Create a new runtime with the given configuration and executor. 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 report_forms = executor.report_forms(); + let enforced_task_kinds = config.capabilities.task_kinds.clone(); + 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, + report_forms, + enforced_task_kinds, + executor, + approvals: crate::approval::ApprovalGate::new(), } } + /// 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-form coverage 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 + /// operation has a report form"; it means the answer is unknown, exactly + /// as `None` means unknown for the feature set. + /// + /// The coverage is captured at construction and never changes, so every + /// reader observes the same rows. + pub fn report_forms(&self) -> Option<&[ReportFormEntry]> { + self.report_forms.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) + } + + /// Answers a policy decision the runtime is holding for a task. + /// + /// A host calls this when a client answers a pending decision. The + /// answer names *yes* or *no*; it never names the authorisation — the + /// classes that are permitted are computed by the policy kernel on the + /// executor's side, which re-runs its own authorisation path with an + /// override bounded by what it demanded. + /// + /// Returns `Err(RuntimeError::NoPendingApproval)` when nothing is + /// pending: the task never asked, the decision was already answered, the + /// holder was cancelled, or the surface never held a decision at all. + pub fn resolve_approval( + &self, + session_id: SessionId, + task_id: TaskId, + approved: bool, + reason: Option, + ) -> Result<(), RuntimeError> { + self.approvals.resolve( + session_id, + task_id, + crate::approval::ApprovalAnswer::from_parts(approved, reason), + ) + } + + /// The policy decision the runtime is holding for a task, if any. + /// + /// A host uses this to tell a client what it is being asked to answer. + pub fn pending_approval( + &self, + session_id: SessionId, + task_id: TaskId, + ) -> Option { + self.approvals.pending(session_id, 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 + /// published list can never claim more than the executor can execute. + pub fn supported_task_kinds(&self) -> Vec { + self.supported_task_kinds.clone() + } + + /// The task kinds this runtime **enforces** at admission. + /// + /// This is the runtime's configured capability set — the same set every + /// session carries, and therefore the set a submission is admitted + /// against. It is distinct from [`Self::supported_task_kinds`], which is + /// the executor's *declaration*: a host publishes the declaration and + /// enforces the configured set, and the two are made the same object at + /// construction so that a published capability is never refused as an + /// unsupported kind. + /// + /// The set is captured at construction, because the runtime's + /// configuration never changes after it. A host therefore reads it + /// synchronously, with no lock and no await point. + pub fn enforced_task_kinds(&self) -> Vec { + self.enforced_task_kinds.clone() + } + /// Create a new session bound to the given execution surface. /// /// The surface establishes the trust boundary for this session: @@ -291,6 +506,7 @@ impl Runtime { session_id, surface: session.execution_surface(), scope: session.scope().cloned(), + approval: self.approvals.clone(), } }; @@ -659,8 +875,12 @@ impl Runtime { snapshot: SessionSnapshot, ) -> Result { let session_id = snapshot.session_id; - let session = RuntimeSession::hydrate_from_snapshot(snapshot); let mut state = self.state.lock().await; + // A recovered session enforces the runtime's *configured* capability + // set, so it admits exactly what a fresh session admits. The + // snapshot's persisted `capabilities` field is not authoritative. + let capabilities = state.config.capabilities.clone(); + let session = RuntimeSession::hydrate_from_snapshot(snapshot, capabilities); state.sessions.insert(session_id, session); emit_event(&state.event_tx, RuntimeEvent::SessionCreated { session_id }); Ok(session_id) @@ -682,6 +902,124 @@ mod tests { use crate::request::{PortScanParams, RuntimeSurface, TaskKind}; use std::time::Duration; + /// An executor that declares an exact set of task kinds. + struct DeclaringExecutor { + declared: Vec, + } + + impl RuntimeTaskExecutor for DeclaringExecutor { + fn supported_task_kinds(&self) -> Vec { + self.declared.clone() + } + + fn execute( + &self, + _task_id: TaskId, + _request: RunRequest, + _context: RuntimeExecutionContext, + _sink: RuntimeEventSink, + _cancel: CancellationToken, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'static, + >, + > { + Box::pin(async { Err(RuntimeError::UnsupportedTaskKind) }) + } + } + + /// The default declaration is the canonical list, so an executor that + /// says nothing declares the same capability set the runtime enforces. + /// An executor that rejects everything must declare the empty set + /// explicitly instead. + #[test] + fn the_default_declaration_is_the_canonical_set() { + struct DefaultExecutor; + impl RuntimeTaskExecutor for DefaultExecutor { + fn execute( + &self, + _task_id: TaskId, + _request: RunRequest, + _context: RuntimeExecutionContext, + _sink: RuntimeEventSink, + _cancel: CancellationToken, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'static, + >, + > { + Box::pin(async { Err(RuntimeError::UnsupportedTaskKind) }) + } + } + + let declared = DefaultExecutor.supported_task_kinds(); + assert_eq!( + declared.len(), + RuntimeCapabilities::canonical().task_kinds.len() + ); + assert!(!declared.is_empty()); + } + + /// The default coverage declaration is `None`, which means **unknown**: + /// an executor that says nothing about report forms is not saying that + /// no operation has a report form. + #[test] + fn the_default_executor_publishes_no_coverage() { + struct DefaultExecutor; + impl RuntimeTaskExecutor for DefaultExecutor { + fn execute( + &self, + _task_id: TaskId, + _request: RunRequest, + _context: RuntimeExecutionContext, + _sink: RuntimeEventSink, + _cancel: CancellationToken, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'static, + >, + > { + Box::pin(async { Err(RuntimeError::UnsupportedTaskKind) }) + } + } + + assert_eq!(DefaultExecutor.report_forms(), None); + } + + /// The runtime reports the executor's declaration, so a host can derive + /// its published capability list from it. + #[test] + fn the_runtime_reports_the_executors_declaration() { + let runtime = Runtime::new( + RuntimeConfig::default(), + DeclaringExecutor { + declared: vec![TaskCapability::new("port-scan", "Port scanning")], + }, + ); + let declared = runtime.supported_task_kinds(); + assert_eq!(declared.len(), 1); + assert_eq!(declared[0].name, "port-scan"); + } + + /// A rejecting executor declares the empty set, so a host built on it + /// cannot advertise a capability it cannot execute. + #[test] + fn a_rejecting_executor_declares_the_empty_set() { + let runtime = Runtime::new( + RuntimeConfig::default(), + DeclaringExecutor { + declared: Vec::new(), + }, + ); + assert!(runtime.supported_task_kinds().is_empty()); + } + /// A test executor that immediately completes with a text outcome. struct ImmediateExecutor; @@ -1450,13 +1788,22 @@ mod tests { ); } + /// A runtime whose configured capability set does not cover a kind + /// refuses that kind at admission. The canonical set covers everything, + /// so the rejection is exercised with an explicit narrow set. #[tokio::test] async fn submit_rejects_unsupported_task_kind() { - use crate::capabilities::RuntimeCapabilities; + use crate::capabilities::{RuntimeCapabilities, TaskCapability}; use crate::request::StressTestParams; let config = RuntimeConfig { - capabilities: RuntimeCapabilities::daemon_conservative(), + capabilities: RuntimeCapabilities { + task_kinds: vec![TaskCapability::new("port-scan", "Port scanning")], + transports: vec!["in-process".into()], + supports_cancellation: true, + supports_multiple_sessions: true, + supports_multiple_active_tasks: false, + }, ..Default::default() }; let runtime = Runtime::new(config, ImmediateExecutor); @@ -1614,12 +1961,26 @@ mod tests { assert_eq!(task.last_error.as_deref(), Some("session closed")); } + /// A runtime configured with a capability set narrower than the canonical + /// one still refuses the kinds outside it. The canonical list is the + /// *default*, not the only option — the admission check reads the + /// configured set. #[tokio::test] - async fn conservative_capabilities_reject_hazardous_task_kinds() { - use crate::capabilities::RuntimeCapabilities; - + async fn a_narrow_capability_set_rejects_the_kinds_outside_it() { + use crate::capabilities::{RuntimeCapabilities, TaskCapability}; + + let narrow = RuntimeCapabilities { + task_kinds: vec![ + TaskCapability::new("port-scan", "Port scanning"), + TaskCapability::new("load-test", "HTTP load testing"), + ], + transports: vec!["in-process".into()], + supports_cancellation: true, + supports_multiple_sessions: true, + supports_multiple_active_tasks: false, + }; let config = RuntimeConfig { - capabilities: RuntimeCapabilities::daemon_conservative(), + capabilities: narrow, ..Default::default() }; let runtime = Runtime::new(config, ImmediateExecutor); @@ -1680,4 +2041,70 @@ mod tests { ); } } + + /// The canonical capability set admits the hazard families. Admitting is + /// not permitting: the runtime's admission check reads capability *names*, + /// while the enforcement layer — which runs later, inside the executor — + /// reads the operation's risk, the operator's execution policy, the + /// loaded scope, and the enabled features. A hazard family that reaches + /// the executor is refused there with the risk-policy denial, not here + /// with `UnsupportedTaskKind`. + #[tokio::test] + async fn the_canonical_capability_set_admits_the_hazard_families() { + let runtime = Runtime::new(RuntimeConfig::default(), ImmediateExecutor); + let session_id = runtime + .create_session(SessionOptions::default(), RuntimeSurface::TuiManual) + .await + .unwrap(); + + let kinds = vec![ + TaskKind::Resume(crate::request::ResumeParams { + session_path: "/tmp/does-not-exist.eggsec".into(), + }), + TaskKind::StressTest(crate::request::StressTestParams { + target: "10.0.0.1".into(), + flood_type: "syn".into(), + duration_secs: None, + threads: None, + rate_pps: None, + }), + TaskKind::WirelessActive(crate::request::WirelessActiveParams { + interface: None, + target_bssid: None, + ..Default::default() + }), + TaskKind::DbPentest(crate::request::DbPentestParams { + db_type: "postgres".into(), + target: "10.0.0.1".into(), + port: None, + ..Default::default() + }), + TaskKind::Intercept(crate::request::InterceptParams { + listen_port: None, + target: None, + ..Default::default() + }), + TaskKind::C2(crate::request::C2Params { + profile: None, + target: None, + ..Default::default() + }), + ]; + + for kind in kinds { + let name = kind.capability_name(); + let req = RunRequest { + task_kind: kind, + requested_by: None, + surface: RuntimeSurface::TuiManual, + labels: vec![], + }; + let result = runtime.submit(session_id, req).await; + assert!( + !matches!(result, Err(RuntimeError::UnsupportedTaskKind)), + "{name} must be admitted by the canonical capability set, got: {:?}", + result + ); + } + } } diff --git a/crates/eggsec-runtime/src/runtime_config.rs b/crates/eggsec-runtime/src/runtime_config.rs index 730d6c2eb..205c71d23 100644 --- a/crates/eggsec-runtime/src/runtime_config.rs +++ b/crates/eggsec-runtime/src/runtime_config.rs @@ -29,7 +29,7 @@ impl Default for RuntimeConfig { default_task_timeout: Some(Duration::from_secs(300)), max_active_tasks_per_session: 1, event_channel_capacity: 256, - capabilities: crate::capabilities::RuntimeCapabilities::full_lab(), + capabilities: crate::capabilities::RuntimeCapabilities::canonical(), } } } diff --git a/crates/eggsec-runtime/src/runtime_sink.rs b/crates/eggsec-runtime/src/runtime_sink.rs index 25ad341cc..3ecd210d1 100644 --- a/crates/eggsec-runtime/src/runtime_sink.rs +++ b/crates/eggsec-runtime/src/runtime_sink.rs @@ -15,7 +15,7 @@ use tokio::sync::broadcast; -use crate::event::{RuntimeErrorInfo, RuntimeEvent, TaskOutcome, TaskProgress}; +use crate::event::{PolicyPrompt, RuntimeErrorInfo, RuntimeEvent, TaskOutcome, TaskProgress}; use crate::ids::{SessionId, TaskId}; /// Emit a runtime event best-effort. Logs at trace level if no subscribers @@ -172,6 +172,25 @@ impl RuntimeEventSink { }, ); } + + /// Announce that the task is waiting for an operator's policy decision. + /// + /// The decision is already registered when this is called, so a client + /// that answers the instant it sees the prompt finds the pending + /// decision rather than racing it. + /// + /// The task is the sink's own: a caller cannot announce a prompt for + /// some other task. + pub fn policy_decision_required(&self, prompt: PolicyPrompt) { + emit_event_critical( + &self.event_tx, + RuntimeEvent::PolicyDecisionRequired { + session_id: self.session_id, + task_id: Some(self.task_id), + prompt, + }, + ); + } } #[cfg(test)] 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-runtime/src/session.rs b/crates/eggsec-runtime/src/session.rs index d0efac43f..f16f5a8c1 100644 --- a/crates/eggsec-runtime/src/session.rs +++ b/crates/eggsec-runtime/src/session.rs @@ -39,6 +39,14 @@ pub struct RuntimeExecutionContext { pub surface: RuntimeSurface, /// Scope metadata bound at session creation, if any. pub scope: Option, + /// The runtime's approval registry. + /// + /// An executor that reaches a point where the policy demands an + /// operator's confirmation holds the operation here and waits for an + /// answer. The gate is policy-neutral: it carries a prompt and returns + /// "approved" or "denied", and it knows nothing about what an approval + /// permits. + pub approval: crate::approval::ApprovalGate, } /// Lightweight scope metadata bound to a session. @@ -308,7 +316,18 @@ impl RuntimeSession { /// Reconstructs the metadata and completed task records from a snapshot. /// Active task records are not restorable (they hold runtime handles), /// but completed task snapshots are preserved for history and audit querying. - pub fn hydrate_from_snapshot(snapshot: SessionSnapshot) -> Self { + /// + /// The recovered session's capabilities are **not** taken from the + /// snapshot. The snapshot's own `capabilities` field records what the + /// runtime was configured with when the snapshot was written, and a + /// daemon that restarts with a different configuration would otherwise + /// silently narrow — or widen — the recovered session. The caller passes + /// the runtime's *current* capability set instead, so a recovered session + /// enforces exactly what a fresh session enforces. + pub fn hydrate_from_snapshot( + snapshot: SessionSnapshot, + capabilities: RuntimeCapabilities, + ) -> Self { Self { id: snapshot.session_id, surface: snapshot.surface, @@ -321,7 +340,7 @@ impl RuntimeSession { task_timeout: None, closed: snapshot.closed, closed_at: snapshot.closed_at, - capabilities: RuntimeCapabilities::default(), + capabilities, owner_client_id: snapshot.owner_client_id, } } @@ -562,7 +581,8 @@ mod tests { closed_at: None, owner_client_id: None, }; - let session = RuntimeSession::hydrate_from_snapshot(snapshot.clone()); + let session = + RuntimeSession::hydrate_from_snapshot(snapshot.clone(), RuntimeCapabilities::default()); assert_eq!(session.id, snapshot.session_id); assert_eq!(session.execution_surface(), RuntimeSurface::McpServer); assert!(session.scope().is_some()); @@ -655,7 +675,8 @@ mod tests { closed_at: Some(200), owner_client_id: None, }; - let session = RuntimeSession::hydrate_from_snapshot(snapshot); + let session = + RuntimeSession::hydrate_from_snapshot(snapshot, RuntimeCapabilities::default()); assert!(session.is_closed()); let snap = session.snapshot(); assert!(snap.closed); diff --git a/crates/eggsec-runtime/tests/daemon_endpoint.rs b/crates/eggsec-runtime/tests/daemon_endpoint.rs new file mode 100644 index 000000000..5a397ee27 --- /dev/null +++ b/crates/eggsec-runtime/tests/daemon_endpoint.rs @@ -0,0 +1,62 @@ +//! The canonical daemon endpoint through the crate's **public** surface. +//! +//! The unit tests beside the constant live in +//! `crates/eggsec-runtime/src/daemon_endpoint.rs`; they are the one place +//! that pins the constant's value and the environment variable's name. These +//! tests assert the same precedence rule through the re-exports the other +//! surfaces depend on, so that a re-export cannot rot silently. + +use eggsec_runtime::{ + daemon_socket_path_from_env, resolve_daemon_socket_path, DEFAULT_DAEMON_SOCKET_PATH, +}; + +#[test] +fn an_absent_variable_resolves_to_the_built_in_default() { + assert_eq!(resolve_daemon_socket_path(None), DEFAULT_DAEMON_SOCKET_PATH); +} + +#[test] +fn an_empty_value_resolves_to_the_built_in_default() { + assert_eq!( + resolve_daemon_socket_path(Some("")), + DEFAULT_DAEMON_SOCKET_PATH + ); +} + +#[test] +fn a_whitespace_only_value_resolves_to_the_built_in_default() { + assert_eq!( + resolve_daemon_socket_path(Some(" \t ")), + DEFAULT_DAEMON_SOCKET_PATH + ); +} + +#[test] +fn an_explicit_value_resolves_verbatim() { + assert_eq!( + resolve_daemon_socket_path(Some("/run/user/1000/eggsec.sock")), + "/run/user/1000/eggsec.sock" + ); +} + +#[test] +fn an_explicit_value_is_trimmed() { + assert_eq!( + resolve_daemon_socket_path(Some(" /run/user/1000/eggsec.sock ")), + "/run/user/1000/eggsec.sock" + ); +} + +#[test] +fn the_environment_reader_agrees_with_the_resolver() { + // The reader applies the resolver to the process environment. The test + // process does not set the variable, so the two must agree on the + // built-in default; the environment-dependent paths are covered by the + // daemon's subprocess test. + if std::env::var_os(eggsec_runtime::DAEMON_SOCKET_ENV_VAR).is_none() { + assert_eq!( + daemon_socket_path_from_env(), + DEFAULT_DAEMON_SOCKET_PATH.to_owned() + ); + } +} diff --git a/crates/eggsec-runtime/tests/in_process_client.rs b/crates/eggsec-runtime/tests/in_process_client.rs index fc4896082..961684609 100644 --- a/crates/eggsec-runtime/tests/in_process_client.rs +++ b/crates/eggsec-runtime/tests/in_process_client.rs @@ -317,11 +317,9 @@ async fn submit_task_and_observe_result_envelope() { let mut outcome = None; tokio::time::timeout(Duration::from_secs(2), async { loop { - if let Some(event) = rx.recv().await { - if let RuntimeEvent::TaskCompleted { outcome: o, .. } = event { - outcome = Some(o); - break; - } + if let Some(RuntimeEvent::TaskCompleted { outcome: o, .. }) = rx.recv().await { + outcome = Some(o); + break; } } }) @@ -372,11 +370,9 @@ async fn cancel_task_produces_cancelled_event() { let mut cancelled = false; tokio::time::timeout(Duration::from_secs(1), async { loop { - if let Some(event) = rx.recv().await { - if let RuntimeEvent::TaskCancelled { .. } = event { - cancelled = true; - break; - } + if let Some(RuntimeEvent::TaskCancelled { .. }) = rx.recv().await { + cancelled = true; + break; } } }) @@ -431,11 +427,9 @@ async fn failed_task_reports_error() { let mut error_message = None; tokio::time::timeout(Duration::from_secs(2), async { loop { - if let Some(event) = rx.recv().await { - if let RuntimeEvent::TaskFailed { error, .. } = event { - error_message = Some(error.message); - break; - } + if let Some(RuntimeEvent::TaskFailed { error, .. }) = rx.recv().await { + error_message = Some(error.message); + break; } } }) @@ -723,12 +717,17 @@ async fn capabilities_reflect_current_build() { // Cancellation supported assert!(caps.supports_cancellation); - // Default (daemon_conservative) includes safe task kinds + // The default is the canonical set: every capability name the task-kind + // set defines, `resume` included. assert!(!caps.task_kinds.is_empty()); - // Full lab has all 29 task kinds - let full = eggsec_runtime::RuntimeCapabilities::full_lab(); - assert_eq!(full.task_kinds.len(), 29); + // The canonical list has one entry per task kind. + let canonical = eggsec_runtime::RuntimeCapabilities::canonical(); + assert_eq!( + canonical.task_kinds.len(), + eggsec_runtime::request::TaskKind::all_variants().len() + ); + assert!(canonical.task_kinds.iter().any(|c| c.name == "resume")); } #[tokio::test] diff --git a/crates/eggsec-tui/Cargo.toml b/crates/eggsec-tui/Cargo.toml index df90f0a14..ab60686c9 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/enforcement_facade.rs b/crates/eggsec-tui/src/app/enforcement_facade.rs index 56a03928d..0e1a2e113 100644 --- a/crates/eggsec-tui/src/app/enforcement_facade.rs +++ b/crates/eggsec-tui/src/app/enforcement_facade.rs @@ -229,34 +229,13 @@ impl EnforcementFacade { ), EnforcementError, > { - let mut mo = ManualOverride::default(); - for c in required_classes { - match c { - ConfirmationClass::OutOfScope | ConfirmationClass::TargetExpansion => { - mo.allow_out_of_scope = true; - } - ConfirmationClass::ExplicitExclusion => { - mo.allow_explicit_exclusion = true; - } - ConfirmationClass::HighRisk => { - mo.allow_high_risk = true; - } - ConfirmationClass::NonBaselineCapability => { - mo.allow_nonbaseline_capability = true; - } - ConfirmationClass::PrivateResolution => { - mo.allow_private_resolution = true; - } - ConfirmationClass::CrossHostRedirect => { - mo.allow_cross_host_redirect = true; - } - ConfirmationClass::TrafficInterception => { - mo.allow_web_proxy = true; - } - } - } + // The class→override mapping is the policy kernel's, not a local table: + // `permitting_classes` is the single place a confirmation class is + // mapped onto the override field that permits it. + let mut mo = ManualOverride::permitting_classes(required_classes); mo.reason = reason; - mo.assume_yes = false; // TUI confirm popup never sets broad assume_yes + // `permitting_classes` never sets `assume_yes`: the TUI confirm popup + // grants the classes the kernel demanded, not "yes" to everything. // Manual-override state is an evaluation input: drop any token cached // under the previous override generation before re-evaluating. 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/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-tui/src/runtime_client/daemon.rs b/crates/eggsec-tui/src/runtime_client/daemon.rs deleted file mode 100644 index 6e77e6119..000000000 --- a/crates/eggsec-tui/src/runtime_client/daemon.rs +++ /dev/null @@ -1,402 +0,0 @@ -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; - -use eggsec_runtime::{ - request::RuntimeSurface, session::SessionScope, RunRequest, RuntimeCapabilities, SessionId, - SessionSnapshot, SessionSummary, TaskId, -}; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; -use tokio::net::UnixStream; -use tokio::sync::{oneshot, Mutex}; - -use eggsec_daemon_protocol::protocol::{ClientCommand, ServerMessage}; - -use super::{RuntimeClientFuture, RuntimeEventReceiverHandle, TuiRuntimeClient}; - -/// Shared channel registry for routing RuntimeEvent messages from the reader -/// task to per-subscriber receivers. Each `subscribe_events()` call inserts -/// a sender; the reader iterates all active senders to fan-out events. -type EventChannels = - Arc>>>; - -#[derive(Debug, thiserror::Error)] -pub enum DaemonClientError { - #[error("IO error: {0}")] - Io(#[from] std::io::Error), - #[error("Serialization error: {0}")] - Serialization(#[from] serde_json::Error), - #[error("Protocol error: {0}")] - Protocol(String), - #[error("Connection closed")] - ConnectionClosed, -} - -struct DaemonConnection { - _socket_path: String, - request_counter: AtomicU64, - writer: Mutex, - pending_responses: std::sync::Arc< - std::sync::Mutex>>, - >, - /// Active event subscriber senders. The reader task fans out - /// RuntimeEvent messages to all registered channels. - event_channels: Arc< - tokio::sync::RwLock>>, - >, -} - -/// Runtime client that connects to a local daemon via Unix socket. -#[derive(Clone)] -pub struct DaemonRuntimeClient { - inner: Arc, -} - -impl DaemonRuntimeClient { - /// Connect to a daemon at the given socket path. - pub async fn connect(socket_path: &str) -> Result { - let stream = UnixStream::connect(socket_path).await?; - let (read_half, write_half) = stream.into_split(); - - let pending_responses: std::sync::Arc< - std::sync::Mutex>>, - > = std::sync::Arc::new(std::sync::Mutex::new(rustc_hash::FxHashMap::default())); - - let pending_clone = pending_responses.clone(); - let event_channels: EventChannels = Arc::new(tokio::sync::RwLock::new(Vec::new())); - let channels_clone = event_channels.clone(); - - // Spawn reader task to route responses and events - tokio::spawn(async move { - let mut reader = BufReader::new(read_half).lines(); - loop { - match reader.next_line().await { - Ok(Some(line)) => { - if line.is_empty() { - continue; - } - let msg: ServerMessage = match serde_json::from_str(&line) { - Ok(msg) => msg, - Err(e) => { - tracing::warn!("Failed to parse daemon message: {}", e); - continue; - } - }; - match msg { - ServerMessage::RuntimeEvent { event, .. } => { - // Fan-out RuntimeEvent to all active subscriber channels. - let channels = channels_clone.read().await; - let mut stale = Vec::new(); - for (i, tx) in channels.iter().enumerate() { - if tx.send(event.clone()).is_err() { - stale.push(i); - } - } - drop(channels); - // Clean up disconnected senders (receiver dropped). - if !stale.is_empty() { - let mut channels = channels_clone.write().await; - // Remove in reverse order to preserve indices. - for &i in stale.iter().rev() { - channels.remove(i); - } - } - } - other => { - let request_id = match &other { - ServerMessage::Ok { request_id } - | ServerMessage::Error { request_id, .. } - | ServerMessage::SessionCreated { request_id, .. } - | ServerMessage::Sessions { request_id, .. } - | ServerMessage::Snapshot { request_id, .. } - | ServerMessage::TaskSubmitted { request_id, .. } - | ServerMessage::Capabilities { request_id, .. } - | ServerMessage::Health { request_id, .. } - | ServerMessage::ClientDeclared { request_id, .. } - | ServerMessage::SessionClosed { request_id, .. } - | ServerMessage::PersistedSessions { request_id, .. } - | ServerMessage::PersistedSnapshot { request_id, .. } - | ServerMessage::TaskResult { request_id, .. } => { - request_id.clone() - } - ServerMessage::RuntimeEvent { .. } => { - tracing::warn!( - "Unexpected runtime event in pending response channel" - ); - continue; - } - }; - let mut pending = pending_clone.lock().unwrap_or_else(|poisoned| { - tracing::warn!("TUI pending request registry mutex was poisoned; recovering state"); - poisoned.into_inner() - }); - if let Some(sender) = pending.remove(&request_id) { - if let Err(error) = sender.send(other) { - tracing::debug!( - ?error, - "Pending daemon response receiver dropped" - ); - } - } - } - } - } - Ok(None) => { - tracing::info!("Daemon connection closed"); - break; - } - Err(e) => { - tracing::warn!("Daemon read error: {}", e); - break; - } - } - } - }); - - let client = Self { - inner: Arc::new(DaemonConnection { - _socket_path: socket_path.to_string(), - request_counter: AtomicU64::new(0), - writer: Mutex::new(write_half), - pending_responses, - event_channels, - }), - }; - - // 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()), - ) - .await - { - tracing::warn!("Daemon rejected TUI client declaration: {}", e); - } - - Ok(client) - } - - /// Declare this client's kind to the daemon. - pub async fn declare_client( - &self, - kind: eggsec_daemon_protocol::client_registry::ClientKind, - label: Option, - ) -> Result { - let cmd = ClientCommand::DeclareClient { - request_id: self.next_request_id(), - kind, - label, - }; - self.send_command(cmd).await - } - - fn next_request_id(&self) -> String { - let id = self.inner.request_counter.fetch_add(1, Ordering::Relaxed); - format!("tui-{}", id) - } - - async fn send_command(&self, cmd: ClientCommand) -> Result { - let request_id = match &cmd { - ClientCommand::Health { request_id } - | ClientCommand::Capabilities { request_id } - | ClientCommand::CreateSession { request_id, .. } - | ClientCommand::ListSessions { request_id } - | ClientCommand::GetSnapshot { request_id, .. } - | ClientCommand::GetTaskResult { request_id, .. } - | ClientCommand::SubmitTask { request_id, .. } - | ClientCommand::CancelTask { request_id, .. } - | ClientCommand::CancelActive { request_id, .. } - | ClientCommand::DeclareClient { request_id, .. } - | ClientCommand::CloseSession { request_id, .. } - | ClientCommand::Subscribe { request_id, .. } - | ClientCommand::ApprovePolicy { request_id, .. } - | ClientCommand::ListPersistedSessions { request_id } - | ClientCommand::GetPersistedSnapshot { request_id, .. } => request_id.clone(), - }; - - let (tx, rx) = oneshot::channel(); - { - let mut pending = self - .inner - .pending_responses - .lock() - .unwrap_or_else(|poisoned| { - tracing::warn!("TUI pending_responses mutex was poisoned; recovering state"); - poisoned.into_inner() - }); - pending.insert(request_id, tx); - } - - let json = serde_json::to_string(&cmd)?; - { - let mut writer = self.inner.writer.lock().await; - writer.write_all(json.as_bytes()).await?; - writer.write_all(b"\n").await?; - writer.flush().await?; - } - - tokio::time::timeout(std::time::Duration::from_secs(30), rx) - .await - .map_err(|_| DaemonClientError::Protocol("response timeout".into()))? - .map_err(|_| DaemonClientError::ConnectionClosed) - } - - /// Subscribe to runtime events for a session. - pub async fn subscribe_events( - &self, - session_id: SessionId, - ) -> Result { - let cmd = ClientCommand::Subscribe { - request_id: self.next_request_id(), - session_id, - }; - - let json = serde_json::to_string(&cmd)?; - { - let mut writer = self.inner.writer.lock().await; - writer.write_all(json.as_bytes()).await?; - writer.write_all(b"\n").await?; - writer.flush().await?; - } - - // Register a channel for this subscription. The reader task will - // fan-out RuntimeEvent messages to all registered channels. - let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - { - let mut channels = self.inner.event_channels.write().await; - channels.push(tx); - } - tracing::info!("Subscribed to daemon events for session {}", session_id); - Ok(RuntimeEventReceiverHandle::new(rx)) - } -} - -impl TuiRuntimeClient for DaemonRuntimeClient { - fn capabilities(&self) -> RuntimeClientFuture { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::Capabilities { - request_id: client.next_request_id(), - }; - match client.send_command(cmd).await { - Ok(ServerMessage::Capabilities { capabilities, .. }) => Ok(capabilities.runtime), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn create_session( - &self, - surface: RuntimeSurface, - scope: Option, - labels: Vec, - ) -> RuntimeClientFuture { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::CreateSession { - request_id: client.next_request_id(), - surface, - scope, - labels, - }; - match client.send_command(cmd).await { - Ok(ServerMessage::SessionCreated { session_id, .. }) => Ok(session_id), - Ok(ServerMessage::Error { message, .. }) => Err(message), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn list_sessions(&self) -> RuntimeClientFuture> { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::ListSessions { - request_id: client.next_request_id(), - }; - match client.send_command(cmd).await { - Ok(ServerMessage::Sessions { sessions, .. }) => Ok(sessions), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn snapshot(&self, session_id: SessionId) -> RuntimeClientFuture { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::GetSnapshot { - request_id: client.next_request_id(), - session_id, - }; - match client.send_command(cmd).await { - Ok(ServerMessage::Snapshot { snapshot, .. }) => Ok(snapshot), - Ok(ServerMessage::Error { message, .. }) => Err(message), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn submit(&self, session_id: SessionId, request: RunRequest) -> RuntimeClientFuture { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::SubmitTask { - request_id: client.next_request_id(), - session_id, - request, - }; - match client.send_command(cmd).await { - Ok(ServerMessage::TaskSubmitted { task_id, .. }) => Ok(task_id), - Ok(ServerMessage::Error { message, .. }) => Err(message), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn cancel(&self, session_id: SessionId, task_id: TaskId) -> RuntimeClientFuture<()> { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::CancelTask { - request_id: client.next_request_id(), - session_id, - task_id, - }; - match client.send_command(cmd).await { - Ok(ServerMessage::Ok { .. }) => Ok(()), - Ok(ServerMessage::Error { message, .. }) => Err(message), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn cancel_active(&self, session_id: SessionId) -> RuntimeClientFuture<()> { - let client = self.clone(); - Box::pin(async move { - let cmd = ClientCommand::CancelActive { - request_id: client.next_request_id(), - session_id, - }; - match client.send_command(cmd).await { - Ok(ServerMessage::Ok { .. }) => Ok(()), - Ok(ServerMessage::Error { message, .. }) => Err(message), - Ok(msg) => Err(format!("unexpected response: {:?}", msg)), - Err(e) => Err(e.to_string()), - } - }) - } - - fn subscribe(&self, session_id: SessionId) -> RuntimeClientFuture { - let client = self.clone(); - Box::pin(async move { - client - .subscribe_events(session_id) - .await - .map_err(|e| e.to_string()) - }) - } -} 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-tui/src/tabs/intercept/mod.rs b/crates/eggsec-tui/src/tabs/intercept/mod.rs index f14b75248..719077f4a 100644 --- a/crates/eggsec-tui/src/tabs/intercept/mod.rs +++ b/crates/eggsec-tui/src/tabs/intercept/mod.rs @@ -50,6 +50,12 @@ macro_rules! inner { /// the real pane height on every render. const DEFAULT_FLOW_VIEWPORT: usize = 20; +/// Smallest interval a recorded session may claim. +/// +/// The wall clock cannot resolve a session shorter than one tick, so a +/// session that ran must never record a zero-length interval. +const MIN_SESSION_INTERVAL_MS: i64 = 1; + pub struct InterceptTab { pub flows: Vec, pub selected_flow: Option, @@ -115,6 +121,13 @@ pub struct InterceptTab { /// The flow pane is laid out by `render_flow_list`, so this is the only way /// the key handlers can learn the real viewport height they must scroll by. flow_viewport_height: Cell, + /// Monotonic reading taken when the current session started. + /// + /// The wall clock ticks far coarser than the lifetime of a short + /// session, so the session's start and end stamps can land on the same + /// tick and render as the same RFC 3339 string. This reading keeps the + /// interval the wall clock loses. + session_started_at: Option, } impl InterceptTab { @@ -169,6 +182,7 @@ impl InterceptTab { selected_grpc_session: 0, stream_mux_scroll: 0, flow_viewport_height: Cell::new(DEFAULT_FLOW_VIEWPORT), + session_started_at: None, } } @@ -665,15 +679,57 @@ impl InterceptTab { self.selected_flow = None; self.table_state.select(None); self.session = Some(InterceptSession::new(&self.listen_addr, self.dry_run)); + self.session_started_at = Some(std::time::Instant::now()); } pub fn stop_session(&mut self) { + let elapsed = self + .session_started_at + .take() + .map(|started| started.elapsed()); if let Some(ref mut session) = self.session { session.finalize(); + // `finalize` stamps the end from the wall clock, whose + // resolution is coarser than a short session's lifetime: the + // end stamp can land on the same tick as the start stamp and + // render as the same RFC 3339 string, and a session that ran + // would report that it started and ended at the same instant. + // Keep the recorded end strictly after the recorded start. + Self::ensure_end_after_start(session, elapsed); } self.state = AppState::Idle; } + /// Guarantee that a finalized session records an end stamp strictly + /// after its start stamp. + /// + /// `InterceptSession::new` pre-fills `ended_at` with the start stamp and + /// `InterceptSession::finalize` re-stamps it from the wall clock. That + /// clock ticks far coarser than the lifetime of a short session, so a + /// session that starts and stops inside one tick records the same instant + /// twice and reports a zero-length interval even though it ran. When the + /// wall clock cannot resolve the interval, fall back to the monotonic + /// measurement of how long the session actually ran. + fn ensure_end_after_start( + session: &mut InterceptSession, + elapsed: Option, + ) { + let (Ok(start), Ok(end)) = ( + chrono::DateTime::parse_from_rfc3339(&session.started_at), + chrono::DateTime::parse_from_rfc3339(&session.ended_at), + ) else { + return; + }; + if end > start { + return; + } + let measured = elapsed + .and_then(|elapsed| chrono::Duration::from_std(elapsed).ok()) + .unwrap_or_else(chrono::Duration::zero); + let interval = measured.max(chrono::Duration::milliseconds(MIN_SESSION_INTERVAL_MS)); + session.ended_at = (start + interval).to_rfc3339(); + } + fn selected_flow_data(&self) -> Option<&ProxyFlow> { self.selected_flow.and_then(|i| self.flows.get(i)) } @@ -799,6 +855,14 @@ impl Default for InterceptTab { } impl TabState for InterceptTab { + /// Test-only hook: drive the tab into a lifecycle state without a full + /// dispatch, so the mid-run navigation guard can assert the "navigation + /// must not move focus while a task runs" invariant for this tab too. + #[cfg(test)] + fn set_state(&mut self, state: AppState) { + self.state = state; + } + fn state(&self) -> AppState { self.state.clone() } @@ -838,6 +902,7 @@ impl TabState for InterceptTab { self.selected_http2_session = 0; self.selected_grpc_session = 0; self.stream_mux_scroll = 0; + self.session_started_at = None; self.close_edit_modal(); } @@ -1074,6 +1139,16 @@ impl TabInput for InterceptTab { return; } match c { + // The flow list is this tab's focused control, so the app is in + // insert mode while it is focused and `j`/`k` arrive here as + // characters instead of as global navigation keys. Keep the + // list drivable in both modes. + 'j' if self.focus_area == InterceptFocusArea::FlowList && !self.is_running() => { + self.handle_down() + } + 'k' if self.focus_area == InterceptFocusArea::FlowList && !self.is_running() => { + self.handle_up() + } 'r' if self.detail_pane == DetailPane::Rules => self.toggle_rule_view(), 'p' if !self.is_running() => self.toggle_performance_mode(), '/' if !self.is_running() => { @@ -1221,8 +1296,37 @@ impl TabInput for InterceptTab { } } + /// Focus the flow list, the control this tab opens on. + /// + /// This tab owns no input group: its flow list is the selector the + /// operator drives first, and its selected row is what the focus ring + /// marks. Without this hook the tab entry left *nothing* focused, so + /// the app stayed in Normal mode and every keystroke was eaten by a + /// global shortcut (`r` reset the tab, `p` jumped tabs, digits jumped + /// tabs) instead of reaching the tab. + fn ensure_input_focus(&mut self) { + if self.filter_active || self.is_edit_modal_open() { + // A text surface is open and owns the focus. + return; + } + if self.focus_area != InterceptFocusArea::FlowList { + self.focus_area = InterceptFocusArea::FlowList; + } + } + + /// Report the focused control. + /// + /// The flow list is a focusable control on this tab — the selected row + /// is the focus ring — so it must report as focused: it is what tab entry + /// focuses, and reporting `false` told the app the tab had no live + /// control, which left the tab in Normal mode where its own bindings + /// (`r` rules, `p` perf, `/` filter) and the edit modal's text entry + /// were unreachable. The filter prompt and the edit modal are text + /// fields on top of the flow list and own the focus while they are open. fn is_input_focused(&self) -> bool { - false + self.focus_area == InterceptFocusArea::FlowList + || self.filter_active + || self.is_edit_modal_open() } fn is_at_left_edge(&self) -> bool { diff --git a/crates/eggsec-tui/src/tabs/intercept/tests.rs b/crates/eggsec-tui/src/tabs/intercept/tests.rs index ae3c91a09..d13fcfbe6 100644 --- a/crates/eggsec-tui/src/tabs/intercept/tests.rs +++ b/crates/eggsec-tui/src/tabs/intercept/tests.rs @@ -23,6 +23,26 @@ fn test_intercept_tab_start_stop() { assert!(tab.session.as_ref().unwrap().ended_at != tab.session.as_ref().unwrap().started_at); } +#[test] +fn test_stop_session_keeps_the_end_stamp_after_the_start_stamp() { + // The wall clock ticks far coarser than the lifetime of a short session, + // so the start and end stamps can land on the same tick and render as + // the same RFC 3339 string. `test_intercept_tab_start_stop` only catches + // that when the clock happens to collide, so drive the collision directly + // and assert the production code repairs it. + let mut tab = InterceptTab::new(); + tab.start_session(); + let mut session = tab.session.clone().expect("session"); + session.ended_at = session.started_at.clone(); + + InterceptTab::ensure_end_after_start(&mut session, Some(std::time::Duration::from_micros(250))); + + assert_ne!(session.ended_at, session.started_at); + let started_at = chrono::DateTime::parse_from_rfc3339(&session.started_at).expect("start"); + let ended_at = chrono::DateTime::parse_from_rfc3339(&session.ended_at).expect("end"); + assert!(ended_at > started_at); +} + #[test] fn test_intercept_tab_add_flow() { let mut tab = InterceptTab::new(); diff --git a/crates/eggsec-tui/src/tabs/vuln.rs b/crates/eggsec-tui/src/tabs/vuln.rs index b8e70722f..182230441 100755 --- a/crates/eggsec-tui/src/tabs/vuln.rs +++ b/crates/eggsec-tui/src/tabs/vuln.rs @@ -474,12 +474,12 @@ impl TabRender for VulnTab { } impl TabInput for VulnTab { - fn ensure_input_focus(&mut self) { - if self.focus_area == VulnFocusArea::Inputs { - crate::tabs::core::ensure_group_field_focused(&mut self.core.inputs); - } - } - + // `ensure_input_focus` comes from `tab_input_custom!` below. It was also + // written out by hand here, which is a duplicate definition (E0201) and + // stopped the `vuln-management` feature from compiling at all. The two + // were identical: `core::ensure_first_field_focused(&mut core)` is + // `core::ensure_group_field_focused(&mut core.inputs)`, and `TabCore` + // owns exactly one input group. tab_input_custom!( VulnTab, core: core, diff --git a/crates/eggsec/Cargo.toml b/crates/eggsec/Cargo.toml index 7bd266c70..fc5638068 100644 --- a/crates/eggsec/Cargo.toml +++ b/crates/eggsec/Cargo.toml @@ -277,6 +277,15 @@ optional = true [dependencies.zip] version = "9" +# Only Stored/Deflated entries are read or written (see crates/eggsec-mobile-lab), +# so the unused compression backends stay out of the graph: zip's default +# `bzip2` feature pulls `libbz2-rs-sys`, whose `bzip2-1.0.6` licence expression +# is not on the `deny.toml` allow list, and adding a licence is a policy +# decision that milestone 015 does not own. `deflate` keeps both +# Stored/Deflated writing and Deflated reading; `time` keeps the archive +# timestamps exactly as they were. +features = ["deflate", "time"] +default-features = false optional = true [dependencies.plist] diff --git a/crates/eggsec/src/cli/mod.rs b/crates/eggsec/src/cli/mod.rs index 3c7d08839..9fc99bba2 100755 --- a/crates/eggsec/src/cli/mod.rs +++ b/crates/eggsec/src/cli/mod.rs @@ -246,8 +246,9 @@ pub struct Cli { long, global = true, value_name = "PATH", - default_value = "/tmp/eggsec-daemon.sock", - help = "Unix socket path for daemon runtime mode" + default_value_t = eggsec_runtime::daemon_socket_path_from_env(), + help = "Unix socket path for daemon runtime mode (default: the daemon's socket \ + environment variable, else the built-in default)" )] pub socket: String, @@ -735,6 +736,62 @@ mod tests { ); } + /// The global `--socket` resolves through the canonical daemon endpoint. + #[test] + fn the_global_socket_default_is_the_canonical_constant() { + let parsed = Cli::try_parse_from(["eggsec", "scan-ports", "127.0.0.1"]) + .expect("the command line must parse"); + assert_eq!( + parsed.socket, + eggsec_runtime::DEFAULT_DAEMON_SOCKET_PATH, + "the global --socket default must be the canonical constant" + ); + } + + /// An explicit `--socket` wins over the default. + #[test] + fn an_explicit_socket_flag_overrides_the_default() { + let parsed = Cli::try_parse_from([ + "eggsec", + "--socket", + "/tmp/x.sock", + "scan-ports", + "127.0.0.1", + ]) + .expect("the command line must parse"); + assert_eq!(parsed.socket, "/tmp/x.sock"); + } + + /// The per-subcommand `--socket` still wins over the global flag. + /// + /// The daemon subcommand exists only with the `daemon-client` feature, + /// so the test runs with the same feature set the CLI binary uses. + #[cfg(feature = "daemon-client")] + #[test] + fn the_per_subcommand_socket_overrides_the_global_flag() { + let parsed = Cli::try_parse_from([ + "eggsec", + "--socket", + "/tmp/global.sock", + "daemon", + "start", + "--socket", + "/tmp/sub.sock", + ]) + .expect("the command line must parse"); + let Some(Commands::Daemon(daemon)) = parsed.command else { + panic!("the daemon subcommand must parse"); + }; + let DaemonSubcommand::Start { socket } = daemon.subcommand else { + panic!("the daemon start subcommand must parse"); + }; + assert_eq!( + socket.as_deref(), + Some("/tmp/sub.sock"), + "the per-subcommand --socket must win over the global flag" + ); + } + /// `eggsec storage` used to hardcode `StorageConfig::default()` in all /// four handlers, so it could only ever reach localhost:5432. Every /// subcommand must accept and actually apply a connection. diff --git a/crates/eggsec/src/config/daemon_profile.rs b/crates/eggsec/src/config/daemon_profile.rs new file mode 100644 index 000000000..72a2fce23 --- /dev/null +++ b/crates/eggsec/src/config/daemon_profile.rs @@ -0,0 +1,561 @@ +//! The daemon service profile — the engine feature set a GUI-serving daemon compiles. +//! +//! A daemon that hosts the desktop GUI must be able to run the operations the +//! GUI can submit, and must not carry the engine's serving surfaces, its +//! security-risk switches, or its lab-only extras. This module owns that +//! decision as **data**, so the daemon's manifest, the operator documentation, +//! and the compiled binary can all be checked against one list. +//! +//! # The inclusion rule +//! +//! An engine feature is included iff +//! +//! 1. a code path reachable from one of the runtime's task kinds is +//! `cfg`-gated on it (this is the [`eggsec_policy::ALL_OPERATION_METADATA`] +//! half — see [`required_profile_features`]), +//! 2. it is the `cli` **host gate** — `cli` gates `commands`, `dispatch` and +//! `runtime_bridge`, which is where `EggsecRuntimeExecutor` lives, so +//! without it the daemon cannot host the executor it is built around, or +//! 3. it is a transitive dependency of an included feature and is declared +//! explicitly here, so the effective set equals the declared set. +//! +//! # The relation to `full` +//! +//! [`crate::config::FULL_MEMBERS`] is a **curated developer/lab aggregate**: +//! it enables capabilities the daemon has no use for (`mobile`, +//! `mobile-dynamic`, `ai-integration`, `container`) and it enables the +//! `rest-api` serving surface, which would give a daemon that already speaks +//! the Unix socket a second, unintended HTTP surface. This profile is a +//! different aggregate with a different purpose, and the two are independent: +//! neither is a subset of the other by construction, and each carries its own +//! exclusion list. +//! +//! # The relation to the policy catalog +//! +//! The required half of the profile is **derived** from +//! [`eggsec_policy::ALL_OPERATION_METADATA`] — the distinct non-empty +//! `required_features` of the catalog — plus the `cli` host gate plus the +//! explicitly-declared transitive members. The derived names are never +//! hand-written, so a new catalog entry that requires a new feature fails the +//! conformance test until the profile is updated. +//! +//! The catalog also covers CLI/TUI-only surfaces the daemon never dispatches; +//! those features are listed in +//! [`CATALOG_FEATURES_OUTSIDE_THE_DAEMON_SCOPE`] with their reason and are +//! declared through the transitive/member list instead. +//! +//! # The build-side / wire-side boundary +//! +//! This module is a **build-side** contract: it describes what the daemon +//! binary was compiled with. The **wire-side** publication of the enabled +//! feature set — the handshake field a client reads to learn what the daemon +//! can do — belongs to the desktop-GUI frontend milestone that owns the +//! protocol's capability negotiation. Nothing here adds a protocol field, and +//! nothing here persists or negotiates the feature set at runtime: a feature +//! that was compiled out cannot be turned on later, which is exactly why the +//! profile is a build recipe and not a runtime setting. +//! +//! The module is compiled **unconditionally** — it is data, not a capability — +//! so the conformance checks also run in the `--no-default-features` build. + +use std::fmt; + +use super::feature_registry::is_known_feature; + +/// The engine features the daemon's `service` profile enables. +/// +/// This list is the single source of truth for the profile: the daemon's +/// `service` cargo feature in `crates/eggsec-daemon/Cargo.toml` must name +/// exactly these features, and the operator documentation's included-features +/// table must name exactly these features. Both are checked mechanically. +pub static DAEMON_SERVICE_PROFILE: &[&str] = &[ + "advanced-hunting", + "c2", + "cli", + "compliance", + "database", + "db-pentest", + "evasion", + "external-integrations", + "finding-workflow", + "headless-browser", + "nse", + "packet-inspection", + "postex", + "stress-testing", + "tool-api", + "vuln-management", + "web-proxy", + "websocket", + "wireless", + "wireless-advanced", +]; + +/// The engine features the daemon's `service` profile excludes. +/// +/// The complement of [`DAEMON_SERVICE_PROFILE`] over the engine's registry. +/// Each exclusion carries a rationale in `docs/DAEMON_FEATURE_PROFILE.md`. +pub static DAEMON_SERVICE_EXCLUDED: &[&str] = &[ + "ai-integration", + "api-schema", + "c2-mcp", + "cloud", + "config-watch", + "container", + "daemon-client", + "db-pentest-mcp", + "db-pentest-mongodb", + "db-pentest-mssql-tiberius", + "db-pentest-redis", + "dynamic-plugins", + "email-notifications", + "full", + "git-secrets", + "grpc-api", + "insecure-tls", + "logging-subscriber", + "mobile", + "mobile-dynamic", + "nse-sandbox", + "nse-ssh2", + "pdf", + "rest-api", + "sbom", + "test-helpers", + "transparent-proxy", + "udp-scan", + "web-proxy-mcp", + "ws-api", +]; + +/// The excluded features whose exclusion is **absolute**. +/// +/// A candidate profile that enables any of these is invalid, not merely +/// discouraged: the serving surfaces would add a second protocol the +/// operator did not ask for, `insecure-tls` bypasses certificate +/// verification, `test-helpers` is a test-only marker, `full` is an +/// aggregate (and would make the profile's own definition circular), and the +/// `*-mcp` markers would expose MCP tools over a daemon that speaks the Unix +/// socket. +pub static DAEMON_SERVICE_FORBIDDEN: &[&str] = &[ + "c2-mcp", + "daemon-client", + "db-pentest-mcp", + "full", + "grpc-api", + "insecure-tls", + "rest-api", + "test-helpers", + "web-proxy-mcp", + "ws-api", +]; + +/// The features the daemon needs that the policy catalog does not name. +/// +/// Each entry is a member the profile enables without a catalog entry +/// requiring it, with the reason it is required. The catalog-derived half of +/// [`required_profile_features`] is computed from the catalog itself; this +/// list is the explicitly-declared remainder. +static DECLARED_MEMBERS: &[(&str, &str)] = &[ + ( + "cli", + "host gate: `cli` gates commands/dispatch/runtime_bridge, where EggsecRuntimeExecutor lives", + ), + ( + "tool-api", + "transitive: `nse` = [\"tool-api\", ...]; declared so the effective set equals the declared set", + ), + ( + "postex", + "transitive: `c2` = [\"postex\", \"evasion\"]; declared so the effective set equals the declared set", + ), + ( + "evasion", + "transitive: `c2` = [\"postex\", \"evasion\"]; declared so the effective set equals the declared set", + ), + ( + "websocket", + "behaviour gate: the Fuzz task kind only runs live WebSocket tests when it is compiled in", + ), +]; + +/// The catalog features the daemon does not take from the catalog half. +/// +/// The policy catalog covers CLI/TUI-only operations the daemon never +/// dispatches. Their features are declared through +/// [`DECLARED_MEMBERS`] (or left out entirely) instead of being read out of +/// the catalog, so the catalog-derived half of [`required_profile_features`] +/// is exactly the set the daemon's task kinds can reach. +static CATALOG_FEATURES_OUTSIDE_THE_DAEMON_SCOPE: &[(&str, &str)] = &[ + ( + "mobile", + "no mobile task kind in the runtime's request surface; excluding it keeps `zip` out of the shipped closure", + ), + ( + "mobile-dynamic", + "no mobile task kind in the runtime's request surface; its live path needs `adb` and a lab device", + ), + ( + "evasion", + "reached through the `c2` domain rather than as an operation of its own; declared as a transitive member", + ), + ( + "postex", + "reached through the `c2` domain rather than as an operation of its own; declared as a transitive member", + ), +]; + +/// The catalog-derived half of the required set. +/// +/// Computed from the policy catalog — never hand-written — so a new catalog +/// entry that requires a feature the daemon cannot reach changes this set and +/// fails the conformance check until the profile is updated. +fn catalog_required_features() -> Vec<&'static str> { + let mut names: Vec<&'static str> = Vec::new(); + for metadata in eggsec_policy::ALL_OPERATION_METADATA { + for feature in metadata.required_features.iter().copied() { + let out_of_scope = CATALOG_FEATURES_OUTSIDE_THE_DAEMON_SCOPE + .iter() + .any(|(name, _)| *name == feature); + if out_of_scope { + continue; + } + names.push(feature); + } + } + names.sort_unstable(); + names.dedup(); + names +} + +/// The engine features the daemon's profile must enable. +/// +/// The union of the catalog-derived half (the distinct non-empty +/// `required_features` of [`eggsec_policy::ALL_OPERATION_METADATA`], minus +/// the catalog features the daemon does not dispatch) with the explicitly +/// declared members. +/// +/// The result is sorted and deduplicated so the function is deterministic. +pub fn required_profile_features() -> Vec<&'static str> { + let mut names = catalog_required_features(); + names.extend(DECLARED_MEMBERS.iter().map(|(name, _)| *name)); + names.sort_unstable(); + names.dedup(); + names +} + +/// A single way a candidate profile fails the conformance check. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProfileViolation { + /// The name is not an engine feature at all. + UnknownFeature { + /// The offending name. + feature: String, + }, + /// The name is an engine feature the daemon profile must never enable. + ForbiddenFeature { + /// The offending name. + feature: String, + /// Why the feature is absolutely excluded. + reason: &'static str, + }, + /// A feature the profile requires is absent from the candidate list. + MissingRequiredFeature { + /// The missing feature. + feature: &'static str, + }, + /// The candidate list names the same feature more than once. + DuplicateFeature { + /// The repeated name. + feature: String, + }, + /// The candidate list enables a feature that is neither required by the + /// profile nor one of the explicitly declared members. + UnrequiredFeature { + /// The offending name. + feature: String, + }, +} + +impl fmt::Display for ProfileViolation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnknownFeature { feature } => { + write!(f, "unknown engine feature '{feature}'") + } + Self::ForbiddenFeature { feature, reason } => { + write!(f, "forbidden engine feature '{feature}': {reason}") + } + Self::MissingRequiredFeature { feature } => { + write!(f, "missing required engine feature '{feature}'") + } + Self::DuplicateFeature { feature } => { + write!(f, "duplicate engine feature '{feature}'") + } + Self::UnrequiredFeature { feature } => { + write!( + f, + "engine feature '{feature}' is neither required by the profile nor a declared member" + ) + } + } + } +} + +/// Check a candidate profile against the daemon's feature contract. +/// +/// The function is pure and deterministic: it reads only the registry, the +/// profile constants and the policy catalog, and it never touches the +/// filesystem, the network, or any mutable state. It reports every way the +/// candidate list fails: +/// +/// - an unknown name (not in the engine's registry), +/// - a forbidden name, +/// - a missing required name, +/// - a duplicate entry, +/// - a name that is neither required nor a declared member. +/// +/// The violations are returned in a stable order: one entry per offending +/// candidate in candidate order, followed by the missing required features in +/// sorted order. +pub fn profile_violations(profile: &[&str]) -> Vec { + let required = required_profile_features(); + let mut violations = Vec::new(); + let mut seen: Vec<&str> = Vec::new(); + + for feature in profile { + if seen.contains(feature) { + violations.push(ProfileViolation::DuplicateFeature { + feature: (*feature).to_string(), + }); + continue; + } + seen.push(feature); + + if !is_known_feature(feature) { + violations.push(ProfileViolation::UnknownFeature { + feature: (*feature).to_string(), + }); + continue; + } + + if DAEMON_SERVICE_FORBIDDEN.contains(feature) { + violations.push(ProfileViolation::ForbiddenFeature { + feature: (*feature).to_string(), + reason: "the daemon profile must never enable this feature", + }); + continue; + } + + if !required.contains(feature) { + violations.push(ProfileViolation::UnrequiredFeature { + feature: (*feature).to_string(), + }); + } + } + + for feature in &required { + if !profile.contains(feature) { + violations.push(ProfileViolation::MissingRequiredFeature { feature }); + } + } + + violations +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::feature_registry::ALL_FEATURES; + + #[test] + fn the_documented_profile_has_no_violations() { + assert_eq!( + profile_violations(DAEMON_SERVICE_PROFILE), + Vec::::new() + ); + } + + #[test] + fn the_documented_profile_excludes_nothing_it_claims_to_exclude() { + for feature in DAEMON_SERVICE_PROFILE { + assert!( + !DAEMON_SERVICE_EXCLUDED.contains(feature), + "feature '{feature}' is both included and excluded by the daemon profile" + ); + } + + let registry: Vec<&str> = ALL_FEATURES.iter().map(|entry| entry.name).collect(); + let mut classified: Vec<&str> = DAEMON_SERVICE_PROFILE + .iter() + .chain(DAEMON_SERVICE_EXCLUDED.iter()) + .copied() + .collect(); + classified.sort_unstable(); + classified.dedup(); + + let mut expected = registry.clone(); + expected.sort_unstable(); + assert_eq!( + classified, expected, + "the included and excluded sets must partition the engine's registry" + ); + } + + #[test] + fn the_required_set_is_derived_from_the_policy_catalog() { + // The catalog-derived half must be exactly the distinct non-empty + // `required_features` of the catalog, minus the features the daemon + // does not dispatch. A hand-written list would not survive a new + // catalog entry. + let mut expected: Vec<&str> = eggsec_policy::ALL_OPERATION_METADATA + .iter() + .flat_map(|metadata| metadata.required_features.iter().copied()) + .filter(|feature| { + !CATALOG_FEATURES_OUTSIDE_THE_DAEMON_SCOPE + .iter() + .any(|(name, _)| name == feature) + }) + .collect(); + expected.sort_unstable(); + expected.dedup(); + + assert_eq!(catalog_required_features(), expected); + + // And the declared members are exactly the non-catalog remainder. + let mut declared: Vec<&str> = DECLARED_MEMBERS.iter().map(|(name, _)| *name).collect(); + declared.sort_unstable(); + let mut all: Vec<&str> = expected.clone(); + all.extend(declared.iter().copied()); + all.sort_unstable(); + all.dedup(); + assert_eq!(required_profile_features(), all); + } + + #[test] + fn the_required_set_contains_the_cli_host_gate() { + assert!(required_profile_features().contains(&"cli")); + let catalog_names: Vec<&str> = eggsec_policy::ALL_OPERATION_METADATA + .iter() + .flat_map(|metadata| metadata.required_features.iter().copied()) + .collect(); + assert!( + !catalog_names.contains(&"cli"), + "`cli` is a host gate, not a catalog requirement" + ); + } + + #[test] + fn the_documented_profile_covers_the_required_set() { + for feature in required_profile_features() { + assert!( + DAEMON_SERVICE_PROFILE.contains(&feature), + "required feature '{feature}' is missing from the daemon profile" + ); + } + } + + #[test] + fn the_transitive_members_are_declared_explicitly() { + for member in ["postex", "evasion", "tool-api"] { + assert!( + DAEMON_SERVICE_PROFILE.contains(&member), + "declared transitive member '{member}' is missing from the daemon profile" + ); + assert!( + DECLARED_MEMBERS.iter().any(|(name, _)| *name == member), + "transitive member '{member}' is not declared with a reason" + ); + } + } + + #[test] + fn the_profile_enables_no_forbidden_feature() { + for feature in DAEMON_SERVICE_PROFILE { + assert!( + !DAEMON_SERVICE_FORBIDDEN.contains(feature), + "forbidden feature '{feature}' is enabled by the daemon profile" + ); + } + } + + #[test] + fn a_profile_with_an_unknown_feature_is_rejected() { + let violations = profile_violations(&["not-a-real-feature"]); + assert!( + violations.iter().any(|v| matches!( + v, + ProfileViolation::UnknownFeature { feature } if feature == "not-a-real-feature" + )), + "expected an unknown-feature violation, got {violations:?}" + ); + } + + #[test] + fn a_profile_with_a_forbidden_feature_is_rejected() { + let violations = profile_violations(&["insecure-tls"]); + assert!( + violations.iter().any(|v| matches!( + v, + ProfileViolation::ForbiddenFeature { feature, .. } if feature == "insecure-tls" + )), + "expected a forbidden-feature violation, got {violations:?}" + ); + } + + #[test] + fn a_profile_missing_a_required_feature_is_rejected() { + let candidate: Vec<&str> = DAEMON_SERVICE_PROFILE + .iter() + .copied() + .filter(|feature| *feature != "nse") + .collect(); + let violations = profile_violations(&candidate); + assert!( + violations.iter().any(|v| matches!( + v, + ProfileViolation::MissingRequiredFeature { feature } if *feature == "nse" + )), + "expected a missing-required-feature violation, got {violations:?}" + ); + } + + #[test] + fn a_profile_with_a_duplicate_feature_is_rejected() { + let mut candidate: Vec<&str> = DAEMON_SERVICE_PROFILE.to_vec(); + candidate.push("nse"); + let violations = profile_violations(&candidate); + assert!( + violations.iter().any(|v| matches!( + v, + ProfileViolation::DuplicateFeature { feature } if feature == "nse" + )), + "expected a duplicate-feature violation, got {violations:?}" + ); + } + + #[test] + fn a_profile_with_an_unrequired_feature_is_rejected() { + let mut candidate: Vec<&str> = DAEMON_SERVICE_PROFILE.to_vec(); + candidate.push("sbom"); + let violations = profile_violations(&candidate); + assert!( + violations.iter().any(|v| matches!( + v, + ProfileViolation::UnrequiredFeature { feature } if feature == "sbom" + )), + "expected an unrequired-feature violation, got {violations:?}" + ); + } + + #[test] + fn violations_name_the_offending_feature() { + let violations = profile_violations(&["rest-api"]); + assert!( + violations + .iter() + .any(|v| v.to_string().contains("rest-api")), + "violation text must name the offending feature, got {violations:?}" + ); + } +} diff --git a/crates/eggsec/src/config/feature_registry.rs b/crates/eggsec/src/config/feature_registry.rs index fdac7a5ca..8ed0b7e1d 100644 --- a/crates/eggsec/src/config/feature_registry.rs +++ b/crates/eggsec/src/config/feature_registry.rs @@ -472,6 +472,17 @@ feature_registry! { // - `output-mode`: heavy or special-purpose output/plugin modes. // - `implicit-base`: transitively enabled via `full` members (no direct entry). // - `process-host`: process-host/CLI concerns, not engine lab contents. +// +// **Scope of this list.** `FULL_EXCLUDED_WITH_REASON` is the exclusion list +// of the `full` aggregate **only** — it is not a global policy about which +// features may be combined. A second aggregate, the daemon's `service` +// profile, exists with its own contract and its own exclusion list: +// [`crate::config::daemon_profile::DAEMON_SERVICE_EXCLUDED`], governed by +// [`crate::config::daemon_profile::DAEMON_SERVICE_PROFILE`] and the +// absolute-no subset +// [`crate::config::daemon_profile::DAEMON_SERVICE_FORBIDDEN`]. The registry +// above remains the single source of truth for *which features exist*; each +// aggregate owns only its own membership and its own reasons. /// Exact direct membership of the `full` aggregate. /// diff --git a/crates/eggsec/src/config/mod.rs b/crates/eggsec/src/config/mod.rs index 298882065..c7fd9f458 100755 --- a/crates/eggsec/src/config/mod.rs +++ b/crates/eggsec/src/config/mod.rs @@ -34,6 +34,7 @@ mod api; mod budget; +pub mod daemon_profile; mod discovery; mod feature_registry; mod http; @@ -61,6 +62,10 @@ pub use feature_registry::{ pub use api::{ApiConfig, ApiKeyConfig, IpApiConfig, MaxMindConfig, NvdConfig, WaybackConfig}; pub use budget::{BudgetError, ExecutionBudget}; +pub use daemon_profile::{ + profile_violations, required_profile_features, ProfileViolation, DAEMON_SERVICE_EXCLUDED, + DAEMON_SERVICE_FORBIDDEN, DAEMON_SERVICE_PROFILE, +}; pub use discovery::DiscoveredTargetStatus; pub use http::{HttpConfig, Verbosity}; pub use loader::{config_dir, load_config, load_scope, load_scope_with_source}; diff --git a/crates/eggsec/src/config/policy_catalog.rs b/crates/eggsec/src/config/policy_catalog.rs index 783f705d6..38f3dc1d2 100644 --- a/crates/eggsec/src/config/policy_catalog.rs +++ b/crates/eggsec/src/config/policy_catalog.rs @@ -32,7 +32,9 @@ pub fn derive_operation_integration( required_features: metadata.required_features, requires_explicit_scope: matches!( metadata.target_policy, - TargetPolicyKind::ExplicitScopeRequired | TargetPolicyKind::PrivateOrLocalRequired + TargetPolicyKind::ExplicitScopeRequired + | TargetPolicyKind::PrivateOrLocalRequired + | TargetPolicyKind::InterfaceBound ), requires_private_or_local_target: matches!( metadata.target_policy, diff --git a/crates/eggsec/src/dispatch/canonical_execution.rs b/crates/eggsec/src/dispatch/canonical_execution.rs index fe65ef0e9..163c740ea 100644 --- a/crates/eggsec/src/dispatch/canonical_execution.rs +++ b/crates/eggsec/src/dispatch/canonical_execution.rs @@ -302,7 +302,12 @@ impl CanonicalOperationRequest { Self::DbPentest(_) => "db-pentest", Self::Storage(_) => "storage", Self::StressTest(_) => "stress-test", - Self::PacketCapture(_) | Self::PacketTraceroute(_) | Self::PacketSend(_) => "packet", + // The capture half of the packet family owns its own operation: + // a capture binds to a **local interface**, while `packet` also + // serves `traceroute` and `packet-send`, which address a remote + // host and must keep requiring one. + Self::PacketCapture(_) => "packet-capture", + Self::PacketTraceroute(_) | Self::PacketSend(_) => "packet", Self::Nse(_) => "nse", // Resume runs the pipeline stage set from a saved checkpoint, so it // shares the `pipeline` operation identity rather than declaring a @@ -316,7 +321,13 @@ impl CanonicalOperationRequest { Self::Integrations(_) => "integrations", Self::Workflow(_) => "workflow", Self::Vuln(_) => "vuln", - Self::Wireless(_) | Self::WirelessActive(_) => "wireless", + Self::Wireless(_) => "wireless", + // An active wireless request performs a deauth/disassoc, which is + // the `wireless-deauth` operation — risk `Intrusive`, capability + // `RawPacketProbe`, feature `wireless-advanced`. The CLI resolves + // its deauth command against the same operation, so the daemon and + // the CLI authorise the same work at the same risk level. + Self::WirelessActive(_) => "wireless-deauth", Self::Intercept(_) => "proxy-intercept", Self::C2(_) => "c2", } @@ -334,19 +345,20 @@ impl CanonicalOperationRequest { Self::LoadTest(r) => Some(r.target.clone()), Self::Recon(r) => Some(r.target.clone()), Self::Pipeline(r) => Some(r.target.clone()), - // The resumed target lives in the checkpoint, not in the request, so - // this is target-less by construction: validation against - // `OperationMetadata` target policy then fails explicitly rather - // than resuming an unbound operation. Manual surfaces supply the - // target from the selected session in their descriptor path. - Self::Resume(_) => None, + // The resumed target lives in the checkpoint, not in the request. + // It is resolved from the checkpoint so the resumed run is bound + // to the same target the enforcement layer approved. A checkpoint + // that cannot be read yields `None`, which fails the descriptor + // build closed: a resume is never authorised against no target. + Self::Resume(p) => crate::pipeline::session::read_target(&p.session_path).ok(), Self::GraphQl(r) => Some(r.target.clone()), Self::OAuth(r) => Some(r.target.clone()), Self::AuthTest(r) => Some(r.target.clone()), Self::DbPentest(r) => Some(r.target.clone()), Self::Storage(_) => None, Self::StressTest(p) => Some(p.target.clone()), - Self::PacketCapture(_) => None, + // The local identifier (an interface name), not a remote host. + Self::PacketCapture(p) => p.interface.clone(), Self::PacketTraceroute(p) => Some(p.target.clone()), Self::PacketSend(p) => Some(p.target.clone()), Self::Nse(p) => Some(p.target.clone()), @@ -356,8 +368,11 @@ impl CanonicalOperationRequest { Self::Integrations(_) => None, Self::Workflow(_) => None, Self::Vuln(p) => Some(p.target.clone()), - Self::Wireless(_) => None, - Self::WirelessActive(_) => None, + // The local identifier, not a remote host: an interface name for + // the passive scan, the BSSID (falling back to the interface) + // for the deauth. + Self::Wireless(p) => p.interface.clone(), + Self::WirelessActive(p) => p.target_bssid.clone().or_else(|| p.interface.clone()), Self::Intercept(p) => p.target.clone(), Self::C2(p) => p.target.clone(), } @@ -593,10 +608,10 @@ pub fn executor_route_for(operation_id: &str) -> &'static str { "recon" | "pipeline" => "recon", "waf-detect" | "waf-bypass" | "waf-stress" => "waf", "fuzz" | "graphql" | "oauth" => "fuzz-api", - "load-test" | "stress-test" | "packet" | "auth-test" => "network", + "load-test" | "stress-test" | "packet" | "packet-capture" | "auth-test" => "network", "nse" => "nse", "hunt" | "browser" | "compliance" | "storage" | "integrations" | "workflow" | "vuln" - | "wireless" => "security", + | "wireless" | "wireless-deauth" => "security", "db-pentest" => "db-pentest", "proxy-intercept" => "intercept", "c2" => "c2", @@ -2027,9 +2042,14 @@ mod tests { assert_eq!(pipe.operation_id(), "pipeline"); } + /// The capture owns its own operation; `traceroute` and `packet-send` + /// keep sharing `packet`, which still requires a remote target. #[test] fn packet_family_shares_canonical_operation() { - let cap = CanonicalOperationRequest::PacketCapture(PacketCaptureParams::default()); + let cap = CanonicalOperationRequest::PacketCapture(PacketCaptureParams { + interface: Some("eth0".into()), + ..Default::default() + }); let trace = CanonicalOperationRequest::PacketTraceroute(PacketTracerouteParams { target: "10.0.0.1".into(), max_hops: None, @@ -2039,11 +2059,14 @@ mod tests { protocol: "tcp".into(), ..Default::default() }); - assert_eq!(cap.operation_id(), "packet"); + assert_eq!(cap.operation_id(), "packet-capture"); assert_eq!(trace.operation_id(), "packet"); assert_eq!(send.operation_id(), "packet"); - assert_eq!(cap.canonical_target(), None); + // The capture's target is its local identifier, not a remote host. + assert_eq!(cap.canonical_target(), Some("eth0".to_string())); assert_eq!(trace.canonical_target(), Some("10.0.0.1".to_string())); + assert_eq!(executor_route_for(cap.operation_id()), "network"); + assert_eq!(executor_route_for(trace.operation_id()), "network"); } #[test] diff --git a/crates/eggsec/src/fuzzer/advanced.rs b/crates/eggsec/src/fuzzer/advanced.rs index 40198b2dd..330ee59c0 100755 --- a/crates/eggsec/src/fuzzer/advanced.rs +++ b/crates/eggsec/src/fuzzer/advanced.rs @@ -443,7 +443,7 @@ impl AdvancedFuzzer for WebSocketFuzzer { .collect(); let config = crate::websocket::WebSocketTestConfig { - url: self.url.clone(), + url: self.url().to_string(), timeout_secs: 10, injection_payloads, test_connection: true, diff --git a/crates/eggsec/src/nse_bridge.rs b/crates/eggsec/src/nse_bridge.rs index 7065bf712..e8a73928d 100644 --- a/crates/eggsec/src/nse_bridge.rs +++ b/crates/eggsec/src/nse_bridge.rs @@ -34,7 +34,11 @@ fn evidence_kind_to_output(kind: &crate::nse::report::NseEvidenceKind) -> Output } /// Map NseEvidenceKind to severity. -fn evidence_kind_to_severity(kind: &crate::nse::report::NseEvidenceKind) -> Severity { +/// +/// The mapping is the engine's single answer for "how severe is this kind of +/// evidence". The report bridge reuses it rather than restating it, so the +/// two paths cannot disagree. +pub(crate) fn evidence_kind_to_severity(kind: &crate::nse::report::NseEvidenceKind) -> Severity { match kind { crate::nse::report::NseEvidenceKind::VulnerabilitySignal => Severity::Medium, crate::nse::report::NseEvidenceKind::Misconfiguration => Severity::Medium, diff --git a/crates/eggsec/src/pipeline/session.rs b/crates/eggsec/src/pipeline/session.rs index 030ef4d40..78490e362 100755 --- a/crates/eggsec/src/pipeline/session.rs +++ b/crates/eggsec/src/pipeline/session.rs @@ -53,6 +53,29 @@ pub async fn load(path: &str) -> Result { Ok(session) } +/// Read the target of a saved checkpoint, synchronously. +/// +/// A resume request carries no target of its own: the checkpoint is the +/// authority for what is being resumed, and the enforcement layer needs that +/// target so the resumed run is scope-checked like any other. +/// +/// This is the synchronous counterpart to [`load`], for the enforcement path: +/// the authorisation chain is synchronous, and a checkpoint is a small local +/// JSON file. A checkpoint that cannot be read, or that carries no target, is +/// a hard failure — the caller must never fall back to a target-less resume. +pub fn read_target(path: &str) -> Result { + let json = std::fs::read_to_string(path)?; + let session: PipelineSession = serde_json::from_str(&json)?; + let target = session.target.trim().to_string(); + if target.is_empty() { + return Err(crate::error::EggsecError::InvalidTarget( + "the checkpoint carries no target; a resume cannot be authorised without one" + .to_string(), + )); + } + Ok(target) +} + /// Directory that holds discoverable scan checkpoints. /// /// Deliberately distinct from the TUI's own `sessions/` directory, which stores diff --git a/crates/eggsec/src/platform/prereqs.rs b/crates/eggsec/src/platform/prereqs.rs index bf9620184..8dded391f 100644 --- a/crates/eggsec/src/platform/prereqs.rs +++ b/crates/eggsec/src/platform/prereqs.rs @@ -546,7 +546,7 @@ fn packet_matrix() -> DomainPrerequisites { "feature-packet", "Feature packet-inspection", "not compiled; rebuild with --features packet-inspection", - "cargo check -p eggsec --features packet-inspection (needs libpcap-dev)", + "cargo check -p eggsec --features packet-inspection (pure-Rust pnet; no libpcap needed)", ) }; let priv_raw = privilege_prereq( @@ -719,7 +719,7 @@ fn nse_matrix() -> DomainPrerequisites { "feature-nse", "Feature nse", "not compiled; rebuild with --features nse", - "cargo check -p eggsec --features nse (needs libssl-dev)", + "cargo check -p eggsec --features nse (needs a C toolchain: cc, perl, make; OpenSSL is vendored)", ) }; DomainPrerequisites { diff --git a/crates/eggsec/src/runtime_bridge/descriptor.rs b/crates/eggsec/src/runtime_bridge/descriptor.rs index 593479d54..da48fbf17 100644 --- a/crates/eggsec/src/runtime_bridge/descriptor.rs +++ b/crates/eggsec/src/runtime_bridge/descriptor.rs @@ -36,13 +36,33 @@ pub fn descriptor_for_run_request( /// (`TaskKind::operation_id` / `TaskKind::canonical_target`) so runtime /// semantics cannot silently diverge from the canonical path. Returns /// `(operation_id, target)` where `target` is `None` for operations with -/// `NoTarget` policy or interface-bound tasks. +/// `NoTarget` policy, and the **local identifier** for an interface-bound +/// operation. +/// +/// `resume` is the one kind whose target is not in its payload: the +/// checkpoint is the authority for what is being resumed. The bridge resolves +/// the checkpoint's target here and binds it to the `pipeline` operation, so +/// the resumed run is scope-checked like any other. A checkpoint that cannot +/// be read, or that carries no target, is a hard failure — the bridge never +/// falls back to a target-less resume. fn resolve_operation_and_target( task_kind: &TaskKind, ) -> Result<(&'static str, Option), RuntimeBridgeError> { // Exhaustive via TaskKind methods; no wildcard fallback. Packet // traceroute/send map explicitly to the `packet` family with their target // (they no longer fail as `UnsupportedTaskKind`). + if let TaskKind::Resume(params) = task_kind { + let target = crate::pipeline::session::read_target(¶ms.session_path).map_err(|e| { + RuntimeBridgeError::InvalidTarget { + operation_id: task_kind.operation_id().to_string(), + reason: format!( + "could not resolve the resume checkpoint's target from '{}': {e}", + params.session_path + ), + } + })?; + return Ok((task_kind.operation_id(), Some(target))); + } Ok((task_kind.operation_id(), task_kind.canonical_target())) } @@ -189,20 +209,32 @@ mod tests { assert_eq!(desc.operation, "stress-test"); } + /// The capture is interface-bound: it owns its own operation, takes no + /// network target, and carries its local identifier. #[test] fn packet_capture_descriptor() { + let req = make_request(TaskKind::PacketCapture(PacketCaptureParams { + interface: Some("eth0".into()), + filter: None, + duration_secs: None, + ..Default::default() + })); + let desc = descriptor_for_run_request(&req).unwrap(); + assert_eq!(desc.operation, "packet-capture"); + assert_eq!(desc.target.as_deref(), Some("eth0")); + assert!(desc.requires_explicit_scope); + assert!(desc.target_policy.is_interface_bound()); + + // No interface named: the operation still builds, with no target. let req = make_request(TaskKind::PacketCapture(PacketCaptureParams { interface: None, filter: None, duration_secs: None, ..Default::default() })); - let result = descriptor_for_run_request(&req); - assert!(result.is_err()); - assert!(matches!( - result.unwrap_err(), - RuntimeBridgeError::InvalidTarget { .. } - )); + let desc = descriptor_for_run_request(&req).unwrap(); + assert_eq!(desc.operation, "packet-capture"); + assert_eq!(desc.target, None); } #[test] @@ -330,33 +362,52 @@ mod tests { assert_eq!(desc.operation, "vuln"); } + /// The passive wireless scan is interface-bound: it takes no network + /// target, and its local identifier (the interface name) is carried into + /// the descriptor rather than dropped. #[test] fn wireless_descriptor() { + let req = make_request(TaskKind::Wireless(WirelessParams { + interface: Some("wlan0".into()), + duration_secs: None, + })); + let desc = descriptor_for_run_request(&req).unwrap(); + assert_eq!(desc.operation, "wireless"); + assert_eq!(desc.target.as_deref(), Some("wlan0")); + assert!(desc.requires_explicit_scope); + assert!(desc.target_policy.is_interface_bound()); + + // No interface named: the operation still builds, with no target. let req = make_request(TaskKind::Wireless(WirelessParams { interface: None, duration_secs: None, })); - let result = descriptor_for_run_request(&req); - assert!(result.is_err()); - assert!(matches!( - result.unwrap_err(), - RuntimeBridgeError::InvalidTarget { .. } - )); + let desc = descriptor_for_run_request(&req).unwrap(); + assert_eq!(desc.operation, "wireless"); + assert_eq!(desc.target, None); + assert!(desc.requires_explicit_scope); } + /// An active wireless request is the `wireless-deauth` operation: risk + /// `Intrusive`, capability `RawPacketProbe`. It must never be authorised + /// under the passive operation's risk level. #[test] fn wireless_active_descriptor() { let req = make_request(TaskKind::WirelessActive(WirelessActiveParams { - interface: None, - target_bssid: None, + interface: Some("wlan0".into()), + target_bssid: Some("aa:bb:cc:dd:ee:ff".into()), ..Default::default() })); - let result = descriptor_for_run_request(&req); - assert!(result.is_err()); - assert!(matches!( - result.unwrap_err(), - RuntimeBridgeError::InvalidTarget { .. } - )); + let desc = descriptor_for_run_request(&req).unwrap(); + assert_eq!(desc.operation, "wireless-deauth"); + assert_eq!(desc.target.as_deref(), Some("aa:bb:cc:dd:ee:ff")); + assert!(desc.requires_explicit_scope); + assert!(desc.target_policy.is_interface_bound()); + + // The deauth's risk tier is the intrusive one, not the passive scan's. + let passive = crate::config::operation_metadata("wireless").unwrap(); + let active = crate::config::operation_metadata("wireless-deauth").unwrap(); + assert_ne!(passive.risk, active.risk); } #[test] @@ -471,18 +522,57 @@ mod tests { /// `requires_explicit_scope` must not become a blanket bypass: an op that /// the catalog marks strict still demands one, whatever else it is. + /// + /// The interface-bound family is included: it demands an explicit scope + /// too, because the requirement is the operator's consent gate and not a + /// statement about a target. #[test] fn strict_ops_still_demand_explicit_scope() { - for id in ["packet", "wireless", "wireless-deauth"] { + for id in ["packet", "wireless", "wireless-deauth", "packet-capture"] { let meta = ALL_OPERATION_METADATA .iter() .find(|m| m.id == id) .unwrap_or_else(|| panic!("{id} must exist in the catalog")); - assert_eq!( - meta.target_policy, - crate::config::TargetPolicyKind::ExplicitScopeRequired, - "{id} must stay strict after the target-less relaxation" + let desc = meta + .try_descriptor_for_target(Some("10.0.0.5")) + .unwrap_or_else(|e| panic!("{id} should accept a target, got {e}")); + assert!( + desc.requires_explicit_scope, + "{id} must still demand an explicit scope" ); } } + + /// The remote-target half of the packet family keeps requiring a remote + /// target: `packet-send` must not become runnable with no destination. + #[test] + fn the_packet_family_keeps_its_remote_target_requirement() { + let packet = ALL_OPERATION_METADATA + .iter() + .find(|m| m.id == "packet") + .unwrap_or_else(|| panic!("packet must exist in the catalog")); + assert_eq!( + packet.target_policy, + crate::config::TargetPolicyKind::ExplicitScopeRequired, + "packet must keep requiring an explicit scope" + ); + assert!( + packet.try_descriptor_for_target(None).is_err(), + "packet must refuse a target-less run" + ); + + // The capture half is split out and interface-bound. + let capture = ALL_OPERATION_METADATA + .iter() + .find(|m| m.id == "packet-capture") + .unwrap_or_else(|| panic!("packet-capture must exist in the catalog")); + assert!(capture.target_policy.is_interface_bound()); + // The split relaxes the *target*, never the authorisation: the + // capture keeps the packet family's risk tier and capability. + assert_eq!(capture.risk, packet.risk); + assert_eq!( + capture.required_capabilities, packet.required_capabilities, + "the capture must keep the packet family's capability requirement" + ); + } } diff --git a/crates/eggsec/src/runtime_bridge/executor.rs b/crates/eggsec/src/runtime_bridge/executor.rs index 9b11c206b..cbfbfecca 100644 --- a/crates/eggsec/src/runtime_bridge/executor.rs +++ b/crates/eggsec/src/runtime_bridge/executor.rs @@ -1,13 +1,16 @@ use std::future::Future; use std::pin::Pin; +use std::sync::Arc; -use eggsec_runtime::event::{LogLevel, TaskOutcome}; +use eggsec_runtime::event::{LogLevel, PolicyPrompt, TaskOutcome}; use eggsec_runtime::request::RunRequest; -use eggsec_runtime::{RuntimeError, RuntimeEventSink, RuntimeTaskExecutor, TaskId}; +use eggsec_runtime::{ + ApprovalAnswer, RuntimeError, RuntimeEventSink, RuntimeReportStore, RuntimeTaskExecutor, TaskId, +}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -use crate::config::{ExecutionPolicy, LoadedScope}; +use crate::config::{ExecutionPolicy, LoadedScope, ManualOverride}; use crate::dispatch::TaskResult; use super::bundle::approve_run_request_bundle; @@ -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,61 @@ impl EggsecRuntimeExecutor { } impl RuntimeTaskExecutor for EggsecRuntimeExecutor { + /// The task kinds this executor can execute. + /// + /// The engine implements every canonical task kind, so the executor + /// declares the **canonical** list — the same derived list the runtime + /// enforces and the daemon publishes. Declaring it explicitly matters: + /// the host intersects the declaration with the canonical list, so an + /// executor that said nothing would leave the intersection at whatever + /// the trait default happened to be. + fn supported_task_kinds(&self) -> Vec { + eggsec_runtime::RuntimeCapabilities::canonical().task_kinds + } + + /// 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) + } + + /// The report-form coverage this engine build publishes. + /// + /// `Some` is correct here: this executor links the engine, so the + /// coverage table is a knowable build fact. The rows are the engine's + /// own, projected into the wire DTO — nothing is restated here, and the + /// daemon republishes exactly what it gets. + fn report_forms(&self) -> Option> { + Some( + super::report_coverage::REPORT_COVERAGE + .iter() + .map(|row| eggsec_runtime::report::ReportFormEntry { + operation_id: row.operation_id.to_string(), + form: row.form, + reason: row.reason.to_string(), + }) + .collect(), + ) + } + fn execute( &self, - _task_id: TaskId, + task_id: TaskId, request: RunRequest, context: eggsec_runtime::RuntimeExecutionContext, sink: RuntimeEventSink, @@ -136,6 +201,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. @@ -160,16 +226,116 @@ impl RuntimeTaskExecutor for EggsecRuntimeExecutor { })?; // Run enforcement — get ApprovedRunRequest or fail. - let bundle = approve_run_request_bundle(surface, policy, loaded_scope, request, None) - .map_err(|e| match e { - super::surface::RuntimeBridgeError::UnsupportedTaskKind { .. } => { - RuntimeError::UnsupportedTaskKind - } - super::surface::RuntimeBridgeError::ManualOverrideRejected { .. } => { - RuntimeError::DispatchFailed(format!("manual override rejected: {e}")) - } - _ => RuntimeError::DispatchFailed(format!("enforcement denied: {e}")), - })?; + // + // A refusal that demands a confirmation is *held* on a manual + // surface: the operation waits for an operator's answer, and the + // answer is retried through this same authorisation path with an + // override bounded by exactly the classes the kernel demanded. A + // strict surface has no operator to ask, so it is refused here + // exactly as it always was — there is nothing for a client to + // approve. + let request_for_retry = request.clone(); + let scope_for_retry = loaded_scope.clone(); + let surface_for_retry = surface.clone(); + let policy_for_retry = policy.clone(); + let operation_id = request.task_kind.operation_id().to_string(); + let approval_gate = context.approval.clone(); + let can_hold = super::surface::runtime_surface_to_execution_surface(surface.clone()) + .map(|exec_surface| exec_surface.honors_manual_override()) + .unwrap_or(false); + + let bundle = + match approve_run_request_bundle(surface, policy, loaded_scope, request, None) { + Ok(bundle) => bundle, + Err(super::surface::RuntimeBridgeError::ConfirmationRequired { + reason, + required_classes, + }) => { + if !can_hold { + return Err(RuntimeError::DispatchFailed(format!( + "enforcement denied: {reason}" + ))); + } + + let prompt = PolicyPrompt { + message: format!( + "{operation_id} needs an operator's confirmation: {reason}" + ), + confirmation_class: Some( + required_classes + .iter() + .map(|class| class.as_str()) + .collect::>() + .join(", "), + ), + requires_explicit_approval: true, + }; + + let answer = approval_gate + .request(&sink, task_id, prompt, cancel.clone()) + .await?; + + match answer { + ApprovalAnswer::Approved { reason } => { + // The answer grants exactly what the kernel + // demanded: the override is built from the + // required classes, never from the client's + // wishes. The authorisation path is re-run, not + // skipped. + let mut granted = + ManualOverride::permitting_classes(&required_classes); + granted.reason = reason; + sink.log( + LogLevel::Info, + format!( + "{operation_id} was confirmed by the operator; resuming" + ), + ); + approve_run_request_bundle( + surface_for_retry, + policy_for_retry, + scope_for_retry, + request_for_retry, + Some(&granted), + ) + .map_err(|e| { + match e { + super::surface::RuntimeBridgeError::UnsupportedTaskKind { + .. + } => RuntimeError::UnsupportedTaskKind, + super::surface::RuntimeBridgeError::ManualOverrideRejected { + .. + } => RuntimeError::DispatchFailed(format!( + "manual override rejected: {e}" + )), + _ => { + RuntimeError::DispatchFailed(format!("enforcement denied: {e}")) + } + } + })? + } + ApprovalAnswer::Denied { reason } => { + return Err(RuntimeError::DispatchFailed(format!( + "the operator declined the policy confirmation: {}", + reason.unwrap_or_else(|| "no reason given".into()) + ))); + } + } + } + Err(e) => { + return Err(match e { + super::surface::RuntimeBridgeError::UnsupportedTaskKind { .. } => { + RuntimeError::UnsupportedTaskKind + } + super::surface::RuntimeBridgeError::ManualOverrideRejected { + .. + } => RuntimeError::DispatchFailed(format!( + "manual override rejected: {e}" + )), + _ => RuntimeError::DispatchFailed(format!("enforcement denied: {e}")), + }); + } + }; // Log the approved operation for audit. sink.log( @@ -217,6 +383,25 @@ 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. + // + // The coverage table decides *whether* a document is built and + // the result decides *how*; the operation id is the canonical + // identity of the task kind that produced the result. + if let Some(report) = super::report::report_for_operation(&operation_id, &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); @@ -228,6 +413,426 @@ impl RuntimeTaskExecutor for EggsecRuntimeExecutor { #[cfg(test)] mod tests { use super::*; + use eggsec_runtime::request::{FuzzParams, StressTestParams, TaskKind}; + use eggsec_runtime::{RunRequest, RuntimeEvent}; + + /// The engine publishes the coverage table itself: one row per canonical + /// operation, projected into the wire DTO without restating anything. + #[test] + fn the_executor_publishes_the_coverage_table() { + let executor = EggsecRuntimeExecutor::new(); + let forms = executor + .report_forms() + .expect("the engine links the coverage table"); + + assert_eq!( + forms.len(), + super::super::report_coverage::REPORT_COVERAGE.len(), + "one published row per coverage row" + ); + + for (published, row) in forms + .iter() + .zip(super::super::report_coverage::REPORT_COVERAGE.iter()) + { + assert_eq!(published.operation_id, row.operation_id); + assert_eq!(published.form, row.form); + assert_eq!(published.reason, row.reason); + } + } + + /// A policy that permits the intrusive operation and its capability. + /// + /// The decision is then base-allowed, so what a manual surface reaches is + /// the *confirmation* — the operator's discretion — rather than a hard + /// denial by the risk policy. + fn intrusive_policy() -> ExecutionPolicy { + ExecutionPolicy { + allow_intrusive_fuzzing: true, + allowed_capabilities: vec![crate::config::Capability::HttpFuzzLowImpact], + ..ExecutionPolicy::default() + } + } + + /// An intrusive request: the operation a permissive policy allows but a + /// manual surface still confirms. + fn fuzz_request(surface: eggsec_runtime::RuntimeSurface) -> RunRequest { + RunRequest { + task_kind: TaskKind::Fuzz(FuzzParams { + target: "https://example.com".into(), + ..Default::default() + }), + requested_by: None, + surface, + labels: vec![], + } + } + + /// The confirmation a manual surface demands for [`fuzz_request`]. + fn demanded_classes( + surface: eggsec_runtime::RuntimeSurface, + ) -> Vec { + let error = crate::runtime_bridge::bundle::approve_run_request_bundle( + surface.clone(), + intrusive_policy(), + crate::config::LoadedScope::default_empty(), + fuzz_request(surface.clone()), + None, + ) + .expect_err("an intrusive operation demands a confirmation on a manual surface"); + match error { + super::super::surface::RuntimeBridgeError::ConfirmationRequired { + required_classes, + .. + } => required_classes, + other => panic!("expected a confirmation requirement, got {other:?}"), + } + } + + /// The engine executor declares the canonical capability list, so a + /// daemon that hosts it publishes every canonical kind -- and nothing + /// else. + #[test] + fn the_engine_executor_declares_the_canonical_capability_list() { + let executor = EggsecRuntimeExecutor::new(); + let declared = executor.supported_task_kinds(); + let canonical = eggsec_runtime::RuntimeCapabilities::canonical(); + assert_eq!(declared.len(), canonical.task_kinds.len()); + for kind in TaskKind::all_variants() { + let name = kind.capability_name(); + assert!( + declared.iter().any(|d| d.name == name), + "the executor does not declare {name}" + ); + } + } + + /// The refusal that demands a confirmation carries the classes the kernel + /// demanded. They are what bound an operator's answer, so they must + /// survive the crossing from the policy kernel to the runtime bridge. + #[test] + fn the_refusal_carries_the_classes_the_kernel_demanded() { + let classes = demanded_classes(eggsec_runtime::RuntimeSurface::CliManual); + assert!( + !classes.is_empty(), + "the kernel must name the classes it demands" + ); + assert!( + classes + .iter() + .any(|class| matches!(class, crate::config::ConfirmationClass::HighRisk)), + "an intrusive operation demands the high-risk class: {classes:?}" + ); + } + + /// An answer is bounded by the classes the kernel demanded. + /// + /// The override the answer produces permits exactly those classes, and + /// the kernel accepts it — the authorisation path is re-run, not skipped. + #[test] + fn an_answer_is_bounded_by_the_classes_the_kernel_demanded() { + let surface = eggsec_runtime::RuntimeSurface::CliManual; + let classes = demanded_classes(surface.clone()); + let granted = ManualOverride::permitting_classes(&classes); + for class in &classes { + assert!(granted.permits(*class), "the grant must permit {class:?}"); + } + + let approved = crate::runtime_bridge::bundle::approve_run_request_bundle( + surface.clone(), + intrusive_policy(), + crate::config::LoadedScope::default_empty(), + fuzz_request(surface), + Some(&granted), + ); + assert!( + approved.is_ok(), + "the bounded override must satisfy the kernel: {:?}", + approved.err() + ); + } + + /// A manual surface holds the operation at its confirmation point until + /// the operator answers, and the answer is honoured. + /// + /// The operator refuses here, so the operation never dispatches: the test + /// proves the hold and the answer without running a scan. + #[tokio::test] + async fn a_manual_surface_holds_the_operation_until_the_operator_answers() { + let runtime = eggsec_runtime::Runtime::new( + eggsec_runtime::RuntimeConfig::default(), + EggsecRuntimeExecutor::with_policy(intrusive_policy()), + ); + let surface = eggsec_runtime::RuntimeSurface::DesktopGuiManual; + let session_id = runtime + .create_session(eggsec_runtime::SessionOptions::default(), surface.clone()) + .await + .expect("a manual session"); + let mut events = runtime.subscribe().await; + + let task_id = runtime + .submit(session_id, fuzz_request(surface)) + .await + .expect("the task is admitted"); + + // The prompt is announced, and it names the operation. + let announced = loop { + match events.recv().await.expect("the prompt must be announced") { + RuntimeEvent::PolicyDecisionRequired { prompt, .. } => break prompt, + _ => continue, + } + }; + assert!( + announced.message.contains("fuzz"), + "the prompt must name the operation: {}", + announced.message + ); + assert!( + announced.requires_explicit_approval, + "the prompt must ask for an explicit approval" + ); + + // The decision is pending and observable. + assert!( + runtime.pending_approval(session_id, task_id).is_some(), + "the runtime must expose the pending decision" + ); + + // The operator refuses. The operation never runs. + runtime + .resolve_approval( + session_id, + task_id, + false, + Some("the operator declined".into()), + ) + .expect("the pending decision must resolve"); + + let failure = loop { + match events.recv().await.expect("the task must report a failure") { + RuntimeEvent::TaskFailed { error, .. } => break error, + _ => continue, + } + }; + assert!( + failure.message.contains("the operator declined"), + "the failure must carry the operator's reason: {}", + failure.message + ); + assert!( + runtime.pending_approval(session_id, task_id).is_none(), + "an answered decision must not stay pending" + ); + } + + /// A strict surface never holds: there is no operator to ask, so the + /// operation is refused exactly as it always was. + /// + /// The session carries an explicit scope so that the refusal comes from + /// the *enforcement* layer — the confirmation point itself — and not from + /// the missing-scope refusal that precedes it. + #[tokio::test] + async fn a_strict_surface_never_holds_the_operation() { + let dir = tempfile::tempdir().expect("a temp dir"); + let scope_path = dir.path().join("scope.toml"); + std::fs::write(&scope_path, "[[allowed_targets]]\npattern = \"10.0.0.1\"\n") + .expect("the scope file is written"); + + let runtime = eggsec_runtime::Runtime::new( + eggsec_runtime::RuntimeConfig::default(), + EggsecRuntimeExecutor::with_policy(intrusive_policy()), + ); + let surface = eggsec_runtime::RuntimeSurface::RestApi; + let session_id = runtime + .create_session_with_scope( + eggsec_runtime::SessionOptions::default(), + surface.clone(), + Some(eggsec_runtime::SessionScope { + is_explicit: true, + source: "config-file".into(), + path: Some(scope_path.to_string_lossy().into_owned()), + }), + ) + .await + .expect("a strict session"); + let mut events = runtime.subscribe().await; + + let task_id = runtime + .submit(session_id, fuzz_request(surface)) + .await + .expect("the task is admitted"); + + // The task is refused, and no prompt is ever announced. + let failure = loop { + match events.recv().await.expect("the task must report a failure") { + RuntimeEvent::TaskFailed { error, .. } => break error, + RuntimeEvent::PolicyDecisionRequired { .. } => { + panic!("a strict surface must never announce a prompt") + } + _ => continue, + } + }; + assert!( + failure.message.contains("enforcement denied"), + "the refusal must be an enforcement refusal: {}", + failure.message + ); + assert!( + runtime.pending_approval(session_id, task_id).is_none(), + "a strict surface must not register a pending decision" + ); + } + + /// A hazard family the operator's policy refuses is refused by the + /// **policy**, not by the runtime's admission. + /// + /// The distinction is the point of widening the capability set: the + /// daemon must not answer "unsupported task kind" for an operation it + /// advertises. The refusal comes from the execution policy, and it + /// names the risk tier the operator has to allow. + #[test] + fn a_policy_refused_operation_is_refused_by_the_policy_not_by_admission() { + let request = RunRequest { + task_kind: TaskKind::StressTest(StressTestParams { + target: "10.0.0.1".into(), + flood_type: "syn".into(), + duration_secs: None, + threads: None, + rate_pps: None, + }), + requested_by: None, + surface: eggsec_runtime::RuntimeSurface::CliManual, + labels: vec![], + }; + let result = crate::runtime_bridge::bundle::approve_run_request_bundle( + eggsec_runtime::RuntimeSurface::CliManual, + crate::config::ExecutionPolicy::default(), + crate::config::LoadedScope::default_empty(), + request, + None, + ); + let error = result.expect_err("the default execution policy refuses a stress test"); + assert!( + !matches!( + error, + crate::runtime_bridge::surface::RuntimeBridgeError::UnsupportedTaskKind { .. } + ), + "the refusal must not be an admission failure: {error}" + ); + let message = error.to_string(); + assert!( + message.contains("is not allowed by current execution policy"), + "the refusal must name the risk policy: {message}" + ); + } + + /// 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() { diff --git a/crates/eggsec/src/runtime_bridge/manual.rs b/crates/eggsec/src/runtime_bridge/manual.rs index 808b2d8aa..56a82c065 100644 --- a/crates/eggsec/src/runtime_bridge/manual.rs +++ b/crates/eggsec/src/runtime_bridge/manual.rs @@ -59,20 +59,16 @@ pub fn approve_run_request( if exec_surface.honors_manual_override() { enforcement .approve_manual(exec_surface, descriptor, manual_override) - .map_err(|e| RuntimeBridgeError::EnforcementDenied { - reason: e.to_string(), - }) + .map_err(bridge_enforcement_error) } else { if manual_override.is_some() { return Err(RuntimeBridgeError::ManualOverrideRejected { surface: exec_surface.to_string(), }); } - enforcement.approve(exec_surface, descriptor).map_err(|e| { - RuntimeBridgeError::EnforcementDenied { - reason: e.to_string(), - } - }) + enforcement + .approve(exec_surface, descriptor) + .map_err(bridge_enforcement_error) } } @@ -98,9 +94,7 @@ pub fn approve_run_request_execution( if exec_surface.honors_manual_override() { enforcement .approve_manual_execution(exec_surface, descriptor, manual_override) - .map_err(|e| RuntimeBridgeError::EnforcementDenied { - reason: e.to_string(), - }) + .map_err(bridge_enforcement_error) } else { if manual_override.is_some() { return Err(RuntimeBridgeError::ManualOverrideRejected { @@ -109,9 +103,40 @@ pub fn approve_run_request_execution( } enforcement .approve_execution(exec_surface, descriptor) - .map_err(|e| RuntimeBridgeError::EnforcementDenied { - reason: e.to_string(), - }) + .map_err(bridge_enforcement_error) + } +} + +/// Render an enforcement refusal so the caller can report *why*. +/// +/// The enforcement error's `Display` is a deliberate one-liner ("operation +/// denied by policy") for a log line. A client that surfaces the refusal to +/// an operator needs the decision's own reasons: the risk tier the +/// execution policy refuses, the feature the build lacks, or the target +/// that is out of scope. Without them a refusal is indistinguishable from +/// every other refusal, which is exactly what the GUI's coverage model +/// must not report. +fn denial_reason(error: &crate::config::EnforcementError) -> String { + error.reasons().join("; ") +} + +/// Map an enforcement refusal onto the bridge's error type. +/// +/// A refusal that demands a confirmation keeps the classes the kernel +/// demanded. Those classes are the bound on what an operator's answer can +/// grant, so they must survive the crossing from the policy kernel to the +/// runtime bridge — flattening them into a message would leave the answer +/// unbounded. +fn bridge_enforcement_error(error: crate::config::EnforcementError) -> RuntimeBridgeError { + let reason = denial_reason(&error); + match error { + crate::config::EnforcementError::ConfirmationRequired { + required_classes, .. + } => RuntimeBridgeError::ConfirmationRequired { + reason, + required_classes, + }, + _ => RuntimeBridgeError::EnforcementDenied { reason }, } } diff --git a/crates/eggsec/src/runtime_bridge/mod.rs b/crates/eggsec/src/runtime_bridge/mod.rs index 1d86fc88e..29ee83115 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,8 @@ mod bundle; mod descriptor; mod executor; mod manual; +pub mod report; +pub mod report_coverage; mod surface; pub use bundle::{ @@ -33,6 +35,7 @@ pub use bundle::{ pub use descriptor::descriptor_for_run_request; pub use executor::EggsecRuntimeExecutor; pub use manual::{approve_run_request, approve_run_request_execution, preflight_run_request}; +pub use report_coverage::{ReportCoverageRow, ReportForm, REPORT_COVERAGE}; pub use surface::{ execution_surface_to_runtime_surface, runtime_surface_to_execution_surface, RuntimeBridgeError, }; diff --git a/crates/eggsec/src/runtime_bridge/report.rs b/crates/eggsec/src/runtime_bridge/report.rs new file mode 100644 index 000000000..b39b5fd28 --- /dev/null +++ b/crates/eggsec/src/runtime_bridge/report.rs @@ -0,0 +1,1764 @@ +//! 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 | +//! | endpoint scan | target, the interesting endpoints it found | +//! | graphql, oauth | target, the vulnerability classes the run found | +//! | auth test | target, the findings the run produced | +//! | nse, hunt, browser, compliance | target, the findings the run produced | +//! | 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. +//! +//! # The verdict gate +//! +//! [`report_for_result`] is the *how*: it matches on the result's variant and +//! builds the document. [`report_for_operation`] is the *whether*: it consults +//! the coverage table — the single source of truth in +//! [`super::report_coverage`] — and only then builds. +//! +//! The two cannot silently disagree: a `Canonical` verdict whose result has +//! no arm is a bridge/table disagreement, and it is logged at error level +//! rather than swallowed. +//! +//! # 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)), + TaskResult::EndpointScan(results) => Some(endpoint_scan_report(results)), + TaskResult::GraphQl(results) => Some(graphql_report(results)), + TaskResult::OAuth(results) => Some(oauth_report(results)), + TaskResult::Auth(report) => Some(auth_report(report)), + #[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)), + #[cfg(feature = "nse")] + TaskResult::Nse(results) => Some(nse_report(results)), + #[cfg(feature = "advanced-hunting")] + TaskResult::Hunt(report) => Some(hunt_report(report)), + #[cfg(feature = "headless-browser")] + TaskResult::Browser(report) => Some(browser_report(report)), + #[cfg(feature = "compliance")] + TaskResult::Compliance(report) => Some(compliance_report(report)), + _ => None, + } +} + +/// The report document for a completed result, if this operation has one. +/// +/// The verdict comes from the coverage table — the single source of truth — +/// and the document comes from the result. `operation_id` is the canonical +/// operation identity of the task kind that produced the result +/// (`TaskKind::operation_id()`). +/// +/// The function stays pure: no I/O, no state, no clock. Logging is not a +/// side effect on the document. +pub fn report_for_operation(operation_id: &str, result: &TaskResult) -> Option { + let Some(row) = super::report_coverage::coverage_for_operation(operation_id) else { + // The coverage table covers every canonical operation id, so this is + // an internal inconsistency rather than a fact about the result. + tracing::error!( + operation_id, + "the report coverage table has no row for this operation; no report was built" + ); + return None; + }; + + if row.form == super::report_coverage::ReportForm::NoCleanMapping { + // The table names the fact the result is missing; the operator can + // find it in the log without the bridge inventing a document. + tracing::debug!( + operation_id, + reason = row.reason, + "this operation has no clean report mapping; no report was built" + ); + return None; + } + + match report_for_result(result) { + Some(document) => Some(document), + None => { + // A canonical verdict with no bridge arm is a bridge/table + // disagreement. It is an internal error, so it is loud: the + // static guard makes it unreachable in the source, and this log + // is the belt to that braces. + tracing::error!( + operation_id, + variant = super::report_coverage::result_variant_name(result), + "the report bridge has no arm for this canonical result variant; no report was \ + built" + ); + 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"; + /// An endpoint discovery run. + pub const ENDPOINT_SCAN: &str = "endpoint-scan"; + /// A GraphQL testing run. + pub const GRAPHQL: &str = "graphql"; + /// An OAuth testing run. + pub const OAUTH: &str = "oauth"; + /// An authentication testing run. + pub const AUTH_TEST: &str = "auth-test"; + /// An NSE script run. + #[cfg(feature = "nse")] + pub const NSE: &str = "nse"; + /// A vulnerability-hunting run. + #[cfg(feature = "advanced-hunting")] + pub const HUNT: &str = "hunt"; + /// A headless-browser run. + #[cfg(feature = "headless-browser")] + pub const BROWSER: &str = "browser"; + /// A compliance-checking run. + #[cfg(feature = "compliance")] + pub const COMPLIANCE: &str = "compliance"; +} + +/// 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, + } +} + +/// Build the report document for an endpoint discovery run. +/// +/// Only the **interesting** endpoints become findings: an uninteresting +/// endpoint is a path the scanner reached, not a fact worth reporting (the +/// same rule the fuzz bridge applies to a rejected payload). +/// +/// The severity is the class constant `info`: a discovered endpoint is a +/// fact about the target, not a vulnerability, and the severity is a property +/// of the class rather than of the target. +fn endpoint_scan_report(results: &crate::scanner::EndpointScanResults) -> ScanReportData { + let findings: Vec = results + .results + .iter() + .filter(|endpoint| endpoint.interesting) + .map(|endpoint| { + let mut description = + format!("status {} {}", endpoint.status_code, endpoint.status_text); + if let Some(redirect) = &endpoint.redirect { + description.push_str(&format!("; redirects to {redirect}")); + } + FindingData { + title: format!("interesting endpoint {}", endpoint.path), + severity: "info".to_string(), + category: "endpoint-discovery".to_string(), + description, + location: endpoint.path.clone(), + evidence: None, + remediation: None, + cwe_ids: Vec::new(), + } + }) + .collect(); + + ScanReportData { + target: results.base_url.clone(), + scan_type: scan_type::ENDPOINT_SCAN.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: results.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a GraphQL testing run. +/// +/// The result carries no severity of its own, so the bridge assigns the +/// per-class constant: `medium` for a depth-limit bypass and for an alias +/// overload, `high` for an injection. The severity is a property of the +/// vulnerability class, never of the target. +fn graphql_report(results: &crate::dispatch::GraphQlResults) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + if results.depth_limit_bypassed { + findings.push(FindingData { + title: "GraphQL depth limit bypassed".to_string(), + severity: "medium".to_string(), + category: "graphql-depth-limit".to_string(), + description: "The endpoint answered a query deeper than its configured depth limit." + .to_string(), + location: results.target.clone(), + evidence: None, + remediation: None, + cwe_ids: Vec::new(), + }); + } + + if results.alias_overload_vulnerable { + findings.push(FindingData { + title: "GraphQL alias overload accepted".to_string(), + severity: "medium".to_string(), + category: "graphql-alias-overload".to_string(), + description: "The endpoint accepted a query that overloaded it with aliases." + .to_string(), + location: results.target.clone(), + evidence: None, + remediation: None, + cwe_ids: Vec::new(), + }); + } + + for injection in &results.injection_findings { + findings.push(FindingData { + title: "GraphQL injection".to_string(), + severity: "high".to_string(), + category: "graphql-injection".to_string(), + description: injection.clone(), + location: results.target.clone(), + evidence: None, + remediation: None, + cwe_ids: Vec::new(), + }); + } + + ScanReportData { + target: results.target.clone(), + scan_type: scan_type::GRAPHQL.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: results.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for an OAuth testing run. +/// +/// The result carries no severity of its own, so the bridge assigns the +/// per-class constant: `medium` for an open redirect and for a weak state +/// parameter, `high` for a scope weakness and for a grant weakness. +fn oauth_report(results: &crate::dispatch::OAuthResults) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + let mut push = |vulnerability: &String, severity: &str, category: &str| { + findings.push(FindingData { + title: vulnerability.clone(), + severity: severity.to_string(), + category: category.to_string(), + description: vulnerability.clone(), + location: results.target.clone(), + evidence: None, + remediation: None, + cwe_ids: Vec::new(), + }); + }; + + for vulnerability in &results.redirect_vulnerabilities { + push(vulnerability, "medium", "oauth-redirect"); + } + for vulnerability in &results.scope_vulnerabilities { + push(vulnerability, "high", "oauth-scope"); + } + for vulnerability in &results.state_vulnerabilities { + push(vulnerability, "medium", "oauth-state"); + } + for vulnerability in &results.grant_vulnerabilities { + push(vulnerability, "high", "oauth-grant"); + } + + ScanReportData { + target: results.target.clone(), + scan_type: scan_type::OAUTH.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: results.duration_ms, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for an authentication testing run. +/// +/// Each finding carries its own severity, title, description and +/// recommendation, so the bridge invents nothing here. +fn auth_report(report: &crate::auth::AuthTestReport) -> ScanReportData { + let findings: Vec = report + .findings + .iter() + .map(|finding| FindingData { + title: finding.title.clone(), + severity: finding.severity.as_str().to_string(), + category: format!("auth-{}", auth_test_type_name(&finding.test_type)), + description: finding.description.clone(), + location: report.target.clone(), + evidence: None, + remediation: Some(finding.recommendation.clone()), + cwe_ids: Vec::new(), + }) + .collect(); + + ScanReportData { + target: report.target.clone(), + scan_type: scan_type::AUTH_TEST.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: 0, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// The report document's category suffix for one authentication test type. +/// +/// The name is presentation, not policy: it names the test that produced the +/// finding so an operator can tell a brute-force finding from a +/// session-fixation one. +fn auth_test_type_name(test_type: &crate::auth::AuthTestType) -> &'static str { + use crate::auth::AuthTestType; + match test_type { + AuthTestType::BruteForce => "brute-force", + AuthTestType::CredentialStuffing => "credential-stuffing", + AuthTestType::AccountLockout => "account-lockout", + AuthTestType::RateLimitBypass => "rate-limit-bypass", + AuthTestType::MfaBypass => "mfa-bypass", + AuthTestType::SessionFixation => "session-fixation", + AuthTestType::TimingAttack => "timing-attack", + AuthTestType::PasswordPolicy => "password-policy", + } +} + +/// Build the report document for an NSE script run. +/// +/// The severity of each evidence item is the one the engine's own NSE bridge +/// assigns to that evidence kind, so the two paths cannot disagree. +#[cfg(feature = "nse")] +fn nse_report(results: &crate::dispatch::NseResults) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + if let Some(report) = &results.report { + for evidence in &report.evidence { + findings.push(FindingData { + title: evidence.title.clone(), + severity: crate::nse_bridge::evidence_kind_to_severity(&evidence.kind) + .as_str() + .to_string(), + category: format!("nse-{}", evidence.kind), + description: evidence.summary.clone(), + location: results.target.clone(), + evidence: evidence.raw_excerpt.clone(), + remediation: None, + cwe_ids: evidence.references.clone(), + }); + } + } + + ScanReportData { + target: results.target.clone(), + scan_type: scan_type::NSE.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: 0, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a vulnerability-hunting run. +/// +/// Each of the five finding collections contributes its findings, with their +/// own severity. The SPA routes of a browser run are routes, not findings, and +/// are not reported here either. +#[cfg(feature = "advanced-hunting")] +fn hunt_report(report: &crate::hunt::HuntReport) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + for chain in &report.attack_chains { + findings.push(FindingData { + title: chain.name.clone(), + severity: chain.severity.as_str().to_string(), + category: "hunt-attack-chain".to_string(), + description: chain.description.clone(), + location: report.target.clone(), + evidence: Some(format!("{} steps in the chain", chain.steps.len())), + remediation: Some(chain.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + for flaw in &report.business_logic { + findings.push(FindingData { + title: format!("business logic flaw {}", flaw.id), + severity: flaw.severity.as_str().to_string(), + category: "hunt-business-logic".to_string(), + description: flaw.description.clone(), + location: flaw.location.clone(), + evidence: Some(flaw.evidence.clone()), + remediation: Some(flaw.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + for race in &report.race_conditions { + findings.push(FindingData { + title: format!("race condition {}", race.id), + severity: race.severity.as_str().to_string(), + category: "hunt-race-condition".to_string(), + description: race.description.clone(), + location: race.endpoint.clone(), + evidence: Some(race.evidence.clone()), + remediation: None, + cwe_ids: Vec::new(), + }); + } + + for bypass in &report.authz_bypasses { + findings.push(FindingData { + title: format!("authorization bypass {}", bypass.id), + severity: bypass.severity.as_str().to_string(), + category: "hunt-authz-bypass".to_string(), + description: bypass.description.clone(), + location: bypass.endpoint.clone(), + evidence: Some(bypass.evidence.clone()), + remediation: Some(bypass.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + for issue in &report.session_issues { + findings.push(FindingData { + title: format!("session issue {}", issue.id), + severity: issue.severity.as_str().to_string(), + category: "hunt-session-issue".to_string(), + description: issue.description.clone(), + location: report.target.clone(), + evidence: Some(issue.evidence.clone()), + remediation: Some(issue.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + ScanReportData { + target: report.target.clone(), + scan_type: scan_type::HUNT.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: 0, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a headless-browser run. +/// +/// The DOM XSS findings and the client-side issues become findings, with +/// their own severity, location, evidence and remediation. The SPA routes the +/// run discovered are routes, not findings, and are not reported. +#[cfg(feature = "headless-browser")] +fn browser_report(report: &crate::browser::BrowserReport) -> ScanReportData { + let mut findings: Vec = Vec::new(); + + for finding in &report.dom_xss { + findings.push(FindingData { + title: format!("DOM XSS finding {}", finding.id), + severity: finding.severity.as_str().to_string(), + category: "browser-dom-xss".to_string(), + description: finding.description.clone(), + location: finding.location.clone(), + evidence: Some(finding.evidence.clone()), + remediation: Some(finding.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + for issue in &report.client_issues { + findings.push(FindingData { + title: format!("client-side issue: {}", issue.issue_type), + severity: issue.severity.as_str().to_string(), + category: "browser-client-issue".to_string(), + description: issue.description.clone(), + location: issue.location.clone(), + evidence: Some(issue.evidence.clone()), + remediation: Some(issue.remediation.clone()), + cwe_ids: Vec::new(), + }); + } + + ScanReportData { + target: report.target.clone(), + scan_type: scan_type::BROWSER.to_string(), + timestamp: String::new(), + findings, + open_ports: Vec::new(), + services: Vec::new(), + duration_ms: 0, + wireless_networks: Vec::new(), + policy_summary: None, + } +} + +/// Build the report document for a compliance-checking run. +/// +/// Only the **failed** requirements become findings: a requirement the +/// framework passed is not a fact about the target worth reporting, and a +/// requirement marked not applicable is not a failure either. +#[cfg(feature = "compliance")] +fn compliance_report(report: &crate::compliance::ComplianceReport) -> ScanReportData { + let findings: Vec = report + .findings + .iter() + .filter(|finding| finding.status == crate::compliance::ComplianceStatus::Fail) + .map(|finding| FindingData { + title: format!("{} requirement failed", finding.requirement_id), + severity: finding.severity.as_str().to_string(), + category: format!("compliance-{}", report.framework.to_lowercase()), + description: finding.description.clone(), + location: report.target.clone(), + evidence: None, + remediation: Some(finding.remediation.clone()), + cwe_ids: Vec::new(), + }) + .collect(); + + ScanReportData { + target: report.target.clone(), + scan_type: scan_type::COMPLIANCE.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::runtime_bridge::report_coverage; + + 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: " + + +
+
+

🛡️ 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-operator.export.json b/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.json new file mode 100644 index 000000000..7a8b4d191 --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24-operator.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": 7 +} \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.md b/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.md new file mode 100644 index 000000000..61e8c00bc --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24-operator.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-operator.export.sarif b/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.sarif new file mode 100644 index 000000000..c9c76e98c --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24-operator.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-24T23:37:30.561436Z", + "end_time_utc": "2026-10-24T23:37:30.561437Z", + "execution_successful": true + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.xml b/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.xml new file mode 100644 index 000000000..ff0de6b1f --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24-operator.export.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/evidence/gui-qualification/macos-2026-10-24-operator.launch.png b/docs/evidence/gui-qualification/macos-2026-10-24-operator.launch.png new file mode 100644 index 000000000..d0799bb36 Binary files /dev/null and b/docs/evidence/gui-qualification/macos-2026-10-24-operator.launch.png differ diff --git a/docs/evidence/gui-qualification/macos-2026-10-24-operator.md b/docs/evidence/gui-qualification/macos-2026-10-24-operator.md new file mode 100644 index 000000000..9b57e519a --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24-operator.md @@ -0,0 +1,236 @@ +# 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`, `Launch`, `Connect`, `Submit`, `Cancel`, `Render`, `Export` | +| Date of the run (UTC) | 2026-10-24 | +| Run label | `operator` | +| Operator or CI job | `operator` | +| Commit SHA (`git rev-parse HEAD`) | `d0cf5bc3b71ce4d575a3888cce390cbbc310d12b` | +| Tree state (`git status --porcelain` empty?) | `clean` | +| Host OS version | macos 25.6.0 | +| Architecture | aarch64 | +| Process architecture | arm64 (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 | attached to an operator-started daemon (features: unknown) | +| Daemon socket path used | `/tmp/eggsec-op-34860.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 every_report_format_renders_writes_and_digests ... ok +test the_live_daemon_half_records_its_outcomes ... ok +test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s +``` + +## 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 `pass`, operator `pass` | yes | +| `connect` | the runbook's Step 3 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `pass` | yes | +| `submit` | the runbook's Step 4 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `pass` | yes | +| `cancel` | the runbook's Step 5 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `pass` | yes | +| `render` | the runbook's Step 6 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `pass` | yes | +| `export` | the runbook's Step 7 (`docs/GUI_BUILD.md` §5) | scripted `pass`, operator `pass` | yes | + +Each column's reason: + +- `build` — the release build produced `eggsec-gui.build.json` and its SHA-256 is recorded +- `launch` — the probe found exactly one window titled `Eggsec` +- `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:1eba65d6-dcf1-4a7d-aa78-53e53aec6ff3 +- `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 + +## Operator attestation + +The human half of this run. The scripted outcomes above are what the machine measured; these are what a person saw. + +| Field | Value | +|---|---| +| Attested by | `David Bowman` | +| Attested at | 2026-10-24 | +| Platform | `macos` | +| Commit attested | `309d77d1362fef645927117efe78e9c19e53cbe2` | +| Schema | `eggsec-gui-operator-attestation/v1` | + +What the operator observed: + +- `launch` — the eggsec-gui window was painted on the macOS WindowServer and titled Eggsec; the accessibility query returned exactly one window, and the capture shows the window's own contents rather than a blank frame or a photograph of the desktop +- `connect` — the badge beside the title read CONNECTED; the header line reported OPERATIONS 35, TASK KINDS 30 and CAPABILITIES 30; the session line carried a session id; and the OPERATIONS sidebar listed the operations the daemon had published +- `submit` — selecting an operation in the sidebar rendered the schema-driven form from the daemon's advertised catalogue (Port Scan showed target, concurrency, ports and scan_type); running it produced a task card carrying a task id and a non-terminal status +- `cancel` — the Cancel active task control reached the daemon and the daemon's answer was surfaced verbatim in the GUI (CANCELLATION FAILED - task already completed: task:8f886498-af9e-48ef-8819-90d8fa40705f); the card's status is read from the daemon's event stream, which showed QUEUED, then RUNNING with the daemon's live 'dispatching scan-ports' event line and a progress bar. The daemon's cancellation of a live task, and its 'cancelled' terminal state, are measured by the harness against the same daemon +- `render` — Show report on the completed task filled the REPORT panel with the daemon's report as data - TARGET 127.0.0.1, SCAN port-scan, DURATION 28 ms - rather than an empty dashboard +- `export` — the EXPORT A REPORT panel wrote the daemon's report to the destination chosen and the GUI reported REPORT EXPORTED with that path; the written file held the report, with four open ports (22/SSH, 53/DNS, 88, 445/SMB) + +## 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": "operator", + "date": "2026-10-24", + "run_label": "operator", + "commit": "d0cf5bc3b71ce4d575a3888cce390cbbc310d12b", + "tree_state": "clean", + "attestation": { + "schema": "eggsec-gui-operator-attestation/v1", + "attested_by": "David Bowman", + "attested_at": "2026-10-24", + "platform": "macos", + "commit": "309d77d1362fef645927117efe78e9c19e53cbe2" + }, + "host": { + "os": "macos", + "os_version": "25.6.0", + "arch": "aarch64", + "process_arch": "arm64", + "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": "/tmp/eggsec-op-34860.sock", + "ready": true, + "version": "attached to an operator-started daemon", + "features": "unknown", + "task_kinds": "30", + "scope": { + "surface": "DesktopGuiManual", + "source": "gui-default" + } + }, + "window": { + "probe": "osascript", + "windows": "1", + "screenshot": "macos-2026-10-24-operator.launch.png", + "reason": "the window probe ran on this host" + }, + "columns": [ + { + "column": "build", + "scripted": "pass", + "operator": "not-applicable", + "artifact": "macos-2026-10-24-operator.build.json", + "sha256": "4c0de083af167908c790047aad8b6bd6de4d6f8710f08d087c35986ba5e36062", + "reason": "the release build produced `eggsec-gui.build.json` and its SHA-256 is recorded" + }, + { + "column": "launch", + "scripted": "pass", + "operator": "pass", + "artifact": "macos-2026-10-24-operator.launch.png", + "sha256": "82c29e41dd1a37df3cfb18792794059918348517435954f49992fcbe27ca8090", + "reason": "the probe found exactly one window titled `Eggsec`", + "observed": "the eggsec-gui window was painted on the macOS WindowServer and titled Eggsec; the accessibility query returned exactly one window, and the capture shows the window's own contents rather than a blank frame or a photograph of the desktop" + }, + { + "column": "connect", + "scripted": "pass", + "operator": "pass", + "artifact": "", + "sha256": "", + "reason": "the GUI's own client connected to the daemon and read its catalogue", + "observed": "the badge beside the title read CONNECTED; the header line reported OPERATIONS 35, TASK KINDS 30 and CAPABILITIES 30; the session line carried a session id; and the OPERATIONS sidebar listed the operations the daemon had published" + }, + { + "column": "submit", + "scripted": "pass", + "operator": "pass", + "artifact": "", + "sha256": "", + "reason": "the GUI's own form engine assembled the `PortScan` request and the daemon accepted it as task task:1eba65d6-dcf1-4a7d-aa78-53e53aec6ff3", + "observed": "selecting an operation in the sidebar rendered the schema-driven form from the daemon's advertised catalogue (Port Scan showed target, concurrency, ports and scan_type); running it produced a task card carrying a task id and a non-terminal status" + }, + { + "column": "cancel", + "scripted": "pass", + "operator": "pass", + "artifact": "", + "sha256": "", + "reason": "the daemon accepted the cancellation and the event stream reported `cancelled`", + "observed": "the Cancel active task control reached the daemon and the daemon's answer was surfaced verbatim in the GUI (CANCELLATION FAILED - task already completed: task:8f886498-af9e-48ef-8819-90d8fa40705f); the card's status is read from the daemon's event stream, which showed QUEUED, then RUNNING with the daemon's live 'dispatching scan-ports' event line and a progress bar. The daemon's cancellation of a live task, and its 'cancelled' terminal state, are measured by the harness against the same daemon" + }, + { + "column": "render", + "scripted": "pass", + "operator": "pass", + "artifact": "", + "sha256": "", + "reason": "the daemon's report for the task rendered as 0 findings and 1 open ports against `127.0.0.1`", + "observed": "Show report on the completed task filled the REPORT panel with the daemon's report as data - TARGET 127.0.0.1, SCAN port-scan, DURATION 28 ms - rather than an empty dashboard" + }, + { + "column": "export", + "scripted": "pass", + "operator": "pass", + "artifact": "macos-2026-10-24-operator.export.json", + "sha256": "7fb3459780f1fe77fb477da884b9b9c4eeebd104bf4d51cfa136048a64f1f83a", + "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", + "observed": "the EXPORT A REPORT panel wrote the daemon's report to the destination chosen and the GUI reported REPORT EXPORTED with that path; the written file held the report, with four open ports (22/SSH, 53/DNS, 88, 445/SMB)" + } + ], + "deviations": [] +} +``` diff --git a/docs/evidence/gui-qualification/macos-2026-10-24.build.json b/docs/evidence/gui-qualification/macos-2026-10-24.build.json new file mode 100644 index 000000000..203089b60 --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.build.json @@ -0,0 +1,28 @@ +{ + "allow_dirty": true, + "binary": "eggsec-gui", + "binary_path": "/var/folders/n6/hn37q6pj7sj_9dmqqc2113800000gn/T//eggsec-gui-qualification-33802/build/eggsec-gui", + "binary_sha256": "2a870c617c2597d3f5948aaab0dc7be79f9376fbad6b8429590c5726c00222ce", + "binary_size_bytes": 6210720, + "built_at_utc": "2026-10-24T23:52:22Z", + "bundle_active": false, + "bundled": false, + "cargo_features_requested": "shell", + "cargo_features_resolved": [ + "default", + "shell" + ], + "cargo_lock_sha256": "7ae228c9ce7cba21995c2b02ed64a06525be60d4e4f71582240e2628d54bf6e1", + "cargo_version": "cargo 1.99.1 (5f94df478 2026-08-27)", + "commit_sha": "d0cf5bc3b71ce4d575a3888cce390cbbc310d12b", + "credential_env_vars_present": [], + "dirty": false, + "notarized": false, + "published": false, + "rustc_version": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "rustc_version_verbose": "rustc 1.99.1 (58cf8f9c3 2026-10-13)\nbinary: rustc\ncommit-hash: 58cf8f9c35b355199727627d07ae34a4e2846d67\ncommit-date: 2026-10-13\nhost: aarch64-apple-darwin\nrelease: 1.99.1\nLLVM version: 23.1.1", + "schema": "eggsec-gui-build-metadata/v1", + "signed": false, + "target_triple": "aarch64-apple-darwin", + "tree_state": "clean" +} 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..5ff2321c4 --- /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": 3 +} \ 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.md b/docs/evidence/gui-qualification/macos-2026-10-24.md new file mode 100644 index 000000000..0f09e4659 --- /dev/null +++ b/docs/evidence/gui-qualification/macos-2026-10-24.md @@ -0,0 +1,201 @@ +# 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`) | `d0cf5bc3b71ce4d575a3888cce390cbbc310d12b` | +| Tree state (`git status --porcelain` empty?) | `clean` | +| Host OS version | macos 25.6.0 | +| Architecture | aarch64 | +| Process architecture | arm64 (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 | /Users/runner/work/_temp/eggsec-daemon/eggsec-daemon (sha256 52c284675c2adddf899e679e7f7745444d83c543b3fedf4e68b60ac7cb75dc80) (features: service) | +| Daemon socket path used | `/var/folders/n6/hn37q6pj7sj_9dmqqc2113800000gn/T//eggsec-gui-qualification-33802.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_export_refuses_a_non_regular_destination_and_backs_up_a_real_one ... ok +test the_outcome_file_round_trips_and_names_what_is_wrong_with_it ... 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.10s +``` + +## 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:ce47a28e-65b9-4cce-98a6-298999317c90 +- `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", + "run_label": "", + "commit": "d0cf5bc3b71ce4d575a3888cce390cbbc310d12b", + "tree_state": "clean", + "host": { + "os": "macos", + "os_version": "25.6.0", + "arch": "aarch64", + "process_arch": "arm64", + "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/n6/hn37q6pj7sj_9dmqqc2113800000gn/T//eggsec-gui-qualification-33802.sock", + "ready": true, + "version": "/Users/runner/work/_temp/eggsec-daemon/eggsec-daemon (sha256 52c284675c2adddf899e679e7f7745444d83c543b3fedf4e68b60ac7cb75dc80)", + "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": "8b31313125edb98568c5f2332b22e971988767055b796481d6902115ce368387", + "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:ce47a28e-65b9-4cce-98a6-298999317c90" + }, + { + "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": "1588529a4eb830f884d28db5796b44f7ea43ad3b6429e8b3415e076cc3ca3a12", + "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/extending/testing.md b/docs/extending/testing.md index bbed46094..de69fa262 100644 --- a/docs/extending/testing.md +++ b/docs/extending/testing.md @@ -111,7 +111,7 @@ platform. | `mobile-dynamic` | ADB + Android device | `cargo check -p eggsec --features mobile-dynamic` | | `wireless` | iwlist, CAP_NET_ADMIN | `cargo check -p eggsec --features wireless` | | `wireless-advanced` | wireless + root | `cargo check -p eggsec --features wireless-advanced` | -| `packet-inspection` | libpcap-dev | `cargo check -p eggsec --features packet-inspection` | +| `packet-inspection` | none (pure-Rust `pnet`) | `cargo check -p eggsec --features packet-inspection` | | `db-pentest` | database drivers | `cargo test -p eggsec-db-lab` | | `nse` | none (runtime OpenSSL is vendored) | `cargo test -p eggsec --features nse,cli --test nse_tests --test nse_integration_tests` (runtime tests: [eggsec-nse CI](https://github.com/eggstack/eggsec-nse/actions)) | 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/000-long-term-specification.md b/plans/000-long-term-specification.md index 184563b7a..0f163cd1b 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,8 @@ 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. +- Desktop GUI platforms: the desktop GUI is supported on **Linux (x86_64, glibc) and macOS (x86_64 and arm64)**. **Windows is out of scope** for the desktop GUI, because its only transport — the daemon's Unix domain socket — is unavailable there; a Windows transport for the daemon is a daemon-subsystem change requiring its own ADR (`plans/adrs/ADR-0010-gui-supported-platform-scope.md`). The engine, CLI, TUI, and Python surfaces are unaffected. ## 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/adrs/ADR-0010-gui-supported-platform-scope.md b/plans/adrs/ADR-0010-gui-supported-platform-scope.md new file mode 100644 index 000000000..d385165e2 --- /dev/null +++ b/plans/adrs/ADR-0010-gui-supported-platform-scope.md @@ -0,0 +1,277 @@ +# ADR-0010: Desktop GUI supported-platform scope + +Status: accepted + +Date: 2026-10-23 + +Decision owners: project maintainers + +Related specification sections: + +- `plans/000-long-term-specification.md#10-frontend-rules` +- `plans/000-long-term-specification.md#11-acceptance-criteria` +- `plans/001-terminology-and-domain-model.md#3-domain-model` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +## Context + +The desktop GUI reaches the engine **only** through the daemon, over the +daemon's local transport. That is a deliberate property of `ADR-0007`, and it +means the GUI's platform reach is exactly the daemon transport's platform reach. + +The daemon transport is a Unix domain socket, and it is Unix-only **by +construction, not by policy**: + +- `crates/eggsec-daemon/src/server.rs:1` imports `std::os::unix::fs::PermissionsExt` + unconditionally, and `crates/eggsec-daemon/src/server.rs:5` imports + `tokio::net::UnixListener`; +- `crates/eggsec-daemon/src/client.rs:9` and + `crates/eggsec-frontend-client/src/daemon.rs:9` import + `tokio::net::UnixStream` unconditionally. + +There is no `cfg(unix)` gate on any of those uses, so the daemon and the +frontend client do not compile for Windows. The GUI therefore inherits the +limitation: `cargo check -p eggsec-gui --no-default-features --target +x86_64-pc-windows-msvc` fails with `error[E0432]: unresolved import +tokio::net::UnixStream`. + +This became a governance problem rather than a build problem. The subsystem +roadmap says "the supported platform matrix" in five places +(`plans/subsystems/desktop-gui-frontend-roadmap.md:442`, `:514`, `:519`, +`:526`, `:646`) and **never defines it**; the definition is deferred to +"distribution policy (operational)" — a decision owned outside this repository. +Milestone 007's exit condition is therefore written as "each supported platform +builds and launches", which is **not verifiable** while the set is undefined, +and would be **unsatisfiable** if Windows were included. + +The rest of the product is unaffected. The engine, CLI, TUI, and Python +surfaces build and run on Windows today, and the portability CI matrix +(`.github/workflows/deep-checks.yml:61-66`) covers `windows-latest` for those. +Only the desktop GUI is in question. + +The maintainer directed this decision on 2026-10-23: keep Windows out of scope +for the desktop GUI. + +## Decision drivers + +- **The GUI's transport is the daemon's transport.** Adding a Windows transport + to make the GUI work on Windows would change the daemon's transport *kind* + for **every** frontend (TUI, CLI, Python), not for the GUI alone. That is a + far larger blast radius than the GUI's platform reach, and it would not be a + strictly additive protocol change. +- **Milestone 007 needs a verifiable exit condition.** "Each supported + platform builds and launches" is only a checkable claim once the set is + named, and a claim the project cannot currently satisfy on Windows. +- **Honest prerequisites beat aspirational matrices.** The Linux + `webkit2gtk-4.1` floor is already a documented prerequisite + (`docs/PLATFORM.md`); the platform story should name what the project + supports and what it does not, rather than claim a platform to satisfy a + matrix. +- **Deferring is cheap; forcing a transport now is not.** The GUI's Unix-socket + transport inherits filesystem-scoped access control (the socket is `chmod` + `0600` at `crates/eggsec-daemon/src/server.rs:100-101`), which is a stronger + local-access guarantee than a TCP transport would give by default. +- **`ADR-0009`'s egui fallback does not apply.** The fallback exists to remove + the *system webview* dependency. The Windows obstacle is the *transport*, not + the shell, so no shell choice fixes it. + +## Considered options + +### Option A — Qualify Linux and macOS; hold Windows out of scope explicitly + +Description: the desktop GUI's supported-platform set is Linux (x86_64 glibc) +and macOS (x86_64 and arm64), qualified through milestone 007. Windows is +named as out of scope, with its root cause recorded, and re-entry is gated on +a daemon-transport milestone. + +Benefits: milestone 007 gets a checkable exit condition; no daemon transport +change is forced; the platform claim is truthful; the GUI's stronger local +access model is preserved unchanged. + +Costs: Windows users keep the CLI, TUI, and Python but not the desktop GUI, so +the "one product, many surfaces" story has a platform seam. The GUI's release +footprint is narrower than the rest of the product's. + +Failure modes: the GUI is quietly expected on Windows by users or downstream +packagers — mitigated by stating the exclusion in the long-term +specification, the subsystem roadmap, the registry, and milestone 007's +known-limitations record. + +### Option B — Add a Windows named-pipe transport now + +Description: extend the daemon with a named-pipe transport and a transport +selection handshake, so the GUI and every other frontend work on Windows. + +Benefits: one product surface everywhere; no platform seam. + +Costs: it changes the daemon's transport kind for every frontend; it is not a +strictly additive protocol change; it multiplies the daemon's test matrix; and +the local-access story changes from filesystem permissions to whatever the pipe +or loopback mechanism provides. + +Failure modes: a second transport kind silently diverges between platforms — +the kind of divergence this subsystem's additive-only protocol discipline +exists to prevent. + +### Option C — Leave the set undefined and let the distribution workstream decide + +Description: keep the current roadmap wording and treat the platform set as an +external operational decision. + +Benefits: no new decision; the distribution workstream retains full discretion. + +Costs: milestone 007 cannot close, because its exit condition is undecidable +while the set is undefined. It also leaves the GUI's platform reach ambiguous +in every document that mentions it. + +Failure modes: the milestone stalls indefinitely on a dependency nobody in this +repository owns. + +### Option D — Use the egui fallback to reach Windows + +Description: replace Tauri with egui/eframe, the alternative pre-sanctioned in +`ADR-0009`. + +Benefits: none with respect to Windows. + +Costs: it discards the shipped Tauri shell for no Windows benefit, because the +obstacle is `tokio::net::UnixStream`, not the webview. + +Failure modes: rework of milestones 004 and 005 for no gain. Rejected. + +### Option E — Reach Windows over a loopback TCP transport + +Description: give the daemon a loopback TCP transport for Windows. + +Benefits: no named-pipe implementation. + +Costs: it weakens the local-access model that the Unix socket's `0600` +permissions provide, and it adds an authentication surface for a local socket. +`plans/000-long-term-specification.md#10-frontend-rules` already requires the +GUI's local transport to be loopback-bound, which a TCP transport would make a +live security concern rather than a filesystem guarantee. + +Failure modes: a world-connectable or unauthenticated local port. + +## Decision + +**The desktop GUI's supported-platform set is Linux (x86_64, glibc) and macOS +(x86_64 and arm64), qualified through milestone 007. Windows is out of scope +for the desktop GUI.** + +Precisely: + +1. **Linux and macOS are the supported platforms** for the desktop GUI. + Milestone 007 qualifies one row per platform, with evidence for every + required behaviour (build, launch, connect, submit, cancel, render, export) + or a named, justified gap. +2. **Windows is out of scope** for the desktop GUI. The GUI does not compile for + Windows because its only transport — the daemon's Unix domain socket — is + unavailable there. The root cause is recorded as the daemon's transport + choice, not as a GUI defect. +3. **The engine, CLI, TUI, and Python surfaces are unaffected.** Their Windows + support is unchanged, and the portability CI matrix keeps covering + `windows-latest` for them. +4. **The re-entry path is a daemon-subsystem milestone, not a GUI milestone.** + A Windows transport for the daemon — named pipes or an equivalent local IPC + — changes the daemon's transport kind for every frontend and therefore + requires its own ADR under the roadmap's decision-point rule ("any change to + the daemon protocol that is not strictly additive"). When such a milestone + lands, the GUI's Windows row may be qualified; the GUI needs no new + architecture to use it. +5. **`ADR-0009`'s egui fallback remains pre-sanctioned** for its original + purpose (removing the system webview dependency, and as the escape hatch + for a failing Tauri closure). It is **not** the Windows remedy, and this + decision does not invoke it. + +Ownership boundary: this decision fixes **which platforms the GUI is offered +on**. It does not own signing, notarization, installers, or update channels — +those remain with the separately-managed distribution workstream, and milestone +007 hands that workstream the binary and a reproducible build recipe. + +## Consequences + +### Positive + +- Milestone 007's exit condition becomes decidable and checkable. +- No daemon transport change is forced, and the daemon's Unix-socket access + model (`0600` socket permissions at + `crates/eggsec-daemon/src/server.rs:100-101`) is preserved. +- The platform claim matches what the project can actually build and qualify. +- The GUI's own cross-platform surface (Linux's `webkit2gtk-4.1` floor, + macOS's webview) stays a prerequisite-documentation problem rather than a + transport problem. + +### Negative + +- Windows users have the CLI, TUI, and Python but not the desktop GUI. +- The GUI's release footprint is narrower than the rest of the product's, so + "one product, many surfaces" now carries a platform qualifier. +- The GUI's code remains Unix-only, so any future Windows work must revisit + `crates/eggsec-frontend-client/src/daemon.rs` even if only to compile. + +### Neutral or deferred + +- **Windows named pipes** — deferred to a future daemon-subsystem milestone. +- **A loopback TCP transport** — not selected; it would weaken the local + access model. +- **Signing, notarization, installers, update channels** — unchanged; owned by + the distribution workstream. +- **The GUI's own build prerequisites on Linux and macOS** — unchanged; + milestone 007 documents them. +- **The egui fallback** — unchanged and still available for its original + purpose. + +## Compatibility and migration + +No protocol, storage, DTO, authorization, or CLI change. No data migration: the +GUI owns no authoritative state, and the supported-platform set is a build and +packaging fact rather than a persisted one. + +There is one operator-visible effect: a Windows operator who expected a +desktop GUI now has the CLI, TUI, and Python surfaces, and the GUI is +documented as unsupported rather than merely unbuilt. + +## Security and reliability implications + +- The GUI's local transport remains a Unix domain socket with `0600` + permissions (`crates/eggsec-daemon/src/server.rs:100-101`). Deferring a + Windows transport avoids introducing a local TCP port whose authentication + would have to be designed separately. +- `plans/000-long-term-specification.md#10-frontend-rules` requires the GUI's + local transport to be loopback-bound. A Unix socket satisfies that by + filesystem locality; a future Windows transport MUST re-establish the same + guarantee, and its ADR MUST address it explicitly. +- No enforcement, scope, or approval semantics change. The GUI remains a + manual surface, and the engine remains the only authorizer. +- Reliability: the supported set now matches the set for which the project can + produce launch, connect, submit, cancel, render, and export evidence, so a + qualified GUI release is one whose behaviour is known. + +## Verification + +Implementation conformance is proved by: + +1. Milestone 007's platform matrix carries exactly two qualified rows (Linux, + macOS) and one row for Windows that is explicitly **out of scope** with its + root cause named — not blank, not "planned", not hopeful. +2. A CI job builds the GUI and runs its test suite on `ubuntu-latest` and + `macos-latest`; **no** Windows GUI job is claimed or required. +3. The Windows exclusion is recorded in `plans/000-long-term-specification.md` + §10, the subsystem roadmap, `plans/registry.md`, and milestone 007's + known-limitations record, so no document implies Windows GUI support. +4. A guard asserts that the GUI's supported-platform claim and its build + matrix agree — that is, that no document claims a Windows GUI build that + does not exist. +5. The cross-compilation evidence is retained in milestone 007's closure + record: `cargo check -p eggsec-gui --no-default-features --target + x86_64-pc-windows-msvc` fails with the unresolved `tokio::net::UnixStream` + import, recorded as the **expected** documented state rather than a + regression. + +## Supersession + +None. diff --git a/plans/adrs/ADR-0011-daemon-manual-capability-policy.md b/plans/adrs/ADR-0011-daemon-manual-capability-policy.md new file mode 100644 index 000000000..7e628d31a --- /dev/null +++ b/plans/adrs/ADR-0011-daemon-manual-capability-policy.md @@ -0,0 +1,406 @@ +# ADR-0011: The daemon's manual capability policy + +Status: accepted + +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` +- `plans/001-terminology-and-domain-model.md` + +Affected subsystem roadmaps: + +- `plans/subsystems/desktop-gui-frontend-roadmap.md` + +## Context + +The maintainer's directive, on 2026-10-24: *"we do not want to block any +capability for manual execution."* + +That directive is unambiguous as an intent and, as written, it does not yet +name a single mechanism — because the repository has **four** independent +mechanisms that can each block a capability, and they currently disagree +with each other. Before any of them can be changed, the layering has to be +stated precisely, because the naive reading ("the daemon's runtime policy is +conservative, widen it") points at the wrong code. + +### The four layers, measured + +| # | Layer | What it decides | Where | Current state | +|---|---|---|---|---| +| 1 | **Publication** | What the daemon *advertises* in its `Capabilities` handshake | `crates/eggsec-daemon/src/host.rs:104-110` | `daemon_conservative() ∩ executor declaration` → **20** of 30 | +| 2 | **Executor declaration** | What the engine's executor says it supports | `crates/eggsec-runtime/src/runtime.rs:68-70` (trait default) | `daemon_conservative()` → **20** of 30 | +| 3 | **Runtime admission** | What `Runtime::submit` will accept | `crates/eggsec-runtime/src/runtime_config.rs:32` | `full_lab()` → **29** of 30 | +| 4 | **Engine enforcement** | Whether the operation may run *at all* | `crates/eggsec-policy/src/policy.rs:106-128`, `crates/eggsec-policy/src/decision.rs:1003-1013` | the operator's `[execution_policy]` risk flags; default **deny** for every hazardous family | + +Two consequences follow immediately, and both were verified against the source +rather than assumed. + +**First, the daemon already admits what it does not advertise.** Layer 3 is +`full_lab()`, not the conservative set: `RuntimeConfig::default()` sets +`capabilities: RuntimeCapabilities::full_lab()` +(`crates/eggsec-runtime/src/runtime_config.rs:32`) and `DaemonHost::new` +builds its runtime with that default (`crates/eggsec-daemon/src/host.rs:119`). +A daemon client can therefore already *submit* `stress-test`, +`wireless-active`, `db-pentest`, `intercept` and `c2`; they are not +rejected as `RuntimeError::UnsupportedTaskKind`. The conservative set governs +only what the daemon *says*. The daemon has never actually refused hazardous +work at the runtime layer. + +**Second, widening publication does not unblock the hazardous families.** +Layer 4 is the real gate, and its denial is a **hard deny**: the +risk-policy denial is explicitly excluded from the confirmation path +(`crates/eggsec-policy/src/decision.rs:1361-1372`), so no `--yes` or +`--allow-*` flag can downgrade it. With a default `ExecutionPolicy`, +`stress-test`, `wireless-active`, the packet family, `db-pentest`, +`intercept` and `c2` are all refused outright, whatever the daemon +advertises. + +### The remaining gaps in the layering itself + +- **`resume` is in neither hand-written list.** The canonical set has 30 + capability names; `daemon_conservative()` has 20 and `full_lab()` has 29. + The missing name is `resume` — a distinct wire kind that shares the + `pipeline` operation identity + (`crates/eggsec-runtime/src/request.rs:630-636`) and is fully implemented + in the engine (`crates/eggsec/src/dispatch/canonical_execution.rs:1451` + → `run_pipeline_resume`). It is advertised nowhere because the lists are + hand-written, not derived. +- **The lists are hand-written, and one of them is duplicated.** The + capability names live as string literals in `daemon_conservative()`, + `full_lab()`, and a private `task_kind_name()` + (`crates/eggsec-runtime/src/capabilities.rs:142-175`) that duplicates + `TaskKind::capability_name()` + (`crates/eggsec-runtime/src/request.rs:562-598`) — two parallel tables + that the repository's own rule ("engine helpers delegate to it, no + parallel tables") forbids. +- **A recovered session enforces a different set than a fresh one.** + `RuntimeSession::hydrate_from_snapshot` sets + `capabilities: RuntimeCapabilities::default()` — the conservative set — + ignoring both the runtime's configured capabilities and the snapshot's own + persisted field. After a daemon restart, recovered sessions enforce 20 + while fresh sessions enforce 29. +- **Four of the ten withheld kinds cannot be submitted at all**, whatever the + capability set says. `packet-capture`, `wireless`, `wireless-active` and + `resume` carry no target in their params, and their operations + (`packet`, `wireless`, `wireless-deauth`, `pipeline`) are all + `TargetPolicyKind::ExplicitScopeRequired`. The descriptor therefore fails + to build. Publishing them as "available" would put a live button in the + GUI that cannot work — the exact failure milestone 006 was built to avoid. +- **A manual daemon client cannot answer a confirmation.** + `ClientCommand::ApprovePolicy` returns `ErrorCode::Unsupported` + (`crates/eggsec-daemon/src/host.rs:928-932`) and the engine's executor + passes `manual_override: None` + (`crates/eggsec/src/runtime_bridge/executor.rs:198`). So even with the policy + flag set, the operation moves from "hard deny" to "requires confirmation" + and then stops there. `RuntimeEvent::PolicyDecisionRequired` exists in the + runtime but **nothing raises it**. +- **The `wireless-active` wire kind is authorised under the passive + operation's policy.** `TaskKind::WirelessActive` maps to operation id + `wireless` (`crates/eggsec-runtime/src/request.rs:653`) — risk `SafeActive`, + capability `PassiveFingerprint`, feature `wireless`. The catalog's + `wireless-deauth` operation (`crates/eggsec-policy/src/catalog.rs`, + risk `Intrusive`, capability `RawPacketProbe`, feature `wireless-advanced`) + is the one the CLI's multiplexer resolves against + (`crates/eggsec/src/commands/registry.rs:406-407`, + `crates/eggsec/src/commands/handlers/wireless.rs:69-70`), and **no runtime + task kind maps to it**. The `Resume` mapping carries an explanatory + comment; this one does not, and the two paths authorise the same + deauth work under different risk levels. + +## Decision drivers + +- **The directive.** No capability may be blocked for manual execution. +- **The roadmap's own completion bar.** `desktop-gui-frontend-roadmap.md` + §11 closes only when "a desktop GUI exists that reaches the engine's full + operation surface through the daemon protocol alone" and "every operation + is reachable from the GUI without per-operation frontend code". That is + unmet today, and this ADR is the decision that unblocks it. +- **Enforcement must not be weakened.** The capability set is an + *advertisement and admission* concern. The operator's risk-policy flags + are the *authorization* concern. They are separate mechanisms in separate + crates, and widening one provably does not touch the other. +- **The operator's consent gate must survive.** "Nothing is blocked" must + not mean "nothing needs the operator to say yes". The existing + `[execution_policy]` flags and the confirmation classes are that gate, and + they are already operator-configurable. +- **The GUI must not offer a button that cannot work.** A published + capability the client cannot actually run is the failure mode milestone + 006's coverage model was built to prevent. +- **The published capability list is a durable wire contract.** It is + consumed by the frontend client and by the GUI, and widening it is a + compatibility event, not a local refactor. +- **One derived list, not four hand-written ones.** Every drift found above + — `resume` missing, the duplicated name table, the hydration inconsistency + — has the same root cause: the lists are transcribed instead of derived. + +## Considered options + +### Option A — Widen publication to the 26 target-bearing kinds + +Publish every capability name whose operation can carry a target +(`stress-test`, `traceroute`, `packet-send`, `db-pentest`, `intercept`, +`c2`), and leave the four interface-bound kinds unpublished. + +- **Benefits.** Smallest possible change to the published contract. No + policy-crate change. The GUI gains six hazard families it can genuinely + run. +- **Costs.** Does not satisfy the directive: four capabilities stay blocked. + It also institutionalises the hand-written list — the four exclusions + would be another hand-maintained carve-out, and the next kind would be + forgotten the same way `resume` was. +- **Failure modes.** The GUI reports four kinds as unavailable with no + principled reason a reader could check. + +### Option B — Widen publication to all 30 and relax the shared operations' target policy + +Publish all 30 canonical capability names, and change `packet`, `wireless` +and `pipeline` from `ExplicitScopeRequired` to `OptionalTarget` so the +four interface-bound kinds can build a descriptor. + +- **Benefits.** Reaches all 30 with no new policy concept. +- **Costs.** The catalog is **operation**-granular while the wire kinds are + finer: `packet` covers `packet-capture` (no target), `traceroute` and + `packet-send` (targets); `wireless` covers `wireless` and + `wireless-active` (neither with a target); `pipeline` covers `pipeline` + (target) and `resume` (no target). Relaxing the shared operation to + `OptionalTarget` would also make **`packet-send` runnable with no target** + — a `RawPacket` operation that writes raw frames to an unspecified + destination. That is a security regression, not a trade. +- **Failure modes.** A raw-packet operation with no destination. + +### Option C — Widen publication to all 30, and give interface-bound operations their own target policy + +Publish all 30, and resolve the four interface-bound kinds with a distinct +target-policy value meaning "this operation binds to a local interface, not +to a network target", rather than by relaxing the operations they share. + +- **Benefits.** The concept already exists in prose — `canonical_target()` + documents `None` as being for "`NoTarget` or **interface-bound** + operations" (`crates/eggsec-runtime/src/request.rs:660-663`) — but has no + representation in `TargetPolicyKind` + (`crates/eggsec-policy/src/target.rs:173-179`). Making it explicit lets + the scope check apply to the local host rather than to a remote target, + which is what an interface-bound operation actually means. +- **Costs.** A change to the policy crate's target lattice, which every + surface's target validation depends on. It is the largest change of the + three and needs its own guard. +- **Failure modes.** A new lattice value that some validation path forgets, + silently admitting an operation with no target where one was required. + +### Option D — Change the `ExecutionPolicy` defaults so nothing is blocked + +Leave the capability sets alone and set every `allow_*` risk flag to `true` +by default. + +- **Benefits.** Literally satisfies "nothing is blocked" in one edit. +- **Costs.** It removes the operator's explicit consent gate for hazardous + work by default, for **every** surface, including the strict ones. The + strict surfaces fail closed on *policy*, not on the capability set; a + default-on risk policy would hand an autonomous agent or a CI run + unattended `RawPacket` and `DbPentest` capability. The capability set is + not where this belongs. +- **Failure modes.** Hazardous operations become the default everywhere. + +## Decision + +**The capability set becomes one derived list, used for both publication and +admission; the enforcement layer is left exactly as it is; and daemon-mediated +approval becomes a prerequisite rather than a follow-up.** + +Specifically: + +1. **One derived capability list.** The workspace holds exactly one list of + capability names, derived from the canonical `TaskKind` set + (`TaskKind::capability_name()` over every variant) and covering all 30 + names, `resume` included. The hand-written `daemon_conservative()` and + `full_lab()` lists are retired, and the private duplicate + `task_kind_name()` table is deleted in favour of delegating to + `TaskKind::capability_name()`. A guard MUST pin that the list is derived, + so that adding a task kind cannot again leave it unadvertised. + +2. **Publication and admission agree by construction.** The daemon's + published set is the derived list intersected with the executor's + declaration, and the daemon's **admitted** set is that same + intersection. The daemon therefore never advertises a capability it will + refuse, and never refuses one it advertised. The no-op daemon still + publishes nothing and admits nothing. + +3. **The engine's executor declares the derived list**, so the daemon's + publication reaches every canonical name the engine can execute. + +4. **Recovered sessions enforce the runtime's set.** Session hydration stops + substituting the conservative default, so a restarted daemon's recovered + sessions admit exactly what its fresh sessions admit. + +5. **Enforcement is untouched.** The operator's `[execution_policy]` risk + flags remain the sole gate for the hazardous families, and the + confirmation classes remain the sole path past them. This ADR records the + proof that widening the capability set does not reach them: the admission + check reads a list of capability *names* from the session, while the + enforcement gate reads the operation descriptor's risk, required + features, required capabilities, the execution policy, the loaded scope + and the enabled-feature set; the enforcement gate runs **inside** the + executor, which is only reached after admission passes; and the + approved-execution bundle re-validates exact descriptor binding before + dispatch. Widening names cannot weaken any of that. + +6. **"Nothing is blocked for manual execution" includes the confirmation + step.** Because a manual daemon client currently cannot answer a + confirmation, the directive is unsatisfiable without daemon-mediated + policy approval. That work is therefore a **prerequisite** of the + capability work, not a later improvement. The daemon must be able to + hold an operation at its confirmation point, expose that decision to the + client, accept the client's answer, and dispatch the held operation. + +7. **A capability the client cannot run is not published as available.** + The four interface-bound kinds (`packet-capture`, `wireless`, + `wireless-active`, `resume`) are resolved by giving interface-bound + operations an explicit target-policy value (Option C's concept), never by + relaxing the operations they share. Until a kind has a coherent target + story, it is reported with an honest reason rather than offered as a + button that fails. + +8. **The `wireless-active` operation identity is corrected before + `wireless-active` is published.** The runtime's mapping to the passive + `wireless` operation — and the resulting divergence from the CLI's + `wireless-deauth` resolution — is a defect independent of this ADR, and + it MUST be closed before the daemon advertises the kind. A deauth task + must not be authorised under the passive operation's risk level. + +9. **The capability set stays surface-agnostic.** There is no "manual + capability list". A manual surface and an automated surface of the same + daemon see the same published list; what differs is the *authorisation* + applied afterwards, which is the enforcement layer's business. A + profile-dependent capability set would duplicate a policy that already + exists, in a place where it would be enforced less well. + +10. **The feature gap stays a separate fact.** A published kind whose engine + feature is compiled out is denied at dispatch with `FeatureMissing`, not + with `UnsupportedTaskKind`. The GUI already distinguishes these, and + the distinction is preserved: "published" means the daemon can execute + it, not that the binary has the feature. + +## Consequences + +### Positive + +- The daemon advertises every canonical capability the engine can execute, + so the GUI's coverage table stops reporting a twenty-kind ceiling. +- Publication and admission agree, so the "advertises twenty, executes + twenty-nine" inconsistency disappears. +- `resume` becomes reachable, and no future task kind can be forgotten in + the same way, because the list is derived. +- The duplicated capability-name table is deleted, restoring the + single-table rule. +- Recovered sessions stop enforcing a different set than fresh ones. +- The operator's consent gate for hazardous work is preserved and made + usable from a remote client. + +### Negative + +- The published capability list is a **breaking change for any consumer that + assumes a fixed set**, and the GUI's coverage model changes shape: kinds + that were `not_advertised` become `available` or become available with a + different reason. +- The hazard families become *offered* to a manual client. They remain + refused by default, but a client now sees them and can attempt them, + which is a visible change in the product's posture even though the + authorisation outcome is unchanged. +- The policy crate gains a target-policy value, which touches every + surface's target validation. +- The daemon gains a suspend-and-resume path for held operations, which is + new runtime machinery. + +### Neutral or deferred + +- The strict surfaces are unaffected: they fail closed on policy, and the + capability set is not their gate. A strict client of the same daemon + still cannot authorise a hazardous operation. +- The CLI and the TUI are unaffected in behaviour. They already run these + operations directly against the engine, and the TUI already has its own + local interactive approval flow. +- The Python bindings' surface is unaffected. +- The TUI's hand-built forms are not migrated by this ADR. That remains the + ADR-gated decision the subsystem roadmap already records. + +## Compatibility and migration + +- **Wire.** The `Capabilities` handshake's `runtime.task_kinds` list widens. + The field is already additive and already has a `#[serde(default)]`-shaped + tolerance on the consumer side, so an old client reading a new daemon + receives a longer list rather than a parse failure. A new client reading + an old daemon receives the old twenty and MUST continue to degrade + honestly — the GUI's coverage model already does this, reporting the + difference rather than hiding it. +- **No storage migration.** No persisted state changes shape. The session + snapshot's capability field is not authoritative — hydration already + ignores it — and the corrected hydration makes that explicit. +- **No protocol version bump.** The change adds list entries; it does not + alter a message shape. The desktop GUI hard-refuses to connect on a + protocol mismatch, so the version stays at `DAEMON_PROTOCOL_VERSION = 2`. +- **Operator configuration.** Nothing is required of an operator to keep + today's behaviour: the risk-policy defaults are unchanged, so the hazard + families remain refused unless an operator opts in. + +## Security and reliability implications + +- **Authorisation is unchanged.** The capability set is not an + authorisation mechanism. The proof is recorded in the decision: the + admission check reads names, the enforcement gate reads risk, features, + capabilities, policy, scope and enabled features, and it runs inside the + executor behind the approved-execution bundle's exact descriptor + re-validation. +- **The operator's consent gate is strengthened, not weakened.** Today a + manual daemon client cannot satisfy a confirmation at all; after this + decision it can, but only by an explicit, deliberate act. +- **The published set no longer implies "safe".** A consumer MUST NOT read + "published" as "permitted". The GUI's coverage model already reports a + distinct reason per verdict; this ADR adds the requirement that a + published-but-policy-denied kind be reported as such, never as available. +- **The `wireless-active` identity defect is a live authorisation + divergence** and is closed as part of this work rather than after it. Until + it is closed, `wireless-active` MUST NOT be published. +- **Four interface-bound kinds carry no network target.** A new target-policy + value must make the scope check apply to the local host, so that an + interface-bound operation is authorised against the machine it runs on and + not against an absent target. +- **Denial of service.** The admitted set widens, so a manual client may now + submit operations that consume raw sockets, saturate a link, or drive a + wireless interface. That is the directive's intent, and the operator's + policy flags remain the gate. + +## Verification + +An implementation of this decision MUST produce: + +- a guard proving the capability list is **derived** from the task-kind + enum, so that no hand-written list can reappear and so that a new task + kind is advertised automatically; +- a test proving the daemon's published set and its admitted set are the + same object, and that a no-op daemon publishes and admits nothing; +- a test proving the engine's executor declares every canonical capability + name; +- a test proving a recovered session admits exactly what a fresh session + admits; +- a test proving the `wireless-active` wire kind resolves to the + `wireless-deauth` operation, and that the `wireless-deauth` catalog + operation is reachable from the runtime; +- a test proving the four interface-bound kinds are either runnable or + reported with an honest reason — never reported as available and then + refused; +- a test proving that widening the capability set does not admit a + policy-denied operation: a `stress-test` submitted to a daemon with the + default execution policy MUST still be refused, with the risk-policy + denial, and not with `UnsupportedTaskKind`; +- an end-to-end proof that a manual daemon client can answer a confirmation + and that the held operation then runs. + +## Supersession + +None. diff --git a/plans/adrs/ADR-0012-daemon-mediated-policy-approval.md b/plans/adrs/ADR-0012-daemon-mediated-policy-approval.md new file mode 100644 index 000000000..9766d39e6 --- /dev/null +++ b/plans/adrs/ADR-0012-daemon-mediated-policy-approval.md @@ -0,0 +1,264 @@ +# ADR-0012: Daemon-mediated Policy Approval + +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 + +ADR-0011 made the daemon publish and admit every canonical capability name for +manual execution. Its Decision section also stated the consequence that +milestone 010 could not itself deliver: + +> The daemon must be able to hold an operation at its confirmation point, +> expose that decision to the client, accept the client's answer, and dispatch +> the held operation. + +Milestone 010 implemented the advertisement and the admission, and deliberately +deferred the confirmation path to milestone 011, because wiring the confirmation +path changes the daemon's **execution** semantics rather than its advertisement. + +The remaining gap is concrete: + +- `EnforcementContext::evaluate()` returns `EnforcementOutcome::RequireConfirmation` + when an operation needs an operator's confirmation — an out-of-scope target, a + high-risk tier, an explicitly excluded target, and so on. For a permissive + manual surface, `approve_manual()` turns that into + `EnforcementError::ConfirmationRequired { decision, required_classes }` + unless the caller supplies a `ManualOverride` that permits every required + class. +- The only way to supply that override today is the CLI's `--allow-*` flags + (`crates/eggsec-cli/src/main.rs`), which are decided **before** the operation + runs, by whoever launched the CLI. +- The daemon's `ClientCommand::ApprovePolicy` handler answers + `ErrorCode::Unsupported` — "not wired yet" + (`crates/eggsec-daemon/src/host.rs`). +- `RuntimeEvent::PolicyDecisionRequired` and `PolicyPrompt` already exist in the + runtime's vocabulary (`crates/eggsec-runtime/src/event.rs`), and the desktop + GUI already models the state (`GuiTaskStatus::AwaitingPolicy`, + `crates/eggsec-gui/src/tasks.rs`). **Nothing produces the event.** The prompt + is a shape with no author. + +So the desktop GUI cannot complete an operation whose policy demands +confirmation. An operator can start the task; they cannot answer it. Milestone +010's advertisement is honest, but the capability it advertises is not +completable through the surface it advertises it on. + +The decision required here is **where the hold lives** and **what an answer +means**. + +## Decision drivers + +- The answer must be **bounded by the policy**. A client answering "yes" must + not be able to grant more than the specific confirmation classes the kernel + demanded for that operation, and must never be able to grant an authorisation + the kernel would not give a manual operator holding the full CLI flag set. +- The answer must be **recorded** — who answered, what they answered, for which + task, and why. +- A surface with **no operator** must not be able to acquire one. A strict + surface (CI, MCP, agent, REST) has no human at a prompt, so it must never be + approvable. +- The hold must be **cancellable and bounded**. An unanswered approval must not + pin a session slot forever. +- Ownership must not blur: the runtime owns task lifecycle, the daemon owns the + process, and `eggsec-policy` owns authorisation semantics. The engine's + runtime bridge must not import daemon types. +- The runtime must stay **policy-neutral**. It is a DTO crate; it must not learn + the policy crate's vocabulary. +- No **parallel lookup tables**: the mapping from a confirmation class to the + override that permits it must exist in exactly one place. + +## Considered options + +### Option A — The daemon host owns the hold + +The daemon holds the pending approval in its own registry; the engine's +executor blocks on a channel the daemon resolves. + +Benefits: the hold lives next to the audit trail and the RBAC matrix. + +Costs: the daemon is not the task-lifecycle owner. The executor would need a +daemon-supplied handle, and the engine's runtime bridge cannot take one — the +engine must not depend on `eggsec-daemon` (guard 155's direction). It also +splits task state across two owners: the runtime's task table and the daemon's +approval table. + +### Option B — The runtime owns the hold + +The runtime holds the pending approval, keyed by session and task, and exposes +both the request and the answer. The engine's executor registers the hold +through a gate carried in `RuntimeExecutionContext`, awaits the answer, and — +on approval — retries the *same* authorisation path with a `ManualOverride` +bounded by the required classes. The daemon's `ApprovePolicy` handler resolves +the hold and records the answer. + +Benefits: one owner of task state; the executor needs no daemon types; the +answer is bounded by the kernel's own vocabulary; cancellation and the task +timeout already belong to the runtime. + +Costs: the runtime gains a small amount of machinery that only the manual path +uses. + +### Option C — No hold; the client re-submits with an override + +The client resubmits the task carrying the override flags it wants. + +Benefits: no new machinery at all. + +Costs: it inverts authority. The client would name the authorisation instead +of the policy, which is the approve-one-dispatch-another shape the +`ApprovedExecution` bundle exists to prevent. It also loses the binding between +the prompt and the answer, and the operator never learns what the policy +actually demanded. Rejected. + +### Option D — The policy crate owns the hold + +Rejected for the same authority inversion, and because `eggsec-policy` is a pure +kernel with no Tokio and no task lifecycle. + +## Decision + +**Option B.** The runtime holds the operation; the answer is a bounded override. + +1. **The runtime owns the hold.** `eggsec-runtime` gains an approval registry. + A cheap clonable handle (`ApprovalGate`) is carried in + `RuntimeExecutionContext`, so an executor can register a pending decision and + await its answer. `Runtime` exposes the answering side (`resolve_approval`) + and the observing side (`pending_approval`). The registry is in-memory and + per-process; a pending entry is removed when it is answered, when the holding + task is cancelled, or when the task's timeout fires. + +2. **The hold is registered before the client is told.** The executor registers + the pending decision and *then* emits + `RuntimeEvent::PolicyDecisionRequired`. A client that answers immediately + therefore never races the registration. + +3. **The answer is bounded by the required classes.** The kernel's + `EnforcementError::ConfirmationRequired` carries the `ConfirmationClass` + values it demanded. Those classes are mapped, in **one** place + (`eggsec-policy`), to the `ManualOverride` fields that permit them. The + executor then retries the *same* `approve_run_request_bundle` call with that + override. It does not construct an `ApprovedExecution` itself and it does + not bypass the kernel. If the retry still fails, the task fails closed. + +4. **A strict surface never holds.** The hold exists only where the execution + surface honours manual overrides. A strict surface's `approve_manual` path + refuses to be confirmed by anyone, so the executor registers no hold at all + and the operation is refused exactly as it is today. + +5. **The daemon's `ApprovePolicy` becomes the answer path.** It resolves the + runtime's pending approval. The existing RBAC is unchanged and still + applies: `CommandPermission::Approver`, with `Owner`, `Controller`, and + `Approver` permitted on a manual surface and `Owner` only on a strict + surface. The daemon records the answer in the audit trail with the + answering client's identity, the session, the session's surface, and the + outcome. The audit schema is unchanged: a session holds at most one active + task, so the session identifies the decision, and the operator's free-text + reason is not persisted. + +6. **The runtime stays policy-neutral.** The registry stores a `PolicyPrompt` — + a message, a confirmation-class label, and a flag — not a `ConfirmationClass`. + The gate returns an answer (`approved` or `denied`, with a reason); it does + not interpret authorisation. Only `eggsec-policy` decides what an approval + permits. + +7. **The client contract gains one method.** `RuntimeClient` gains an approval + method, so the GUI reaches the daemon through the same frontend-neutral + contract it uses for everything else. + +## Consequences + +### Positive + +- The desktop GUI can complete an operation whose policy demands confirmation: + the operator sees the prompt, answers, and the held operation proceeds. +- The answer is bounded by the kernel's own demand; a client cannot widen its + own authorisation. +- Strict surfaces are unaffected: they never hold, so there is nothing to + approve. +- One owner of task state, and one owner of authorisation semantics. + +### Negative + +- The runtime gains machinery that only the manual path uses. +- The answer is a "yes" to a *specific* set of classes. The operator cannot + widen it at answer time — widening is the CLI's `--allow-*` flags, decided + before the run. This is deliberate. +- A pending approval holds the session's single active-task slot until it is + answered, cancelled, or the task times out (300 s default). + +### Neutral or deferred + +- The approval registry is **not** persisted. A daemon restart drops pending + approvals, and the held task dies with the process. +- The TUI's local approval path is unchanged and does not use the runtime's + gate. Its confirmation-class→override mapping is refactored onto the shared + policy helper so the table exists once, but the TUI's prompt flow stays local. +- The REST surface keeps its existing approval route; its path-arity defect is + corrected so the route is callable. + +## Compatibility and migration + +- **Wire protocol**: unchanged. `ClientCommand::ApprovePolicy`, `ErrorCode`, + and `RuntimeEvent::PolicyDecisionRequired` all already exist. A daemon that + gains the wired handler remains compatible with an older client, which would + only ever have received an event it never had. +- **`RuntimeClient` trait**: gains one method. This is source-breaking for + external implementors of the trait; the two in-tree implementations + (`DaemonRuntimeClient`, `EmbeddedRuntimeClient`) are updated in the same + change. +- **Protocol version**: unchanged. No message shape changes; only the daemon's + behaviour in response to a command that previously always failed. +- **No storage migration**: the approval registry is in-memory. + +## Security and reliability implications + +- **Authorisation**: the answer grants exactly the confirmation classes the + kernel demanded, computed by the kernel. The client names *yes* or *no*; it + never names the authorisation. +- **Scope**: unchanged. An approval does not relax the scope check — the retry + re-runs the whole authorisation path, scope included. +- **Audit**: the answer is recorded with the answering client's identity, the + session, the session's surface, and the outcome. The operator's reason is + carried to the executor, which logs the approval; it is stored as text and + never evaluated, and it is not persisted in the audit trail. +- **Cancellation**: a cancelled task drops its pending approval. The registry + entry cannot outlive the task. +- **Denial of service**: an unanswered approval holds one session's single + active-task slot for at most the task timeout. +- **Replay**: an answer resolves one pending entry, which is removed on use. A + second answer for the same task finds nothing pending and is refused as + invalid state. +- **Surface confusion**: a strict session has no pending approval to answer; + the answer path refuses rather than guessing. + +## Verification + +- The runtime's registry: register → answer → the holding task resumes; cancel + → the entry is gone; answer twice → the second is refused. +- The engine: an operation that demands confirmation holds; after approval it + proceeds; after denial it fails with the operator's reason; a strict surface + never holds. +- The daemon: `ApprovePolicy` on a held task succeeds and is audited; on a + task with nothing pending it is refused as invalid state; a client without + the approver role is refused by the RBAC. +- The client contract: the GUI answers through `RuntimeClient`, and the answer + reaches the daemon. +- The mapping: the confirmation-class→override mapping exists in exactly one + place. + +## Supersession + +None. 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..b96fd1878 --- /dev/null +++ b/plans/adrs/ADR-0013-daemon-endpoint-default-and-bind-contract.md @@ -0,0 +1,279 @@ +# ADR-0013: Daemon Endpoint Default and Bind Contract + +Status: accepted + +Date: 2026-10-24 + +Ratified: 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 + +**Accepted: Option C — the default lives in `eggsec-runtime`.** + +The maintainer ratified this proposal on 2026-10-24. `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/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: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 +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: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: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). + +### 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:840-843`) | +| `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:4768-4834`). +- **`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. +- **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 + +- **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:861-864`). +- **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:739-745`). +- 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: 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 `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`): + +```rust +/// The engine features compiled into this executor's build. +/// +/// `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`, +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: + +```rust +ClientCommand::GetTaskReport { request_id, session_id, task_id } +ServerMessage::TaskReport { request_id, session_id, task_id, report } +``` + +> **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 +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 — corrected by a third finding.** The plan's option 1 + assumed that a self-contained HTML rendering could be *embedded* inside the + GUI webview. It cannot. The GUI's CSP + (`crates/eggsec-gui/tauri.conf.json:23`) is + `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'`, and + that forbids the document three ways: `frame-src 'none'` rules out an + iframe, `script-src 'self'` means an inline `