feat(bridge): localhost HTTP bridge with strict arg validation and host/origin checks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 13:39:01 +01:00
1 parent 6377c02fec
commit 503d615951
5 files changed
+353 -1

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
[package]
name = "grove-bridge"
description = "Backend of the grove GUI: daemon IPC + allow-listed CLI calls, and a localhost dev server"
edition.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
anyhow = "1.0.104"
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
serde_json = "1.0.154"
toml = "1.2.1"
+175
View File
@@ -0,0 +1,175 @@
//! Everything the GUI needs from the machine, behind three calls. The Tauri shell and the
//! localhost dev server both expose exactly these.
use serde_json::{Value, json};
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
/// `grove` subcommands the GUI may run. Everything else is refused.
const ALLOWED: &[&str] = &[
"init",
"login",
"new",
"import",
"config-repo-init",
"bootstrap",
"resolve",
"secrets",
"sync",
"status",
];
pub struct Bridge {
pub grove_bin: PathBuf,
pub config: Option<PathBuf>,
pub socket: PathBuf,
}
impl Bridge {
/// Forwards one IPC request to the daemon. An unreachable daemon is a normal answer.
pub fn ipc(&self, req: &Value) -> Value {
grove_daemon::ipc::request(&self.socket, req).unwrap_or_else(
|e| json!({"v": 1, "ok": false, "offline": true, "error": format!("daemon not reachable: {e}")}),
)
}
/// Runs an allow-listed `grove` subcommand. `stdin` is passed through (used by `login`).
pub fn cli(&self, args: &[String], stdin: &str) -> Value {
let Some(sub) = args.first() else {
return json!({"ok": false, "output": "no command"});
};
if !ALLOWED.contains(&sub.as_str()) {
return json!({"ok": false, "output": format!("command {sub:?} is not allowed from the GUI")});
}
if let Err(e) = validate(args) {
return json!({"ok": false, "output": format!("rejected: {e}")});
}
let mut cmd = Command::new(&self.grove_bin);
if let Some(c) = &self.config {
cmd.arg("--config").arg(c);
}
cmd.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut run = || -> std::io::Result<std::process::Output> {
let mut child = cmd.spawn()?;
// Feed stdin from a thread so a chatty child cannot deadlock against a full pipe.
let writer = child.stdin.take().map(|mut si| {
let data = stdin.to_owned();
std::thread::spawn(move || {
let _ = si.write_all(data.as_bytes());
})
});
let out = child.wait_with_output();
if let Some(w) = writer {
let _ = w.join();
}
out
};
match run() {
Ok(o) => {
let mut text = String::from_utf8_lossy(&o.stdout).into_owned();
text.push_str(&String::from_utf8_lossy(&o.stderr));
json!({"ok": o.status.success(), "output": text.trim()})
}
Err(e) => {
json!({"ok": false, "output": format!("cannot run {}: {e}", self.grove_bin.display())})
}
}
}
/// `config.toml` as JSON (it holds no secrets), or `None` before onboarding.
pub fn config_json(&self) -> Option<Value> {
let p = self.config.clone().or_else(grove_core_default_config)?;
let t: toml::Value = toml::from_str(&std::fs::read_to_string(p).ok()?).ok()?;
serde_json::to_value(t).ok()
}
}
/// Per-command flag table: (flags without value, flags taking one value).
fn flag_spec(sub: &str) -> (&'static [&'static str], &'static [&'static str]) {
match sub {
"init" => (&[], &["--machine", "--root", "--provider", "--kind", "--group", "--config-repo", "--url"]),
"new" => (&["--public"], &[]),
"resolve" => (&["--take-remote", "--keep-local"], &["--save-as"]),
_ => (&[], &[]),
}
}
/// Strict argument shape: only known flags, no option-like positionals or values (so nothing can
/// smuggle in `--config`, `--force`, `--compare`, ...), and `secrets` limited to init/pull/rekey.
pub fn validate(args: &[String]) -> Result<(), String> {
let sub = args.first().map(String::as_str).unwrap_or("");
let (bools, valued) = flag_spec(sub);
let mut it = args[1..].iter().enumerate();
while let Some((i, a)) = it.next() {
if a.starts_with('-') {
if valued.contains(&a.as_str()) {
match it.next() {
Some((_, v)) if !v.starts_with('-') => {}
_ => return Err(format!("{a} needs a value")),
}
} else if !bools.contains(&a.as_str()) {
return Err(format!("flag {a:?} is not allowed from the GUI"));
}
} else if sub == "secrets" && i == 0 && !["init", "pull", "rekey"].contains(&a.as_str()) {
return Err(format!("secrets {a:?} is not allowed from the GUI"));
}
}
if sub == "secrets" && args.len() != 2 {
return Err("secrets takes exactly one action".into());
}
Ok(())
}
fn grove_core_default_config() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
Some(base.join("grove/config.toml"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_blocks_smuggled_flags() {
let v = |a: &[&str]| validate(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert!(v(&["sync", "--config", "/x"]).is_err());
assert!(v(&["init", "--force"]).is_err());
assert!(v(&["resolve", "/p", "--compare"]).is_err());
assert!(v(&["resolve", "/p", "--save-as", "--take-remote"]).is_err());
assert!(v(&["secrets", "push", "f"]).is_err());
assert!(v(&["new", "g", "-x"]).is_err());
assert!(v(&["resolve", "/p", "--save-as", "b", "--take-remote"]).is_ok());
assert!(v(&["new", "g", "n", "--public"]).is_ok());
assert!(v(&["secrets", "pull"]).is_ok());
}
fn bridge() -> Bridge {
Bridge {
grove_bin: "/nonexistent/grove".into(),
config: None,
socket: "/nonexistent/sock".into(),
}
}
#[test]
fn only_allow_listed_subcommands_run() {
let r = bridge().cli(&["daemon".into(), "pause".into()], "");
assert_eq!(r["ok"], false);
assert!(r["output"].as_str().unwrap().contains("not allowed"));
let r = bridge().cli(&["sync".into()], "");
assert!(r["output"].as_str().unwrap().contains("cannot run"));
}
#[test]
fn offline_daemon_is_a_regular_answer() {
let r = bridge().ipc(&json!({"v": 1, "cmd": "status"}));
assert_eq!(r["ok"], false);
assert_eq!(r["offline"], true);
}
}
+155
View File
@@ -0,0 +1,155 @@
//! Localhost dev server for the GUI frontend: static files plus the `Bridge` calls over HTTP.
//! Binds to 127.0.0.1 only. POSTs need the `X-Grove: 1` header (not sendable cross-origin
//! without a preflight, which is never answered); the Host must be exactly 127.0.0.1:<port> or
//! localhost:<port> and any Origin must match too (DNS rebinding).
use anyhow::{Context, Result};
use grove_bridge::Bridge;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
fn arg(name: &str) -> Option<String> {
let a: Vec<String> = std::env::args().collect();
a.iter()
.position(|x| x == name)
.and_then(|i| a.get(i + 1))
.cloned()
}
fn main() -> Result<()> {
let ui = PathBuf::from(arg("--ui").unwrap_or_else(|| "gui/ui".into()));
let port: u16 = arg("--port")
.map_or(Ok(4780), |p| p.parse())
.context("bad --port")?;
let bridge = Arc::new(Bridge {
grove_bin: arg("--grove-bin").map_or_else(|| "grove".into(), PathBuf::from),
config: arg("--config").map(PathBuf::from),
socket: arg("--socket")
.map(PathBuf::from)
.unwrap_or_else(grove_daemon::ipc::default_socket_path),
});
let l = TcpListener::bind(("127.0.0.1", port)).with_context(|| format!("port {port}"))?;
eprintln!(
"grove GUI dev server on http://127.0.0.1:{port}/ (ui: {})",
ui.display()
);
for s in l.incoming().filter_map(Result::ok) {
let (b, ui) = (bridge.clone(), ui.clone());
let _ = s.set_read_timeout(Some(std::time::Duration::from_secs(10)));
std::thread::spawn(move || {
let _ = handle(s, &b, &ui, port);
});
}
Ok(())
}
fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) -> std::io::Result<()> {
write!(
s,
"HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
body.len()
)?;
s.write_all(body)
}
fn handle(mut s: TcpStream, b: &Bridge, ui: &std::path::Path, port: u16) -> std::io::Result<()> {
// Cap what a client can make us buffer while reading the request head.
let mut r = BufReader::new(s.try_clone()?.take(64 * 1024));
let mut line = String::new();
r.read_line(&mut line)?;
let mut it = line.split_whitespace();
let (method, path) = (
it.next().unwrap_or("").to_string(),
it.next().unwrap_or("/").to_string(),
);
let (mut len, mut host, mut marker, mut origin) = (0usize, String::new(), false, None);
loop {
let mut h = String::new();
if r.read_line(&mut h)? == 0 || h.trim().is_empty() {
break;
}
let lower = h.to_ascii_lowercase();
if let Some(v) = lower.strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
} else if let Some(v) = lower.strip_prefix("host:") {
host = v.trim().to_string();
} else if let Some(v) = lower.strip_prefix("origin:") {
origin = Some(v.trim().to_string());
} else if lower.starts_with("x-grove:") {
marker = true;
}
}
// Exact match: a prefix check would accept `localhost.evil.com` (DNS rebinding).
let local = [format!("127.0.0.1:{port}"), format!("localhost:{port}")];
if !local.contains(&host) {
return respond(&mut s, "403 Forbidden", "text/plain", b"bad host");
}
if let Some(o) = &origin
&& !local.iter().any(|h| *o == format!("http://{h}"))
{
return respond(&mut s, "403 Forbidden", "text/plain", b"bad origin");
}
if method == "POST" {
if !marker || len > 1 << 20 {
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
}
r.get_mut().set_limit(1 << 20); // head parsed; allow the (capped) body
let mut body = vec![0u8; len];
r.read_exact(&mut body)?;
let req: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
let out = match path.as_str() {
"/api/ipc" => b.ipc(&req),
"/api/cli" => {
let args: Vec<String> = req["args"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
b.cli(&args, req["stdin"].as_str().unwrap_or(""))
}
_ => return respond(&mut s, "404 Not Found", "text/plain", b"not found"),
};
return respond(
&mut s,
"200 OK",
"application/json",
out.to_string().as_bytes(),
);
}
if path == "/api/config" {
let body = match b.config_json() {
Some(c) => json!({"exists": true, "config": c}),
None => json!({"exists": false}),
};
return respond(
&mut s,
"200 OK",
"application/json",
body.to_string().as_bytes(),
);
}
let name = match path.split('?').next().unwrap_or("/") {
"/" => "index.html",
p => p.trim_start_matches('/'),
};
if name.contains("..") {
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
}
let ctype = match name.rsplit('.').next() {
Some("html") => "text/html; charset=utf-8",
Some("js") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("svg") => "image/svg+xml",
_ => "application/octet-stream",
};
match std::fs::read(ui.join(name)) {
Ok(data) => respond(&mut s, "200 OK", ctype, &data),
Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"not found"),
}
}