From 117be6dfb1fd8066f42e49636c493cfea83f3941 Mon Sep 17 00:00:00 2001 From: StephanSchipal Date: Thu, 3 Dec 2026 19:43:56 +0100 Subject: [PATCH] fix: apply workspace lints to every crate; random serve token Workspace lints: Cargo.toml declares [workspace.lints.clippy] (deny unwrap_used, expect_used, panic, unimplemented, todo), but no crate had `[lints] workspace = true`, so the table applied nowhere. Only devcraft-app enforced the rules through its own #![deny]. An unwrap() added to devcraft-core passed `cargo clippy -D warnings`; with this change it is rejected. A root clippy.toml allows unwrap, expect and panic in tests. No existing code needed a change. Serve token: `devcraft-mcp serve` created .devcraft/mobile.token as hex(nanos since epoch) + hex(pid), which narrows to a small search space for anyone who can guess when the companion first ran. It is now 32 bytes from the OS random source (getrandom 0.4, already in the tree), 64 hex characters. authorized() compares tokens without an early exit. An existing token file is kept; deleting it rotates the token. Tests: new_token shape and uniqueness, mobile_token create-then-reuse, token_eq, authorized() for query and Bearer. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + clippy.toml | 3 ++ crates/devcraft-app/Cargo.toml | 3 ++ crates/devcraft-core/Cargo.toml | 3 ++ crates/devcraft-mcp/Cargo.toml | 4 ++ crates/devcraft-mcp/src/serve.rs | 79 ++++++++++++++++++++++++++++---- 6 files changed, 86 insertions(+), 8 deletions(-) create mode 100644 clippy.toml diff --git a/CHANGELOG.md b/CHANGELOG.md index 14e90ac..37e1b54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- **Workspace lints apply to every crate** (Claude): `devcraft-core`, `devcraft-mcp` and `devcraft-app` opt into `[workspace.lints]` with `[lints] workspace = true`. Until now only the app's own `#![deny]` attribute was enforced, so `unwrap_used`, `expect_used`, `panic`, `unimplemented` and `todo` were not checked in core and mcp (an `unwrap()` added to core passed `cargo clippy -D warnings`). A root `clippy.toml` allows unwrap, expect and panic in tests. No existing code needed a change. +- **Serve token from OS randomness** (Claude): `devcraft-mcp serve` creates `.devcraft/mobile.token` from 32 bytes of OS randomness (64 hex characters, `getrandom`) instead of the clock in nanoseconds and the process id, which anyone who could guess the first start could narrow down. Presented tokens are compared without stopping at the first differing byte. An existing token file is kept; delete it to get a new token. Tests in `serve.rs`. - **NSSM services: list, test, start, stop, create, edit, remove** (Claude): the Services page and six tools (`devcraft_nssm_list`, `devcraft_nssm_health`, `devcraft_nssm_install`, `devcraft_nssm_edit`, `devcraft_nssm_remove`, `devcraft_nssm_control`). The list comes from one PowerShell call without administrator rights: state, start mode, account, application, parameters, folder, logs, exit action, the nssm.exe process tree and the ports those processes listen on, plus ports named in the parameters (`--port`, `--rest-port`) or the environment (`PORT=`, `SPEECH_MCP_PORT=`). Environment values whose names hold PASS, SECRET, TOKEN, KEY, CREDENTIAL, PWD or AUTH show as `***`. The test probes every listening or named port with TCP and `GET /` and reads the log tails; verdicts are healthy, degraded (application not running, named port not listening, HTTP 5xx), down or disabled. Changes run as one elevated PowerShell script each, so one UAC prompt on the desktop; values are written to the NSSM registry keys with `Set-ItemProperty` instead of `nssm set` on a command line, because Windows PowerShell 5.1 drops embedded quotes from native arguments. Start, stop and restart try `sc.exe` as the user first and elevate only on access denied; nothing kills a child process. Writes need `confirm=true`, remove needs the service name as confirm. Verified on Goliath: the list (17 services) and health tests; create, edit, remove and an elevated control were not run live, they need someone at the UAC prompt. - **Lunch page (optional, QoL)** (Claude): today's set lunch menus from the restaurants in `{workspace}/.devcraft/lunch.json`, on the Lunch page (sidebar group QoL, off by default; Setup and the page itself turn it on) and as `devcraft_lunch`. Two kinds of source: a text page that lists the week under German weekday headings (Gasthaus Orlik: soups, dishes and prices are parsed, today's day is picked by date) and a weekly sheet published as a picture (The Golden Harp Alsergrund: the JPEG is shown, its text is not read). Fetched with curl, cached for three hours and per day; nothing is fetched while the page is off. Restaurants can be added, edited and switched off on the page. Spec: `docs/SPEC_SERVICES_AND_LUNCH.md`. - **CLI `--args`** (Claude): `devcraft-mcp tool --args key=value` (repeatable, or a JSON object) passes fields that have no flag, such as `--args name=speech-mcp`. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..7bada54 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,3 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true diff --git a/crates/devcraft-app/Cargo.toml b/crates/devcraft-app/Cargo.toml index fd4f6fa..97a55f6 100644 --- a/crates/devcraft-app/Cargo.toml +++ b/crates/devcraft-app/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true license.workspace = true authors.workspace = true +[lints] +workspace = true + [[bin]] name = "devcraft" path = "src/main.rs" diff --git a/crates/devcraft-core/Cargo.toml b/crates/devcraft-core/Cargo.toml index eac530e..acc83e9 100644 --- a/crates/devcraft-core/Cargo.toml +++ b/crates/devcraft-core/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true license.workspace = true authors.workspace = true +[lints] +workspace = true + [dependencies] serde.workspace = true serde_json.workspace = true diff --git a/crates/devcraft-mcp/Cargo.toml b/crates/devcraft-mcp/Cargo.toml index 4bc2ef3..eba5c32 100644 --- a/crates/devcraft-mcp/Cargo.toml +++ b/crates/devcraft-mcp/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true license.workspace = true authors.workspace = true +[lints] +workspace = true + [[bin]] name = "devcraft-mcp" path = "src/main.rs" @@ -15,3 +18,4 @@ serde.workspace = true serde_json.workspace = true tokio.workspace = true clap.workspace = true +getrandom = "0.4" diff --git a/crates/devcraft-mcp/src/serve.rs b/crates/devcraft-mcp/src/serve.rs index 9c41610..f9b5633 100644 --- a/crates/devcraft-mcp/src/serve.rs +++ b/crates/devcraft-mcp/src/serve.rs @@ -14,7 +14,6 @@ use serde_json::{json, Value}; use std::collections::HashMap; use std::path::PathBuf; use std::sync::{Mutex, MutexGuard, OnceLock}; -use std::time::{SystemTime, UNIX_EPOCH}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; @@ -68,15 +67,30 @@ fn mobile_token(root: &Path) -> Result { return Ok(token); } } - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let token = format!("{:x}{:x}", nanos, std::process::id()); + let token = new_token()?; std::fs::write(&path, &token).map_err(|e| e.to_string())?; Ok(token) } +/// 256 bits from the OS random source, as 64 hex characters. A token made +/// from the clock and the process id can be narrowed down by anyone who can +/// guess when the companion first ran. +fn new_token() -> Result { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|e| format!("no OS randomness: {e}"))?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Compare a presented token with the real one without stopping at the +/// first differing byte, so response time does not reveal a matching prefix. +fn token_eq(given: &str, token: &str) -> bool { + let (a, b) = (given.as_bytes(), token.as_bytes()); + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + /// Tailscale IPv4 from `tailscale ip -4`, empty when Tailscale is down. fn tailscale_ip() -> String { let output = std::process::Command::new("tailscale") @@ -111,14 +125,14 @@ fn response(status: u16, content_type: &str, body: &str) -> Vec { fn authorized(query: &str, headers: &HashMap, token: &str) -> bool { for pair in query.split('&') { if let Some(value) = pair.strip_prefix("token=") { - if value == token { + if token_eq(value, token) { return true; } } } if let Some(auth) = headers.get("authorization") { if let Some(bearer) = auth.strip_prefix("Bearer ") { - if bearer.trim() == token { + if token_eq(bearer.trim(), token) { return true; } } @@ -401,3 +415,52 @@ pub async fn run(bind: &str) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn new_token_is_long_random_hex() { + let a = new_token().unwrap(); + let b = new_token().unwrap(); + assert_eq!(a.len(), 64); + assert!(a.chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a, b); + } + + #[test] + fn mobile_token_is_created_random_then_reused() { + let root = std::env::temp_dir().join(format!("devcraft_token_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let first = mobile_token(&root).unwrap(); + let second = mobile_token(&root).unwrap(); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(first.len(), 64); + assert_eq!(first, second); + } + + #[test] + fn token_eq_compares_the_whole_value() { + assert!(token_eq("abc123", "abc123")); + assert!(!token_eq("abc124", "abc123")); + assert!(!token_eq("abc12", "abc123")); + assert!(!token_eq("abc1234", "abc123")); + assert!(!token_eq("", "abc123")); + } + + #[test] + fn authorized_needs_the_exact_token_in_query_or_bearer() { + let token = "f00d"; + let none = HashMap::new(); + assert!(authorized("a=1&token=f00d", &none, token)); + assert!(!authorized("token=f00e", &none, token)); + assert!(!authorized("token=f00", &none, token)); + assert!(!authorized("", &none, token)); + let mut headers = HashMap::new(); + headers.insert("authorization".to_string(), "Bearer f00d".to_string()); + assert!(authorized("", &headers, token)); + headers.insert("authorization".to_string(), "Bearer nope".to_string()); + assert!(!authorized("", &headers, token)); + } +}