From 622d10cf683815645485098889f67c23e3f638a8 Mon Sep 17 00:00:00 2001 From: poli0981 Date: Wed, 2 Dec 2026 19:48:43 +0700 Subject: [PATCH 1/3] build: add the Cargo workspace skeleton and xtask MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The M0 exit criterion is "CI green on an empty workspace" (doc 17 §3), so the workspace exists before any product crate: a virtual manifest with xtask as its only member, the doc 13 §2 lints, the doc 15 §2 profiles, rust-toolchain.toml (1.100.0 with rustfmt, clippy, llvm-tools), rustfmt.toml, clippy.toml (the doc 13 §5 bans clippy can express), deny.toml (doc 14 §4) and a nextest `ci` profile. xtask implements the gates CI and doc 14 §4 rely on: - `rules`: the doc 03 §3 layer table on direct first-party dependencies, GPUI / network clients / `windows` confined to their crates, and #![forbid(unsafe_code)] at every crate root except mv-platform; - `coverage `: the doc 14 §2 per-crate line-coverage thresholds; - `check`: rustfmt, clippy, cargo-deny, cargo-machete, then `rules`. Its only dependencies are anyhow and serde_json at the doc 02 versions (anyhow held at 1.0.104 with --precise). deny.toml passes with cargo-deny 0.22.1 and with 0.20.2, the version the ops security.yml runs. rustfmt's imports_granularity and group_imports are still nightly-only on 1.100.0, so doc 13 §1 now says so instead of setting them; doc 02 and doc 13 record the other details. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 7 + .config/nextest.toml | 13 ++ Cargo.lock | 112 +++++++++++++++ Cargo.toml | 64 +++++++++ clippy.toml | 20 +++ deny.toml | 79 +++++++++++ docs/02_TECH_STACK.md | 4 +- docs/13_CODESTYLE.md | 20 ++- rust-toolchain.toml | 7 + rustfmt.toml | 6 + xtask/Cargo.toml | 16 +++ xtask/src/coverage.rs | 261 ++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 152 ++++++++++++++++++++ xtask/src/metadata.rs | 179 +++++++++++++++++++++++ xtask/src/rules.rs | 322 ++++++++++++++++++++++++++++++++++++++++++ xtask/src/run.rs | 50 +++++++ 16 files changed, 1308 insertions(+), 4 deletions(-) create mode 100644 .cargo/config.toml create mode 100644 .config/nextest.toml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 clippy.toml create mode 100644 deny.toml create mode 100644 rust-toolchain.toml create mode 100644 rustfmt.toml create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/coverage.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/metadata.rs create mode 100644 xtask/src/rules.rs create mode 100644 xtask/src/run.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..c21e3ff --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,7 @@ +[alias] +# `cargo xtask check | rules | coverage ` (doc 15 §3). +xtask = "run --package xtask --quiet --" + +# Dependencies come from crates.io only (doc 15 §5). No other registry or git +# source is configured here, and deny.toml's [sources] section is what fails +# the build if one appears. diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000..07e2932 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,13 @@ +# cargo-nextest configuration (doc 14 §1). CI runs `--profile ci`. +# +# Tests that change the machine (clipboard, registry, hotkeys, tray, Windows +# Hello) are `#[ignore]`d with a `machine` reason. Neither profile runs ignored +# tests; they are run by hand in a VM (doc 14 §9, doc 15 §4.4). + +[profile.default] +slow-timeout = { period = "60s", terminate-after = 5 } + +[profile.ci] +# Report every failure in one run rather than stopping at the first. +fail-fast = false +slow-timeout = { period = "60s", terminate-after = 5 } diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e59c61d --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,112 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "xtask" +version = "0.0.0" +dependencies = [ + "anyhow", + "serde_json", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d65ff89 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,64 @@ +[workspace] +resolver = "3" +# Crates join as they are created (doc 03 §2): crates/mv-*, bins/*, fuzz stays +# outside the workspace (cargo-fuzz builds it with nightly). +members = ["xtask"] + +[workspace.package] +edition = "2024" +rust-version = "1.100" +license = "GPL-3.0-only" +repository = "https://git.poli0981.dev/poli0981/mutevault" +publish = false + +# Every version is declared once here and inherited (doc 13 §1). Each one is the +# exact version recorded in doc 02; Cargo.lock pins it. +[workspace.dependencies] +anyhow = "1.0.104" +serde_json = "1.0.154" + +# Doc 13 §2. Lints that apply to one layer only (`clippy::indexing_slicing` in +# parsers, `clippy::arithmetic_side_effects` in mv-vault and mv-interop) are set +# with a crate-level attribute in those crates, because a crate that inherits +# these lints cannot also extend them in its Cargo.toml. mv-platform does not +# inherit `unsafe_code = "forbid"`: it carries its own [lints] table (rule 4). +[workspace.lints.rust] +unsafe_code = "forbid" +rust_2018_idioms = { level = "deny", priority = -1 } +unused_must_use = "deny" +missing_docs = "warn" + +[workspace.lints.clippy] +undocumented_unsafe_blocks = "deny" +# Allowed in tests through clippy.toml. +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +todo = "deny" +unimplemented = "deny" +dbg_macro = "deny" +print_stdout = "deny" +print_stderr = "deny" +# The bans themselves are listed in clippy.toml (doc 13 §5). +disallowed_types = "deny" +disallowed_methods = "deny" + +# Doc 15 §2. +[profile.dev] +opt-level = 1 + +# Dependencies, including argon2 and the ciphers: a debug build must still +# unlock a vault in reasonable time. +[profile.dev.package."*"] +opt-level = 3 + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 +# Destructors must run so secrets are zeroised. +panic = "unwind" +# Arithmetic on untrusted lengths must not wrap. +overflow-checks = true +strip = "symbols" +debug = false diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..73101c3 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,20 @@ +# Doc 13 §2: these are denied outside tests only. +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-print-in-tests = true + +# Doc 13 §5. Clippy can only ban a path for the whole workspace, so each ban +# below applies everywhere, and a crate the doc allows (xtask, mv-platform) +# opts out at the call site with `#[allow(clippy::disallowed_…, reason = "…")]`. +# Bans that concern one crate or a crate not yet in the tree (`std::fs::write` +# in mv-vault, `SystemTime::now` in domain code, `rand`) are added together with +# that crate. +disallowed-types = [ + { path = "std::process::Command", reason = "only xtask and mv-platform start processes (doc 13 §5)" }, +] +disallowed-methods = [ + { path = "std::env::var", reason = "secrets are never read from the environment (doc 13 §5); a non-secret variable is read with an explicit allow and a reason" }, + { path = "std::env::var_os", reason = "secrets are never read from the environment (doc 13 §5); a non-secret variable is read with an explicit allow and a reason" }, + { path = "std::string::String::from_utf8_lossy", reason = "decode explicitly and fallibly (doc 13 §5)" }, +] diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..3e694b4 --- /dev/null +++ b/deny.toml @@ -0,0 +1,79 @@ +# cargo-deny configuration (doc 14 §4, doc 15 §5). +# +# Run by the ops `security.yml` (job "Rust (cargo-deny)", `rust: true`), which pins +# cargo-deny 0.20.2, and locally by `cargo xtask check` with the version in doc 02. +# Keep this file valid for both: check a change with each before committing. + +[graph] +targets = ["x86_64-pc-windows-msvc", "x86_64-unknown-linux-gnu"] +all-features = true + +[advisories] +# Vulnerabilities and unsound advisories always fail. Yanked crates fail too. +yanked = "deny" +# Doc 14 §4 asks for "unmaintained → warn"; cargo-deny can no longer lower the +# level, only the scope. Unmaintained advisories fail for crates the workspace +# depends on directly, where the choice is ours, and are skipped further down. +unmaintained = "workspace" +ignore = [] + +[licenses] +# GPL-3.0-compatible licences only (doc 14 §4). Anything else is a decision +# recorded in doc 02 before it is added here. +allow = [ + "MIT", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "0BSD", + "Zlib", + "Unicode-3.0", + "MPL-2.0", + "CC0-1.0", + "Unlicense", +] +confidence-threshold = 0.9 +# The list is doc 14 §4's policy, not an inventory of today's tree: a licence no +# crate uses yet is not worth a warning on every run. +unused-allowed-license = "allow" + +[licenses.private] +# The workspace's own crates are GPL-3.0-only and unpublished. +ignore = true + +[bans] +multiple-versions = "warn" +wildcards = "deny" +# Workspace path dependencies carry no version; they are not wildcards from a +# registry. +allow-wildcard-paths = true +deny = [ + # Network code lives only in mv-net (CLAUDE.md rule 5, doc 03 §9). No crate + # may pull an HTTP, TLS or socket stack today. The change that adds mv-net + # gives the one client it uses `wrappers = ["mv-net"]` (allowed only as + # mv-net's direct dependency) — not every entry, or cargo-deny warns about + # each unused wrapper on every run. + # The Velopack crate brings its own HTTP client for updates; spike S9 decides + # how that fits rule 5 before `velopack` is added (doc 17 §6). + { crate = "reqwest", reason = "network code only in mv-net" }, + { crate = "ureq", reason = "network code only in mv-net" }, + { crate = "hyper", reason = "network code only in mv-net" }, + { crate = "h2", reason = "network code only in mv-net" }, + { crate = "isahc", reason = "network code only in mv-net" }, + { crate = "curl", reason = "network code only in mv-net" }, + { crate = "quinn", reason = "network code only in mv-net" }, + { crate = "rustls", reason = "network code only in mv-net" }, + { crate = "native-tls", reason = "network code only in mv-net" }, + # Doc 14 §4: no OpenSSL on Windows. cargo-deny cannot scope a ban to one target; + # revisit when the Fedora build is brought up (v1.x, doc 15 §1). + { crate = "openssl-sys", reason = "no OpenSSL in the Windows build (doc 14 §4)" }, + { crate = "openssl", reason = "no OpenSSL in the Windows build (doc 14 §4)" }, +] + +[sources] +# crates.io only; no git dependencies (doc 14 §4). +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = [] diff --git a/docs/02_TECH_STACK.md b/docs/02_TECH_STACK.md index 06c4cba..c07a5fa 100644 --- a/docs/02_TECH_STACK.md +++ b/docs/02_TECH_STACK.md @@ -64,7 +64,7 @@ so the framework and component versions always match. |---|---|---|---| | `serde` | 1.0.229 | MIT OR Apache-2.0 | Serialisation framework | | `ciborium` | 0.2.2 | Apache-2.0 | CBOR payload codec | -| `serde_json` | 1.0.154 | MIT OR Apache-2.0 | IPC messages, JSON import/export | +| `serde_json` | 1.0.154 | MIT OR Apache-2.0 | IPC messages, JSON import/export; reading `cargo metadata` in `xtask` | | `csv` | 1.4.0 | Unlicense/MIT | CSV import/export | | `keepass` | 0.17.0 | MIT | KDBX 3/4 import (read-only use) | | `zip` | 9.8.1 | MIT | 1PUX and CXF archives (P1) | @@ -113,7 +113,7 @@ dependencies. |---|---|---| | `cargo-nextest` | 0.9.152 | Test runner | | `cargo-llvm-cov` | 0.9.2 | Coverage (LCOV and HTML report; per-crate thresholds in CI) | -| `cargo-deny` | 0.22.0 | Advisories, licences, bans, sources | +| `cargo-deny` | 0.22.0 | Advisories, licences, bans, sources. In CI it runs inside the ops `security.yml`, which pins **0.20.2**; `deny.toml` is kept valid for both versions | | `cargo-audit` | 0.23.0 | Local RustSec check; CI relies on osv-scanner and `cargo-deny` | | `cargo-vet` | 0.10.3 | Dependency audits (P1) | | `cargo-fuzz` | 0.13.2 | libFuzzer targets | diff --git a/docs/13_CODESTYLE.md b/docs/13_CODESTYLE.md index 2d8b5ff..b41d25b 100644 --- a/docs/13_CODESTYLE.md +++ b/docs/13_CODESTYLE.md @@ -5,8 +5,11 @@ ## 1. Rust baseline - Edition 2024, toolchain pinned in `rust-toolchain.toml`. -- `rustfmt` defaults plus `max_width = 100`, `imports_granularity = "Crate"`, - `group_imports = "StdExternalCrate"`. +- `rustfmt` defaults plus `max_width = 100`, `edition = "2024"` and + `newline_style = "Unix"`. Imports are grouped std / external / crate and merged per + crate. `imports_granularity` and `group_imports` would enforce that, but they are + still nightly-only in rustfmt 1.100.0 (checked 2026-12-02), so `rustfmt.toml` does not + set them and the grouping is kept by hand until they are stable. - All dependency versions are declared once in `[workspace.dependencies]` and inherited. - `Cargo.lock` is committed; CI builds with `--locked`. @@ -29,6 +32,11 @@ Declared in `[workspace.lints]` and inherited by every crate. CI runs `cargo clippy --workspace --all-targets -- -D warnings`. +A crate that inherits `[workspace.lints]` cannot add to them in its `Cargo.toml`, so the +two layer-specific lints (`indexing_slicing`, `arithmetic_side_effects`) are crate-level +attributes in the crates concerned, and `mv-platform` carries its own `[lints]` table +instead of inheriting `unsafe_code = "forbid"`. + ## 3. Structure and naming - One concept per module; files under roughly 400 lines; split before they grow. @@ -73,6 +81,14 @@ CI runs `cargo clippy --workspace --all-targets -- -D warnings`. | `println!`, `eprintln!`, `dbg!` | `tracing` | | `String::from_utf8_lossy` on secret bytes | Explicit, fallible decoding | +Clippy can only ban a path for the whole workspace. The root `clippy.toml` therefore bans +`std::process::Command`, `std::env::var`, `std::env::var_os` and +`String::from_utf8_lossy` everywhere, and code the table allows (xtask, `mv-platform`, a +non-secret variable such as `MUTEVAULT_DATA_DIR`) opts out at the call site with +`#[allow(clippy::disallowed_…, reason = "…")]`. The bans that concern a single crate or a +crate not yet in the workspace (`std::fs::write` in `mv-vault`, `SystemTime::now` in +domain code, `rand`) are added together with that crate. + ## 6. Logging - `tracing` with structured fields. Levels: `error` (operation failed), `warn` diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..df3054c --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,7 @@ +# The one place the Rust version lives (doc 02 §1). CI reads it: the Windows job +# with `rustup toolchain install`, the Linux job by passing `channel` to the +# toolchain action. Release builds are rebuildable from this pin (doc 15 §11). +[toolchain] +channel = "1.100.0" +components = ["rustfmt", "clippy", "llvm-tools"] +profile = "minimal" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..eb0aea9 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,6 @@ +# Doc 13 §1. `imports_granularity` and `group_imports` are still nightly-only in +# rustfmt 1.100.0 (stable prints a warning and ignores them), so they are not set +# here; keep imports grouped std / external / crate by hand. +edition = "2024" +max_width = 100 +newline_style = "Unix" diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..156ecfb --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "xtask" +version = "0.0.0" +description = "Developer tasks for the MuteVault workspace: checks, layer rules, coverage gate" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/xtask/src/coverage.rs b/xtask/src/coverage.rs new file mode 100644 index 0000000..d61ca56 --- /dev/null +++ b/xtask/src/coverage.rs @@ -0,0 +1,261 @@ +//! Per-crate line-coverage gate over an LCOV report (doc 14 §2). +//! +//! Lines are attributed to a crate by the `crates//` segment of each source +//! path, so the report of `cargo llvm-cov nextest --workspace --lcov` is enough. + +use std::collections::BTreeMap; + +use anyhow::{Context, Result, bail}; + +/// Minimum line coverage in percent (doc 14 §2). `mv-platform` (best effort, FFI) +/// and `mv-ui` (not gated) are deliberately absent. +pub const THRESHOLDS: &[(&str, u64)] = &[ + ("mv-core", 90), + ("mv-crypto", 90), + ("mv-vault", 90), + ("mv-otp", 90), + ("mv-ipc", 80), + ("mv-passkey", 80), + ("mv-interop", 80), + ("mv-app", 80), +]; + +/// Instrumented and executed line counts. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Lines { + pub found: u64, + pub hit: u64, +} + +impl Lines { + /// Coverage with one decimal, computed in integers. + pub fn percent(self) -> String { + if self.found == 0 { + return String::from("-"); + } + let tenths = self.hit.saturating_mul(1000) / self.found; + format!("{}.{}", tenths / 10, tenths % 10) + } +} + +/// The verdict for one gated crate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Outcome { + Passed, + Below, + /// The crate is in the workspace but the report has no line of it. + NoData, + /// The crate does not exist yet: nothing to check. + NotInWorkspace, +} + +impl Outcome { + pub fn is_checked(self) -> bool { + self != Self::NotInWorkspace + } + + pub fn passed(self) -> bool { + matches!(self, Self::Passed | Self::NotInWorkspace) + } + + pub fn label(self) -> &'static str { + match self { + Self::Passed => "ok", + Self::Below => "BELOW THRESHOLD", + Self::NoData => "NO COVERAGE DATA", + Self::NotInWorkspace => "not in workspace", + } + } +} + +/// One row of the gate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Row { + pub krate: &'static str, + pub threshold: u64, + pub lines: Lines, + pub outcome: Outcome, +} + +/// Applies [`THRESHOLDS`] to an LCOV report; `members` are the workspace members. +pub fn evaluate(lcov: &str, members: &[&str]) -> Result> { + let totals = per_crate(lcov)?; + Ok(THRESHOLDS + .iter() + .map(|&(krate, threshold)| { + let lines = totals.get(krate).copied().unwrap_or_default(); + let outcome = if !members.contains(&krate) { + Outcome::NotInWorkspace + } else if lines.found == 0 { + Outcome::NoData + } else if lines.hit.saturating_mul(100) >= threshold.saturating_mul(lines.found) { + Outcome::Passed + } else { + Outcome::Below + }; + Row { + krate, + threshold, + lines, + outcome, + } + }) + .collect()) +} + +/// Sums the line counts of an LCOV report per `crates//` directory. +/// Files outside `crates/` (bins, xtask) are ignored. +pub fn per_crate(lcov: &str) -> Result> { + let mut totals: BTreeMap = BTreeMap::new(); + let mut current: Option = None; + let mut from_da = Lines::default(); + let mut from_summary = Lines::default(); + + for (index, line) in lcov.lines().enumerate() { + let number = index.saturating_add(1); + let line = line.trim(); + if let Some(path) = line.strip_prefix("SF:") { + current = crate_of(path); + from_da = Lines::default(); + from_summary = Lines::default(); + } else if let Some(record) = line.strip_prefix("DA:") { + let count = + da_count(record).with_context(|| format!("LCOV line {number}: `{line}`"))?; + from_da.found = from_da.found.saturating_add(1); + if count > 0 { + from_da.hit = from_da.hit.saturating_add(1); + } + } else if let Some(value) = line.strip_prefix("LF:") { + from_summary.found = parse_count(value, number)?; + } else if let Some(value) = line.strip_prefix("LH:") { + from_summary.hit = parse_count(value, number)?; + } else if line == "end_of_record" + && let Some(krate) = current.take() + { + // DA records are the detail; LF/LH only stand in when they are absent. + let lines = if from_da.found > 0 { + from_da + } else { + from_summary + }; + let total = totals.entry(krate).or_default(); + total.found = total.found.saturating_add(lines.found); + total.hit = total.hit.saturating_add(lines.hit); + } + } + Ok(totals) +} + +/// `/…/crates//…` → ``, for both `/` and `\` separators. +fn crate_of(path: &str) -> Option { + let normalized = format!("/{}", path.replace('\\', "/")); + let (_, rest) = normalized.rsplit_once("/crates/")?; + let (name, _) = rest.split_once('/')?; + (!name.is_empty()).then(|| name.to_owned()) +} + +/// `DA:,[,]` → count. +fn da_count(record: &str) -> Result { + let mut fields = record.split(','); + let (Some(line), Some(count)) = (fields.next(), fields.next()) else { + bail!("a DA record needs `,`"); + }; + line.parse::() + .context("DA line number is not a number")?; + count.parse::().context("DA count is not a number") +} + +fn parse_count(value: &str, number: usize) -> Result { + value + .parse() + .with_context(|| format!("LCOV line {number}: `{value}` is not a count")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(path: &str, hits: &[u64]) -> String { + let mut out = format!("SF:{path}\n"); + for (i, hit) in hits.iter().enumerate() { + out.push_str(&format!("DA:{},{hit}\n", i + 1)); + } + out.push_str(&format!("LF:{}\nLH:999\nend_of_record\n", hits.len())); + out + } + + fn hits(hit: usize, miss: usize) -> Vec { + let mut v = vec![3; hit]; + v.extend(std::iter::repeat_n(0, miss)); + v + } + + #[test] + fn lines_are_summed_per_crate_for_windows_and_unix_paths() { + let lcov = [ + record(r"E:\mutevault\crates\mv-core\src\lib.rs", &hits(8, 2)), + record("/w/crates/mv-core/src/url.rs", &hits(10, 0)), + record("/w/crates/mv-crypto/src/kdf.rs", &hits(1, 1)), + record("/w/xtask/src/main.rs", &hits(0, 50)), + ] + .concat(); + let totals = per_crate(&lcov).unwrap(); + assert_eq!(totals.len(), 2); + assert_eq!(totals["mv-core"], Lines { found: 20, hit: 18 }); + assert_eq!(totals["mv-crypto"], Lines { found: 2, hit: 1 }); + } + + #[test] + fn summary_counts_stand_in_when_there_are_no_da_records() { + let lcov = "SF:/w/crates/mv-otp/src/lib.rs\nLF:10\nLH:7\nend_of_record\n"; + assert_eq!( + per_crate(lcov).unwrap()["mv-otp"], + Lines { found: 10, hit: 7 } + ); + } + + #[test] + fn the_threshold_is_inclusive_and_a_shortfall_fails() { + let lcov = [ + record("/w/crates/mv-core/src/lib.rs", &hits(9, 1)), + record("/w/crates/mv-vault/src/lib.rs", &hits(89, 11)), + record("/w/crates/mv-app/src/lib.rs", &hits(4, 1)), + ] + .concat(); + let rows = evaluate(&lcov, &["mv-core", "mv-vault", "mv-app"]).unwrap(); + let outcome = |name: &str| rows.iter().find(|r| r.krate == name).unwrap().outcome; + assert_eq!(outcome("mv-core"), Outcome::Passed); + assert_eq!(outcome("mv-vault"), Outcome::Below); + assert_eq!(outcome("mv-app"), Outcome::Passed); + assert_eq!(outcome("mv-crypto"), Outcome::NotInWorkspace); + } + + #[test] + fn a_gated_crate_without_lines_in_the_report_fails() { + let rows = evaluate("", &["mv-crypto"]).unwrap(); + let crypto = rows.iter().find(|r| r.krate == "mv-crypto").unwrap(); + assert_eq!(crypto.outcome, Outcome::NoData); + assert!(!crypto.outcome.passed()); + } + + #[test] + fn an_empty_workspace_has_nothing_to_check() { + let rows = evaluate("", &["xtask"]).unwrap(); + assert!( + rows.iter() + .all(|r| !r.outcome.is_checked() && r.outcome.passed()) + ); + } + + #[test] + fn a_malformed_da_record_is_an_error() { + assert!(per_crate("SF:/w/crates/mv-core/a.rs\nDA:1\nend_of_record\n").is_err()); + assert!(per_crate("SF:/w/crates/mv-core/a.rs\nDA:x,1\nend_of_record\n").is_err()); + } + + #[test] + fn percent_is_rounded_down_to_one_decimal() { + assert_eq!(Lines { found: 3, hit: 2 }.percent(), "66.6"); + assert_eq!(Lines { found: 0, hit: 0 }.percent(), "-"); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..918e4bf --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,152 @@ +//! Developer tasks for the MuteVault workspace (doc 15 §3). +//! +//! - `cargo xtask check`: the local gate before a push: rustfmt, clippy, cargo-deny, +//! cargo-machete and the workspace rules, in that order. +//! - `cargo xtask rules`: the dependency and `unsafe` rules of doc 03 §3 (CI runs this). +//! - `cargo xtask coverage `: the per-crate line-coverage gate of doc 14 §2. + +#![forbid(unsafe_code)] +#![allow( + clippy::print_stdout, + clippy::print_stderr, + reason = "xtask is a developer command-line tool: its output is the product" +)] + +mod coverage; +mod metadata; +mod rules; +mod run; + +use std::{fs, process::ExitCode}; + +use anyhow::{Context, Result, bail}; + +const USAGE: &str = "\ +usage: cargo xtask + +commands: + check rustfmt, clippy, cargo-deny, cargo-machete, then `rules` + rules dependency layers, confined crates and #![forbid(unsafe_code)] (doc 03 §3) + coverage per-crate line-coverage thresholds over an LCOV report (doc 14 §2)"; + +fn main() -> ExitCode { + match run_command() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("error: {error:#}"); + ExitCode::FAILURE + } + } +} + +fn run_command() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + match args + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + ["check"] => check(), + ["rules"] => check_rules(), + ["coverage", lcov] => check_coverage(lcov), + ["help" | "--help" | "-h"] => { + println!("{USAGE}"); + Ok(()) + } + _ => bail!("unknown or incomplete command\n\n{USAGE}"), + } +} + +/// The local gate: every blocking static check of doc 14 §4 that runs without CI. +fn check() -> Result<()> { + let steps: [(&str, &[&str], &str); 4] = [ + ( + "rustfmt", + &["fmt", "--all", "--check"], + "run `cargo fmt --all`", + ), + ( + "clippy", + &[ + "clippy", + "--workspace", + "--all-targets", + "--locked", + "--", + "-D", + "warnings", + ], + "fix the lints above", + ), + ( + "cargo-deny", + &["deny", "check"], + "needs cargo-deny (doc 15 §1 step 4)", + ), + ( + "cargo-machete", + &["machete"], + "needs cargo-machete (doc 15 §1 step 4)", + ), + ]; + for (name, args, hint) in steps { + println!("==> {name}"); + run::cargo_status(args).with_context(|| format!("{name} failed: {hint}"))?; + } + println!("==> workspace rules"); + check_rules() +} + +fn check_rules() -> Result<()> { + let packages = metadata::load()?; + let violations = rules::check(&packages, |path| fs::read_to_string(path)); + if violations.is_empty() { + println!( + "workspace rules: {} crate(s) checked, no violation", + packages.len() + ); + return Ok(()); + } + for violation in &violations { + println!(" - {violation}"); + } + bail!( + "{} workspace rule violation(s) (doc 03 §3)", + violations.len() + ) +} + +fn check_coverage(lcov_path: &str) -> Result<()> { + let lcov = fs::read_to_string(lcov_path) + .with_context(|| format!("cannot read the LCOV report `{lcov_path}`"))?; + let packages = metadata::load()?; + let members: Vec<&str> = packages.iter().map(|p| p.name.as_str()).collect(); + let rows = coverage::evaluate(&lcov, &members)?; + + let checked: Vec<_> = rows.iter().filter(|row| row.outcome.is_checked()).collect(); + if checked.is_empty() { + println!("coverage: no gated crate is in the workspace yet (doc 14 §2), nothing to check"); + return Ok(()); + } + println!( + "{:<12} {:>8} {:>8} {:>8} {:>10} result", + "crate", "lines", "covered", "percent", "threshold" + ); + for row in &checked { + println!( + "{:<12} {:>8} {:>8} {:>8} {:>9}% {}", + row.krate, + row.lines.found, + row.lines.hit, + row.lines.percent(), + row.threshold, + row.outcome.label() + ); + } + let failed = checked.iter().filter(|row| !row.outcome.passed()).count(); + if failed > 0 { + bail!("{failed} crate(s) below their coverage threshold (doc 14 §2)"); + } + Ok(()) +} diff --git a/xtask/src/metadata.rs b/xtask/src/metadata.rs new file mode 100644 index 0000000..94a06bb --- /dev/null +++ b/xtask/src/metadata.rs @@ -0,0 +1,179 @@ +//! The workspace members and their direct dependencies, read from `cargo metadata`. + +use std::path::PathBuf; + +use anyhow::{Context, Result, bail}; +use serde_json::Value; + +/// How a dependency is declared. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DepKind { + Normal, + Dev, + Build, +} + +impl DepKind { + /// A suffix for messages: empty for normal dependencies. + pub fn suffix(self) -> &'static str { + match self { + Self::Normal => "", + Self::Dev => " (dev-dependency)", + Self::Build => " (build-dependency)", + } + } +} + +/// A direct dependency, by package name (a `rename` does not hide it). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Dependency { + pub name: String, + pub kind: DepKind, +} + +/// A workspace member. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Package { + pub name: String, + pub dependencies: Vec, + /// Root source files of the library, binary and proc-macro targets. + pub crate_roots: Vec, +} + +/// Target kinds whose root file must carry the crate-level attributes. +const ROOT_KINDS: &[&str] = &[ + "lib", + "rlib", + "dylib", + "cdylib", + "staticlib", + "proc-macro", + "bin", +]; + +/// Reads the workspace members. `--no-deps` lists only the members, with their +/// declared dependencies, and needs no dependency resolution. +pub fn load() -> Result> { + let json = + crate::run::cargo_output(&["metadata", "--format-version", "1", "--no-deps", "--locked"])?; + parse(&json) +} + +/// Parses the JSON of `cargo metadata --format-version 1`. +pub fn parse(json: &str) -> Result> { + let root: Value = serde_json::from_str(json).context("cargo metadata did not print JSON")?; + let Some(packages) = root.get("packages").and_then(Value::as_array) else { + bail!("cargo metadata printed no `packages` array"); + }; + packages.iter().map(parse_package).collect() +} + +fn parse_package(package: &Value) -> Result { + let name = string_field(package, "name")?; + let dependencies = array_field(package, "dependencies") + .iter() + .map(parse_dependency) + .collect::>>() + .with_context(|| format!("package `{name}`"))?; + let mut crate_roots = Vec::new(); + for target in array_field(package, "targets") { + let is_root = array_field(target, "kind") + .iter() + .filter_map(Value::as_str) + .any(|kind| ROOT_KINDS.contains(&kind)); + if is_root { + crate_roots.push(PathBuf::from(string_field(target, "src_path")?)); + } + } + Ok(Package { + name, + dependencies, + crate_roots, + }) +} + +fn parse_dependency(dependency: &Value) -> Result { + let name = string_field(dependency, "name")?; + let kind = match dependency.get("kind").and_then(Value::as_str) { + None => DepKind::Normal, + Some("dev") => DepKind::Dev, + Some("build") => DepKind::Build, + Some(other) => bail!("dependency `{name}` has an unknown kind `{other}`"), + }; + Ok(Dependency { name, kind }) +} + +fn string_field(value: &Value, field: &str) -> Result { + value + .get(field) + .and_then(Value::as_str) + .map(str::to_owned) + .with_context(|| format!("missing string field `{field}` in cargo metadata")) +} + +fn array_field<'a>(value: &'a Value, field: &str) -> &'a [Value] { + value + .get(field) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = r#"{ + "packages": [{ + "name": "mv-vault", + "dependencies": [ + { "name": "mv-crypto", "kind": null, "rename": null }, + { "name": "tempfile", "kind": "dev", "rename": null }, + { "name": "cc", "kind": "build", "rename": "compiler" } + ], + "targets": [ + { "kind": ["lib"], "src_path": "/w/crates/mv-vault/src/lib.rs" }, + { "kind": ["test"], "src_path": "/w/crates/mv-vault/tests/save.rs" }, + { "kind": ["custom-build"], "src_path": "/w/crates/mv-vault/build.rs" } + ] + }], + "workspace_members": [] + }"#; + + #[test] + fn parses_members_dependencies_and_crate_roots() { + let packages = parse(SAMPLE).unwrap(); + assert_eq!(packages.len(), 1); + let vault = &packages[0]; + assert_eq!(vault.name, "mv-vault"); + let deps: Vec<_> = vault + .dependencies + .iter() + .map(|d| (d.name.as_str(), d.kind)) + .collect(); + assert_eq!( + deps, + [ + ("mv-crypto", DepKind::Normal), + ("tempfile", DepKind::Dev), + ("cc", DepKind::Build) + ] + ); + assert_eq!( + vault.crate_roots, + [PathBuf::from("/w/crates/mv-vault/src/lib.rs")] + ); + } + + #[test] + fn rejects_output_without_packages() { + assert!(parse(r#"{ "workspace_members": [] }"#).is_err()); + assert!(parse("not json").is_err()); + } + + #[test] + fn rejects_an_unknown_dependency_kind() { + let json = r#"{ "packages": [{ "name": "a", "targets": [], + "dependencies": [{ "name": "b", "kind": "weird" }] }] }"#; + assert!(parse(json).is_err()); + } +} diff --git a/xtask/src/rules.rs b/xtask/src/rules.rs new file mode 100644 index 0000000..315fb15 --- /dev/null +++ b/xtask/src/rules.rs @@ -0,0 +1,322 @@ +//! Workspace rules checked on `cargo metadata` and the crate roots: +//! +//! - the layer table of doc 03 §3 for first-party dependencies; +//! - third-party crates confined to named members (GPUI, network clients, `windows`); +//! - `#![forbid(unsafe_code)]` at every crate root except `mv-platform` (CLAUDE.md rule 4). +//! +//! Direct dependencies only. Transitive network crates are cargo-deny's job +//! (`deny.toml`, `[bans]` with `wrappers`). + +use std::{io, path::Path}; + +use crate::metadata::Package; + +const INFRASTRUCTURE: &[&str] = &[ + "mv-vault", + "mv-otp", + "mv-passkey", + "mv-interop", + "mv-ipc", + "mv-platform", + "mv-net", +]; +const BINARIES: &[&str] = &["mutevault", "mutevault-host", "mutevault-cli"]; + +/// The first-party crates a member may depend on directly, or `None` when the +/// member is not in doc 03 §3 at all. +fn allowed_first_party(member: &str) -> Option<&'static [&'static str]> { + const DOMAIN_AND_CRYPTO: &[&str] = &["mv-core", "mv-crypto"]; + const BELOW_APPLICATION: &[&str] = &[ + "mv-core", + "mv-crypto", + "mv-vault", + "mv-otp", + "mv-passkey", + "mv-interop", + "mv-ipc", + "mv-platform", + "mv-net", + ]; + Some(match member { + "mv-core" | "xtask" => &[], + "mv-crypto" => &["mv-core"], + m if INFRASTRUCTURE.contains(&m) => DOMAIN_AND_CRYPTO, + "mv-app" => BELOW_APPLICATION, + "mv-ui" | "mutevault-cli" => &["mv-app", "mv-core"], + // main() starts the UI (doc 03 §2). + "mutevault" => &["mv-ui", "mv-app", "mv-core"], + // A stateless relay: framing only, never crypto or the vault (doc 03 §3). + "mutevault-host" => &["mv-ipc"], + _ => return None, + }) +} + +fn is_first_party(name: &str, members: &[&str]) -> bool { + name.starts_with("mv-") + || BINARIES.contains(&name) + || name == "xtask" + || members.contains(&name) +} + +/// HTTP, TLS and socket client crates (CLAUDE.md rule 5). +const NETWORK_CRATES: &[&str] = &[ + "reqwest", + "ureq", + "hyper", + "hyper-util", + "h2", + "h3", + "quinn", + "isahc", + "curl", + "attohttpc", + "minreq", + "surf", + "rustls", + "native-tls", + "openssl", + "tokio-rustls", + "tungstenite", + "tokio-tungstenite", + "socket2", +]; + +/// (crates, members allowed to depend on them directly, reason). +const CONFINED: &[(&[&str], &[&str], &str)] = &[ + ( + &["gpui", "gpui-kit", "gpui-component"], + &["mv-ui", "mutevault"], + "GPUI appears only in mv-ui and bins/mutevault (doc 03 §3)", + ), + ( + NETWORK_CRATES, + &["mv-net"], + "network code lives only in mv-net (CLAUDE.md rule 5)", + ), + ( + &["windows", "windows-sys"], + &["mv-platform", "mutevault-host"], + "the windows crate appears only in mv-platform and mutevault-host (doc 03 §3)", + ), +]; + +/// The only member allowed to contain `unsafe` (CLAUDE.md rule 4). +const UNSAFE_ALLOWED: &str = "mv-platform"; + +/// Checks every member; `read` returns the source of a crate root. +pub fn check(packages: &[Package], read: impl Fn(&Path) -> io::Result) -> Vec { + let members: Vec<&str> = packages.iter().map(|p| p.name.as_str()).collect(); + let mut violations = Vec::new(); + for package in packages { + check_layers(package, &members, &mut violations); + check_confined(package, &mut violations); + check_unsafe(package, &read, &mut violations); + } + violations +} + +fn check_layers(package: &Package, members: &[&str], violations: &mut Vec) { + let Some(allowed) = allowed_first_party(&package.name) else { + violations.push(format!( + "`{}` is not in the layer table of doc 03 §3: add it there and to xtask's rules first", + package.name + )); + return; + }; + for dep in &package.dependencies { + if is_first_party(&dep.name, members) && !allowed.contains(&dep.name.as_str()) { + violations.push(format!( + "`{}` depends on `{}`{}: doc 03 §3 allows only [{}]", + package.name, + dep.name, + dep.kind.suffix(), + allowed.join(", ") + )); + } + } +} + +fn check_confined(package: &Package, violations: &mut Vec) { + for dep in &package.dependencies { + for (crates, owners, reason) in CONFINED { + if crates.contains(&dep.name.as_str()) && !owners.contains(&package.name.as_str()) { + violations.push(format!( + "`{}` depends on `{}`{}: {reason}", + package.name, + dep.name, + dep.kind.suffix() + )); + } + } + } +} + +fn check_unsafe( + package: &Package, + read: &impl Fn(&Path) -> io::Result, + violations: &mut Vec, +) { + if package.name == UNSAFE_ALLOWED { + return; + } + for root in &package.crate_roots { + match read(root) { + Ok(source) if forbids_unsafe(&source) => {} + Ok(_) => violations.push(format!( + "`{}` ({}) lacks `#![forbid(unsafe_code)]` (CLAUDE.md rule 4)", + package.name, + root.display() + )), + Err(error) => violations.push(format!( + "`{}`: cannot read {}: {error}", + package.name, + root.display() + )), + } + } +} + +/// True when the source has an inner `#![forbid(…)]` attribute listing `unsafe_code`. +fn forbids_unsafe(source: &str) -> bool { + source.lines().any(|line| { + let compact: String = line.chars().filter(|c| !c.is_whitespace()).collect(); + compact + .strip_prefix("#![forbid(") + .and_then(|rest| rest.strip_suffix(")]")) + .is_some_and(|lints| lints.split(',').any(|lint| lint == "unsafe_code")) + }) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + use crate::metadata::{DepKind, Dependency}; + + const FORBID: &str = "//! A crate.\n#![forbid(unsafe_code)]\n"; + + fn package(name: &str, deps: &[(&str, DepKind)]) -> Package { + Package { + name: name.to_owned(), + dependencies: deps + .iter() + .map(|&(name, kind)| Dependency { + name: name.to_owned(), + kind, + }) + .collect(), + crate_roots: vec![PathBuf::from(format!("{name}/src/lib.rs"))], + } + } + + fn check_all(packages: &[Package]) -> Vec { + check(packages, |_| Ok(FORBID.to_owned())) + } + + #[test] + fn a_workspace_that_follows_the_layers_passes() { + let packages = [ + package("mv-core", &[("serde", DepKind::Normal)]), + package("mv-crypto", &[("mv-core", DepKind::Normal)]), + package( + "mv-vault", + &[("mv-crypto", DepKind::Normal), ("mv-core", DepKind::Dev)], + ), + package( + "mv-net", + &[("ureq", DepKind::Normal), ("mv-core", DepKind::Normal)], + ), + package( + "mv-app", + &[("mv-vault", DepKind::Normal), ("mv-net", DepKind::Normal)], + ), + package( + "mv-ui", + &[("mv-app", DepKind::Normal), ("gpui-kit", DepKind::Normal)], + ), + package( + "mutevault", + &[("mv-ui", DepKind::Normal), ("gpui-kit", DepKind::Normal)], + ), + package( + "mutevault-host", + &[("mv-ipc", DepKind::Normal), ("windows", DepKind::Normal)], + ), + package("xtask", &[("anyhow", DepKind::Normal)]), + ]; + assert_eq!(check_all(&packages), Vec::::new()); + } + + #[test] + fn an_upward_dependency_is_reported() { + let violations = check_all(&[package("mv-core", &[("mv-crypto", DepKind::Dev)])]); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("`mv-core` depends on `mv-crypto` (dev-dependency)")); + } + + #[test] + fn the_host_may_not_reach_the_vault_or_crypto() { + let violations = check_all(&[package( + "mutevault-host", + &[ + ("mv-ipc", DepKind::Normal), + ("mv-vault", DepKind::Normal), + ("mv-crypto", DepKind::Normal), + ], + )]); + assert_eq!(violations.len(), 2, "{violations:?}"); + } + + #[test] + fn a_member_missing_from_the_layer_table_is_reported() { + let violations = check_all(&[package("mv-sync", &[])]); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("not in the layer table")); + } + + #[test] + fn confined_crates_outside_their_owners_are_reported() { + let violations = check_all(&[ + package("mv-app", &[("reqwest", DepKind::Normal)]), + package("mv-vault", &[("gpui", DepKind::Normal)]), + package("mv-ipc", &[("windows-sys", DepKind::Build)]), + ]); + assert_eq!(violations.len(), 3, "{violations:?}"); + assert!(violations[0].contains("only in mv-net")); + assert!(violations[1].contains("GPUI")); + assert!(violations[2].contains("(build-dependency)")); + } + + #[test] + fn a_crate_root_without_forbid_unsafe_is_reported_except_in_mv_platform() { + let packages = [ + package("mv-core", &[]), + package("mv-platform", &[("mv-core", DepKind::Normal)]), + ]; + let violations = check(&packages, |_| Ok(String::from("//! No attribute.\n"))); + assert_eq!(violations.len(), 1, "{violations:?}"); + assert!(violations[0].starts_with("`mv-core`")); + } + + #[test] + fn an_unreadable_crate_root_is_reported() { + let violations = check(&[package("mv-core", &[])], |_| { + Err(io::ErrorKind::NotFound.into()) + }); + assert_eq!(violations.len(), 1); + assert!(violations[0].contains("cannot read")); + } + + #[test] + fn forbid_unsafe_is_recognised_only_as_an_inner_forbid_attribute() { + assert!(forbids_unsafe("#![forbid(unsafe_code)]")); + assert!(forbids_unsafe( + " #![ forbid( missing_docs, unsafe_code ) ]" + )); + assert!(!forbids_unsafe("// #![forbid(unsafe_code)]")); + assert!(!forbids_unsafe("#![deny(unsafe_code)]")); + assert!(!forbids_unsafe("#[forbid(unsafe_code)]")); + assert!(!forbids_unsafe("#![forbid(unsafe_op_in_unsafe_fn)]")); + } +} diff --git a/xtask/src/run.rs b/xtask/src/run.rs new file mode 100644 index 0000000..743d863 --- /dev/null +++ b/xtask/src/run.rs @@ -0,0 +1,50 @@ +//! Starts cargo and its subcommands. + +#![allow( + clippy::disallowed_types, + reason = "xtask is one of the two crates allowed to start processes (doc 13 §5)" +)] + +use std::{ffi::OsString, process::Command}; + +use anyhow::{Context, Result, bail}; + +/// The cargo that started xtask, so a subcommand runs on the same toolchain. +#[allow( + clippy::disallowed_methods, + reason = "CARGO is the path cargo sets for its subprocesses, not a secret" +)] +fn cargo() -> OsString { + std::env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")) +} + +/// Runs `cargo ` with the terminal attached and fails if it fails. +pub fn cargo_status(args: &[&str]) -> Result<()> { + let status = Command::new(cargo()) + .args(args) + .status() + .with_context(|| format!("cannot start `cargo {}`", args.join(" ")))?; + if !status.success() { + bail!("`cargo {}` exited with {status}", args.join(" ")); + } + Ok(()) +} + +/// Runs `cargo ` and returns its standard output. +pub fn cargo_output(args: &[&str]) -> Result { + let output = Command::new(cargo()) + .args(args) + .output() + .with_context(|| format!("cannot start `cargo {}`", args.join(" ")))?; + if !output.status.success() { + let stderr = String::from_utf8(output.stderr) + .unwrap_or_else(|_| String::from("(standard error was not UTF-8)")); + bail!( + "`cargo {}` exited with {}:\n{stderr}", + args.join(" "), + output.status + ); + } + String::from_utf8(output.stdout) + .with_context(|| format!("`cargo {}` printed non-UTF-8 output", args.join(" "))) +} -- 2.54.1 From 8d134532bbba8df0f2c338f52c5ef9a4e168297e Mon Sep 17 00:00:00 2001 From: poli0981 Date: Wed, 2 Dec 2026 19:53:19 +0700 Subject: [PATCH 2/3] ci: add the Gitea Actions workflows and Renovate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The M0 set from doc 15 §4.2, each checked against the ops repo at v2026.11.5 (b93b3711), the tag A-01 waited for: - ci.yml: `linux` (container) runs rustfmt, clippy, `cargo xtask rules`, cargo-machete and the tests under cargo-llvm-cov with the per-crate gate; `windows` (host mode) runs clippy and nextest with the toolchain from rust-toolchain.toml via `rustup toolchain install --no-self-update` (never `rustup default`, never dtolnay on the PC) and MUTEVAULT_DATA_DIR in the job's temp dir; `ci-ok` is the required check. nextest, llvm-cov and machete are release binaries at the doc 02 versions, SHA-256 verified, run from the job's temp directory. - security.yml: `workflow-lint` (actionlint + shellcheck, zizmor) and the ops security.yml with rust and node; weekly 57 13 * * 2. - qodana.yml: qodana-rust through the ops reusable on windows-latest in Docker (-u root, CARGO_HOME in the cache); push to main and weekly 9 14 * * 5; report-only. - notify-ci-failure.yml: the ops notifier for CI, Security and Qodana. - renovate.json: the central preset, nothing else. Deferred until there is something to run: extension.yml (M3), fuzz.yml (first fuzz target; slot 17 15 * * 6 kept), release.yml and announce-release.yml (M5, after S9). Docs follow the runbook where it differs: Qodana Cloud only takes github/gitlab/bitbucket VCS URLs, so the project points at the GitLab mirror (doc 14 §6, doc 15 §14.5); doc 15 lists the required checks, the ops pin, the host-mode toolchain rule and the secrets needed at M0; doc 02 records how CI pins the cargo tools and the Qodana image. actionlint 1.7.12 and zizmor 1.32.0 (offline, medium) pass on all four workflows locally. Co-Authored-By: Claude Opus 5.5 --- .gitea/actionlint.yaml | 11 ++ .gitea/requirements-ci.in | 4 + .gitea/requirements-ci.txt | 18 +++ .gitea/workflows/ci.yml | 207 +++++++++++++++++++++++++ .gitea/workflows/notify-ci-failure.yml | 29 ++++ .gitea/workflows/qodana.yml | 41 +++++ .gitea/workflows/security.yml | 101 ++++++++++++ .gitea/zizmor.yml | 10 ++ docs/02_TECH_STACK.md | 8 +- docs/14_TESTING_QUALITY.md | 19 ++- docs/15_BUILD_RELEASE.md | 74 ++++++--- qodana.yaml | 24 +++ renovate.json | 4 + 13 files changed, 523 insertions(+), 27 deletions(-) create mode 100644 .gitea/actionlint.yaml create mode 100644 .gitea/requirements-ci.in create mode 100644 .gitea/requirements-ci.txt create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitea/workflows/notify-ci-failure.yml create mode 100644 .gitea/workflows/qodana.yml create mode 100644 .gitea/workflows/security.yml create mode 100644 .gitea/zizmor.yml create mode 100644 qodana.yaml create mode 100644 renovate.json diff --git a/.gitea/actionlint.yaml b/.gitea/actionlint.yaml new file mode 100644 index 0000000..5f51469 --- /dev/null +++ b/.gitea/actionlint.yaml @@ -0,0 +1,11 @@ +# actionlint settings (security.yml, job `workflow-lint`, and a local +# `actionlint -config-file .gitea/actionlint.yaml .gitea/workflows/*.yml`), as in +# the ops repo poli0981/.github. Only Gitea features that actionlint does not +# know are ignored here; everything else stays an error. +paths: + .gitea/workflows/*.yml: + ignore: + # Gitea's own token scope for releases (ops runbook §3.2 item 5); release.yml (M5) + - 'unknown permission scope "releases"' + # Gitea resolves full-URL actions; bare owner/repo goes to github.com (ops runbook §1) + - 'specifying action "https://gitea\.com/[^"]+" in invalid format' diff --git a/.gitea/requirements-ci.in b/.gitea/requirements-ci.in new file mode 100644 index 0000000..0758b91 --- /dev/null +++ b/.gitea/requirements-ci.in @@ -0,0 +1,4 @@ +# Python tools the workflows run (security.yml, job `workflow-lint`: zizmor). +# Lock: requirements-ci.txt, regenerated by Renovate (pip-compile manager) or by +# the command in its header. +zizmor==1.32.0 diff --git a/.gitea/requirements-ci.txt b/.gitea/requirements-ci.txt new file mode 100644 index 0000000..3c97dc7 --- /dev/null +++ b/.gitea/requirements-ci.txt @@ -0,0 +1,18 @@ +# zizmor for security.yml (job `workflow-lint`), hash-locked. zizmor is a +# self-contained wheel with no Python dependencies. Regenerate (and let +# Renovate's pip-compile manager keep it current) with: +# uv pip compile .gitea/requirements-ci.in --generate-hashes --python-platform x86_64-manylinux_2_28 --python-version 3.12 -o .gitea/requirements-ci.txt +zizmor==1.32.0 \ + --hash=sha256:0a999c98015becd9f69919ce01febadfb1c2be9b8ec2ce9ef7eb13ff23ba8eba \ + --hash=sha256:0cdd38fca6eb34ceb567548548d706332e3535ea66894b9168c048e03207b68c \ + --hash=sha256:3f404b26791ed06a5ea9eaa0bfd5b973fc5228bac7db8b3c5ec7f0c7ad2ed16d \ + --hash=sha256:84a6acb975accc13408786a2bd274b572537ca19c933ebbc13e78f3988562071 \ + --hash=sha256:913fd3943bc1358aa6e23b33fe01cc98bf67af23985258b8fbf24eaa2f8728ea \ + --hash=sha256:9cd1dd7734042f40ca0faa2a31fb4e9033dede620d996af2f903744b8f04fca9 \ + --hash=sha256:aa4b4e216321dd5cf202cd79fc83296468f0eed79d850cd65ac8187a6bbc5496 \ + --hash=sha256:bddcdb0e37d1aa53c9f831c55627a5829d0d552cb0afb4b80fbe16a3a3140366 \ + --hash=sha256:d34dcfa702875202b4163d90ebb9cc5222f3d1a7d4b72bf796d87b5a15b24194 \ + --hash=sha256:dd818f99d833b86cd432d5412d620d936b5df074b33404fff8b67acff55d3259 \ + --hash=sha256:eaedf57859f026a0a7da2a6b574517b1fe01e256c6875b3319a06ee1cee026a7 \ + --hash=sha256:f0b664d394576e08605fe8094e8e992056d74b808f30c0c9ca9ed227001dcf67 + # via -r .gitea/requirements-ci.in diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..131ba22 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,207 @@ +name: CI + +# Lint, workspace rules, tests and the coverage gate on every push to main and +# every pull request (doc 15 §4.2, doc 14 §4). Gitea Actions; forge and runner +# facts are in the ops runbook (poli0981/.github, docs/GITEA-MIGRATION.md). +# +# - `windows-latest` is HOST MODE on the maintainer's PC (doc 15 §4.4). The +# toolchain comes from the PC's own rustup through rust-toolchain.toml, with +# `rustup toolchain install --no-self-update`: never `rustup default`, never +# dtolnay/rust-toolchain there (it sets the default, and once left the PC's +# `stable` broken). Tools run from the job's temp directory, the app's data +# goes to MUTEVAULT_DATA_DIR under it, and tests #[ignore]d for touching the +# machine never run: no `--ignored`, no `--include-ignored`. +# - `ubuntu-latest` is a Docker container (docker.gitea.com/runner-images): +# rustfmt, clippy, the workspace rules, unused dependencies, and the tests +# under coverage with the per-crate gate. +# - cargo-nextest, cargo-llvm-cov and cargo-machete are release binaries at the +# doc 02 versions, SHA-256 verified. Renovate does not update them: bump the +# version and the checksum together, by hand (doc 02 §3). +# - `ci-ok` is the check branch protection requires: `CI / ci-ok (*)`. + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + # Only superseded pull-request runs are cancelled; every commit on main gets a full run. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: '0' + # nextest reads its profile from here, also under `cargo llvm-cov nextest`. + NEXTEST_PROFILE: ci + NEXTEST_VERSION: 0.9.152 + +jobs: + linux: + name: Linux · fmt, clippy, rules, tests, coverage + runs-on: ubuntu-latest # Gitea: Docker, docker.gitea.com/runner-images + timeout-minutes: 45 + permissions: + contents: read + env: + NEXTEST_SHA256: d039b43c3e0958441b6ad0a39c8884d018b3d2e8fb9928f209074b1100b5e17a # cargo-nextest-0.9.152-x86_64-unknown-linux-gnu.tar.gz (no checksum file upstream; hashed 2026-12-02) + LLVM_COV_VERSION: 0.9.2 + LLVM_COV_SHA256: 1e0ed5c64f11e9217f7b9d7c776b3125eab26f27d49313919c909881a2fc7cff # cargo-llvm-cov-x86_64-unknown-linux-gnu.tar.gz v0.9.2 (no checksum file upstream; hashed 2026-12-02) + MACHETE_VERSION: 0.10.1 + MACHETE_SHA256: 785d381985140ffa172246d82089adeb7f2eb9c774d961c48f77a4494023afb5 # cargo-machete-v0.10.1-x86_64-unknown-linux-musl.tar.gz (the release's .sha256) + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Read the pinned toolchain + id: toolchain + run: | + channel="$(sed -n 's/^channel *= *"\(.*\)"/\1/p' rust-toolchain.toml)" + test -n "$channel" || { echo "::error::no channel in rust-toolchain.toml"; exit 1; } + echo "channel=$channel" >> "$GITHUB_OUTPUT" + + # In this container only. rust-toolchain is pinned to a MASTER commit and + # given its toolchain: its `stable` branch is regenerated on top of master, + # so a commit of that branch can disappear. + - name: Setup Rust + uses: dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc # master + with: + toolchain: ${{ steps.toolchain.outputs.channel }} + components: rustfmt, clippy, llvm-tools + + # Build scripts need a C linker. The job container runs as root; sudo only + # where there is one. + - name: C toolchain + run: | + if command -v cc >/dev/null 2>&1; then cc --version | head -n 1; exit 0; fi + SUDO=""; if command -v sudo >/dev/null 2>&1 && [ "$(id -u)" != 0 ]; then SUDO=sudo; fi + $SUDO apt-get -o Acquire::Retries=5 update -q + $SUDO apt-get -o Acquire::Retries=5 install -y -q --no-install-recommends build-essential + + - name: Install cargo-nextest, cargo-llvm-cov and cargo-machete + run: | + set -euo pipefail + tmp="${RUNNER_TEMP:-/tmp}" + bin="$tmp/cargo-tools" + mkdir -p "$bin" + fetch() { # + curl -fsSL --retry 3 -o "$tmp/$3" "$1" + echo "$2 $tmp/$3" | sha256sum -c - + } + fetch "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-${NEXTEST_VERSION}/cargo-nextest-${NEXTEST_VERSION}-x86_64-unknown-linux-gnu.tar.gz" \ + "$NEXTEST_SHA256" nextest.tar.gz + tar -xzf "$tmp/nextest.tar.gz" -C "$bin" cargo-nextest + fetch "https://github.com/taiki-e/cargo-llvm-cov/releases/download/v${LLVM_COV_VERSION}/cargo-llvm-cov-x86_64-unknown-linux-gnu.tar.gz" \ + "$LLVM_COV_SHA256" llvm-cov.tar.gz + tar -xzf "$tmp/llvm-cov.tar.gz" -C "$bin" cargo-llvm-cov + fetch "https://github.com/bnjbvr/cargo-machete/releases/download/v${MACHETE_VERSION}/cargo-machete-v${MACHETE_VERSION}-x86_64-unknown-linux-musl.tar.gz" \ + "$MACHETE_SHA256" machete.tar.gz + tar -xzf "$tmp/machete.tar.gz" -C "$bin" --strip-components=1 \ + "cargo-machete-v${MACHETE_VERSION}-x86_64-unknown-linux-musl/cargo-machete" + echo "$bin" >> "$GITHUB_PATH" + + - name: rustfmt + run: cargo fmt --all --check + + # The whole workspace today. When mv-ui and the GUI binary join it, they are + # excluded here (`--exclude mv-ui --exclude mutevault`) and build on the + # Windows job only (doc 15 §4.2). + - name: clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + + - name: Workspace rules (doc 03 §3) + run: cargo xtask rules + + - name: Unused dependencies + run: cargo machete + + - name: Tests under coverage + run: | + cargo llvm-cov nextest --workspace --locked --lcov --output-path target/lcov.info + cargo llvm-cov report --html --output-dir target/coverage + + - name: Coverage gate (doc 14 §2) + run: cargo xtask coverage target/lcov.info + + - name: Keep the coverage report + if: ${{ !cancelled() }} + uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4 + with: + name: coverage + path: | + target/lcov.info + target/coverage/html + if-no-files-found: ignore + retention-days: 14 + + windows: + name: Windows · clippy, tests + runs-on: windows-latest # HOST MODE on the maintainer's PC (doc 15 §4.4) + timeout-minutes: 45 + permissions: + contents: read + defaults: + run: + shell: pwsh + env: + NEXTEST_SHA256: cc6bf4b6a7ac18e462cd6c9bae67e26921b888249c2988c6acabf3df387ed9d6 # cargo-nextest-0.9.152-x86_64-pc-windows-msvc.zip (no checksum file upstream; hashed 2026-12-02) + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # Installs the channel and components rust-toolchain.toml names, if missing. + # It changes neither the PC's default toolchain nor rustup itself. + - name: Toolchain from rust-toolchain.toml + run: | + rustup --version + rustup toolchain install --no-self-update + rustup show active-toolchain + cargo --version + + - name: Install cargo-nextest + run: | + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $tmp = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } else { [IO.Path]::GetTempPath() } + $zip = Join-Path $tmp 'nextest.zip' + Invoke-WebRequest -UseBasicParsing -OutFile $zip ` + -Uri "https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-$($env:NEXTEST_VERSION)/cargo-nextest-$($env:NEXTEST_VERSION)-x86_64-pc-windows-msvc.zip" + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $zip).Hash.ToLowerInvariant() + if ($hash -ne $env:NEXTEST_SHA256) { Write-Host "::error::cargo-nextest checksum mismatch: $hash"; exit 1 } + $bin = Join-Path $tmp 'cargo-tools' + Expand-Archive -LiteralPath $zip -DestinationPath $bin -Force + $bin >> $env:GITHUB_PATH + + - name: clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + + - name: Tests + env: + MUTEVAULT_DATA_DIR: ${{ runner.temp }}\mutevault-data + run: cargo nextest run --workspace --locked + + # The check branch protection requires. + ci-ok: + name: ci-ok + if: ${{ always() }} + needs: [linux, windows] + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: {} + steps: + - name: All CI jobs passed + env: + LINUX: ${{ needs.linux.result }} + WINDOWS: ${{ needs.windows.result }} + run: | + echo "linux: $LINUX, windows: $WINDOWS" + test "$LINUX" = success && test "$WINDOWS" = success diff --git a/.gitea/workflows/notify-ci-failure.yml b/.gitea/workflows/notify-ci-failure.yml new file mode 100644 index 0000000..9e4187a --- /dev/null +++ b/.gitea/workflows/notify-ci-failure.yml @@ -0,0 +1,29 @@ +name: Notify CI failures + +# A failed run of the workflows below on `main` posts to Discord through the +# ops repo's notify-ci-failure.yml (its script is loaded at `ops_ref`, the same +# commit as `uses:`). The name starts with "Notify", so the notifier never +# reports itself. Neither this file nor the shared one checks out the +# triggering run's code: they read run metadata only and pass every untrusted +# field to the notifier through `env:`. +# +# Add a workflow's `name:` here when it is created (Extension, Fuzz). + +on: + workflow_run: # zizmor: ignore[dangerous-triggers] + workflows: ['CI', 'Security', 'Qodana'] + types: [completed] + +permissions: {} + +jobs: + notify: + permissions: + contents: read + actions: read + uses: poli0981/.github/.gitea/workflows/notify-ci-failure.yml@b93b3711b3049a879cfdfd515f7e72c23864da8f # ops v2026.11.5 + with: + default_branch: main + ops_ref: b93b3711b3049a879cfdfd515f7e72c23864da8f + secrets: + DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }} diff --git a/.gitea/workflows/qodana.yml b/.gitea/workflows/qodana.yml new file mode 100644 index 0000000..e6f7575 --- /dev/null +++ b/.gitea/workflows/qodana.yml @@ -0,0 +1,41 @@ +name: Qodana + +# JetBrains Qodana for Rust (qodana-rust, Early Access) over the workspace, +# through the ops repo's reusable-qodana.yml (Qodana CLI). Findings go to Qodana +# Cloud and to the `qodana-report` artifact; Gitea has no code-scanning UI. +# Report-only: the EAP linter is not a gate (doc 14 §4, risk R-08), so +# qodana.yaml sets no failureConditions. +# +# - qodana-rust exists only as an image: it runs on the Windows host in Docker +# Desktop (`within-docker`), as root, with the crates in the Qodana cache +# (`-u root -e CARGO_HOME=…`, ops runbook §3.5). Spike S10 confirms it works +# here and whether it can analyse the UI crates once they exist (doc 17 §2). +# - Runs that Renovate starts skip the scan (the reusable says why). +# - Not on pull requests (doc 15 §4.2). Weekly as well: Friday 14:09 UTC = +# 21:09 Vietnam (slot in the ops repo's cron registry). + +on: + push: + branches: [main] + schedule: + - cron: '9 14 * * 5' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: qodana-${{ github.ref }} + cancel-in-progress: false + +jobs: + rust: + permissions: + contents: read + uses: poli0981/.github/.gitea/workflows/reusable-qodana.yml@b93b3711b3049a879cfdfd515f7e72c23864da8f # ops v2026.11.5 + with: + runs-on: windows-latest + within-docker: true + extra-args: -u root -e CARGO_HOME=/data/cache/cargo + secrets: + QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }} diff --git a/.gitea/workflows/security.yml b/.gitea/workflows/security.yml new file mode 100644 index 0000000..d86102e --- /dev/null +++ b/.gitea/workflows/security.yml @@ -0,0 +1,101 @@ +name: Security + +# Gitea has no CodeQL, no dependency review and no code-scanning UI (ops +# runbook §1). This workflow covers (doc 14 §4, §6): +# +# workflow-lint actionlint + shellcheck and zizmor over .gitea/workflows/*.yml +# scan the ops repo's security.yml: gitleaks (full history), Opengrep +# (Rust and TypeScript rules), osv-scanner (Cargo.lock; later +# pnpm-lock.yaml) and cargo-deny (deny.toml) +# +# Opengrep reports without failing until its first run on this repository is +# clean; then `sast-fail-on-findings: true` makes it blocking (doc 14 §4). +# +# Weekly as well, so a new advisory against an unchanged lockfile turns it red: +# Tuesday 13:57 UTC = 20:57 Vietnam (slot in the ops repo's cron registry; the +# runner is the maintainer's PC and only runs 13:00–16:00 UTC). + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '57 13 * * 2' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: security-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +jobs: + # Both linters without Docker: actionlint and shellcheck as release binaries + # at the versions and checksums the ops repo's ops-lint.yml pins; zizmor from + # the hash-locked .gitea/requirements-ci.txt. Renovate does not update the + # binaries: bump version and checksum together, by hand. + workflow-lint: + name: workflow-lint + runs-on: ubuntu-latest # Gitea: Docker, docker.gitea.com/runner-images + timeout-minutes: 10 + permissions: + contents: read + env: + ACTIONLINT_VERSION: 1.7.12 + ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 # actionlint_1.7.12_linux_amd64.tar.gz (release checksums file) + SHELLCHECK_VERSION: v0.11.0 + SHELLCHECK_SHA256: 8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 # shellcheck-v0.11.0.linux.x86_64.tar.xz (no checksums file upstream; hashed 2026-11-23 by the ops repo) + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.12' + + - name: Install zizmor + run: | + python -m pip install --quiet --require-hashes --only-binary :all: -r .gitea/requirements-ci.txt + + # The files by name: zizmor only looks for .github/workflows by itself. + # Offline: its online audits ask GitHub's API about the actions, with a + # token this runner does not have. Any finding at medium or above fails. + - name: zizmor (workflow security audit) + run: zizmor --offline --min-severity medium --config .gitea/zizmor.yml .gitea/workflows/*.yml + + - name: Install actionlint ${{ env.ACTIONLINT_VERSION }} + shellcheck ${{ env.SHELLCHECK_VERSION }} + run: | + set -euo pipefail + tmp="${RUNNER_TEMP:-/tmp}" + bin="$tmp/lint-bin" + mkdir -p "$bin" + curl -fsSL --retry 3 -o "$tmp/actionlint.tar.gz" \ + "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + echo "${ACTIONLINT_SHA256} $tmp/actionlint.tar.gz" | sha256sum -c - + tar -xzf "$tmp/actionlint.tar.gz" -C "$bin" actionlint + curl -fsSL --retry 3 -o "$tmp/shellcheck.tar.xz" \ + "https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" + echo "${SHELLCHECK_SHA256} $tmp/shellcheck.tar.xz" | sha256sum -c - + tar -xJf "$tmp/shellcheck.tar.xz" -C "$bin" --strip-components=1 "shellcheck-${SHELLCHECK_VERSION}/shellcheck" + echo "$bin" >> "$GITHUB_PATH" + + # .gitea/actionlint.yaml ignores only the Gitea features actionlint does + # not know; everything else stays an error. + - name: actionlint (workflow syntax and expressions) + run: | + actionlint -version + actionlint -color -config-file .gitea/actionlint.yaml \ + -shellcheck "$(command -v shellcheck)" .gitea/workflows/*.yml + + scan: + permissions: + contents: read + uses: poli0981/.github/.gitea/workflows/security.yml@b93b3711b3049a879cfdfd515f7e72c23864da8f # ops v2026.11.5 + with: + rust: true + node: true diff --git a/.gitea/zizmor.yml b/.gitea/zizmor.yml new file mode 100644 index 0000000..18d16db --- /dev/null +++ b/.gitea/zizmor.yml @@ -0,0 +1,10 @@ +# zizmor (workflow security linter) configuration, run by +# .gitea/workflows/security.yml (job `workflow-lint`, offline). +rules: + unpinned-uses: + config: + policies: + # Every action and every call into the ops repo (poli0981/.github) is + # pinned to a full commit SHA. Renovate bumps the actions; the ops pins + # are bumped by hand when the ops repo is tagged (doc 15 §4.3). + "*": hash-pin diff --git a/docs/02_TECH_STACK.md b/docs/02_TECH_STACK.md index c07a5fa..bd92921 100644 --- a/docs/02_TECH_STACK.md +++ b/docs/02_TECH_STACK.md @@ -126,6 +126,12 @@ dependencies. | `rstest` | 0.28.0 | Parameterised tests | | `criterion` | 0.8.2 | Benchmarks | +`ci.yml` does not install `cargo-nextest`, `cargo-llvm-cov` or `cargo-machete` with +`cargo install`: it downloads the release binary of the version above, checks its SHA-256 +against the value pinned in the workflow, and runs it from the job's temp directory — +never from the maintainer's `~/.cargo/bin` (doc 15 §4.4). Renovate does not see these +pins; a version bump here and the workflow's version and checksum move together, by hand. + ## 4. Browser extension | Package | Version | Use | @@ -150,7 +156,7 @@ no UI framework, no schema library. Every package above is a dev dependency. | GitLab | Free | Read-only push mirror of the source | | Cloudflare R2 (`releases.poli0981.dev`) | Existing bucket | Installers and the update feed | | Renovate, self-hosted | — | Dependency-update pull requests and OSV vulnerability alerts, from the central preset `poli0981/renovate-config` | -| Qodana | Ultimate (existing) | `qodana-rust` linter, image `jetbrains/qodana-rust:2026.2-eap` | +| Qodana | Ultimate (existing) | `qodana-rust` linter (EAP). `qodana.yaml` names the linter, and the image release follows the Qodana CLI that the ops `reusable-qodana.yml` pins (2026.3.1 at ops v2026.11.5); S10 records the image actually pulled | | gitleaks, Opengrep, osv-scanner, cargo-deny | Open source | Secrets, static analysis and dependency checks, run by the ops `security.yml` | ## 6. Deviations from the maintainer's usual conventions diff --git a/docs/14_TESTING_QUALITY.md b/docs/14_TESTING_QUALITY.md index 6c5a562..8733743 100644 --- a/docs/14_TESTING_QUALITY.md +++ b/docs/14_TESTING_QUALITY.md @@ -142,15 +142,20 @@ cron slots are in doc 15 §4. **Security workflow.** `security.yml` is a caller of the ops repository's reusable `security.yml`, pinned by commit SHA, with `rust: true` and `node: true`. It runs on pushes to `main`, on pull requests and weekly. Tool versions and checksums are pinned in -the ops repo and bumped there. +the ops repo and bumped there. The same workflow's own `workflow-lint` job runs +actionlint (with shellcheck) and zizmor over `.gitea/workflows/`, as the other +repositories on the forge do. **Qodana.** `qodana.yaml` at the repository root selects the Rust linter -(`jetbrains/qodana-rust:2026.2-eap`). `qodana.yml` calls the ops `reusable-qodana.yml` -with `runs-on: windows-latest` and `within-docker: true`, because the Rust linter has no -native mode and the Linux image needs Docker Desktop on the runner PC (spike S10). The -Qodana Cloud project's repository URL points at the Gitea HTTPS URL. If the UI crates -cannot be analysed inside the container, the scan is limited to the non-UI crates; if -the Docker route does not work at all, MuteVault drops Qodana. +(`linter: qodana-rust`; the image release follows the Qodana CLI pinned in the ops repo, +and S10 records the image actually pulled). `qodana.yml` calls the ops +`reusable-qodana.yml` with `runs-on: windows-latest`, `within-docker: true` and +`-u root -e CARGO_HOME=/data/cache/cargo`, because the Rust linter has no native mode +and the Linux image needs Docker Desktop on the runner PC (spike S10). The Qodana Cloud +project's VCS URL points at the GitLab mirror: Qodana Cloud accepts only github.com, +gitlab.com and bitbucket.org URLs. If the UI crates cannot be analysed inside the +container, the scan is limited to the non-UI crates; if the Docker route does not work +at all, MuteVault drops Qodana. **Renovate.** `renovate.json` extends the central preset; nothing else is configured in this repository (doc 15 §5). diff --git a/docs/15_BUILD_RELEASE.md b/docs/15_BUILD_RELEASE.md index dae634e..4e02463 100644 --- a/docs/15_BUILD_RELEASE.md +++ b/docs/15_BUILD_RELEASE.md @@ -49,8 +49,10 @@ debug = false | Command | Does | |---|---| | `cargo xtask check` | fmt, clippy, deny, machete, layer rules | +| `cargo xtask rules` | Layer rules only (doc 03 §3): first-party layers, confined crates, `#![forbid(unsafe_code)]` | | `cargo nextest run --workspace --locked` | Tests | | `cargo llvm-cov nextest --workspace --lcov --output-path target/lcov.info` | Coverage | +| `cargo xtask coverage target/lcov.info` | Per-crate coverage thresholds (doc 14 §2) over that report | | `cargo run -p mutevault` | Run the app (debug) | | `cargo xtask host-register --dev` | Register the debug native host for the dev extension id | | `pnpm -C extension dev` | Extension dev build in a throwaway browser profile | @@ -78,19 +80,33 @@ MuteVault's Rust build and test workflows are **project-local** — the ops repo Rust reusable, and keeping the build readable in this repository suits a security product. Security scanning, Qodana, notifications and R2 publishing call the ops repo. -| Workflow | Trigger | Jobs | Kind | Permissions | -|---|---|---|---|---| -| `ci.yml` | Push to `main`, pull request | fmt · clippy · nextest on `windows-latest` (whole workspace) and `ubuntu-latest` (non-UI crates) · `cargo xtask check` · coverage with per-crate thresholds, report as an artifact | Local | `contents: read` | -| `extension.yml` | Push to `main`, pull request | pnpm install with scripts off · Biome · `tsc --noEmit` · Vitest · Chromium and Firefox builds | Local | `contents: read` | -| `security.yml` | Push to `main`, pull request, weekly `57 13 * * 2` | gitleaks · Opengrep · osv-scanner · cargo-deny, through the ops `security.yml` with `rust: true`, `node: true` | Ops caller | `contents: read` | -| `qodana.yml` | Push to `main`, weekly `9 14 * * 5` | `qodana-rust` through the ops `reusable-qodana.yml` | Ops caller | `contents: read` | -| `fuzz.yml` | Weekly `17 15 * * 6`, manual | `cargo fuzz` per target on `ubuntu-latest`, corpus cache | Local | `contents: read` | -| `notify-ci-failure.yml` | `workflow_run` | Discord notice through the ops notifier | Ops caller | `contents: read`, `actions: read` | -| `release.yml` | Tag `v*`, manual on a tag | §6, §8, §13 | Local, with the ops `publish-r2.yml` | `contents: write`, `releases: write` | -| `announce-release.yml` | Manual with a tag (dispatched by `release.yml`) | Discord announcement through the ops workflow | Ops caller | `contents: read` | +| Workflow | Trigger | Jobs | Kind | Permissions | Since | +|---|---|---|---|---|---| +| `ci.yml` | Push to `main`, pull request, manual | `linux` (`ubuntu-latest`, non-UI crates): rustfmt · clippy · `cargo xtask rules` · `cargo machete` · nextest under `cargo llvm-cov` · `cargo xtask coverage` (per-crate thresholds, doc 14 §2), report as an artifact. `windows` (`windows-latest`, whole workspace): clippy · nextest. `ci-ok`: the required check | Local | `contents: read` | M0 | +| `extension.yml` | Push to `main`, pull request | pnpm install with scripts off · Biome · `tsc --noEmit` · Vitest · Chromium and Firefox builds | Local | `contents: read` | Extension scaffold (M3) | +| `security.yml` | Push to `main`, pull request, weekly `57 13 * * 2`, manual | `workflow-lint`: actionlint + shellcheck and zizmor over the workflows. `scan`: gitleaks · Opengrep · osv-scanner · cargo-deny, through the ops `security.yml` with `rust: true`, `node: true` | Local + ops caller | `contents: read` | M0 | +| `qodana.yml` | Push to `main`, weekly `9 14 * * 5`, manual | `qodana-rust` through the ops `reusable-qodana.yml` on `windows-latest` with `within-docker` | Ops caller | `contents: read` | M0; stays only if S10 passes | +| `fuzz.yml` | Weekly `17 15 * * 6`, manual | `cargo fuzz` per target on `ubuntu-latest`, corpus cache | Local | `contents: read` | First fuzz target (M1) | +| `notify-ci-failure.yml` | `workflow_run` of CI, Security, Qodana (and later workflows) | Discord notice through the ops notifier | Ops caller | `contents: read`, `actions: read` | M0 | +| `release.yml` | Tag `v*`, manual on a tag | §6, §8, §13 | Local, with the ops `publish-r2.yml` | `contents: write`, `releases: write` | M5, after S9 | +| `announce-release.yml` | Manual with a tag (dispatched by `release.yml`) | Discord announcement through the ops workflow | Ops caller | `contents: read` | M5 | -The three cron slots are **proposed**: they were free in the ops registry on 2026-11-23 -and are added to it in the same change that adds the workflows (H-13). +Ops callers pin **ops v2026.11.5**, commit `b93b3711b3049a879cfdfd515f7e72c23864da8f`. + +`cargo xtask check` is the local form of the static part of `ci.yml` (rustfmt, clippy, +cargo-deny, cargo-machete, `cargo xtask rules`). CI runs those as separate steps, so a +failure names its tool, and cargo-deny runs in the ops `security.yml`. + +**Required checks** for branch protection on `main`: `CI / ci-ok (*)`, +`Security / workflow-lint (*)`, `Reusable / Security / Secrets (gitleaks) (*)`, +`Reusable / Security / Dependencies (osv-scanner) (*)` and +`Reusable / Security / Rust (cargo-deny) (*)`. Opengrep and Qodana report and are not +required; Opengrep becomes blocking (`sast-fail-on-findings: true`) after its first clean +run (doc 14 §4). + +Cron slots: `57 13 * * 2` (security) and `9 14 * * 5` (Qodana) are registered in the ops +repo's registry when this repository is bootstrapped (H-13). `17 15 * * 6` is kept for +`fuzz.yml` and registered in the change that adds it. All three were free on 2026-12-02. ### 4.3 Rules @@ -103,6 +119,12 @@ and are added to it in the same change that adds the workflows (H-13). need their full URL. - Artifacts use `christopherhx/gitea-upload-artifact` and `gitea-download-artifact` at the SHAs the ops repo pins; the upstream v4 actions refuse to run on Gitea. +- Tools that are not actions (`cargo-nextest`, `cargo-llvm-cov`, `cargo-machete`, + actionlint, shellcheck) are downloaded as release binaries at pinned versions, checked + against a SHA-256 pinned in the workflow, and run from the job's temp directory. + Renovate does not see these pins; they are bumped by hand, version and checksum + together (doc 02 §3). zizmor is installed from the hash-locked + `.gitea/requirements-ci.txt`. - `permissions:` blocks stay explicit. `id-token`, `attestations`, `security-events`, `checks`, `statuses`, `deployments` and `pages` do not exist on Gitea and are not used. - Release credentials (`R2_RELEASES_*`, the update-signing key, store tokens) are @@ -125,7 +147,12 @@ CI job registration, Run key, file association), global hotkeys, tray, Windows Hello. Those tests are `#[ignore]`d with a `machine` reason and CI never passes `--ignored` or `--include-ignored`; they are run by hand (doc 14 §9); -- installs toolchains through `rustup` and the runner tool cache, never system-wide. +- installs toolchains through `rustup` and the runner tool cache, never system-wide. The + Rust toolchain comes from `rust-toolchain.toml` through + `rustup toolchain install --no-self-update`, which changes neither the PC's default + toolchain nor rustup itself. `dtolnay/rust-toolchain` is used only in Linux + containers: it sets rustup's default toolchain, and on this PC it once left `stable` + broken (ops repo, free-steam-games-list guide). Qodana's Rust linter has no native mode: it runs with `runs-on: windows-latest` and `within-docker: true`, in Docker Desktop on the PC (**VERIFY**, S10). If that cannot be @@ -422,12 +449,17 @@ there. There is no public issue tracker (D-28). On an empty Gitea repository the first branch pushed becomes the default branch, and only the default branch's scheduled workflows run. So: -1. Push `main` first (`git push -u origin main`), before any topic branch. -2. Maintainer steps, in this order (H-13): branch protection on `main`; enable Actions; - create the repo-level secrets (§14.7); run `maintainer/gitea-repo-setup.ps1 -Only - mutevault` (Renovate collaborator and labels) and `setup-mirrors.ps1 -Only mutevault` - (GitLab mirror) from the ops tooling; register the three cron slots in the ops - registry; point the Qodana Cloud project at the Gitea HTTPS URL. +1. Push `main` first (`git push -u origin main`), before any topic branch. Its first + commit is the documentation suite alone; the workspace and CI arrive through the + first pull request (`chore/ci-bootstrap`), which is also CI's first run. +2. Maintainer steps, in this order (H-13): branch protection on `main` with the required + checks of §4.2; enable Actions; create the repo-level secrets (§14.7); run + `maintainer/gitea-repo-setup.ps1 -Only mutevault` (Renovate collaborator and labels) + and `setup-mirrors.ps1 -Only mutevault` (GitLab mirror) from the ops tooling; register + the security and Qodana cron slots in the ops registry (§4.2); point the Qodana Cloud + project's VCS URL at the **GitLab mirror** — Qodana Cloud accepts only github.com, + gitlab.com and bitbucket.org URLs (ops runbook, HashTool guide). +3. Push `chore/ci-bootstrap` and open its pull request on Gitea. ### 14.6 Applying outside contributions @@ -449,6 +481,10 @@ repository, in logs or in a session. | `DISCORD_CI_WEBHOOK`, `DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK` | secret | repo | notifier callers | | Browser-store and Partner Center credentials | secret | repo | Tag-only store jobs, once automated | +Needed from M0: `QODANA_TOKEN` and `DISCORD_CI_WEBHOOK`. The others arrive with the +workflows that use them: the update-signing key, `DISCORD_RELEASES_WEBHOOK` and +`DISCORD_REPO_WEBHOOK` with `release.yml` and `announce-release.yml` (M5). + ### 14.8 Rules for AI agents working in this repository 1. Push only to `origin`, only to a topic branch. Never push to `main`, never force diff --git a/qodana.yaml b/qodana.yaml new file mode 100644 index 0000000..6a37bd5 --- /dev/null +++ b/qodana.yaml @@ -0,0 +1,24 @@ +# Qodana for Rust (Early Access) over the whole workspace. Run by +# .gitea/workflows/qodana.yml through the ops repo's reusable-qodana.yml, in +# Docker Desktop on the Windows runner (spike S10, doc 14 §6). +# +# `linter:` names the linter, not an image tag, as in the other poli0981 +# repositories: the image release follows the Qodana CLI the ops repo pins +# (2026.3.1 at ops v2026.11.5; the sibling repos saw qodana-rust 2026.3-eap). +# Spike S10 records the image actually pulled in doc 02 §5. +version: "1.0" +linter: qodana-rust +profile: + name: qodana.recommended +# No failureConditions: the EAP linter reports, it does not gate (doc 14 §4). +# Opening a Cargo project in Docker Desktop on the runner PC can take longer +# than the linter's default 10 minutes on a cold cache (seen on +# free-steam-games-list, November 2026). The reusable gives the job 45. +properties: + qd.rust.configuration.timeout.minutes: "25" +exclude: + - name: All + paths: + - target + - docs + - legal diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..1564446 --- /dev/null +++ b/renovate.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["local>poli0981/renovate-config"] +} -- 2.54.1 From c8dba76c7033627a466228d9de861a96a65d03d1 Mon Sep 17 00:00:00 2001 From: poli0981 Date: Wed, 2 Dec 2026 19:54:01 +0700 Subject: [PATCH 3/3] docs: record the M0 bootstrap and the S1 kick-off doc 17: - A-01 is done: the workflows pin ops v2026.11.5. - H-13 now lists the bootstrap steps in order. It registers two cron slots now; the fuzz slot is registered with fuzz.yml. The Qodana Cloud project points at the GitLab mirror. - New decision D-29 (flagged for review): the M0 workflow set, and the kick-off order after M0. S1 (gpui-kit shell) goes first, because R-01 is the highest-likelihood risk, S1 is the only P0 spike that can change the stack, and S2/S3 build on it. S5 (crypto core and format) runs in parallel. - Three open questions found while bootstrapping: Velopack's HTTP client vs rule 5, the host's transitive reach to mv-crypto, and where spike code lives. CHANGELOG records the bootstrap under [Unreleased]. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++++++++++++++ docs/17_SPIKES_ROADMAP.md | 31 ++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4139cc..ab4ea08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,14 @@ format are prefixed **Format** and say whether older versions can still open the ## [Unreleased] ### Added +- Repository bootstrap (2026-12-02), D-29: + - the documentation suite at the repository root, plus the GPL-3.0 licence text; + - a Cargo workspace whose only member is `xtask`. It enforces the doc 03 §3 layer + rules and the doc 14 §2 coverage gate, and runs the local check; + - the config files `deny.toml`, `clippy.toml`, `rustfmt.toml` and `rust-toolchain.toml`; + - the Gitea Actions workflows `ci.yml`, `security.yml` (with workflow linting), + `qodana.yml` and `notify-ci-failure.yml`, pinned to ops v2026.11.5; + - Renovate, through the central preset. - Documentation suite v1.0 (2026-11-22): charter, feasibility study, tech stack, architecture, cryptography, vault format, data model, threat model, browser integration, passkeys, desktop integration, import/export, UI/UX, code style, testing @@ -36,6 +44,10 @@ format are prefixed **Format** and say whether older versions can still open the - winget dropped as a distribution channel (D-25 revised). - SonarQube Cloud and Snyk removed from the pipeline (D-15 revised). - `.github/FUNDING.yml` removed. +- The Qodana Cloud project points at the GitLab mirror, because Qodana Cloud accepts + only github.com, gitlab.com and bitbucket.org URLs (doc 14 §6, doc 15 §14.5). +- rustfmt's `imports_granularity` and `group_imports` are not set: they are still + nightly-only (doc 13 §1). ### Decided - Name MuteVault; Windows 11 first; passkeys through the browser extension in v1; own @@ -43,6 +55,8 @@ format are prefixed **Format** and say whether older versions can still open the - Distribution through the project's release host and the Microsoft Store; winget dropped (D-25). - Forge, CI, release hosting and support channels (D-26 to D-28). +- The M0 workflow set, and the kick-off order after M0: S1 (`gpui-kit` shell) first, + with S5 (crypto core and format) as a parallel track (D-29, flagged for review).