diff --git a/README.md b/README.md index ddb19ee..881629b 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ set as `PROOFLINE_TOKEN`. A token that works in one organization needs no To register MCP without a prompt, run `proofline agent install CLIENT --yes`. Supported clients include `claude-code` (or `claude`), `cursor`, `codex`, `gemini`, and `kiro`. Without `--yes`, the command previews the entry and asks for confirmation, while `--print` previews without writing. Existing Proofline entries remain unchanged. 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 CLIENT`. This read-only, offline command reports whether the user-level configuration has a missing, invalid, or valid Proofline registration structure. It exits `0` when printing `Configuration valid:` or `Unable to verify:` (for example, when `CLAUDE_CONFIG_DIR` or a relative `CODEX_HOME` is set), and exits `1` when printing `Missing registration:` or `Invalid registration:`. Executable availability, local and project scopes, and live MCP connectivity are not checked, and the configured command is never executed. + Native knowledge, plan, fix and configuration commands send the selected organization as `organization_id` in each MCP tool call. These commands need a person's token: a service account key reads only reviews, findings and review guidance over MCP, and the server refuses it the rest. With a `PROOFLINE_TOKEN` that works in more than one organization, select an authorized UUID using `--org ORGANIZATION_ID` or `PROOFLINE_ORGANIZATION_ID`; the flag takes precedence. A token that works in exactly one, such as a personal token, needs neither. A stored device sign-in uses its approved organization and refuses a different selection. For example, `proofline --org ORGANIZATION_ID wiki list --repo owner/name` and `proofline --org ORGANIZATION_ID config get` target that organization with a shared MCP OAuth credential. Selection grants no authority: the server checks each call, and a foreign target returns its refusal with a nonzero exit. MCP OAuth credentials remain limited to MCP and cannot use REST commands. The raw `proofline mcp` bridge preserves the caller's messages and per-call target unchanged. It needs no organization selection and sends the MCP server nothing before the caller's first message, so it works with a service account key or a token that works in several organizations. ## Reviews, history, and reruns diff --git a/src/agent.rs b/src/agent.rs index 0e6466a..8f1dd07 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)] @@ -18,30 +19,39 @@ use crate::origin::Origin; #[derive(Debug, Args)] pub(crate) struct AgentArgs { #[command(subcommand)] - command: AgentCommand, + pub(crate) command: AgentCommand, } #[derive(Debug, Subcommand)] -enum AgentCommand { +pub(crate) enum AgentCommand { /// Add Proofline to a coding agent's user configuration after confirmation. Install(InstallArgs), + /// Inspect a coding agent's existing user configuration for Proofline registration structure. + Status(StatusArgs), } #[derive(Debug, Args)] -struct InstallArgs { +pub(crate) struct StatusArgs { + /// Coding agent whose user configuration is inspected. + #[arg(value_enum)] + pub(crate) client: Client, +} + +#[derive(Debug, Args)] +pub(crate) struct InstallArgs { /// Coding agent whose user configuration receives the MCP server. #[arg(value_enum)] - client: Client, + pub(crate) client: Client, /// Print the credential-free server entry without writing any file. #[arg(long)] - print: bool, + pub(crate) print: bool, /// Save the previewed entry without an interactive confirmation. #[arg(long, conflicts_with = "print")] - yes: bool, + pub(crate) yes: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] -enum Client { +pub(crate) enum Client { #[value(alias = "claude")] ClaudeCode, Codex, @@ -158,33 +168,41 @@ 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; - 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); +pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result { + match args.command { + AgentCommand::Install(args) => { + tokio::task::spawn_blocking(move || { + 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); + } + let stdin = io::stdin(); + let stdout = io::stdout(); + let stderr = io::stderr(); + install( + &home, + codex_home.as_deref(), + &args, + &origin, + &mut stdin.lock(), + &mut stdout.lock(), + &mut stderr.lock(), + ) + }) + .await + .map_err(InstallError::Task)??; + Ok(crate::Verdict::Done) } - let stdin = io::stdin(); - let stdout = io::stdout(); - let stderr = io::stderr(); - install( - &home, - codex_home.as_deref(), - &args, - &origin, - &mut stdin.lock(), - &mut stdout.lock(), - &mut stderr.lock(), - ) - }) - .await - .map_err(InstallError::Task)??; - Ok(()) + AgentCommand::Status(args) => status_run(args.client), + } +} + +pub(crate) fn status_run(client: Client) -> anyhow::Result { + status::run(client) } fn install( diff --git a/src/agent/config.rs b/src/agent/config.rs index 43b20c6..699f463 100644 --- a/src/agent/config.rs +++ b/src/agent/config.rs @@ -52,6 +52,239 @@ pub(super) fn prepare( } } +pub(super) fn inspect_registration(client: Client, bytes: &[u8]) -> super::status::Status { + match client { + Client::Codex => inspect_codex(bytes), + Client::ClaudeCode | Client::Cursor | Client::Gemini | Client::Kiro => { + inspect_json(client, bytes) + } + } +} + +fn inspect_json(client: Client, bytes: &[u8]) -> super::status::Status { + use super::status::Status; + if serde_json::from_slice::(bytes).is_err() { + return Status::Invalid("could not parse configuration file as valid JSON."); + } + let document: Value = match serde_json::from_slice(bytes) { + Ok(v) => v, + Err(_) => return Status::Invalid("could not parse configuration file as valid JSON."), + }; + let Some(root) = document.as_object() else { + return Status::Invalid("configuration root must be a JSON object."); + }; + let Some(servers) = root.get("mcpServers") else { + return Status::Missing("No Proofline MCP server is registered in the configuration."); + }; + let Some(servers_obj) = servers.as_object() else { + return Status::Invalid("mcpServers member must be an object."); + }; + let Some(proofline) = servers_obj.get("proofline") else { + return Status::Missing("No Proofline MCP server is registered in the configuration."); + }; + validate_json_proofline(client, proofline) +} + +const INVALID_ENV_ENTRY: &str = "env contains an invalid environment entry."; + +fn valid_env_entry(key: &str, value: &str) -> bool { + !key.is_empty() && !key.contains('\0') && !key.contains('=') && !value.contains('\0') +} + +fn validate_json_proofline(_client: Client, proofline: &Value) -> super::status::Status { + use super::status::Status; + let Some(obj) = proofline.as_object() else { + return Status::Invalid("Proofline registration must be an object."); + }; + if let Some(transport) = obj.get("type") + && transport.as_str() != Some("stdio") + { + return Status::Invalid("Proofline registration type must be \"stdio\"."); + } + let Some(cmd) = obj.get("command") else { + return Status::Invalid("Proofline registration must include a command field."); + }; + let Some(cmd_str) = cmd.as_str() else { + return Status::Invalid("command field must be a string."); + }; + if cmd_str.trim().is_empty() { + return Status::Invalid("command field must be a non-empty string."); + } + if cmd_str.contains('\0') { + return Status::Invalid("command field contains an invalid NUL character."); + } + if let Some(args) = obj.get("args") { + let Some(arr) = args.as_array() else { + return Status::Invalid("args field must be an array of strings."); + }; + for arg in arr { + let Some(arg_str) = arg.as_str() else { + return Status::Invalid("args elements must be strings."); + }; + if arg_str.contains('\0') { + return Status::Invalid("args elements must not contain NUL characters."); + } + } + } + if let Some(env) = obj.get("env") { + let Some(map) = env.as_object() else { + return Status::Invalid("env field must be an object."); + }; + for (k, v) in map { + let Some(val_str) = v.as_str() else { + return Status::Invalid(INVALID_ENV_ENTRY); + }; + if !valid_env_entry(k, val_str) { + return Status::Invalid(INVALID_ENV_ENTRY); + } + } + } + Status::Valid +} + +fn inspect_codex(bytes: &[u8]) -> super::status::Status { + use super::status::Status; + let Ok(raw) = std::str::from_utf8(bytes) else { + return Status::Invalid("configuration file must be valid UTF-8."); + }; + let Ok(document) = raw.parse::() else { + return Status::Invalid("could not parse configuration file as valid TOML."); + }; + let Some(servers) = document.get("mcp_servers") else { + return Status::Missing("No Proofline MCP server is registered in the configuration."); + }; + match servers { + Item::Table(servers_tbl) => { + let Some(proofline) = servers_tbl.get("proofline") else { + return Status::Missing( + "No Proofline MCP server is registered in the configuration.", + ); + }; + match proofline { + Item::Table(p) => validate_toml_table(p), + Item::Value(toml_edit::Value::InlineTable(p)) => validate_toml_inline(p), + _ => Status::Invalid("Proofline registration must be a table."), + } + } + Item::Value(toml_edit::Value::InlineTable(servers_tbl)) => { + let Some(proofline) = servers_tbl.get("proofline") else { + return Status::Missing( + "No Proofline MCP server is registered in the configuration.", + ); + }; + match proofline { + toml_edit::Value::InlineTable(p) => validate_toml_inline(p), + _ => Status::Invalid("Proofline registration must be a table."), + } + } + _ => Status::Invalid("mcp_servers member must be a table."), + } +} + +fn validate_toml_table(proofline: &Table) -> super::status::Status { + use super::status::Status; + let Some(cmd_item) = proofline.get("command") else { + return Status::Invalid("Proofline registration must include a command field."); + }; + let Some(cmd_val) = cmd_item.as_value() else { + return Status::Invalid("command field must be a string."); + }; + let Some(cmd_str) = cmd_val.as_str() else { + return Status::Invalid("command field must be a string."); + }; + if cmd_str.trim().is_empty() { + return Status::Invalid("command field must be a non-empty string."); + } + if cmd_str.contains('\0') { + return Status::Invalid("command field contains an invalid NUL character."); + } + if let Some(args_item) = proofline.get("args") { + let Some(args_val) = args_item.as_value() else { + return Status::Invalid("args field must be an array of strings."); + }; + let Some(arr) = args_val.as_array() else { + return Status::Invalid("args field must be an array of strings."); + }; + for arg in arr { + let Some(arg_str) = arg.as_str() else { + return Status::Invalid("args elements must be strings."); + }; + if arg_str.contains('\0') { + return Status::Invalid("args elements must not contain NUL characters."); + } + } + } + if let Some(env_item) = proofline.get("env") { + match env_item { + Item::Table(tbl) => { + for (k, v) in tbl { + let Some(val_str) = v.as_value().and_then(|v| v.as_str()) else { + return Status::Invalid(INVALID_ENV_ENTRY); + }; + if !valid_env_entry(k, val_str) { + return Status::Invalid(INVALID_ENV_ENTRY); + } + } + } + Item::Value(toml_edit::Value::InlineTable(tbl)) => { + for (k, v) in tbl { + let Some(val_str) = v.as_str() else { + return Status::Invalid(INVALID_ENV_ENTRY); + }; + if !valid_env_entry(k, val_str) { + return Status::Invalid(INVALID_ENV_ENTRY); + } + } + } + _ => return Status::Invalid("env field must be a table."), + } + } + Status::Valid +} + +fn validate_toml_inline(proofline: &InlineTable) -> super::status::Status { + use super::status::Status; + let Some(cmd_val) = proofline.get("command") else { + return Status::Invalid("Proofline registration must include a command field."); + }; + let Some(cmd_str) = cmd_val.as_str() else { + return Status::Invalid("command field must be a string."); + }; + if cmd_str.trim().is_empty() { + return Status::Invalid("command field must be a non-empty string."); + } + if cmd_str.contains('\0') { + return Status::Invalid("command field contains an invalid NUL character."); + } + if let Some(args_val) = proofline.get("args") { + let Some(arr) = args_val.as_array() else { + return Status::Invalid("args field must be an array of strings."); + }; + for arg in arr { + let Some(arg_str) = arg.as_str() else { + return Status::Invalid("args elements must be strings."); + }; + if arg_str.contains('\0') { + return Status::Invalid("args elements must not contain NUL characters."); + } + } + } + if let Some(env_val) = proofline.get("env") { + let Some(tbl) = env_val.as_inline_table() else { + return Status::Invalid("env field must be a table."); + }; + for (k, v) in tbl { + let Some(val_str) = v.as_str() else { + return Status::Invalid(INVALID_ENV_ENTRY); + }; + if !valid_env_entry(k, val_str) { + return Status::Invalid(INVALID_ENV_ENTRY); + } + } + } + Status::Valid +} + fn arguments(origin: &Origin) -> [String; 3] { ["--base-url".to_owned(), origin.as_key(), "mcp".to_owned()] } diff --git a/src/agent/status.rs b/src/agent/status.rs new file mode 100644 index 0000000..f525988 --- /dev/null +++ b/src/agent/status.rs @@ -0,0 +1,140 @@ +//! Read-only inspection of user-level MCP configuration for coding agents. + +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use clap::ValueEnum as _; + +use super::{Client, InstallError, config, store}; +use crate::Verdict; + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Status { + Missing(&'static str), + Invalid(&'static str), + Valid, + Unverified(&'static str), +} + +impl Status { + pub(super) 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", + "Proofline registration structure is valid.", + ), + Self::Unverified(reason) => ("Unable to verify", reason), + } + } +} + +pub(super) fn run(client: Client) -> anyhow::Result { + let mut output = io::stdout().lock(); + let (status, path_str) = match target(client) { + Ok(path) => { + let path_display = format!("{path:?}"); + (inspect(client, &path), path_display) + } + Err(reason) => (Status::Unverified(reason), "path unresolved".to_owned()), + }; + writeln!(output, "User-level configuration ({client}): {path_str}")?; + let (label, reason) = status.message(); + writeln!(output, "{label}: {reason}")?; + if matches!(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 not inspected. Executable availability and MCP connectivity were not checked." + )?; + Ok( + if matches!(status, Status::Missing(_) | Status::Invalid(_)) { + Verdict::Blocked + } else { + Verdict::Done + }, + ) +} + +fn target(client: Client) -> Result { + target_with( + client, + std::env::var_os("CLAUDE_CONFIG_DIR").is_some(), + std::env::var_os("CODEX_HOME").as_deref(), + std::env::home_dir().as_deref(), + ) +} + +fn target_with( + client: Client, + has_claude_dir: bool, + codex_home: Option<&std::ffi::OsStr>, + home: Option<&Path>, +) -> Result { + if client == Client::ClaudeCode && has_claude_dir { + return Err("CLAUDE_CONFIG_DIR selects custom configuration; inspect it manually."); + } + if client == Client::Codex + && let Some(home) = codex_home + { + let path = PathBuf::from(home); + if !path.is_absolute() { + return Err( + "The configuration path is relative; the agent's working directory is unknown.", + ); + } + return Ok(path.join("config.toml")); + } + let home = home + .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) -> Status { + let bytes = match store::inspect(path) { + Ok(Some(bytes)) => bytes, + Ok(None) => { + return Status::Missing( + "Configuration file not found in the inspected user-level scope.", + ); + } + Err(InstallError::TooLarge) => { + return Status::Unverified( + "Configuration exceeds the 1 MiB inspection limit; inspect it manually.", + ); + } + Err(InstallError::File(_)) => { + return Status::Unverified( + "Configuration is not a readable regular file; check the file or symlink target.", + ); + } + Err(InstallError::Changed(_)) => { + return Status::Unverified("Configuration changed while reading; retry the command."); + } + Err(_) => { + return Status::Unverified( + "Could not inspect the configuration file; check permissions.", + ); + } + }; + config::inspect_registration(client, &bytes) +} + +#[cfg(test)] +mod tests; diff --git a/src/agent/status/tests.rs b/src/agent/status/tests.rs new file mode 100644 index 0000000..8099621 --- /dev/null +++ b/src/agent/status/tests.rs @@ -0,0 +1,586 @@ +use std::ffi::OsStr; +use std::fmt::Write as _; +use std::fs; + +use tempfile::TempDir; + +use super::{Status, inspect, target_with}; +use crate::agent::Client; +use crate::agent::config::inspect_registration; + +#[test] +fn json_registration_valid_and_missing_shapes() { + let clients = [ + Client::ClaudeCode, + Client::Cursor, + Client::Gemini, + Client::Kiro, + ]; + for client in clients { + // Valid registrations + let valid_cases = [ + br#"{"mcpServers":{"proofline":{"command":"proofline","args":["mcp"]}}}"#.as_slice(), + br#"{"mcpServers":{"proofline":{"command":"/usr/local/bin/custom-launcher"}}}"#.as_slice(), + br#"{"mcpServers":{"proofline":{"command":"proofline","args":[],"env":{"KEY":"VAL"}}}}"#.as_slice(), + ]; + for case in valid_cases { + assert_eq!( + inspect_registration(client, case), + Status::Valid, + "expected valid for {case:?}" + ); + } + + // Missing registrations + let missing_cases = [ + b"{}".as_slice(), + br#"{"other":123}"#.as_slice(), + br#"{"mcpServers":{}}"#.as_slice(), + br#"{"mcpServers":{"other":{"command":"other"}}}"#.as_slice(), + ]; + for case in missing_cases { + assert!( + matches!(inspect_registration(client, case), Status::Missing(_)), + "expected missing for {case:?}" + ); + } + } +} + +#[test] +fn json_registration_malformed_shapes() { + let client = Client::ClaudeCode; + + // Syntax errors + assert!(matches!( + inspect_registration(client, b"not json"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"\xff\xfe"), + Status::Invalid(_) + )); + + // Wrong top-level shape + assert!(matches!( + inspect_registration(client, b"[]"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"42"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"\"string\""), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"null"), + Status::Invalid(_) + )); + + // Wrong mcpServers shape + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":null}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":[]}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":42}"#), + Status::Invalid(_) + )); + + // Wrong proofline entry shape + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":null}}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":42}}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":[]}}"#), + Status::Invalid(_) + )); + + // Missing / invalid command + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":{}}}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":{"command":""}}}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":{"command":" "}}}"#), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, br#"{"mcpServers":{"proofline":{"command":123}}}"#), + Status::Invalid(_) + )); + assert_eq!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proof\u0000line"}}}"# + ), + Status::Invalid("command field contains an invalid NUL character.") + ); + + // Duplicate keys in JSON + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"old"},"proofline":{"command":"proofline"}}}"# + ), + Status::Invalid(_) + )); + + // Invalid transport type on Claude Code / Cursor + assert!(matches!( + inspect_registration( + Client::ClaudeCode, + br#"{"mcpServers":{"proofline":{"type":123,"command":"proofline"}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + Client::Cursor, + br#"{"mcpServers":{"proofline":{"type":"http","command":"proofline"}}}"# + ), + Status::Invalid(_) + )); + + // Invalid args + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","args":"mcp"}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","args":[42]}}}"# + ), + Status::Invalid(_) + )); + assert_eq!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","args":["mcp\u0000"]}}}"# + ), + Status::Invalid("args elements must not contain NUL characters.") + ); + + // Invalid env container + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":[]}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":"not-obj"}}}"# + ), + Status::Invalid(_) + )); + + // Invalid env entries (non-string value, empty key, NUL in key, '=' in key, NUL in value) + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":{"PORT":1234}}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":{"":"val"}}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":{"KEY\u0000A":"val"}}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":{"KEY=A":"val"}}}}"# + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + br#"{"mcpServers":{"proofline":{"command":"proofline","env":{"KEY":"val\u0000bad"}}}}"# + ), + Status::Invalid(_) + )); +} + +#[test] +fn toml_registration_valid_and_missing_shapes() { + let client = Client::Codex; + + // Valid table + let valid_table = "[mcp_servers.proofline]\ncommand = 'proofline'\nargs = ['mcp']\n"; + assert_eq!( + inspect_registration(client, valid_table.as_bytes()), + Status::Valid + ); + + // Valid inline table + let valid_inline = "mcp_servers = { proofline = { command = 'proofline', args = ['mcp'] } }\n"; + assert_eq!( + inspect_registration(client, valid_inline.as_bytes()), + Status::Valid + ); + + // Valid with only command + let valid_cmd_only = "[mcp_servers.proofline]\ncommand = 'proofline'\n"; + assert_eq!( + inspect_registration(client, valid_cmd_only.as_bytes()), + Status::Valid + ); + + // Valid with env table + let valid_env = "[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\nPROOFLINE_BASE_URL = 'https://proofline.sh'\n"; + assert_eq!( + inspect_registration(client, valid_env.as_bytes()), + Status::Valid + ); + + // Valid with env inline table + let valid_env_inline = "[mcp_servers.proofline]\ncommand = 'proofline'\nenv = { PROOFLINE_BASE_URL = 'https://proofline.sh' }\n"; + assert_eq!( + inspect_registration(client, valid_env_inline.as_bytes()), + Status::Valid + ); + + // Missing mcp_servers + assert!(matches!( + inspect_registration(client, b""), + Status::Missing(_) + )); + assert!(matches!( + inspect_registration(client, b"[other]\nkey = 'val'\n"), + Status::Missing(_) + )); + + // Missing proofline within mcp_servers + let missing_proofline = "[mcp_servers.other]\ncommand = 'other'\n"; + assert!(matches!( + inspect_registration(client, missing_proofline.as_bytes()), + Status::Missing(_) + )); +} + +#[test] +fn toml_registration_malformed_shapes() { + let client = Client::Codex; + + // Syntax errors + assert!(matches!( + inspect_registration(client, b"[mcp_servers.proofline"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"\xff\xfe"), + Status::Invalid(_) + )); + + // Wrong mcp_servers shape + assert!(matches!( + inspect_registration(client, b"mcp_servers = 'not a table'\n"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"mcp_servers = [1, 2, 3]\n"), + Status::Invalid(_) + )); + + // Wrong proofline shape + assert!(matches!( + inspect_registration(client, b"mcp_servers = { proofline = 42 }\n"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"mcp_servers = { proofline = 'string' }\n"), + Status::Invalid(_) + )); + + // Missing / invalid command + assert!(matches!( + inspect_registration(client, b"[mcp_servers.proofline]\nargs = ['mcp']\n"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"[mcp_servers.proofline]\ncommand = ''\n"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"[mcp_servers.proofline]\ncommand = ' '\n"), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration(client, b"[mcp_servers.proofline]\ncommand = 42\n"), + Status::Invalid(_) + )); + assert_eq!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = \"proof\\u0000line\"\n" + ), + Status::Invalid("command field contains an invalid NUL character.") + ); + + // Invalid args + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nargs = 'mcp'\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nargs = ['--base-url', 42]\n" + ), + Status::Invalid(_) + )); + assert_eq!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nargs = [\"--base-url\", \"mcp\\u0000\"]\n" + ), + Status::Invalid("args elements must not contain NUL characters.") + ); + + // Invalid env container + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nenv = 'invalid'\n" + ), + Status::Invalid(_) + )); + + // Invalid env entries in TOML table + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\nPORT = 1234\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\n\"\" = 'val'\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\n\"KEY\\u0000A\" = 'val'\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\n\"KEY=A\" = 'val'\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\nKEY = \"val\\u0000bad\"\n" + ), + Status::Invalid(_) + )); + + // Invalid env entries in TOML inline table + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nenv = { PORT = 1234 }\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nenv = { \"\" = 'val' }\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nenv = { \"KEY=A\" = 'val' }\n" + ), + Status::Invalid(_) + )); + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\nenv = { KEY = \"val\\u0000bad\" }\n" + ), + Status::Invalid(_) + )); + + // Duplicate keys within proofline registration + assert!(matches!( + inspect_registration( + client, + b"[mcp_servers.proofline]\ncommand = 'proofline'\ncommand = 'other'\n" + ), + Status::Invalid(_) + )); +} + +#[test] +fn toml_registration_handles_nested_configuration_safely() { + let client = Client::Codex; + // Deeply nested keys and dotted tables in unrelated sections do not prevent safe inspection + let mut raw = String::new(); + for i in 0..50 { + let _ = write!(raw, "[section_{i}]\nkey_{i} = 'value_{i}'\n"); + } + let dotted = (0..60) + .map(|i| format!("n{i}")) + .collect::>() + .join("."); + let _ = writeln!(raw, "[{dotted}]\nkey = 'value'"); + raw.push_str("[mcp_servers.proofline]\ncommand = 'proofline'\nargs = ['mcp']\n"); + assert_eq!(inspect_registration(client, raw.as_bytes()), Status::Valid); +} + +#[test] +fn target_resolution_and_custom_homes() { + let dir = TempDir::new().unwrap(); + let abs_custom = dir.path().to_owned(); + + // CLAUDE_CONFIG_DIR returns Unverified + assert!(matches!( + target_with(Client::ClaudeCode, true, None, Some(&abs_custom)), + Err("CLAUDE_CONFIG_DIR selects custom configuration; inspect it manually.") + )); + + // Absolute CODEX_HOME returns that path + assert_eq!( + target_with( + Client::Codex, + false, + Some(abs_custom.as_os_str()), + Some(&abs_custom) + ) + .unwrap(), + abs_custom.join("config.toml") + ); + + // Relative CODEX_HOME returns Unverified + assert!(matches!( + target_with( + Client::Codex, + false, + Some(OsStr::new("relative/path")), + Some(&abs_custom) + ), + Err("The configuration path is relative; the agent's working directory is unknown.") + )); + + // Missing home returns error + assert!(matches!( + target_with(Client::Cursor, false, None, None), + Err( + "Could not resolve an absolute user home directory; check the client configuration manually." + ) + )); +} + +#[test] +fn inspect_file_read_scenarios() { + let dir = TempDir::new().unwrap(); + let config_path = dir.path().join(".claude.json"); + + // Missing file returns Missing + assert!(matches!( + inspect(Client::ClaudeCode, &config_path), + Status::Missing(_) + )); + + // Existing valid file returns Valid + fs::write( + &config_path, + br#"{"mcpServers":{"proofline":{"command":"proofline","args":["mcp"]}}}"#, + ) + .unwrap(); + assert_eq!(inspect(Client::ClaudeCode, &config_path), Status::Valid); + + // Existing file missing proofline returns Missing + fs::write(&config_path, b"{}").unwrap(); + assert!(matches!( + inspect(Client::ClaudeCode, &config_path), + Status::Missing(_) + )); + + // Directory in place of file returns Unverified + fs::remove_file(&config_path).unwrap(); + fs::create_dir_all(&config_path).unwrap(); + assert!(matches!( + inspect(Client::ClaudeCode, &config_path), + Status::Unverified(_) + )); + + // Broken symlink in place of file returns Unverified + #[cfg(unix)] + { + let symlink_path = dir.path().join("broken_link.json"); + std::os::unix::fs::symlink(dir.path().join("does_not_exist"), &symlink_path).unwrap(); + assert!(matches!( + inspect(Client::ClaudeCode, &symlink_path), + Status::Unverified(_) + )); + + let broken_parent = dir.path().join("broken_parent"); + std::os::unix::fs::symlink(dir.path().join("missing_dir"), &broken_parent).unwrap(); + assert!(matches!( + inspect(Client::Cursor, &broken_parent.join("mcp.json")), + Status::Unverified(_) + )); + + let real_dir = dir.path().join("real_dir"); + fs::create_dir_all(&real_dir).unwrap(); + let valid_parent = dir.path().join("valid_parent"); + std::os::unix::fs::symlink(&real_dir, &valid_parent).unwrap(); + assert!(matches!( + inspect(Client::Cursor, &valid_parent.join("mcp.json")), + Status::Missing(_) + )); + } +} diff --git a/src/agent/store.rs b/src/agent/store.rs index 91a607e..30e53ec 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 }) } @@ -320,36 +320,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, @@ -481,3 +480,40 @@ 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 => { + let mut ancestor = target.parent(); + while let Some(dir) = ancestor { + if let Some(meta) = metadata(dir)? { + if meta.file_type().is_symlink() { + if fs::metadata(dir).is_ok_and(|target_meta| target_meta.is_dir()) { + break; + } + return Err(InstallError::Directory(dir.to_owned())); + } + break; + } + ancestor = dir.parent(); + } + 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())); + } + let final_meta = + metadata(&resolved)?.ok_or_else(|| InstallError::Changed(target.to_owned()))?; + if Stamp::read(&resolved, &final_meta)? != file.stamp { + return Err(InstallError::Changed(target.to_owned())); + } + Ok(Some(file.bytes)) +} diff --git a/src/agent/tests.rs b/src/agent/tests.rs index 8a67e1d..6c5e8fa 100644 --- a/src/agent/tests.rs +++ b/src/agent/tests.rs @@ -409,7 +409,7 @@ fn toml_inline_tables_and_separate_arguments_round_trip_in_unicode_homes() { assert_eq!(args, ["--base-url", "http://[::1]:8080", "mcp"]); let cli = Cli::try_parse_from(std::iter::once("proofline").chain(args.iter().copied())).unwrap(); - assert_eq!(cli.base_url, "http://[::1]:8080"); + assert_eq!(cli.base_url.as_deref(), Some("http://[::1]:8080")); assert!(matches!(cli.command, CliCommand::Mcp)); for client in [ Client::ClaudeCode, diff --git a/src/lib.rs b/src/lib.rs index 2ac4644..bc9fb67 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,26 +66,110 @@ const DEFAULT_SCOPES: [&str; 3] = ["reviews:read", "findings:read", "reviews:req about = "Read, request and stop Proofline reviews from a terminal" )] pub struct Cli { - /// Proofline console origin. - #[arg(long, global = true, env = "PROOFLINE_BASE_URL", default_value = DEFAULT_ORIGIN)] - base_url: String, + /// Proofline console origin. [env: `PROOFLINE_BASE_URL`=] [default: ] + #[arg(long, global = true)] + pub base_url: Option, /// Organization ID. Required for a token from the environment, except by the /// raw mcp bridge; a browser sign-in already names its organization. Native /// knowledge, fix and config commands send this target per MCP call; the /// server authorizes it. The raw mcp bridge relays each call's own target and /// only checks this one against a stored sign-in. Any value given must be a - /// UUID. - #[arg(long, global = true, env = "PROOFLINE_ORGANIZATION_ID")] - org: Option, + /// UUID. [env: `PROOFLINE_ORGANIZATION_ID`=] + #[arg(long, global = true)] + pub org: Option, /// PEM file of extra root certificates to trust beside the existing - /// roots, such as the root of a TLS-inspecting corporate proxy. - #[arg(long, global = true, env = "PROOFLINE_CA_CERT", value_name = "FILE")] - ca_cert: Option, + /// roots, such as the root of a TLS-inspecting corporate proxy. [env: `PROOFLINE_CA_CERT`=] + #[arg(long, global = true, value_name = "FILE")] + pub ca_cert: Option, #[command(subcommand)] command: Command, + + #[arg(skip)] + env_resolved: bool, +} + +impl Cli { + pub fn is_agent_status(&self) -> bool { + matches!(&self.command, Command::Agent(args) if matches!(args.command, agent::AgentCommand::Status(_))) + } + + pub fn resolve_environment(&mut self) -> Result<(), clap::Error> { + use clap::CommandFactory as _; + + if self.is_agent_status() { + return Ok(()); + } + + if self.base_url.is_none() { + self.base_url = match std::env::var_os("PROOFLINE_BASE_URL") { + Some(val) => { + let s = val.into_string().map_err(|_| { + Self::command().error( + clap::error::ErrorKind::InvalidUtf8, + "PROOFLINE_BASE_URL must be valid UTF-8", + ) + })?; + Some(s) + } + None => Some(DEFAULT_ORIGIN.to_owned()), + }; + } + if self.org.is_none() + && let Some(val) = std::env::var_os("PROOFLINE_ORGANIZATION_ID") + { + let s = val.into_string().map_err(|_| { + Self::command().error( + clap::error::ErrorKind::InvalidUtf8, + "PROOFLINE_ORGANIZATION_ID must be valid UTF-8", + ) + })?; + let parsed: Uuid = s.parse().map_err(|e| { + Self::command().error( + clap::error::ErrorKind::ValueValidation, + format!("invalid PROOFLINE_ORGANIZATION_ID: {e}"), + ) + })?; + self.org = Some(parsed); + } + if self.ca_cert.is_none() + && let Some(val) = std::env::var_os("PROOFLINE_CA_CERT") + { + if val.is_empty() { + return Err(Self::command().error( + clap::error::ErrorKind::ValueValidation, + "PROOFLINE_CA_CERT must not be empty", + )); + } + self.ca_cert = Some(PathBuf::from(val)); + } + self.env_resolved = true; + Ok(()) + } +} + +pub fn run_agent_status(cli: Cli) -> anyhow::Result { + if cli.base_url.is_some() { + bail!( + "--base-url is not supported for 'agent status' (status is a local, offline diagnostic)" + ); + } + if cli.org.is_some() { + bail!("--org is not supported for 'agent status' (status is a local, offline diagnostic)"); + } + if cli.ca_cert.is_some() { + bail!( + "--ca-cert is not supported for 'agent status' (status is a local, offline diagnostic)" + ); + } + if let Command::Agent(agent) = cli.command + && let agent::AgentCommand::Status(status) = agent.command + { + return agent::status_run(status.client); + } + bail!("expected agent status command"); } #[derive(Debug, Subcommand)] @@ -470,10 +554,17 @@ pub enum Verdict { } /// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller. -pub async fn run(cli: Cli, token: Option) -> anyhow::Result { +pub async fn run(mut cli: Cli, token: Option) -> anyhow::Result { + if cli.is_agent_status() { + return run_agent_status(cli); + } + if !cli.env_resolved { + cli.resolve_environment()?; + } if let Some(path) = &cli.ca_cert { tls::trust(path)?; } + let org = cli.org; if let Command::Review(args) = &cli.command && args.schema { @@ -494,7 +585,8 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result {} } - let origin = Origin::parse(&cli.base_url)?; + let base_url = cli.base_url.as_deref().unwrap_or(DEFAULT_ORIGIN); + let origin = Origin::parse(base_url)?; match cli.command { Command::Completions { shell } => { completions(shell, &mut std::io::stdout().lock())?; @@ -531,15 +623,15 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result config::run(origin, token, cli.org, command).await, - Command::Fix(command) => knowledge::run(origin, token, cli.org, command.request()?).await, - Command::Wiki(command) => knowledge::run(origin, token, cli.org, command.request()?).await, - Command::Ask(args) => knowledge::run(origin, token, cli.org, args.request()?).await, + Command::Config(command) => config::run(origin, token, org, command).await, + Command::Fix(command) => knowledge::run(origin, token, org, command.request()?).await, + Command::Wiki(command) => knowledge::run(origin, token, org, command.request()?).await, + Command::Ask(args) => knowledge::run(origin, token, org, args.request()?).await, Command::Architecture { environment_id } => { knowledge::run( origin, token, - cli.org, + org, ( "get_architecture_document", serde_json::json!({"environment_id": environment_id}), @@ -547,9 +639,9 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result knowledge::run(origin, token, cli.org, command.request()).await, + Command::Plan(command) => knowledge::run(origin, token, org, command.request()).await, Command::Reviews(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::json( &api.list_page( args.repository_id, @@ -560,39 +652,39 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::json( &api.get(api.url_get_review_routing(&review_id.to_string())) .await?, ) } Command::Run(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::json(&retained_run(&api, &args).await?) } Command::Session(command) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::session(&api, command).await } - Command::Agent(args) => agent::run(args, origin).await.map(|()| Verdict::Done), + Command::Agent(args) => agent::run(args, origin).await, Command::Login(args) => { let http = Http::new(origin)?; - login(&http, &args, cli.org, token.is_some()) + login(&http, &args, org, token.is_some()) .await .map(|()| Verdict::Done) } Command::Logout => logout(&origin, token.is_some()) .await .map(|()| Verdict::Done), - Command::Status => status(Http::new(origin)?, token, cli.org) + Command::Status => status(Http::new(origin)?, token, org) .await .map(|()| Verdict::Done), Command::Review(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; review(&api, &args).await } Command::Stop(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; let (raw, stopped) = api.stop_review(args.review_id).await?; let mut stdout = std::io::stdout().lock(); if args.json { @@ -603,16 +695,16 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::rerun(&api, &args).await } Command::Scan(args) => { let request = scan::request(&args)?; - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; scan::run(&api, &args, &request).await } Command::History(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::json( &pull_request_runs(&api, &args.repository, args.pr) .await? @@ -620,28 +712,28 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; let (_, repository) = connected_repository(&api, &args).await?; tools::json(&api.guidance(repository).await?) } Command::FixPrompt { finding_id } => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::json(&api.fix_prompt(finding_id).await?) } Command::Export(args) => { - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; tools::export(&api, &args).await } Command::Findings(args) => { if let Some(head) = &args.selector.head { git::commit_sha(head)?; } - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; findings(&api, &args).await } Command::Mcp => { let http = Http::new(origin)?; - let token = credentials::load_token(http.origin(), token, cli.org).await?; + let token = credentials::load_token(http.origin(), token, org).await?; mcp::run(&http, &token).await?; Ok(Verdict::Done) } @@ -650,7 +742,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { @@ -667,10 +759,8 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - github_actions::api(http, &issuer, cli.org, None).await? - } - (token, _) => connect(http, token, cli.org).await?, + (None, Some(issuer)) => github_actions::api(http, &issuer, org, None).await?, + (token, _) => connect(http, token, org).await?, }; deploy::wait(&api, &args, &commit, reader_run).await } @@ -680,11 +770,11 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result hooks::manage(args).await.map(|()| Verdict::Done), Command::Coverage(coverage::Command::Upload(args)) => { let request = coverage::request(&args).await?; - let api = connect(Http::new(origin)?, token, cli.org).await?; + let api = connect(Http::new(origin)?, token, org).await?; coverage::upload(&api, &args, &request).await?; Ok(Verdict::Done) } - Command::Hook(args) => hooks::run(args, origin, token, cli.org).await, + Command::Hook(args) => hooks::run(args, origin, token, org).await, } } @@ -2586,4 +2676,24 @@ mod tests { missing.join("\n") ); } + + #[test] + fn resolve_environment_preserves_explicit_arguments() { + let explicit_org = Uuid::parse_str(ORG).unwrap(); + let mut cli = Cli::try_parse_from([ + "proofline", + "--base-url", + "https://custom.example", + "--org", + ORG, + "--ca-cert", + "cert.pem", + "status", + ]) + .unwrap(); + cli.resolve_environment().unwrap(); + assert_eq!(cli.base_url.as_deref(), Some("https://custom.example")); + assert_eq!(cli.org, Some(explicit_org)); + assert_eq!(cli.ca_cert, Some(PathBuf::from("cert.pem"))); + } } diff --git a/src/main.rs b/src/main.rs index 04ae422..9229e4b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,12 +7,7 @@ use proofline_cli::{Cli, Verdict, run}; use secrecy::SecretString; fn main() -> ExitCode { - if let Err(error) = use_user_session_bus() { - eprintln!("proofline: could not connect to the user session bus: {error}"); - return ExitCode::FAILURE; - } - proofline_cli::update::on_invocation(); - let cli = match Cli::try_parse() { + let mut cli = match Cli::try_parse() { Ok(cli) => cli, Err(error) => { if error.print().is_err() { @@ -28,6 +23,34 @@ fn main() -> ExitCode { }; } }; + + if cli.is_agent_status() { + return match proofline_cli::run_agent_status(cli) { + Ok(Verdict::Done) => ExitCode::SUCCESS, + Ok(_) => ExitCode::FAILURE, + Err(error) => { + eprintln!("proofline: {error:#}"); + ExitCode::FAILURE + } + }; + } + + if let Err(error) = cli.resolve_environment() { + if error.print().is_err() { + // A closed stream leaves nothing to report the failure to. + } + return if error.use_stderr() { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + }; + } + + if let Err(error) = use_user_session_bus() { + eprintln!("proofline: could not connect to the user session bus: {error}"); + return ExitCode::FAILURE; + } + proofline_cli::update::on_invocation(); // Read here rather than through clap, so the value never appears in help. let token = std::env::var("PROOFLINE_TOKEN") .ok() diff --git a/tests/agent_status.rs b/tests/agent_status.rs new file mode 100644 index 0000000..8b56059 --- /dev/null +++ b/tests/agent_status.rs @@ -0,0 +1,803 @@ +//! Process-level contracts for `proofline agent status`. + +use std::fs; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt as _; +#[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) + .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("Executable availability and MCP connectivity were not checked.")); + assert!(!text.contains("operational"), "{text}"); + 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") + .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("Configuration valid: Proofline registration structure is valid."), + "{text}" + ); + assert!( + text.contains("Executable availability and MCP connectivity were not checked."), + "{text}" + ); + assert!(!text.contains("operational"), "{text}"); + assert_eq!( + fs::metadata(&path).unwrap().modified().unwrap(), + metadata.modified().unwrap() + ); + assert_eq!( + fs::metadata(&path).unwrap().permissions(), + metadata.permissions() + ); + } +} + +#[test] +fn existing_configuration_without_proofline_reports_missing() { + let home = TempDir::new().unwrap(); + for (client, relative) in CLIENTS { + let content = if client == "codex" { + "[mcp_servers.other]\ncommand = 'other'\n" + } else { + r#"{"mcpServers":{"other":{"command":"other"}}}"# + }; + seed(home.path(), relative, content.as_bytes()); + let text = status(home.path(), client, 1, "Missing registration:"); + assert!(text.contains("No Proofline MCP server is registered")); + } +} + +#[test] +fn malformed_json_and_toml_and_wrong_shapes_report_invalid() { + let home = TempDir::new().unwrap(); + for (client, relative) in CLIENTS { + // Syntax error + let bad_syntax = if client == "codex" { + "[mcp_servers.proofline" + } else { + "{\"mcpServers\": " + }; + seed(home.path(), relative, bad_syntax.as_bytes()); + status(home.path(), client, 1, "Invalid registration:"); + + // Wrong top-level shape + let bad_root = if client == "codex" { + "mcp_servers = 'string'\n" + } else { + "[]" + }; + seed(home.path(), relative, bad_root.as_bytes()); + status(home.path(), client, 1, "Invalid registration:"); + + // Malformed proofline entry + let bad_proofline = if client == "codex" { + "[mcp_servers]\nproofline = 42\n" + } else { + r#"{"mcpServers":{"proofline":null}}"# + }; + seed(home.path(), relative, bad_proofline.as_bytes()); + status(home.path(), client, 1, "Invalid registration:"); + + // Missing command in proofline + let missing_cmd = if client == "codex" { + "[mcp_servers.proofline]\nargs = ['mcp']\n" + } else { + r#"{"mcpServers":{"proofline":{"args":["mcp"]}}}"# + }; + seed(home.path(), relative, missing_cmd.as_bytes()); + status(home.path(), client, 1, "Invalid registration:"); + } +} + +#[test] +fn offline_and_updater_guard_does_not_call_the_network() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("http://{}", listener.local_addr().unwrap()); + let home = TempDir::new().unwrap(); + for client in ["claude-code", "codex"] { + check( + home.path(), + command(home.path()) + .env("PROOFLINE_BASE_URL", &address) + .args(["agent", "status", client]), + 1, + "Missing registration:", + ); + } + registration(home.path(), "claude-code", ".claude.json", server()); + registration(home.path(), "codex", ".codex/config.toml", server()); + for client in ["claude-code", "codex"] { + check( + home.path(), + command(home.path()) + .env("PROOFLINE_BASE_URL", &address) + .args(["agent", "status", client]), + 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_or_executed() { + 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!(!targets.path().join("proofline.executed").exists()); + 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); + } +} + +#[test] +fn valid_local_status_ignores_malformed_and_irrelevant_environment_variables() { + let home = TempDir::new().unwrap(); + registration(home.path(), "claude-code", ".claude.json", server()); + + // Malformed PROOFLINE_ORGANIZATION_ID is ignored by status + check( + home.path(), + command(home.path()) + .env("PROOFLINE_ORGANIZATION_ID", "not-a-valid-uuid") + .args(["agent", "status", "claude-code"]), + 0, + "Configuration valid:", + ); + + // Malformed PROOFLINE_BASE_URL is ignored by status + check( + home.path(), + command(home.path()) + .env("PROOFLINE_BASE_URL", ":::not a valid url:::") + .args(["agent", "status", "claude-code"]), + 0, + "Configuration valid:", + ); + + // Unusable PROOFLINE_CA_CERT is ignored by status + check( + home.path(), + command(home.path()) + .env( + "PROOFLINE_CA_CERT", + home.path().join("nonexistent_cert.pem"), + ) + .args(["agent", "status", "claude-code"]), + 0, + "Configuration valid:", + ); + + // Inherited PROOFLINE_TOKEN is ignored and never leaked by status + let output = command(home.path()) + .env("PROOFLINE_TOKEN", SECRET) + .args(["agent", "status", "claude-code"]) + .output() + .unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("Configuration valid:")); + assert!(!stdout.contains(SECRET)); + + // Non-UTF-8 PROOFLINE_BASE_URL on Unix is ignored + #[cfg(unix)] + { + check( + home.path(), + command(home.path()) + .env( + "PROOFLINE_BASE_URL", + std::ffi::OsStr::from_bytes(b"\xFF\xFE\xFD"), + ) + .args(["agent", "status", "claude-code"]), + 0, + "Configuration valid:", + ); + } +} + +#[test] +fn explicit_irrelevant_global_flags_are_rejected_with_usage_error() { + let home = TempDir::new().unwrap(); + registration(home.path(), "claude-code", ".claude.json", server()); + + // Explicit --base-url before and after subcommand + for args in [ + vec![ + "--base-url", + "https://example.com", + "agent", + "status", + "claude-code", + ], + vec![ + "agent", + "status", + "claude-code", + "--base-url", + "https://example.com", + ], + ] { + let output = command(home.path()).args(&args).output().unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("--base-url is not supported for 'agent status'"), + "{stderr}" + ); + } + + // Explicit --org before and after subcommand + for args in [ + vec![ + "--org", + "00000000-0000-0000-0000-000000000000", + "agent", + "status", + "claude-code", + ], + vec![ + "agent", + "status", + "claude-code", + "--org", + "00000000-0000-0000-0000-000000000000", + ], + ] { + let output = command(home.path()).args(&args).output().unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("--org is not supported for 'agent status'"), + "{stderr}" + ); + } + + // Explicit --ca-cert before and after subcommand + for args in [ + vec!["--ca-cert", "cert.pem", "agent", "status", "claude-code"], + vec!["agent", "status", "claude-code", "--ca-cert", "cert.pem"], + ] { + let output = command(home.path()).args(&args).output().unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("--ca-cert is not supported for 'agent status'"), + "{stderr}" + ); + } +} + +#[test] +fn ordinary_non_status_commands_retain_environment_parsing_and_validation() { + let home = TempDir::new().unwrap(); + + // 1. Invalid UUID fails ordinary command + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_ORGANIZATION_ID", "bad-org-uuid") + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + + // 2. Empty string organization ID fails ordinary command + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_ORGANIZATION_ID", "") + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + + // 3. Whitespace-only organization ID fails ordinary command + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_ORGANIZATION_ID", " ") + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + + // 4. UUID surrounded by whitespace fails ordinary command + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env( + "PROOFLINE_ORGANIZATION_ID", + " 0190f3a0-0000-7000-8000-000000000001 ", + ) + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + + // 5. Valid organization UUID is stored and sent to the API + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("http://{}", listener.local_addr().unwrap()); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop_server = stop.clone(); + let server = std::thread::spawn(move || { + use std::io::{Read as _, Write as _}; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let mut stream = loop { + match listener.accept() { + Ok((s, _)) => break s, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + if stop_server.load(std::sync::atomic::Ordering::Relaxed) + || std::time::Instant::now() >= deadline + { + return String::new(); + } + std::thread::yield_now(); + } + Err(e) => panic!("accept failed: {e}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + let mut buf = [0u8; 4096]; + let mut req = Vec::new(); + loop { + let n = stream.read(&mut buf).unwrap(); + if n == 0 { + break; + } + req.extend_from_slice(&buf[..n]); + if req.windows(4).any(|w| w == b"\r\n\r\n") { + break; + } + } + let req = String::from_utf8_lossy(&req).into_owned(); + let body = r#"{"reviews":[],"next_cursor":null}"#; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + stream.write_all(resp.as_bytes()).unwrap(); + req + }); + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", &address) + .env( + "PROOFLINE_ORGANIZATION_ID", + "0190f3a0-0000-7000-8000-000000000001", + ) + .args(["reviews"]) + .output() + .unwrap(); + stop.store(true, std::sync::atomic::Ordering::Relaxed); + let recorded_req = server.join().unwrap(); + assert!( + recorded_req.contains("/api/v1/organizations/0190f3a0-0000-7000-8000-000000000001/reviews"), + "{recorded_req}" + ); + assert!(output.status.success(), "{output:?}"); + + // 6. Non-UTF-8 PROOFLINE_ORGANIZATION_ID on Unix fails ordinary command + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt as _; + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env( + "PROOFLINE_ORGANIZATION_ID", + std::ffi::OsStr::from_bytes(b"\xFF\xFE\xFD"), + ) + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("PROOFLINE_ORGANIZATION_ID must be valid UTF-8"), + "{stderr}" + ); + } + + // 7. Malformed PROOFLINE_BASE_URL fails ordinary command (URL validation preserved) + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", ":::not a valid url:::") + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("is not an absolute URL"), "{stderr}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("is not an absolute URL"), "{stderr}"); + + // 8. Unusable PROOFLINE_CA_CERT fails ordinary command (CA cert handling preserved) + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env( + "PROOFLINE_CA_CERT", + home.path().join("nonexistent_cert.pem"), + ) + .args(["reviews"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("nonexistent_cert.pem") || stderr.contains("certificate"), + "{stderr}" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("nonexistent_cert.pem") || stderr.contains("certificate"), + "{stderr}" + ); + + // 9. Early-return review --schema rejects invalid organization UUID before printing schema + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_ORGANIZATION_ID", "bad-org-uuid") + .args(["review", "--schema"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + assert!(!stdout.contains("$schema"), "{stdout}"); + + // 10. Early-return review --schema succeeds with malformed base URL (no premature URL validation) + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_BASE_URL", ":::not a valid url:::") + .args(["review", "--schema"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(0), "{output:?}"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("$schema"), "{stdout}"); + + // 11. Early-return completions bash rejects invalid organization UUID + let output = command(home.path()) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PROOFLINE_ORGANIZATION_ID", "bad-org-uuid") + .args(["completions", "bash"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stderr.contains("invalid PROOFLINE_ORGANIZATION_ID"), + "{stderr}" + ); + assert!(!stdout.contains("complete -F _proofline"), "{stdout}"); +} + +#[test] +fn env_entries_are_validated_and_secrets_never_leaked() { + let home = TempDir::new().unwrap(); + + // JSON registration with invalid env entry containing secret canary + let bad_json = json!({ + "mcpServers": { + "proofline": { + "command": "proofline", + "env": { + "TOKEN": format!("bad\0{}", SECRET), + } + } + } + }); + seed(home.path(), ".claude.json", bad_json.to_string().as_bytes()); + let output = command(home.path()) + .args(["agent", "status", "claude-code"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stdout.contains("Invalid registration:"), "{stdout}"); + assert!( + stdout.contains("env contains an invalid environment entry"), + "{stdout}" + ); + assert!(!stdout.contains(SECRET), "{stdout}"); + assert!(!stderr.contains(SECRET), "{stderr}"); + + // JSON registration with numeric env value + let bad_json_port = json!({ + "mcpServers": { + "proofline": { + "command": "proofline", + "env": { + "PORT": 1234, + } + } + } + }); + seed( + home.path(), + ".claude.json", + bad_json_port.to_string().as_bytes(), + ); + let output = command(home.path()) + .args(["agent", "status", "claude-code"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("Invalid registration:"), "{stdout}"); + + // TOML registration with invalid env entry containing secret canary + let bad_toml = format!( + "[mcp_servers.proofline]\ncommand = 'proofline'\n[mcp_servers.proofline.env]\nTOKEN = \"bad\\u0000{SECRET}\"\n" + ); + seed(home.path(), ".codex/config.toml", bad_toml.as_bytes()); + let output = command(home.path()) + .args(["agent", "status", "codex"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stdout.contains("Invalid registration:"), "{stdout}"); + assert!( + stdout.contains("env contains an invalid environment entry"), + "{stdout}" + ); + assert!(!stdout.contains(SECRET), "{stdout}"); + assert!(!stderr.contains(SECRET), "{stderr}"); +} + +#[test] +fn deeply_nested_inline_table_terminates_normally_without_stack_overflow_or_canary_leak() { + let home = TempDir::new().unwrap(); + let codex_home = home.path().join("codex"); + fs::create_dir_all(&codex_home).unwrap(); + let key = vec!["x"; 60].join("."); + let nested_prefix = format!("{{{key} = "); + let config = format!( + "a = {nested}1{closing}\nsecret_canary = \"{SECRET}\"\n[mcp_servers.proofline]\ncommand = \"{cmd}\"\nargs = [\"mcp\"]\n", + nested = nested_prefix.repeat(10), + closing = "}".repeat(10), + cmd = env!("CARGO_BIN_EXE_proofline"), + ); + fs::write(codex_home.join("config.toml"), config).unwrap(); + + let output = command(home.path()) + .env("CODEX_HOME", &codex_home) + .args(["agent", "status", "codex"]) + .output() + .unwrap(); + + assert!(output.status.success(), "subprocess failed: {output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stdout.contains("Configuration valid:"), "{stdout}"); + assert!(!stdout.contains(SECRET), "{stdout}"); + assert!(!stderr.contains(SECRET), "{stderr}"); + assert!(!stdout.contains(&key), "{stdout}"); +}