diff --git a/mesh/crates/mesh-llm-cli/src/parser/logging_help.rs b/mesh/crates/mesh-llm-cli/src/parser/logging_help.rs index 036582be46..5eff7edaa8 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/logging_help.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/logging_help.rs @@ -12,7 +12,7 @@ pub fn logging_help() -> &'static str { " Path precedence logging.application_state_root, then ", "MESH_LLM_DATA_DIR/logging, then the local default above.\n", " Retention setting logging.retention_ttl_secs (default: 129600 seconds).\n", - " Terminal lifecycle Pretty/TUI and --log-format json project the same lifecycle facts; fatal output redacts sensitive fragments while retaining context.\n", + " Terminal lifecycle Pretty/TUI and --log-format json project the same lifecycle facts; fatal output redacts credentials and URL-embedded secrets while retaining context. Paths render verbatim on an attached terminal and redact when the event stream is redirected.\n", " Durable ledger The Logs console and /api/logs/* read the local SQLite ledger.\n", " Audit file sink --audit-log-path, --audit-log-format, and --audit-log-level control a separate rotating audit file sink.\n", " TUI event navigation / filter, f follow, PgUp/PgDn page, Home/End jump.\n", diff --git a/mesh/crates/mesh-llm-tui/src/output/console_capture.rs b/mesh/crates/mesh-llm-tui/src/output/console_capture.rs index f66ea5370f..627df775a0 100644 --- a/mesh/crates/mesh-llm-tui/src/output/console_capture.rs +++ b/mesh/crates/mesh-llm-tui/src/output/console_capture.rs @@ -26,6 +26,12 @@ pub(in crate::output) use unix::ConsoleCapture; #[cfg(not(unix))] pub(in crate::output) use fallback::ConsoleCapture; +#[cfg(unix)] +pub(in crate::output) use unix::capture_installed; + +#[cfg(not(unix))] +pub(in crate::output) use fallback::capture_installed; + #[cfg(unix)] mod unix { use mesh_llm_events::OutputEvent; @@ -185,6 +191,16 @@ mod unix { active_captures.load(Ordering::Acquire) > 0 } + /// Is a dashboard currently owning the screen with fd 1/2 captured? + /// + /// The attachment probe in `logging_projection::privacy` reads fd 2, + /// which is the capture pipe while a capture is installed — capture + /// active means the operator is watching the dashboard on the + /// controlling terminal, i.e. the session is interactive. + pub(in crate::output) fn capture_installed() -> bool { + dashboard_capture_active(&ACTIVE_CAPTURES) + } + fn deliver(text: String, passthrough: &mut File) { deliver_with( text, @@ -311,6 +327,13 @@ mod fallback { Ok(()) } } + + /// No descriptor capture exists here, so the attachment probe in + /// `logging_projection::privacy` falls back to the raw stderr check + /// alone (which on these platforms stays the console). + pub(in crate::output) fn capture_installed() -> bool { + false + } } #[cfg(all(test, unix))] diff --git a/mesh/crates/mesh-llm-tui/src/output/formatting.rs b/mesh/crates/mesh-llm-tui/src/output/formatting.rs index 3d1b049766..7a0bb4a000 100644 --- a/mesh/crates/mesh-llm-tui/src/output/formatting.rs +++ b/mesh/crates/mesh-llm-tui/src/output/formatting.rs @@ -1499,6 +1499,17 @@ impl OutputManager { } } +pub(super) fn event_stream_is_terminal(mode: LogFormat) -> bool { + use std::io::IsTerminal; + + match mode { + LogFormat::Pretty => { + io::stderr().is_terminal() || super::console_capture::capture_installed() + } + LogFormat::Json => io::stdout().is_terminal(), + } +} + pub(super) fn write_rendered_output(mode: LogFormat, rendered: &str) -> io::Result<()> { let mut stdout = io::stdout().lock(); let mut stderr = io::stderr().lock(); diff --git a/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs b/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs index 2230625b10..d6cfb314d7 100644 --- a/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs +++ b/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs @@ -1,7 +1,7 @@ -mod privacy; +pub(super) mod privacy; -use super::OutputEvent; use super::formatting::OutputEventPresentation; +use super::{LogFormat, OutputEvent}; use mesh_llm_events::logging::{ envelope::CanonicalEnvelope, events::{LifecycleEvent, TokenUsage}, @@ -10,16 +10,19 @@ use serde_json::{Map, Value, json}; use self::privacy::{ json_scalar, native_category, safe_native_params, sanitize_map, sanitize_text, + sanitize_text_for_mode, }; pub(super) fn projected_message(event: &OutputEvent) -> String { match event { OutputEvent::CanonicalLog(envelope) => envelope.presentation_message(), - OutputEvent::LlamaNativeLog { message, .. } => sanitize_text(message), + OutputEvent::LlamaNativeLog { message, .. } => { + sanitize_text_for_mode(message, LogFormat::Json) + } OutputEvent::Info { message, .. } | OutputEvent::Warning { message, .. } | OutputEvent::Error { message, .. } - | OutputEvent::Fatal { message, .. } => sanitize_text(message), + | OutputEvent::Fatal { message, .. } => sanitize_text_for_mode(message, LogFormat::Json), _ => event.message(), } } @@ -31,7 +34,7 @@ pub(super) fn projected_pretty_text(event: &OutputEvent) -> String { message, params, .. } => { let mut rendered = sanitize_text(message); - for (key, value) in safe_native_params(params) { + for (key, value) in safe_native_params(params, LogFormat::Pretty) { rendered.push_str("\n ↳ "); rendered.push_str(&key); rendered.push('='); @@ -67,7 +70,7 @@ pub(super) fn projected_json_fields(event: &OutputEvent) -> Map { OutputEvent::LlamaNativeLog { category, params, .. } => { - let mut fields = safe_native_params(params); + let mut fields = safe_native_params(params, LogFormat::Json); fields.insert( "native_category".to_string(), Value::String(native_category(category).to_string()), @@ -77,7 +80,7 @@ pub(super) fn projected_json_fields(event: &OutputEvent) -> Map { OutputEvent::Info { .. } | OutputEvent::Warning { .. } | OutputEvent::Error { .. } - | OutputEvent::Fatal { .. } => sanitize_map(event.json_fields()), + | OutputEvent::Fatal { .. } => sanitize_map(event.json_fields(), LogFormat::Json), _ => event.json_fields(), } } diff --git a/mesh/crates/mesh-llm-tui/src/output/logging_projection/privacy.rs b/mesh/crates/mesh-llm-tui/src/output/logging_projection/privacy.rs index 570f39d678..969b8d37f6 100644 --- a/mesh/crates/mesh-llm-tui/src/output/logging_projection/privacy.rs +++ b/mesh/crates/mesh-llm-tui/src/output/logging_projection/privacy.rs @@ -1,26 +1,33 @@ +use crate::output::LogFormat; use serde_json::{Map, Value}; const MAX_PRESENTATION_CHARS: usize = 1024; -pub(super) fn safe_native_params(params: &[(String, Value)]) -> Map { +pub(super) fn safe_native_params( + params: &[(String, Value)], + mode: LogFormat, +) -> Map { params .iter() .filter(|(key, _)| safe_param_key(key)) .filter_map(|(key, value)| match value { Value::Null | Value::Bool(_) | Value::Number(_) => Some((key.clone(), value.clone())), - Value::String(value) => Some((key.clone(), Value::String(sanitize_text(value)))), + Value::String(value) => Some(( + key.clone(), + Value::String(sanitize_text_for_mode(value, mode)), + )), Value::Array(_) | Value::Object(_) => None, }) .collect() } -pub(super) fn sanitize_map(mut fields: Map) -> Map { +pub(super) fn sanitize_map(mut fields: Map, mode: LogFormat) -> Map { fields.retain(|key, value| { safe_param_key(key) && match value { Value::Null | Value::Bool(_) | Value::Number(_) => true, Value::String(text) => { - *text = sanitize_text(text); + *text = sanitize_text_for_mode(text, mode); true } Value::Array(_) | Value::Object(_) => false, @@ -30,18 +37,28 @@ pub(super) fn sanitize_map(mut fields: Map) -> Map } pub(super) fn sanitize_text(input: &str) -> String { - sanitize_text_with_home(input, operator_home().as_deref()) + sanitize_text_for_mode(input, LogFormat::Pretty) } -fn sanitize_text_with_home(input: &str, home: Option<&str>) -> String { - let input = mask_operator_home(input, home); - let normalized = redact_sensitive_fragments(&redact_url_query_values(&input)); - if normalized.chars().count() <= MAX_PRESENTATION_CHARS { - normalized +pub(super) fn sanitize_text_for_mode(input: &str, mode: LogFormat) -> String { + let redact_paths = !interactive_output(mode); + let home = if redact_paths { operator_home() } else { None }; + sanitize_text_with_home(input, home.as_deref(), redact_paths) +} + +fn sanitize_text_with_home(input: &str, home: Option<&str>, redact_paths: bool) -> String { + let masked = if redact_paths { + mask_operator_home(input, home) + } else { + input.to_owned() + }; + let sanitized = redact_sensitive_fragments(&masked, redact_paths); + if sanitized.chars().count() <= MAX_PRESENTATION_CHARS { + sanitized } else { format!( "{}... [TRUNCATED]", - normalized + sanitized .chars() .take(MAX_PRESENTATION_CHARS) .collect::() @@ -49,41 +66,129 @@ fn sanitize_text_with_home(input: &str, home: Option<&str>) -> String { } } +/// Is the process's diagnostics stream attached to a terminal? +/// +/// Interactive sessions get actionable errors: the operator's own +/// command output already prints local paths verbatim (cache +/// locations, config paths, keystores), so redacting paths only in +/// event text turns guidance — a `--config` path the operator just +/// typed — into `[REDACTED_PATH]`. Unattended contexts keep the +/// redaction: when stderr is redirected rather than attached, the +/// reader is no longer the operator at the keyboard but launchd's +/// `stderr.log`, the systemd journal, container logs, or CI capture +/// — collected, archived, and attached to bug reports, where the +/// operator's home-directory layout should not land. +/// +/// The interactive dashboard is the attached case with fd 2 itself +/// redirected: while it owns the screen, `console_capture` points +/// stderr at its capture pipe, so the raw probe alone would read +/// "unattended" for the operator watching the Events panel. An +/// installed capture means a dashboard is live on the controlling +/// terminal, which counts as attached. +fn interactive_output(mode: LogFormat) -> bool { + #[cfg(test)] + if let Some((pretty, json)) = TEST_ATTACHMENT_OVERRIDE.with(std::cell::Cell::get) { + return match mode { + LogFormat::Pretty => pretty, + LogFormat::Json => json, + }; + } + super::super::formatting::event_stream_is_terminal(mode) +} + +#[cfg(test)] +thread_local! { + /// Test-only attachment override: `Some((pretty, json))` while a test + /// forces both probes, `None` when unforced (the real stream probe + /// runs). Thread-local by design — tests run on parallel threads, + /// and a shared flag would let one test's teardown un-force + /// another test's override mid-flight. + static TEST_ATTACHMENT_OVERRIDE: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(in crate::output) mod test_support { + /// Force the attachment probe for the duration of a test body. + /// Restores the real probe on drop. + pub(in crate::output) struct AttachmentOverride; + + impl AttachmentOverride { + pub(in crate::output) fn set(attached: bool) -> Self { + Self::for_streams(attached, attached) + } + + pub(in crate::output) fn for_streams(pretty: bool, json: bool) -> Self { + super::TEST_ATTACHMENT_OVERRIDE.with(|cell| cell.set(Some((pretty, json)))); + Self + } + } + + impl Drop for AttachmentOverride { + fn drop(&mut self) { + super::TEST_ATTACHMENT_OVERRIDE.with(|cell| cell.set(None)); + } + } +} + /// Keep the useful error category and surrounding diagnostic text while -/// replacing only the sensitive value or local path. Fatal output used to -/// collapse an entire message to `[REDACTED]`, which made ordinary startup -/// failures impossible to diagnose. -fn redact_sensitive_fragments(input: &str) -> String { +/// replacing only credential-shaped values on an attached terminal, and +/// additionally redacting absolute paths when the diagnostics stream is +/// redirected (see [`interactive_output`]). Durable artifacts keep the +/// host logging policy's unconditional path redaction; this terminal +/// layer applies its own for unattended readers — every absolute-path +/// word becomes `[REDACTED_PATH]`, not the host policy's `~` home +/// masking that preserves the path tail. +fn redact_sensitive_fragments(input: &str, redact_paths: bool) -> String { let mut redact_next = false; let mut sensitive_key_pending = false; let mut previous = String::new(); - let mut output = Vec::new(); + let mut output = String::with_capacity(input.len()); + let mut rest = input; - for word in input.split_whitespace() { + for token in input.split_whitespace() { + let trimmed_rest = rest.trim_start(); + let separator = &rest[..rest.len() - trimmed_rest.len()]; + rest = &trimmed_rest[token.len()..]; + + let word = redact_query_in_token(token); + if word.is_empty() { + continue; + } + let word = word.as_str(); + if !output.is_empty() { + // Preserve spaces in attached paths while keeping line breaks and + // other control whitespace out of the log projection. + if !redact_paths && separator.bytes().all(|byte| byte == b' ') { + output.push_str(separator); + } else { + output.push(' '); + } + } let trimmed = trim_presentation_punctuation(word); let normalized = trimmed.to_ascii_lowercase(); if redact_next { sensitive_key_pending = false; if matches!(normalized.as_str(), "bearer" | "basic") { - output.push(word.to_owned()); + output.push_str(word); } else { redact_next = false; - output.push(redact_word(word, "[REDACTED]")); + output.push_str(&redact_word(word, "[REDACTED]")); } } else if sensitive_key_pending && matches!(trimmed, ":" | "=") { sensitive_key_pending = false; redact_next = true; - output.push(word.to_owned()); + output.push_str(word); } else { sensitive_key_pending = false; if matches!(normalized.as_str(), "bearer" | "basic") { redact_next = true; - output.push(word.to_owned()); - } else if is_private_absolute_path(trimmed) { - output.push(redact_word(word, "[REDACTED_PATH]")); + output.push_str(word); + } else if redact_paths && is_private_absolute_path(trimmed) { + output.push_str(&redact_word(word, "[REDACTED_PATH]")); } else if is_credential_value(trimmed) { - output.push(redact_word(word, "[REDACTED]")); + output.push_str(&redact_word(word, "[REDACTED]")); } else if !trimmed.contains(['?', '&']) && let Some((key, separator, value)) = split_key_value(trimmed) && is_sensitive_key(key) @@ -93,22 +198,24 @@ fn redact_sensitive_fragments(input: &str) -> String { || matches!(value.to_ascii_lowercase().as_str(), "bearer" | "basic") { redact_next = true; - output.push(word.to_owned()); + output.push_str(word); } else if value == "[REDACTED]" { - output.push(word.to_owned()); + output.push_str(word); } else { - output.push(format!("{key}{separator}[REDACTED]")); + output.push_str(key); + output.push(separator); + output.push_str("[REDACTED]"); } } else { sensitive_key_pending = is_sensitive_key(trimmed) && !is_invite_token_context(&previous, trimmed); - output.push(word.to_owned()); + output.push_str(word); } } previous = normalized; } - output.join(" ") + output } fn trim_presentation_punctuation(word: &str) -> &str { @@ -242,17 +349,7 @@ fn is_windows_absolute_path(value: &str) -> bool { drive_root || unc_or_device } -/// Apply the host logging policy's query-value rule before projecting text. -/// Endpoint and non-sensitive query metadata remain useful to an operator, -/// but credentials may not survive in any TUI surface. -fn redact_url_query_values(input: &str) -> String { - input - .split_whitespace() - .map(redact_query_in_token) - .collect::>() - .join(" ") -} - +/// Apply the host logging policy's URL credential rules to one word. fn redact_query_in_token(token: &str) -> String { let token = redact_url_userinfo(token); let Some((base, query_and_fragment)) = token.split_once('?') else { @@ -359,51 +456,70 @@ fn is_credential_value(value: &str) -> bool { #[cfg(test)] mod tests { - use super::{operator_home, safe_native_params, sanitize_text, sanitize_text_with_home}; + use super::test_support::AttachmentOverride; + use super::{safe_native_params, sanitize_text, sanitize_text_with_home}; + use crate::output::LogFormat; use serde_json::json; #[test] - fn redacts_a_home_directory_that_contains_a_space() { + fn preserves_local_paths_including_homes_with_spaces_when_attached() { + let _attached = AttachmentOverride::set(true); + // Paths render on the operator's own terminal, where command output + // already prints them verbatim; redacting them only in event text + // made failure guidance unactionable (see the T-002 regression pins + // below). let home = r"C:\Users\Jane Doe"; for input in [ format!(r"path={home}\models\model.gguf"), format!(r"failed to open {home}\cache\index.json"), ] { - let sanitized = sanitize_text_with_home(&input, Some(home)); - assert!( - !sanitized.contains("Jane") && !sanitized.contains("Doe"), - "sanitized output leaked part of the home directory: {sanitized:?}" - ); - assert!(sanitized.contains("[REDACTED_PATH]"), "{sanitized:?}"); + assert_eq!(sanitize_text(&input), input); } } - #[cfg(windows)] #[test] - fn redacts_the_home_directory_in_any_case_on_windows() { - let sanitized = sanitize_text_with_home( - r"path=c:\users\jane\models\model.gguf", - Some(r"C:\Users\Jane"), + fn attached_paths_keep_repeated_spaces_without_exposing_credentials() { + let _attached = AttachmentOverride::set(true); + let input = "failed to open /srv/Jane Doe/model.gguf at https://provider.example/v1?api_key=query-secret\nauthorization: Bearer header-secret"; + assert_eq!( + sanitize_text(input), + "failed to open /srv/Jane Doe/model.gguf at https://provider.example/v1?api_key=[REDACTED] authorization: Bearer [REDACTED]" ); - assert!(!sanitized.contains("jane"), "{sanitized:?}"); } #[test] - fn redacts_the_operator_home_inside_a_word() { - // A home path at the start of a word is caught as an absolute path; - // after `key=` or `key:` only the home check sees it. On Windows that - // check has to read USERPROFILE, since HOME is usually unset there. - let home = operator_home().expect("HOME or USERPROFILE should be set"); - let separator = std::path::MAIN_SEPARATOR; - for input in [ - format!("path={home}{separator}models{separator}model.gguf"), - format!("cache dir:{home}{separator}cache"), - ] { - let sanitized = sanitize_text(&input); - assert!( - !sanitized.contains(&home), - "sanitized output leaked the home directory: {sanitized:?}" - ); + fn keeps_paths_after_benign_keys_while_redacting_after_sensitive_keys() { + // Attached-mode assertion: pin the probe so a build account whose + // home literally is /home or /home/operator cannot flip the + // expected mode under the harness's captured stderr. + let _attached = AttachmentOverride::set(true); + let sanitized = sanitize_text("path=/home/operator/model.gguf token=supersecret"); + + assert!( + sanitized.contains("path=/home/operator/model.gguf"), + "{sanitized:?}" + ); + assert!(sanitized.contains("token=[REDACTED]"), "{sanitized:?}"); + assert!(!sanitized.contains("supersecret"), "{sanitized:?}"); + } + + #[test] + fn preserves_the_operators_own_paths_in_cli_guidance_and_errors_when_attached() { + let _attached = AttachmentOverride::set(true); + // T-002 regression pins from the 2026-11-17 behavioral campaign: + // every one of these message shapes came back from the terminal + // projection with `[REDACTED_PATH]` where the operator's own + // argument or path belonged. + let cases = [ + "top-level serving flags now map to `mesh-llm serve`. Please use: mesh-llm serve --model /models/qwen.gguf --console 3131", + "Invalid config /home/operator/.mesh-llm/config.toml failed to parse config TOML", + "reading owner-control credential from /home/operator/.mesh-llm/owner-control-token-v2", + "mesh-llm update only works for release-bundle installs. Current executable: /usr/local/bin/mesh-llm", + "Eager startup model '/models/qwen.gguf' failed to resolve after daemon surfaces became ready", + ]; + + for input in cases { + assert_eq!(sanitize_text(input), input); } } @@ -486,13 +602,14 @@ mod tests { let params = vec![("invite_token".to_string(), json!(invite))]; assert_eq!( - safe_native_params(¶ms).get("invite_token"), + safe_native_params(¶ms, LogFormat::Pretty).get("invite_token"), Some(&json!(invite)) ); } #[test] - fn redacts_unix_windows_unc_and_device_paths() { + fn preserves_unix_windows_unc_and_device_paths_when_attached() { + let _attached = AttachmentOverride::set(true); let cases = [ "/Users/operator/.mesh-llm/config.toml", r"C:\Users\operator\.mesh-llm\config.toml", @@ -501,15 +618,55 @@ mod tests { ]; for path in cases { - assert_eq!( - sanitize_text(&format!("startup failed at {path}")), - "startup failed at [REDACTED_PATH]" - ); + let input = format!("startup failed at {path}"); + assert_eq!(sanitize_text(&input), input); } } #[test] - fn keeps_a_slash_separator_but_redacts_paths_next_to_it() { + fn keeps_slash_separators_and_adjacent_paths_when_attached() { + let _attached = AttachmentOverride::set(true); + assert_eq!( + sanitize_text("no runtime for Skippy runtime 0.76.1 / ABI 0.1.71"), + "no runtime for Skippy runtime 0.76.1 / ABI 0.1.71" + ); + assert_eq!( + sanitize_text("copied / to /srv/private/model.gguf"), + "copied / to /srv/private/model.gguf" + ); + assert_eq!( + sanitize_text("startup failed at (/home/operator/x)"), + "startup failed at (/home/operator/x)" + ); + } + + #[test] + fn unattended_masks_a_home_with_spaces_inside_a_path_assignment() { + let home = r"C:\Users\Jane Doe"; + let input = format!(r"path={home}\models\model.gguf"); + assert_eq!( + sanitize_text_with_home(&input, Some(home), true), + "[REDACTED_PATH]" + ); + } + + #[cfg(windows)] + #[test] + fn unattended_masks_home_case_insensitively() { + let home = r"C:\Users\Jane Doe"; + let input = r"failed to open c:\users\jane doe\cache\index.json"; + assert_eq!( + sanitize_text_with_home(input, Some(home), true), + "failed to open [REDACTED_PATH]" + ); + } + + #[test] + fn unattended_output_keeps_the_category_and_redacts_the_paths() { + // Pin the mode: unforced, the test would ride on the harness's + // captured stderr, and `--nocapture` at a terminal flips the + // probe to attached. + let _unattended = AttachmentOverride::set(false); assert_eq!( sanitize_text("no runtime for Skippy runtime 0.76.1 / ABI 0.1.71"), "no runtime for Skippy runtime 0.76.1 / ABI 0.1.71" @@ -522,11 +679,16 @@ mod tests { sanitize_text("startup failed at (/home/operator/x)"), "startup failed at ([REDACTED_PATH])" ); + // Credentials stay redacted in both modes. + assert_eq!( + sanitize_text("authorization Bearer secret-token"), + "authorization Bearer [REDACTED]" + ); } #[test] - fn redacts_the_operator_logging_privacy_corpus() { - let mut cases = vec![ + fn redacts_the_operator_logging_privacy_credential_corpus() { + let cases = [ ( "provider endpoint https://provider.example/v1?access_token=secret-access&model=qwen" .to_string(), @@ -544,22 +706,7 @@ mod tests { "credential sk-supersecret-key".to_string(), "sk-supersecret-key".to_string(), ), - ( - r#"native error at C:\Users\operator\.mesh-llm\config.toml"#.to_string(), - r#"C:\Users\operator"#.to_string(), - ), - ( - r#"native error at \\server\private\model.gguf"#.to_string(), - r#"\\server\private"#.to_string(), - ), - ( - r#"native error at \\?\C:\private\model.gguf"#.to_string(), - r#"\\?\C:\private"#.to_string(), - ), ]; - if let Some(home) = operator_home() { - cases.push((format!("native error at {home}/.mesh-llm/token"), home)); - } for (input, secret) in cases { let sanitized = sanitize_text(&input); @@ -571,22 +718,16 @@ mod tests { } #[test] - fn preserves_fatal_context_while_selectively_redacting_credentials_and_paths() { - let mut cases = vec![ - r"startup failed opening C:\Users\operator\config.toml".to_owned(), - r"startup failed opening \\server\private\config.toml".to_owned(), - "startup failed: authorization Bearer secret-token".to_owned(), - ]; - if let Some(home) = operator_home() { - cases.push(format!( - "startup failed opening {home}/.mesh-llm/config.toml" - )); - } - for input in cases { - let sanitized = sanitize_text(&input); - assert_ne!(sanitized, "[REDACTED]"); - assert!(sanitized.contains("startup failed")); - } + fn preserves_fatal_context_and_local_paths_while_redacting_credentials_when_attached() { + let _attached = AttachmentOverride::set(true); + let sanitized = sanitize_text("startup failed opening /home/operator/config.toml"); + assert_eq!( + sanitized, + "startup failed opening /home/operator/config.toml" + ); + + let sanitized = sanitize_text("startup failed: authorization Bearer secret-token"); + assert_eq!(sanitized, "startup failed: authorization Bearer [REDACTED]"); } #[test] @@ -598,7 +739,7 @@ mod tests { ("batch_size".to_string(), json!(32)), ]; - let safe = safe_native_params(¶ms); + let safe = safe_native_params(¶ms, LogFormat::Pretty); assert_eq!(safe.len(), 1); assert_eq!(safe.get("batch_size"), Some(&json!(32))); diff --git a/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs b/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs index 65a9dfd18c..4500442449 100644 --- a/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs +++ b/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs @@ -787,6 +787,11 @@ pub(super) fn fatal_events_do_not_consume_startup_history_slots() { #[test] fn startup_history_sanitizes_complete_event_summaries() { + // In production an installed console capture keeps the dashboard on + // the attached (verbatim) side of the probe; the harness installs no + // capture, so force the attached arm for the visibility assertion. + let _attached = + crate::output::logging_projection::privacy::test_support::AttachmentOverride::set(true); let mut formatter = InteractiveDashboardFormatter::default(); formatter .handle_output_event(&OutputEvent::Warning { @@ -804,7 +809,9 @@ fn startup_history_sanitizes_complete_event_summaries() { .summary .as_str(); assert!(summary.contains("startup failed")); - assert!(!summary.contains("/Users/operator")); + // The operator's own path renders (terminal projection); the Bearer + // credential next to it does not. + assert!(summary.contains("/Users/operator/.mesh-llm/config.toml")); assert!(!summary.contains("private-token")); } diff --git a/mesh/crates/mesh-llm-tui/src/output/tests/logging_projection.rs b/mesh/crates/mesh-llm-tui/src/output/tests/logging_projection.rs index 9bec4c6bff..87cd608730 100644 --- a/mesh/crates/mesh-llm-tui/src/output/tests/logging_projection.rs +++ b/mesh/crates/mesh-llm-tui/src/output/tests/logging_projection.rs @@ -160,6 +160,26 @@ fn canonical_projection_exposes_truthful_request_context_in_pretty_and_jsonl() { assert!(pretty.contains(&request_id.as_uuid().to_string())); } +#[test] +fn redirected_json_redacts_paths_even_when_pretty_stderr_is_attached() { + let _attachment = + super::super::logging_projection::privacy::test_support::AttachmentOverride::for_streams( + true, false, + ); + let path = "/srv/operator/model.gguf"; + let event = OutputEvent::Warning { + message: format!("could not open {path}"), + context: Some(format!("using {path}")), + }; + + let json = JsonFormatter.format(&event).expect("JSON projection"); + assert!(!json.contains(path)); + assert!(json.contains("[REDACTED_PATH]")); + + let pretty = PrettyFormatter.format(&event).expect("pretty projection"); + assert!(pretty.contains(path)); +} + #[test] fn canonical_jsonl_uses_stdout_and_pretty_uses_stderr() { let event = canonical_output( @@ -363,16 +383,13 @@ fn canonical_terminal_events_render_once_and_use_existing_event_controls() { #[test] fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ids() { - // HOME is usually unset on Windows, where the home is USERPROFILE. Same - // choice as the redaction: the first non-empty absolute value. - let home = ["HOME", "USERPROFILE"] - .into_iter() - .find_map(|variable| { - std::env::var(variable) - .ok() - .filter(|home| !home.is_empty() && std::path::Path::new(home).is_absolute()) - }) - .expect("HOME or USERPROFILE should be an absolute path"); + // Visibility assertions run against an attached terminal. + let _attached = + crate::output::logging_projection::privacy::test_support::AttachmentOverride::set(true); + // Fixed synthetic path and payload words chosen so no assertion can + // collide with the build account's environment (a home containing + // "private" once false-failed the negative assertions below). + let home = "/var/jenkins-workspace-7013"; let request_id = RequestId::new(); let request_id_text = request_id.as_uuid().to_string(); let canonical = canonical_output( @@ -380,20 +397,20 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ 9, LifecycleEvent::Failed { error: format!( - "prompt=private Bearer secret-token {home} completion=private response=private" + "prompt=confidential-payload Bearer secret-token {home} completion=confidential-payload response=confidential-payload" ), status_code: None, }, ); let native = OutputEvent::LlamaNativeLog { - message: format!("prompt=private {home} {}", "x".repeat(2_000)), + message: format!("prompt=confidential-payload {home} {}", "x".repeat(2_000)), category: "model", params: vec![ ( "request_id".to_string(), Value::String(request_id_text.clone()), ), - ("private_path".to_string(), Value::String(home.clone())), + ("private_path".to_string(), Value::String(home.to_string())), ("progress".to_string(), serde_json::json!(50)), ], }; @@ -404,7 +421,14 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ let canonical_pretty = pretty .format(&canonical) .expect("canonical pretty projection"); - for forbidden in ["private", "secret-token", home.as_str()] { + // Credentials stay redacted in every projection. Canonical lines are + // composed from a fixed vocabulary plus curated metadata (model, + // route, status, duration) and never render the raw error text, so + // the home path is absent from the canonical pretty line by + // construction, not by redaction. The native-log projections below + // do render message text, through this crate's terminal sanitizer, + // where the operator's path is deliberately visible (see privacy.rs). + for forbidden in ["confidential-payload", "secret-token"] { assert!( !canonical_json.contains(forbidden), "canonical JSON leaked {forbidden:?}" @@ -414,6 +438,10 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ "canonical pretty leaked {forbidden:?}" ); } + assert!( + !canonical_pretty.contains(home), + "canonical pretty line never renders the raw error text" + ); assert!(canonical_json.contains(&request_id_text)); assert!(canonical_pretty.contains(&request_id_text)); @@ -421,9 +449,8 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ let json_line = json.format(event).expect("native JSON projection"); let pretty_line = pretty.format(event).expect("native pretty projection"); for forbidden in [ - "private", + "confidential-payload", "secret-token", - home.as_str(), request_id_text.as_str(), "tokens", ] { @@ -433,8 +460,42 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ "pretty leaked {forbidden:?}" ); } + // Compare against the decoded message, not the serialized JSON: + // a Windows `USERPROFILE` (C:\Users\Alice) is backslash-escaped + // in the JSON text, so a raw `contains` would fail even when the + // projection preserved the path. + let json_record: Value = + serde_json::from_str(json_line.trim_end()).expect("native JSON line to parse"); + let json_message = json_record["message"] + .as_str() + .expect("native JSON record to carry a message"); + assert!( + json_message.contains(home), + "native JSON projection should keep the operator's path visible: {json_message:?}" + ); + assert!( + pretty_line.contains(home), + "native pretty projection should keep the operator's path visible: {pretty_line:?}" + ); assert!(pretty_line.chars().count() <= 1_100); } + + // The same native message through an unattended stream (service + // journal, CI capture): the path redacts, the payload still + // redacts, the category text survives. + let _unattended = + crate::output::logging_projection::privacy::test_support::AttachmentOverride::set(false); + let unattended_pretty = pretty + .format(&native) + .expect("native pretty projection, unattended"); + assert!( + !unattended_pretty.contains(home), + "unattended pretty must redact the path: {unattended_pretty:?}" + ); + assert!( + unattended_pretty.contains("prompt="), + "unattended pretty keeps the diagnostic category" + ); } #[test] diff --git a/mesh/docs/LOGGING.md b/mesh/docs/LOGGING.md index 6565255c77..2e5c436e38 100644 --- a/mesh/docs/LOGGING.md +++ b/mesh/docs/LOGGING.md @@ -208,8 +208,15 @@ TUI presentation stays on stderr. The projection retains only bounded local `request_id`, `event_id`, replay `channel` and `sequence`, terminal `outcome`, HTTP `status`, `duration`, and numeric `tokens` when present. It excludes prompts, completions, artifact bodies, credentials, URLs, and free-form -payload/error detail. Fatal startup projection redacts credentials and private -paths selectively, retaining the surrounding diagnostic category. These local correlation IDs do not cross mesh/network or +payload/error detail. Fatal startup projection redacts credentials and +URL-embedded secrets selectively in every mode. The operator's local +paths render verbatim while the event stream is attached to a terminal. +Pretty events use stderr, and JSON events use stdout. The dashboard's Events +panel counts as an attached terminal for pretty events. Redirected event +streams, such as a service journal, container log, or CI capture, redact +local paths as `[REDACTED_PATH]`. Durable artifacts +keep the stricter, unconditional path redaction of the host runtime's +logging policy (`mesh-llm-host-runtime`). These local correlation IDs do not cross mesh/network or OTLP telemetry boundaries, and the CLI stream remains a process-observation projection rather than a replacement for the trusted-local ledger.