diff --git a/Cargo.lock b/Cargo.lock index 2092292..a87aa80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1799,6 +1799,7 @@ dependencies = [ "tokio", "toml", "toml_edit", + "toml_parser", "url", "uuid", "webbrowser", @@ -2617,6 +2618,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" dependencies = [ "indexmap", + "serde_core", + "serde_spanned", "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "toml_writer", diff --git a/Cargo.toml b/Cargo.toml index f6fa2fe..49444ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,8 @@ serde_json = { version = "1", features = ["preserve_order", "raw_value"] } tempfile = "=3.27.0" thiserror = "2" tokio = { version = "1", features = ["rt", "macros", "time", "process", "io-std", "io-util", "fs"] } -toml_edit = "=0.25.15" +toml_edit = { version = "=0.25.15", features = ["serde"] } +toml_parser = "=1.1.3" url = "2" uuid = { version = "1", features = ["serde"] } webbrowser = "1" diff --git a/README.md b/README.md index 25b8097..fe97153 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,25 @@ New entries use this executable's absolute path and store no credentials. Claude Code uses the top-level `mcpServers` in `~/.claude.json`. A custom `CLAUDE_CONFIG_DIR` requires manual configuration with `--print`. +Inspect an existing registration with `proofline agent status codex` or +`proofline agent status claude-code` (also supports `cursor`, `gemini` and `kiro`). +This read-only, offline command reports the user-level configuration path and +whether its registration is missing, invalid, valid, or unable to be verified. +Local/project scopes are not inspected; a missing user-level entry does not mean +Proofline is absent from every scope. Connectivity and authentication are not +checked, and the configured command is never run. Validated origins and their +sources are reported: registration arguments, registration environment, or the +CLI default. Alternate valid origins are accepted. Status rejects explicit +`--base-url` and `--org` options; these do not override the inspected registration. +The invoking process's organization environment is ignored for status inspection. +Custom launchers, remote HTTP transports and relative executables may require +manual verification. Symlinked configuration files are read without changing +them or their targets. An absolute `CODEX_HOME` is respected; custom +`CLAUDE_CONFIG_DIR` configurations require manual inspection. JSON inspection +uses the last repeated member, while installation retains its duplicate-key +safeguards. Valid and unverifiable outcomes exit 0; missing and invalid outcomes +exit 1. Command or output failures also exit nonzero. + See the [CLI documentation](https://proofline.sh/docs/cli/) for commands. `proofline review --path src/main.rs` reviews only that file's local changes diff --git a/src/agent.rs b/src/agent.rs index 1d1ca06..052b1e0 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1,6 +1,7 @@ //! User-level configuration for the existing credential-free MCP launcher. mod config; +mod status; mod store; #[cfg(test)] @@ -25,6 +26,15 @@ pub(crate) struct AgentArgs { enum AgentCommand { /// Add Proofline to a coding agent's user configuration after confirmation. Install(InstallArgs), + /// Inspect user-level MCP configuration offline; project scopes, connectivity and authentication are not checked. + #[command( + after_help = "Status does not accept --base-url or --org; origin and organization are read from the registration." + )] + Status { + /// Coding agent whose user configuration is inspected (read-only). + #[arg(value_enum)] + client: Client, + }, } #[derive(Debug, Args)] @@ -162,16 +172,20 @@ enum Outcome { Installed, } -pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result<()> { - tokio::task::spawn_blocking(move || { - let AgentCommand::Install(args) = args.command; +pub(crate) async fn run(args: AgentArgs, base_url: String) -> anyhow::Result { + tokio::task::spawn_blocking(move || -> anyhow::Result { + let args = match args.command { + AgentCommand::Status { client } => return status::run(client), + AgentCommand::Install(args) => args, + }; + let origin = Origin::parse(&base_url)?; let home = std::env::home_dir().ok_or(InstallError::Home)?; let codex_home = std::env::var_os("CODEX_HOME"); if args.client == Client::ClaudeCode && !args.print && std::env::var_os("CLAUDE_CONFIG_DIR").is_some() { - return Err(InstallError::CustomClaudeHome); + return Err(InstallError::CustomClaudeHome.into()); } let stdin = io::stdin(); let stdout = io::stdout(); @@ -184,11 +198,11 @@ pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result<()> { &mut stdin.lock(), &mut stdout.lock(), &mut stderr.lock(), - ) + )?; + Ok(crate::Verdict::Done) }) .await - .map_err(InstallError::Task)??; - Ok(()) + .map_err(InstallError::Task)? } fn install( diff --git a/src/agent/config.rs b/src/agent/config.rs index 43b20c6..0331b7d 100644 --- a/src/agent/config.rs +++ b/src/agent/config.rs @@ -52,6 +52,110 @@ pub(super) fn prepare( } } +pub(super) fn registration(client: Client, bytes: &[u8]) -> Result, InstallError> { + let document: Value = if client == Client::Codex { + let raw = std::str::from_utf8(bytes).map_err(|_| InstallError::InvalidConfig(client))?; + let document = bounded_toml(raw)?; + Value::deserialize(toml_edit::de::Deserializer::from(document)) + .map_err(|_| InstallError::InvalidConfig(client))? + } else { + // Client JSON parsers use the last occurrence of a repeated member. + serde_json::from_slice(bytes).map_err(|_| InstallError::InvalidConfig(client))? + }; + let root = document.as_object().ok_or(InstallError::ConfigShape { + client, + member: "root", + })?; + let member = if client == Client::Codex { + "mcp_servers" + } else { + "mcpServers" + }; + let Some(servers) = root.get(member) else { + return Ok(None); + }; + let servers = servers + .as_object() + .ok_or(InstallError::ConfigShape { client, member })?; + Ok(servers.get("proofline").cloned()) +} + +fn bounded_toml(raw: &str) -> Result, InstallError> { + use toml_parser::parser::{EventKind, RecursionGuard, parse_document}; + + // Inspect flat events before tree construction, whose error cleanup can + // itself recurse. Reuse the same lexer/parser as toml_edit, including quoted + // keys, strings and comments. The guard bounds the event parser's recursion. + let tokens = toml_parser::Source::new(raw).lex().into_vec(); + let mut events = Vec::new(); + let mut error = None; + parse_document( + &tokens, + &mut RecursionGuard::new(&mut events, 64), + &mut error, + ); + if error.is_some() { + return Err(InstallError::InvalidConfig(Client::Codex)); + } + let mut containers = Vec::new(); + let mut table_depth = 0; + let mut key_depth = 0; + let mut value_depth = 0; + for event in events { + match event.kind() { + EventKind::StdTableOpen | EventKind::ArrayTableOpen => key_depth = 0, + EventKind::SimpleKey => key_depth += 1, + EventKind::StdTableClose | EventKind::ArrayTableClose => { + table_depth = key_depth + usize::from(event.kind() == EventKind::ArrayTableClose); + key_depth = 0; + } + EventKind::KeyValSep => { + value_depth = containers.last().copied().unwrap_or(table_depth) + key_depth; + key_depth = 0; + } + EventKind::InlineTableOpen | EventKind::ArrayOpen => { + if value_depth > 64 { + return Err(InstallError::InvalidConfig(Client::Codex)); + } + containers.push(value_depth); + value_depth += 1; + } + EventKind::InlineTableClose | EventKind::ArrayClose => { + value_depth = containers.pop().unwrap_or(0); + } + EventKind::ValueSep => value_depth = containers.last().copied().unwrap_or(0) + 1, + EventKind::Scalar if value_depth > 64 => { + return Err(InstallError::InvalidConfig(Client::Codex)); + } + _ => {} + } + if key_depth > 64 || table_depth > 64 { + return Err(InstallError::InvalidConfig(Client::Codex)); + } + } + let document = + toml_edit::Document::parse(raw).map_err(|_| InstallError::InvalidConfig(Client::Codex))?; + // Array-of-table ancestors add implicit containers to header paths. The flat + // guard bounds these to at most twice its limit, including error cleanup; + // check the exact structural depth before recursive serde conversion. + let mut pending = vec![(document.as_item(), 0_usize)]; + while let Some((item, depth)) = pending.pop() { + if depth > 64 { + return Err(InstallError::InvalidConfig(Client::Codex)); + } + if let Some(table) = item.as_table_like() { + pending.extend(table.iter().map(|(_, item)| (item, depth + 1))); + } else { + let mut index = 0; + while let Some(child) = item.get(index) { + pending.push((child, depth + 1)); + index += 1; + } + } + } + Ok(document) +} + fn arguments(origin: &Origin) -> [String; 3] { ["--base-url".to_owned(), origin.as_key(), "mcp".to_owned()] } @@ -271,3 +375,151 @@ impl<'de> Visitor<'de> for UniqueVisitor { Ok(UniqueJson) } } + +#[cfg(test)] +mod tests { + use clap::ValueEnum as _; + use serde_json::json; + + use super::{Client, InstallError, registration}; + + #[test] + fn json_extraction_uses_the_effective_container_and_registration() { + for client in Client::value_variants() + .iter() + .copied() + .filter(|client| *client != Client::Codex) + { + for (raw, expected) in [ + (br#"{}"#.as_slice(), None), + (br#"{"mcpServers":{"other":{"command":"private-status-canary"}}}"#.as_slice(), None), + (br#"{"mcpServers":{"proofline":null}}"#.as_slice(), Some(json!(null))), + (br#"{"mcpServers":null,"mcpServers":{"proofline":null,"proofline":{"command":"old","command":"proofline","args":[],"args":["mcp"]}}}"#.as_slice(), Some(json!({"command":"proofline","args":["mcp"]}))), + (br#"{"mcpServers":{"proofline":{},"proofline":null}}"#.as_slice(), Some(json!(null))), + ] { + assert_eq!(registration(client, raw).unwrap(), expected); + } + for raw in [b"[]".as_slice(), b"null".as_slice()] { + assert!(matches!( + registration(client, raw), + Err(InstallError::ConfigShape { member: "root", .. }) + )); + } + for raw in [ + br#"{"mcpServers":null}"#.as_slice(), + br#"{"mcpServers":[]}"#.as_slice(), + ] { + assert!(matches!( + registration(client, raw), + Err(InstallError::ConfigShape { + member: "mcpServers", + .. + }) + )); + } + for raw in [b"\xff".as_slice(), b"{".as_slice()] { + assert!(matches!( + registration(client, raw), + Err(InstallError::InvalidConfig(_)) + )); + } + } + } + + #[test] + fn toml_extraction_accepts_tables_and_keeps_syntax_validation_strict() { + for raw in [ + "[mcp_servers.proofline]\ncommand='proofline'\nargs=['mcp']\n", + "mcp_servers={proofline={command='proofline',args=['mcp']}}\nwhen=2026-11-06T12:00:00Z\n", + "'a.b' = { 'c.d' = '''{ [ x.y = z ] }''' } # { [ ignored.key\n[mcp_servers.proofline]\ncommand='proofline'\nargs=['mcp']\n", + ] { + assert_eq!( + registration(Client::Codex, raw.as_bytes()).unwrap(), + Some(json!({"command":"proofline","args":["mcp"]})) + ); + } + for raw in ["", "[mcp_servers.other]\ncommand='other'\n"] { + assert!( + registration(Client::Codex, raw.as_bytes()) + .unwrap() + .is_none() + ); + } + assert_eq!( + registration(Client::Codex, b"mcp_servers={proofline=42}").unwrap(), + Some(json!(42)) + ); + assert!(matches!( + registration(Client::Codex, b"mcp_servers=[]"), + Err(InstallError::ConfigShape { + member: "mcp_servers", + .. + }) + )); + for raw in [ + b"\xff".as_slice(), + b"[mcp_servers.proofline".as_slice(), + b"private='private-status-canary'\nprivate='duplicate'".as_slice(), + b"[mcp_servers.proofline]\ncommand='first'\ncommand='last'".as_slice(), + ] { + assert!(matches!( + registration(Client::Codex, raw), + Err(InstallError::InvalidConfig(_)) + )); + } + } + + #[test] + fn toml_inspection_bounds_structural_depth_including_dotted_keys_and_arrays() { + for (raw, valid) in [ + (format!("{} = 1\n", vec!["x"; 64].join(".")), true), + (format!("{} = 1\n", vec!["x"; 65].join(".")), false), + (format!("a = {{ {} = 1 }}\n", vec!["x"; 63].join(".")), true), + ( + format!("a = {{ {} = 1 }}\n", vec!["x"; 64].join(".")), + false, + ), + (format!("a = {}1{}\n", "[".repeat(63), "]".repeat(63)), true), + ( + format!("a = {}1{}\n", "[".repeat(64), "]".repeat(64)), + false, + ), + (format!("[[{}]]\na = 1\n", vec!["x"; 62].join(".")), true), + (format!("[[{}]]\na = 1\n", vec!["x"; 63].join(".")), false), + ] { + let result = registration(Client::Codex, raw.as_bytes()); + if valid { + assert!(result.unwrap().is_none()); + } else { + assert!(matches!( + result, + Err(InstallError::InvalidConfig(Client::Codex)) + )); + } + } + for (ancestors, valid) in [(31, true), (32, false)] { + let mut raw: String = (1..=ancestors) + .map(|depth| format!("[[{}]]\n", vec!["x"; depth].join("."))) + .collect(); + raw.push_str("a = 1\n"); + let result = registration(Client::Codex, raw.as_bytes()); + if valid { + assert!(result.unwrap().is_none()); + } else { + assert!(matches!( + result, + Err(InstallError::InvalidConfig(Client::Codex)) + )); + } + } + let raw = format!( + "{} = 1\n[mcp_servers]\nproofline = 42\n", + vec!["x"; 65].join(".") + ); + let origin = crate::origin::Origin::parse("https://proofline.sh").unwrap(); + assert!(matches!( + super::prepare(Client::Codex, Some(raw.as_bytes()), &origin), + Ok(super::Update::Existing) + )); + } +} diff --git a/src/agent/status.rs b/src/agent/status.rs new file mode 100644 index 0000000..3d11c66 --- /dev/null +++ b/src/agent/status.rs @@ -0,0 +1,413 @@ +//! Static inspection never starts the configured MCP server. + +use std::fs; +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use clap::{CommandFactory as _, ValueEnum as _, parser::ValueSource}; +use serde_json::{Map, Value}; +use uuid::Uuid; + +use super::{Client, InstallError, config, store}; +use crate::origin::{DEFAULT_ORIGIN, Origin}; +use crate::{Cli, Verdict}; + +#[derive(Debug)] +enum Status { + Missing(&'static str), + Invalid(&'static str), + Valid, + Unverified(&'static str), +} + +impl Status { + const fn message(&self) -> (&'static str, &'static str) { + match self { + Self::Missing(reason) => ("Missing registration", reason), + Self::Invalid(reason) => ("Invalid registration", reason), + Self::Valid => ("Configuration valid", "local stdio MCP registration."), + Self::Unverified(reason) => ("Unable to verify", reason), + } + } +} + +#[derive(Debug)] +struct Report { + status: Status, + origin: Option<(Origin, &'static str)>, +} + +impl From for Report { + fn from(status: Status) -> Self { + Self { + status, + origin: None, + } + } +} + +pub(super) fn run(client: Client) -> anyhow::Result { + let mut output = io::stdout().lock(); + let report = match target(client) { + Ok(path) => { + writeln!(output, "User-level configuration ({client}): {path:?}")?; + inspect(client, &path).unwrap_or_else(Report::from) + } + Err(reason) => { + writeln!( + output, + "User-level configuration ({client}): path unresolved" + )?; + Report::from(Status::Unverified(reason)) + } + }; + let (label, reason) = report.status.message(); + writeln!(output, "{label}: {reason}")?; + if let Some((origin, source)) = report.origin { + writeln!(output, "Origin: {origin} ({source})")?; + } + if matches!(report.status, Status::Missing(_)) + && let Some(name) = client.to_possible_value() + { + if client == Client::Codex && std::env::var_os("CODEX_HOME").is_some() { + writeln!( + output, + "Next: use `proofline agent install codex --print` and add the entry to the inspected CODEX_HOME configuration." + )?; + } else { + writeln!( + output, + "Next: use `proofline agent install {}` to add a user-level entry.", + name.get_name() + )?; + } + } + writeln!( + output, + "User-level configuration only; local/project scopes, connectivity and authentication were not checked." + )?; + Ok( + if matches!(report.status, Status::Missing(_) | Status::Invalid(_)) { + Verdict::Blocked + } else { + Verdict::Done + }, + ) +} + +fn target(client: Client) -> Result { + if client == Client::ClaudeCode && std::env::var_os("CLAUDE_CONFIG_DIR").is_some() { + return Err("CLAUDE_CONFIG_DIR selects custom configuration; inspect it manually."); + } + if client == Client::Codex + && let Some(home) = std::env::var_os("CODEX_HOME") + { + return Ok(PathBuf::from(home).join("config.toml")); + } + let home = std::env::home_dir() + .filter(|home| home.is_absolute()) + .ok_or("Could not resolve an absolute user home directory; check the client configuration manually.")?; + Ok(home.join(client.relative_path())) +} + +fn inspect(client: Client, path: &Path) -> Result { + if !path.is_absolute() { + return Err(Status::Unverified( + "The configuration path is relative; the agent's working directory is unknown.", + )); + } + let bytes = match store::inspect(path) { + Ok(Some(bytes)) => bytes, + Ok(None) => { + return Err(Status::Missing( + "Configuration file not found in the inspected user-level scope.", + )); + } + Err(InstallError::TooLarge) => { + return Err(Status::Unverified( + "Configuration exceeds the 1 MiB inspection limit; inspect it manually.", + )); + } + Err(InstallError::File(_)) => { + return Err(Status::Unverified( + "Configuration is not a readable regular file; check the file or symlink target.", + )); + } + Err(InstallError::Changed(_)) => { + return Err(Status::Unverified( + "Configuration changed while reading; retry the command.", + )); + } + Err(_) => { + return Err(Status::Unverified( + "Could not read configuration; check the file and its permissions.", + )); + } + }; + let registration = match config::registration(client, &bytes) { + Ok(Some(registration)) => registration, + Ok(None) => { + return Err(Status::Missing( + "No Proofline MCP entry in the inspected user-level scope.", + )); + } + Err(InstallError::ConfigShape { member: "root", .. }) => { + return Err(Status::Invalid( + "Configuration root must be an object or table; correct the document structure.", + )); + } + Err(InstallError::ConfigShape { .. }) => { + return Err(Status::Invalid( + "MCP container must be an object or table; correct its structure.", + )); + } + Err(_) => { + return Err(Status::Invalid( + "Could not parse configuration; check its JSON/TOML syntax and nesting depth.", + )); + } + }; + validate(®istration) +} + +fn validate(registration: &Value) -> Result { + let Some(server) = registration.as_object() else { + return Err(Status::Invalid( + "Proofline entry must be an object or table; replace the invalid entry manually.", + )); + }; + if server.contains_key("url") + || server.contains_key("httpUrl") + || server + .get("type") + .and_then(Value::as_str) + .is_some_and(|kind| { + matches!(kind, "http" | "sse" | "streamable-http" | "streamable_http") + }) + { + return Err(Status::Unverified( + "Remote HTTP/SSE MCP registration; only local stdio launchers are supported by this diagnostic.", + )); + } + let Some(command) = server + .get("command") + .and_then(Value::as_str) + .filter(|command| !command.trim().is_empty() && !command.contains('\0')) + else { + return Err(Status::Invalid( + "command must be a non-empty executable string; correct the Proofline entry.", + )); + }; + let args: Vec<&str> = match server.get("args") { + None => Vec::new(), + Some(Value::Array(args)) => { + let Some(args) = args.iter().map(Value::as_str).collect::>>() else { + return Err(Status::Invalid( + "args must contain only strings; correct the Proofline entry.", + )); + }; + if args.iter().any(|arg| arg.contains('\0')) { + return Err(Status::Invalid( + "args must not contain NUL characters; correct the Proofline entry.", + )); + } + args + } + Some(_) => { + return Err(Status::Invalid( + "args must be an array of strings; correct the Proofline entry.", + )); + } + }; + if server + .get("type") + .is_some_and(|kind| kind.as_str() != Some("stdio")) + { + return Err(Status::Invalid( + "Expected a stdio MCP registration; correct its transport fields.", + )); + } + for key in ["enabled", "disabled"] { + if server.get(key).is_some_and(|value| !value.is_boolean()) { + return Err(Status::Invalid( + "enabled and disabled must be booleans; correct the Proofline entry.", + )); + } + } + let env = match server.get("env") { + None => None, + Some(Value::Object(env)) if env.values().all(Value::is_string) => Some(env), + Some(_) => { + return Err(Status::Invalid( + "env must be an object or table of strings; correct the Proofline entry.", + )); + } + }; + if env.is_some_and(|env| { + env.iter().any(|(key, value)| { + key.contains('\0') || value.as_str().is_some_and(|value| value.contains('\0')) + }) + }) { + return Err(Status::Invalid( + "env keys and values must not contain NUL characters; correct the registration environment.", + )); + } + if !inspect_executable(command)? { + return Err(Status::Unverified( + "Custom executable or launcher; verify its MCP arguments and origin manually. It was not executed.", + )); + } + let disabled = server.get("enabled").and_then(Value::as_bool) == Some(false) + || server.get("disabled").and_then(Value::as_bool) == Some(true); + validate_invocation(Path::new(command), &args, env, disabled) +} + +fn inspect_executable(command: &str) -> Result { + let executable = Path::new(command); + if command.contains("${") { + return Err(Status::Unverified( + "Executable uses variable expansion; verify the agent's resolved path manually.", + )); + } + if executable.is_absolute() { + let metadata = match fs::metadata(executable) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return Err(Status::Invalid( + "Configured executable is missing; update command to an existing executable.", + )); + } + Err(_) => { + return Err(Status::Unverified( + "Could not inspect the configured executable; check its permissions.", + )); + } + }; + if !metadata.is_file() { + return Err(Status::Invalid( + "command does not point to a regular file; select an executable.", + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + if metadata.permissions().mode() & 0o111 == 0 { + return Err(Status::Invalid( + "Configured file has no execute permission; fix permissions or select an executable.", + )); + } + } + } + Ok(executable.file_name().is_some_and(|name| { + name == "proofline" || (cfg!(windows) && name.eq_ignore_ascii_case("proofline.exe")) + }) || std::env::current_exe().is_ok_and(|current| current == executable)) +} + +fn validate_invocation( + executable: &Path, + args: &[&str], + env: Option<&Map>, + disabled: bool, +) -> Result { + if args.iter().any(|arg| arg.contains("${")) { + return Err(Status::Unverified( + "Arguments use variable expansion; verify the agent's resolved MCP arguments and origin manually.", + )); + } + // Ignore this process's environment: the registration belongs to another process. + let parser = Cli::command() + .mut_arg("base_url", |arg| arg.env(None::<&str>)) + .mut_arg("org", |arg| arg.env(None::<&str>)); + let matches = match parser + .try_get_matches_from(std::iter::once("proofline").chain(args.iter().copied())) + { + Ok(matches) if matches.subcommand_name() == Some("mcp") => matches, + _ => { + return Err(Status::Invalid( + "args must invoke `proofline mcp` with valid CLI options; correct the MCP subcommand and arguments.", + )); + } + }; + if matches.get_one::("org").is_none() { + organization(environment( + env, + "PROOFLINE_ORGANIZATION_ID", + cfg!(windows), + )?)?; + } + let (raw_origin, source) = if matches.value_source("base_url") == Some(ValueSource::CommandLine) + { + ( + matches + .get_one::("base_url") + .map_or(DEFAULT_ORIGIN, String::as_str), + "registration args --base-url", + ) + } else if let Some(origin) = environment(env, "PROOFLINE_BASE_URL", cfg!(windows))? { + (origin, "registration env PROOFLINE_BASE_URL") + } else { + (DEFAULT_ORIGIN, "CLI default") + }; + if raw_origin.contains("${") { + return Err(Status::Unverified( + "Origin uses variable expansion; verify the agent's resolved origin manually.", + )); + } + let origin = Origin::parse(raw_origin).map_err(|_| Status::Invalid( + "Origin must be HTTPS or loopback HTTP, without credentials, path, query or fragment; correct the configured base URL." + ))?; + let status = if disabled { + Status::Unverified("Registration is disabled; enable it in the coding agent if intended.") + } else if !executable.is_absolute() { + Status::Unverified( + "Executable depends on PATH or the agent's working directory; use an absolute path or verify it manually.", + ) + } else { + Status::Valid + }; + Ok(Report { + status, + origin: Some((origin, source)), + }) +} + +fn organization(value: Option<&str>) -> Result<(), Status> { + if let Some(value) = value { + if value.contains("${") { + return Err(Status::Unverified( + "Organization ID uses variable expansion; verify its resolved UUID manually.", + )); + } + Uuid::parse_str(value).map_err(|_| { + Status::Invalid( + "PROOFLINE_ORGANIZATION_ID must be a UUID; correct the registration environment.", + ) + })?; + } + Ok(()) +} + +fn environment<'a>( + env: Option<&'a Map>, + name: &str, + windows: bool, +) -> Result, Status> { + let mut found = None; + if let Some(env) = env { + for (key, value) in env { + if key == name || (windows && key.eq_ignore_ascii_case(name)) { + let value = value.as_str(); + if found.is_some() && found != value { + return Err(Status::Unverified( + "Environment has conflicting case variants of a variable; resolve the ambiguity manually.", + )); + } + found = value; + } + } + } + Ok(found) +} + +#[cfg(test)] +mod tests; diff --git a/src/agent/status/tests.rs b/src/agent/status/tests.rs new file mode 100644 index 0000000..7d123e1 --- /dev/null +++ b/src/agent/status/tests.rs @@ -0,0 +1,331 @@ +use std::fs; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +use super::{Report, Status, environment, inspect, organization, validate}; + +const SECRET: &str = "private-status-canary"; + +fn entry() -> Value { + json!({"command": std::env::current_exe().unwrap(), "args": ["mcp"]}) +} + +fn check(value: &Value, label: &str, reason: &str) -> Report { + let report = validate(value).unwrap_or_else(Report::from); + assert_eq!(report.status.message().0, label, "{report:?}"); + assert!(report.status.message().1.contains(reason), "{report:?}"); + assert!(!report.status.message().1.contains(SECRET)); + report +} + +#[test] +fn registration_shape_is_validated_before_local_invocation_semantics() { + for value in [Value::Null, json!(42), json!([])] { + check(&value, "Invalid registration", "Proofline entry"); + } + check(&json!({}), "Invalid registration", "command must"); + for (field, replacement, reason) in [ + ("command", json!(42), "command must"), + ("command", json!(" "), "command must"), + ("command", json!("proofline\0"), "command must"), + ("args", json!(SECRET), "args must"), + ("args", json!(["mcp", 42]), "args must"), + ("args", json!(["mcp\0"]), "NUL"), + ("type", json!("unsupported"), "stdio MCP"), + ("type", json!(42), "stdio MCP"), + ("env", json!([]), "env must"), + ("env", json!({"SECRET":42}), "env must"), + ("enabled", json!(SECRET), "must be booleans"), + ("disabled", json!(SECRET), "must be booleans"), + ] { + let mut registration = entry(); + registration[field] = replacement; + check(®istration, "Invalid registration", reason); + } +} + +#[test] +fn remote_transports_do_not_require_a_local_executable() { + for value in [ + json!({"url":format!("https://user:{SECRET}@example.com/mcp")}), + json!({"httpUrl":"https://example.com/mcp"}), + json!({"type":"sse"}), + json!({"type":"http","command":"missing-executable"}), + json!({"type":"streamable-http"}), + json!({"type":"streamable_http"}), + ] { + check(&value, "Unable to verify", "Remote HTTP/SSE"); + } +} + +#[test] +fn direct_invocations_require_mcp_and_valid_cli_arguments() { + for args in [ + json!([]), + json!(["review"]), + json!(["mcp", "--unknown", SECRET]), + json!(["--base-url"]), + json!(["mcp", "--help"]), + json!(["mcp", "--version"]), + ] { + let mut value = entry(); + value["args"] = args; + check(&value, "Invalid registration", "args must invoke"); + } + let mut value = entry(); + value.as_object_mut().unwrap().remove("args"); + check(&value, "Invalid registration", "args must invoke"); +} + +#[test] +fn direct_origins_follow_argument_environment_and_default_precedence() { + for (args, env, expected, source) in [ + ( + json!(["--base-url", "https://alternate.example:8443", "mcp"]), + json!({"PROOFLINE_BASE_URL":SECRET}), + "https://alternate.example:8443", + "registration args --base-url", + ), + ( + json!(["mcp", "--base-url=http://[::1]:8080"]), + json!({}), + "http://[::1]:8080", + "registration args --base-url", + ), + ( + json!(["mcp"]), + json!({"PROOFLINE_BASE_URL":"https://alternate.example"}), + "https://alternate.example", + "registration env PROOFLINE_BASE_URL", + ), + ( + json!(["mcp"]), + json!({}), + "https://proofline.sh", + "CLI default", + ), + ] { + let mut value = entry(); + value["args"] = args; + value["env"] = env; + let report = check(&value, "Configuration valid", "stdio"); + let (origin, actual_source) = report.origin.unwrap(); + assert_eq!(origin.to_string(), expected); + assert_eq!(actual_source, source); + } + for origin in [ + "invalid", + "http://example.com", + "https://proofline.sh/api", + "https://proofline.sh/?token=private-status-canary", + "https://user:private-status-canary@proofline.sh", + ] { + let mut value = entry(); + value["args"] = json!(["mcp", "--base-url", origin]); + check(&value, "Invalid registration", "Origin must"); + value["args"] = json!(["mcp"]); + value["env"] = json!({"PROOFLINE_BASE_URL":origin}); + check(&value, "Invalid registration", "Origin must"); + } +} + +#[test] +fn direct_organization_environment_and_argument_precedence_use_cli_uuid_formats() { + for organization in [ + "00000000-0000-0000-0000-000000000000", + "0190F3A0000070008000000000000001", + "urn:uuid:0190f3a0-0000-7000-8000-000000000001", + ] { + let mut value = entry(); + value["env"] = json!({"PROOFLINE_ORGANIZATION_ID": organization}); + check(&value, "Configuration valid", "stdio"); + value["args"] = json!(["mcp", "--org", organization]); + value["env"]["PROOFLINE_ORGANIZATION_ID"] = json!(SECRET); + check(&value, "Configuration valid", "stdio"); + } + for organization in [SECRET, ""] { + let mut value = entry(); + value["env"] = json!({"PROOFLINE_ORGANIZATION_ID": organization}); + check(&value, "Invalid registration", "must be a UUID"); + } +} + +#[test] +fn custom_launchers_do_not_inherit_proofline_specific_environment_validation() { + for organization in [SECRET, "${LAUNCHER_TENANT}"] { + let value = json!({"command":"custom-launcher", "args":[SECRET], "env":{"PROOFLINE_ORGANIZATION_ID":organization,"PROOFLINE_BASE_URL":SECRET}}); + let report = check(&value, "Unable to verify", "Custom executable or launcher"); + assert!(report.origin.is_none()); + } +} + +#[test] +fn process_environment_keys_and_values_must_be_representable() { + for env in [ + json!({format!("{SECRET}\0KEY"): "value"}), + json!({"KEY": format!("{SECRET}\0value")}), + ] { + for command in [entry()["command"].clone(), json!("custom-launcher")] { + let mut value = entry(); + value["command"] = command; + value["env"] = env.clone(); + check( + &value, + "Invalid registration", + "env keys and values must not contain NUL", + ); + } + } + let mut value = entry(); + value["env"] = json!({"KEY WITH SPACES": "value=with=equals", "東京": ""}); + check(&value, "Configuration valid", "stdio"); +} + +#[test] +fn disabled_relative_and_expanded_invocations_remain_unverified() { + for (field, replacement, reason) in [ + ("disabled", json!(true), "Registration is disabled"), + ("enabled", json!(false), "Registration is disabled"), + ("command", json!("proofline"), "depends on PATH"), + ( + "command", + json!("${BIN}/proofline"), + "Executable uses variable expansion", + ), + ( + "args", + json!(["${MCP_SUBCOMMAND}"]), + "Arguments use variable expansion", + ), + ( + "env", + json!({"PROOFLINE_ORGANIZATION_ID":"${ORG}"}), + "Organization ID uses variable expansion", + ), + ( + "env", + json!({"PROOFLINE_BASE_URL":"${ORIGIN}"}), + "Origin uses variable expansion", + ), + ] { + let mut value = entry(); + value[field] = replacement; + check(&value, "Unable to verify", reason); + } +} + +#[test] +fn executable_files_and_read_failures_are_classified_without_execution() { + let root = TempDir::new().unwrap(); + let mut value = entry(); + value["command"] = json!(root.path().join("proofline")); + check(&value, "Invalid registration", "executable is missing"); + value["command"] = json!(root.path()); + check(&value, "Invalid registration", "regular file"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let file = root.path().join("proofline"); + fs::write(&file, b"not executed").unwrap(); + fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); + value["command"] = json!(file); + check(&value, "Invalid registration", "execute permission"); + } + let file = root.path().join("config.json"); + for bytes in [b"{}".as_slice(), br#"{"mcpServers":{}}"#.as_slice()] { + fs::write(&file, bytes).unwrap(); + assert!(matches!( + inspect(super::Client::ClaudeCode, &file), + Err(Status::Missing(_)) + )); + } + for (bytes, label, reason) in [ + (b"[]".as_slice(), "Invalid registration", "root"), + (b"\xff".as_slice(), "Invalid registration", "parse"), + ] { + fs::write(&file, bytes).unwrap(); + let error = inspect(super::Client::ClaudeCode, &file).unwrap_err(); + assert_eq!(error.message().0, label); + assert!(error.message().1.contains(reason)); + } + fs::remove_file(&file).unwrap(); + fs::create_dir_all(&file).unwrap(); + assert!(matches!( + inspect(super::Client::ClaudeCode, &file), + Err(Status::Unverified(_)) + )); +} + +#[cfg(unix)] +#[test] +fn dangling_looping_special_and_unreadable_configs_remain_unverifiable() { + use std::os::unix::fs::{PermissionsExt as _, symlink}; + let root = TempDir::new().unwrap(); + let path = root.path().join("config.json"); + for target in [ + root.path().join("missing"), + path.clone(), + root.path().to_owned(), + std::path::PathBuf::from("/dev/null"), + ] { + symlink(&target, &path).unwrap(); + assert!(matches!( + inspect(super::Client::ClaudeCode, &path), + Err(Status::Unverified(_)) + )); + assert_eq!(fs::read_link(&path).unwrap(), target); + fs::remove_file(&path).unwrap(); + } + fs::write( + &path, + serde_json::to_vec(&json!({"mcpServers":{"proofline":entry()}})).unwrap(), + ) + .unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap(); + let readable = fs::File::open(&path).is_ok(); + let report = inspect(super::Client::ClaudeCode, &path); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + if readable { + assert!(matches!(report.unwrap().status, Status::Valid)); + } else { + assert!(matches!(report, Err(Status::Unverified(_)))); + } +} + +#[test] +fn environment_lookup_matches_windows_and_unix_semantics() { + let mut env = json!({"proofline_base_url": "https://alternate.example"}); + assert_eq!( + environment(env.as_object(), "PROOFLINE_BASE_URL", false).unwrap(), + None + ); + assert_eq!( + environment(env.as_object(), "PROOFLINE_BASE_URL", true).unwrap(), + Some("https://alternate.example") + ); + env["PROOFLINE_BASE_URL"] = json!("https://different.example"); + assert!(matches!( + environment(env.as_object(), "PROOFLINE_BASE_URL", true), + Err(Status::Unverified(_)) + )); + assert_eq!( + environment(env.as_object(), "PROOFLINE_BASE_URL", false).unwrap(), + Some("https://different.example") + ); + env["PROOFLINE_BASE_URL"] = json!("https://alternate.example"); + assert_eq!( + environment(env.as_object(), "PROOFLINE_BASE_URL", true).unwrap(), + Some("https://alternate.example") + ); + let env = json!({"Proofline_Organization_ID": "00000000-0000-0000-0000-000000000000"}); + assert!( + organization(environment(env.as_object(), "PROOFLINE_ORGANIZATION_ID", true).unwrap()) + .is_ok() + ); + let env = json!({"proofline_organization_id": "invalid"}); + assert!(matches!( + organization(environment(env.as_object(), "PROOFLINE_ORGANIZATION_ID", true).unwrap()), + Err(Status::Invalid(_)) + )); +} diff --git a/src/agent/store.rs b/src/agent/store.rs index 8ce57c8..dda5d58 100644 --- a/src/agent/store.rs +++ b/src/agent/store.rs @@ -151,7 +151,7 @@ impl Layout { let directories = self.directories()?; self.outside_repository(&directories)?; self.lock_metadata()?; - let file = self.read_file()?; + let file = Self::read_file(&self.target)?; Ok(Snapshot { directories, file }) } @@ -314,36 +314,35 @@ impl Layout { Err(InstallError::GitProbe(self.target.clone())) } - fn read_file(&self) -> Result, InstallError> { - let Some(meta) = metadata(&self.target)? else { + fn read_file(target: &Path) -> Result, InstallError> { + let Some(meta) = metadata(target)? else { return Ok(None); }; - regular(&self.target, &meta)?; + regular(target, &meta)?; if meta.len() > MAX_BYTES { return Err(InstallError::TooLarge); } - let stamp = Stamp::read(&self.target, &meta)?; - let file = File::open(&self.target) - .map_err(|error| InstallError::io("read", &self.target, error))?; - let opened = file.metadata().map_err(|error| { - InstallError::io("inspect the opened configuration", &self.target, error) - })?; - if Stamp::read(&self.target, &opened)? != stamp { - return Err(InstallError::Changed(self.target.clone())); + let stamp = Stamp::read(target, &meta)?; + let file = File::open(target).map_err(|error| InstallError::io("read", target, error))?; + let opened = file + .metadata() + .map_err(|error| InstallError::io("inspect the opened configuration", target, error))?; + if Stamp::read(target, &opened)? != stamp { + return Err(InstallError::Changed(target.to_owned())); } let mut bytes = Vec::new(); file.take(MAX_BYTES + 1) .read_to_end(&mut bytes) - .map_err(|error| InstallError::io("read", &self.target, error))?; + .map_err(|error| InstallError::io("read", target, error))?; if u64::try_from(bytes.len()).map_err(|_| InstallError::TooLarge)? > MAX_BYTES { return Err(InstallError::TooLarge); } - let Some(final_meta) = metadata(&self.target)? else { - return Err(InstallError::Changed(self.target.clone())); + let Some(final_meta) = metadata(target)? else { + return Err(InstallError::Changed(target.to_owned())); }; - regular(&self.target, &final_meta)?; - if Stamp::read(&self.target, &final_meta)? != stamp { - return Err(InstallError::Changed(self.target.clone())); + regular(target, &final_meta)?; + if Stamp::read(target, &final_meta)? != stamp { + return Err(InstallError::Changed(target.to_owned())); } Ok(Some(RecordedFile { bytes, @@ -475,3 +474,22 @@ fn regular(path: &Path, meta: &Metadata) -> Result<(), InstallError> { } Ok(()) } + +pub(super) fn inspect(target: &Path) -> Result>, InstallError> { + let resolved = match target.canonicalize() { + Ok(resolved) => resolved, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return match metadata(target)? { + None => Ok(None), + Some(_) => Err(InstallError::File(target.to_owned())), + }; + } + Err(error) => return Err(InstallError::io("resolve configuration", target, error)), + }; + let file = + Layout::read_file(&resolved)?.ok_or_else(|| InstallError::Changed(target.to_owned()))?; + if target.canonicalize().ok().as_ref() != Some(&resolved) { + return Err(InstallError::Changed(target.to_owned())); + } + Ok(Some(file.bytes)) +} diff --git a/src/lib.rs b/src/lib.rs index 6096711..372b40b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,7 +27,9 @@ use std::path::PathBuf; use std::time::Duration; use anyhow::{Context as _, bail}; -use clap::{Args, Parser, Subcommand}; +use clap::{ + Args, CommandFactory as _, FromArgMatches as _, Parser, Subcommand, parser::ValueSource, +}; use secrecy::{ExposeSecret as _, SecretString}; use uuid::Uuid; @@ -73,6 +75,46 @@ pub struct Cli { command: Command, } +impl Cli { + /// Parse an invocation, rejecting origin overrides for read-only agent inspection. + pub fn parse_invocation() -> Result { + let args: Vec<_> = std::env::args_os().collect(); + let mut parser = Self::command(); + // Identify status without reading the invoking process's configuration. + let matches = parser + .clone() + .ignore_errors(true) + .disable_help_flag(true) + .disable_version_flag(true) + .mut_arg("base_url", |arg| arg.env(None::<&str>)) + .mut_arg("org", |arg| { + arg.env(None::<&str>) + .value_parser(clap::builder::StringValueParser::new()) + }) + .try_get_matches_from(&args); + if let Ok(matches) = matches + && matches + .subcommand_matches("agent") + .and_then(|agent| agent.subcommand_matches("status")) + .is_some() + { + if ["base_url", "org"] + .iter() + .any(|name| matches.value_source(name) == Some(ValueSource::CommandLine)) + { + return Err(clap::Error::raw( + clap::error::ErrorKind::ArgumentConflict, + "agent status reads the registration's origin and organization; --base-url and --org are not supported", + )); + } + parser = parser + .mut_arg("base_url", |arg| arg.env(None::<&str>)) + .mut_arg("org", |arg| arg.env(None::<&str>)); + } + Self::from_arg_matches(&parser.try_get_matches_from(args)?) + } +} + #[derive(Debug, Subcommand)] enum Command { /// Read fix context and verify fixes at an explicitly pushed commit. @@ -119,7 +161,7 @@ enum Command { Update, #[command(name = "__update-check", hide = true)] UpdateCheck, - /// Configure a coding agent to use the existing local MCP bridge. + /// Configure or inspect a coding agent's local MCP bridge. Agent(agent::AgentArgs), /// Sign in through the browser and keep the token in the OS keychain. Login(LoginArgs), @@ -352,7 +394,7 @@ pub enum Verdict { Unavailable, /// A complete review has an open finding at or above `ci review --fail-on`. ThresholdReached, - /// A Git hook's exit policy refuses the commit or push. + /// A command reports a failed check without an additional error message. Blocked, } @@ -366,7 +408,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + return agent::run(args, cli.base_url).await; + } Command::Update => return update::install().await.map(|()| Verdict::Done), Command::UpdateCheck => { update::check().await; @@ -448,7 +493,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result agent::run(args, origin).await.map(|()| Verdict::Done), + Command::Agent(args) => agent::run(args, cli.base_url).await, Command::Login(args) => { let http = Http::new(origin)?; login(&http, &args, cli.org, token.is_some()) diff --git a/src/main.rs b/src/main.rs index 6bb62f6..4bcd050 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,13 +2,12 @@ use std::process::ExitCode; -use clap::Parser as _; use proofline_cli::{Cli, Verdict, run}; use secrecy::SecretString; fn main() -> ExitCode { proofline_cli::update::on_invocation(); - let cli = match Cli::try_parse() { + let cli = match Cli::parse_invocation() { Ok(cli) => cli, Err(error) => { if error.print().is_err() { diff --git a/src/update.rs b/src/update.rs index 76273ab..ad04897 100644 --- a/src/update.rs +++ b/src/update.rs @@ -91,6 +91,7 @@ pub fn on_invocation() { if args .iter() .any(|arg| arg == "update" || arg == "__update-check") + || (args.iter().any(|arg| arg == "agent") && args.iter().any(|arg| arg == "status")) { return; } diff --git a/tests/agent_status.rs b/tests/agent_status.rs new file mode 100644 index 0000000..249ebff --- /dev/null +++ b/tests/agent_status.rs @@ -0,0 +1,556 @@ +//! Process-level contracts; semantic cases live beside the validator and parsers. + +use std::fs; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[cfg(unix)] +use std::os::unix::fs::{PermissionsExt as _, symlink}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +const SECRET: &str = "private-status-canary"; +const CLIENTS: [(&str, &str); 5] = [ + ("claude-code", ".claude.json"), + ("codex", ".codex/config.toml"), + ("cursor", ".cursor/mcp.json"), + ("gemini", ".gemini/settings.json"), + ("kiro", ".kiro/settings/mcp.json"), +]; + +fn command(home: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .env("HOME", home) + .env("USERPROFILE", home) + .env("XDG_CACHE_HOME", home.join("cache")) + .env("LOCALAPPDATA", home.join("cache")) + .env_remove("CODEX_HOME") + .env_remove("CLAUDE_CONFIG_DIR") + .env_remove("PROOFLINE_NO_UPDATE_CHECK") + .env_remove("PROOFLINE_ORGANIZATION_ID") + .env("PROOFLINE_TOKEN", SECRET) + .env("PROOFLINE_BASE_URL", "invalid-invoking-process-origin") + .stdin(Stdio::null()); + command +} + +fn entries(root: &Path) -> Vec<(PathBuf, Option>)> { + fn visit(root: &Path, path: &Path, entries: &mut Vec<(PathBuf, Option>)>) { + for entry in fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + let relative = path.strip_prefix(root).unwrap().to_owned(); + if path.is_dir() { + entries.push((relative, None)); + visit(root, &path, entries); + } else { + entries.push((relative, Some(fs::read(path).unwrap()))); + } + } + } + let mut found = Vec::new(); + visit(root, root, &mut found); + found.sort(); + found +} + +fn check(home: &Path, command: &mut Command, code: i32, expected: &str) -> String { + let before = entries(home); + let output = command.output().unwrap(); + assert_eq!(output.status.code(), Some(code), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains(expected), "{text}"); + assert!(!text.contains(SECRET), "{text}"); + assert!( + text.contains("local/project scopes, connectivity and authentication were not checked") + ); + assert_eq!(entries(home), before); + text +} + +fn status(home: &Path, client: &str, code: i32, expected: &str) -> String { + check( + home, + command(home).args(["agent", "status", client]), + code, + expected, + ) +} + +fn seed(home: &Path, relative: &str, bytes: &[u8]) -> PathBuf { + let path = home.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, bytes).unwrap(); + path +} + +fn registration(home: &Path, client: &str, relative: &str, server: Value) -> PathBuf { + let key = if client == "codex" { + "mcp_servers" + } else { + "mcpServers" + }; + let document = json!({key: {"proofline":server}, "private":SECRET}); + let bytes = if client == "codex" { + toml::to_string(&document).unwrap() + } else { + document.to_string() + }; + seed(home, relative, bytes.as_bytes()) +} + +fn server() -> Value { + json!({"command":env!("CARGO_BIN_EXE_proofline"),"args":["mcp"]}) +} + +#[test] +fn all_clients_report_missing_then_accept_installer_generated_entries_without_writes() { + let home = TempDir::new().unwrap(); + for (client, relative) in CLIENTS { + let path = home.path().join(relative); + let missing = status(home.path(), client, 1, "Missing registration:"); + assert!(missing.contains(&format!("{path:?}"))); + assert!(missing.contains(&format!("proofline agent install {client}"))); + assert!(!missing.contains("CLIENT")); + let preview = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env_remove("PROOFLINE_BASE_URL") + .args(["agent", "install", client, "--print"]) + .output() + .unwrap(); + assert!(preview.status.success(), "{preview:?}"); + seed(home.path(), relative, &preview.stdout); + let metadata = fs::metadata(&path).unwrap(); + let text = status(home.path(), client, 0, "Configuration valid:"); + assert!(text.contains("Origin: https://proofline.sh (registration args --base-url)")); + assert_eq!( + fs::metadata(&path).unwrap().modified().unwrap(), + metadata.modified().unwrap() + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions(), + metadata.permissions() + ); + } + status(home.path(), "claude", 0, "Configuration valid:"); +} + +#[test] +fn deeply_nested_toml_returns_invalid_without_aborting_or_disclosing_contents() { + let home = TempDir::new().unwrap(); + let key = vec!["x"; 60].join("."); + for nesting in [10, 100] { + let config = format!( + "a = {}1{}\nprivate = '{SECRET}'\n", + format!("{{{key} = ").repeat(nesting), + "}".repeat(nesting), + ); + seed(home.path(), ".codex/config.toml", config.as_bytes()); + status( + home.path(), + "codex", + 1, + "Invalid registration: Could not parse configuration; check its JSON/TOML syntax and nesting depth.", + ); + } +} + +#[test] +fn invalid_and_unverified_entries_have_explicit_exit_codes_and_redacted_diagnostics() { + let home = TempDir::new().unwrap(); + let mut bad_origin = server(); + bad_origin["args"] = json!([ + "mcp", + "--base-url", + format!("https://user:{SECRET}@example.com") + ]); + for (entry, code, label) in [ + (json!(42), 1, "Invalid registration: Proofline entry"), + (bad_origin, 1, "Invalid registration: Origin must"), + ( + json!({"command":env!("CARGO_BIN_EXE_proofline"),"args":["mcp"],"env":{"PROOFLINE_ORGANIZATION_ID":SECRET}}), + 1, + "Invalid registration: PROOFLINE_ORGANIZATION_ID", + ), + ( + json!({"command":"custom-launcher","args":[SECRET],"env":{"PROOFLINE_ORGANIZATION_ID":SECRET}}), + 0, + "Unable to verify: Custom executable or launcher", + ), + ( + json!({"url":format!("https://user:{SECRET}@example.com/mcp")}), + 0, + "Unable to verify: Remote HTTP/SSE", + ), + ] { + registration(home.path(), "codex", ".codex/config.toml", entry); + let text = status(home.path(), "codex", code, label); + assert_eq!(text.matches(label).count(), 1); + } +} + +#[test] +fn status_ignores_invoking_organization_but_rejects_explicit_global_overrides() { + let home = TempDir::new().unwrap(); + registration(home.path(), "claude-code", ".claude.json", server()); + check( + home.path(), + command(home.path()) + .env("PROOFLINE_ORGANIZATION_ID", SECRET) + .args(["agent", "status", "claude"]), + 0, + "Configuration valid:", + ); + for args in [ + vec!["--base-url", SECRET, "agent", "status", "claude"], + vec!["agent", "status", "claude", "--base-url", SECRET], + vec!["agent", "--base-url", SECRET, "status", "claude"], + vec![ + "agent", + "status", + "claude", + "--base-url=private-status-canary", + ], + vec!["--org", SECRET, "agent", "status", "claude"], + vec!["agent", "status", "claude", "--org", SECRET], + vec!["agent", "status", "claude", "--org=private-status-canary"], + ] { + let before = entries(home.path()); + let output = command(home.path()) + .env("PROOFLINE_ORGANIZATION_ID", SECRET) + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let text = String::from_utf8(output.stderr).unwrap(); + assert!( + text.contains("--base-url and --org are not supported"), + "{text}" + ); + assert!(!text.contains(SECRET)); + assert_eq!(entries(home.path()), before); + } + for (args, code) in [ + (vec!["agent", "status", "--help"], 0), + (vec!["agent", "status", "unsupported"], 1), + (vec!["agent", "status"], 1), + ] { + let before = entries(home.path()); + let output = command(home.path()) + .env("PROOFLINE_ORGANIZATION_ID", SECRET) + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(code), "{output:?}"); + if code == 0 { + let help = String::from_utf8(output.stdout).unwrap(); + assert!(help.contains("Status does not accept --base-url or --org")); + assert!(!help.contains(SECRET)); + } + assert_eq!(entries(home.path()), before); + } +} + +#[cfg(unix)] +#[test] +fn status_ignores_non_utf8_invoking_origin_without_changing_other_commands() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt as _; + + let home = TempDir::new().unwrap(); + registration(home.path(), "claude-code", ".claude.json", server()); + let origin = OsString::from_vec(vec![0xff]); + check( + home.path(), + command(home.path()) + .env("PROOFLINE_BASE_URL", &origin) + .env("PROOFLINE_ORGANIZATION_ID", SECRET) + .args(["agent", "status", "claude"]), + 0, + "Configuration valid:", + ); + for args in [ + vec!["setup", "--print"], + vec!["agent", "install", "claude", "--print"], + ] { + let before = entries(home.path()); + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", &origin) + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("invalid UTF-8")); + assert_eq!(entries(home.path()), before); + } +} + +#[test] +fn other_commands_keep_invoking_organization_validation() { + let home = TempDir::new().unwrap(); + for args in [ + vec!["setup", "--print"], + vec!["agent", "install", "claude", "--print"], + ] { + let invalid = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", "https://proofline.sh") + .env("PROOFLINE_ORGANIZATION_ID", SECRET) + .args(&args) + .output() + .unwrap(); + assert_eq!(invalid.status.code(), Some(1)); + assert!(invalid.stdout.is_empty()); + let valid = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", "https://proofline.sh") + .env( + "PROOFLINE_ORGANIZATION_ID", + "00000000-0000-0000-0000-000000000000", + ) + .args(&args) + .output() + .unwrap(); + assert_eq!(valid.status.code(), Some(0), "{valid:?}"); + } + for args in [["review", "--help"], ["help", "review"]] { + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .args(args) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(0)); + let help = String::from_utf8(output.stdout).unwrap(); + assert!(help.contains("--help")); + assert!(help.contains("PROOFLINE_ORGANIZATION_ID")); + } +} + +#[test] +fn origin_and_organization_precedence_survive_parsing_and_rendering() { + let home = TempDir::new().unwrap(); + for (args, env, expected) in [ + ( + json!([ + "mcp", + "--base-url=https://alternate.example", + "--org", + "00000000-0000-0000-0000-000000000000" + ]), + json!({"PROOFLINE_BASE_URL":SECRET,"PROOFLINE_ORGANIZATION_ID":SECRET,"PROOFLINE_TOKEN":SECRET}), + "Origin: https://alternate.example (registration args --base-url)", + ), + ( + json!(["mcp"]), + json!({"PROOFLINE_BASE_URL":"http://127.0.0.1:3000","PROOFLINE_ORGANIZATION_ID":"00000000-0000-0000-0000-000000000000","PROOFLINE_TOKEN":SECRET}), + "Origin: http://127.0.0.1:3000 (registration env PROOFLINE_BASE_URL)", + ), + ( + json!(["mcp"]), + json!({}), + "Origin: https://proofline.sh (CLI default)", + ), + ] { + registration( + home.path(), + "cursor", + ".cursor/mcp.json", + json!({"command":env!("CARGO_BIN_EXE_proofline"),"args":args,"env":env}), + ); + status(home.path(), "cursor", 0, expected); + } +} + +#[test] +fn json_inspection_and_installation_keep_separate_duplicate_policies() { + let home = TempDir::new().unwrap(); + let bytes = format!( + "{{\"mcpServers\":{{\"proofline\":null,\"proofline\":{}}}}}", + server() + ); + let path = seed(home.path(), ".claude.json", bytes.as_bytes()); + status(home.path(), "claude", 0, "Configuration valid:"); + let refused = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env_remove("PROOFLINE_BASE_URL") + .args(["agent", "install", "claude", "--yes"]) + .output() + .unwrap(); + assert_eq!(refused.status.code(), Some(1)); + assert!(!String::from_utf8_lossy(&refused.stderr).contains(SECRET)); + assert_eq!(fs::read_to_string(path).unwrap(), bytes); +} + +#[test] +fn inspection_keeps_configurations_and_stale_update_state_unchanged_without_http() { + let home = TempDir::new().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + registration( + home.path(), + "claude-code", + ".claude.json", + json!({"command":env!("CARGO_BIN_EXE_proofline"),"args":["mcp","--base-url",origin]}), + ); + for stale_cache in [false, true] { + if stale_cache { + seed( + home.path(), + "cache/proofline/update.json", + b"{\"checked\":0,\"latest\":\"9.0.0\"}", + ); + } + check( + home.path(), + command(home.path()) + .env("PROOFLINE_BASE_URL", &origin) + .args(["agent", "status", "claude"]), + 0, + "Configuration valid:", + ); + } + assert_eq!( + listener.accept().unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); +} + +#[test] +fn custom_homes_do_not_fall_back_to_default_configuration_or_misleading_hints() { + let home = TempDir::new().unwrap(); + registration(home.path(), "codex", ".codex/config.toml", server()); + let custom = home.path().join("custom"); + let text = check( + home.path(), + command(home.path()) + .env("CODEX_HOME", &custom) + .args(["agent", "status", "codex"]), + 1, + "Missing registration:", + ); + assert!(text.contains(&format!("{:?}", custom.join("config.toml")))); + assert!(text.contains("proofline agent install codex --print")); + registration(home.path(), "codex", "custom/config.toml", server()); + check( + home.path(), + command(home.path()) + .env("CODEX_HOME", &custom) + .args(["agent", "status", "codex"]), + 0, + "Configuration valid:", + ); + check( + home.path(), + command(home.path()) + .env("CODEX_HOME", "relative") + .args(["agent", "status", "codex"]), + 0, + "Unable to verify: The configuration path is relative", + ); + check( + home.path(), + command(home.path()) + .env("CLAUDE_CONFIG_DIR", custom) + .args(["agent", "status", "claude"]), + 0, + "Unable to verify: CLAUDE_CONFIG_DIR", + ); +} + +#[cfg(unix)] +#[test] +fn executable_marker_and_external_symlink_targets_are_never_modified() { + let home = TempDir::new().unwrap(); + let targets = TempDir::new().unwrap(); + let executable = targets.path().join("proofline"); + fs::write( + &executable, + b"#!/bin/sh\nprintf executed > \"$0.executed\"\nexit 99\n", + ) + .unwrap(); + fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap(); + for (client, relative) in [ + ("claude-code", ".claude.json"), + ("codex", ".codex/config.toml"), + ] { + let target = registration( + targets.path(), + client, + relative, + json!({"command":executable,"args":["mcp"]}), + ); + let path = home.path().join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + symlink(&target, &path).unwrap(); + let before = entries(targets.path()); + let metadata = fs::metadata(&target).unwrap(); + status(home.path(), client, 0, "Configuration valid:"); + assert_eq!(entries(targets.path()), before); + assert_eq!( + fs::metadata(&target).unwrap().modified().unwrap(), + metadata.modified().unwrap() + ); + assert_eq!( + fs::metadata(&target).unwrap().permissions(), + metadata.permissions() + ); + assert_eq!(fs::read_link(&path).unwrap(), target); + fs::write(&target, vec![b' '; 1024 * 1024 + 1]).unwrap(); + let before = entries(targets.path()); + status( + home.path(), + client, + 0, + "Unable to verify: Configuration exceeds", + ); + assert_eq!(entries(targets.path()), before); + } + let launcher = targets.path().join("custom launcher"); + fs::rename(executable, &launcher).unwrap(); + registration( + home.path(), + "cursor", + ".cursor/mcp.json", + json!({"command":launcher,"args":[SECRET],"env":{"PROOFLINE_ORGANIZATION_ID":SECRET}}), + ); + let before = entries(targets.path()); + status( + home.path(), + "cursor", + 0, + "Unable to verify: Custom executable or launcher", + ); + assert_eq!(entries(targets.path()), before); +} + +#[cfg(windows)] +#[test] +fn windows_paths_and_environment_casing_work_together() { + let home = TempDir::new().unwrap(); + let executable = home.path().join("install with spaces 東京/PROOFLINE.EXE"); + fs::create_dir_all(executable.parent().unwrap()).unwrap(); + fs::copy(env!("CARGO_BIN_EXE_proofline"), &executable).unwrap(); + let mut entry = json!({"command":executable,"args":["mcp"],"env":{"proofline_base_url":"https://alternate.example","Proofline_Organization_ID":"00000000-0000-0000-0000-000000000000"}}); + registration(home.path(), "codex", ".codex/config.toml", entry.clone()); + status( + home.path(), + "codex", + 0, + "Origin: https://alternate.example (registration env PROOFLINE_BASE_URL)", + ); + entry["env"]["Proofline_Organization_ID"] = json!(SECRET); + registration(home.path(), "codex", ".codex/config.toml", entry); + status( + home.path(), + "codex", + 1, + "Invalid registration: PROOFLINE_ORGANIZATION_ID", + ); +}