From 5bf3769c7863b166cfb1a1743c4b5fe27dafd21b Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:29:45 +0530 Subject: [PATCH 1/5] fix(cli): stop redacting the operator's own paths in terminal errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The terminal event projection replaced every absolute path with [REDACTED_PATH], including paths the operator had just typed. The legacy-surface warning's own correction guidance rendered as '[REDACTED_PATH] serve --model [REDACTED_PATH]' — uncopyable. The same filter gutted 'config validate --config-path' errors (which of my files failed?), the load owner-control credential error, the update release-bundle guard, and the eager startup-model failure line. Success output prints these same paths verbatim, so only failure guidance was punished. Remove the path-redaction arm (and its machinery: home masking with the sentinel, the Windows absolute-path detector) from the TUI terminal projection. Every consumer of this layer is the operator's own screen: pretty/json formatters, dashboard cells, logo mode, and the fatal emergency writer; console capture routes back to stderr and nothing here reaches durable storage. Credential redaction is unchanged byte-for-byte (bearer/basic, sensitive keys, sk-/ghp- values, URL query values and userinfo, the 1024-char cap). Durable sanitization keeps its stricter, independent policy (mesh-llm-events audit sanitization home-masks and redacts; the commandSummary grammar and log-store contracts are separate code). Tests: path-pinning tests now pin path preservation, and a new test pins the five production message shapes that motivated the fix, so the regression cannot quietly return. The canonical projection test documents the layer split it asserts: canonical JSON carries no error text, and canonical pretty still elides paths via the mesh-llm-events envelope presentation layer (out of scope here). Also update mesh/docs/LOGGING.md, whose terminal-output section still promised that the fatal startup projection redacts private paths — the exact behavior removed here. Durable artifacts keep the stricter path redaction of the host logging policy, as the doc now states. --- .../mesh-llm-cli/src/parser/logging_help.rs | 2 +- .../src/output/logging_projection/privacy.rs | 196 +++++------------- .../src/output/tests/dashboard.rs | 4 +- .../src/output/tests/logging_projection.rs | 22 +- mesh/docs/LOGGING.md | 8 +- 5 files changed, 87 insertions(+), 145 deletions(-) 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..2f2953a0a7 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.\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/logging_projection/privacy.rs b/mesh/crates/mesh-llm-tui/src/output/logging_projection/privacy.rs index 570f39d678..eb067a5d56 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 @@ -30,12 +30,7 @@ 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()) -} - -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)); + let normalized = redact_sensitive_fragments(&redact_url_query_values(input)); if normalized.chars().count() <= MAX_PRESENTATION_CHARS { normalized } else { @@ -50,9 +45,15 @@ fn sanitize_text_with_home(input: &str, home: Option<&str>) -> String { } /// 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. +/// replacing only credential-shaped values. Terminal projections render on +/// the operator's own screen, where command output already prints local +/// paths verbatim (cache locations, config paths, keystores), so absolute +/// paths stay visible here too: redacting them only in event text turned +/// actionable guidance — a `--config` path the operator just typed, or the +/// corrected command the legacy-surface warning suggests — into +/// `[REDACTED_PATH]`. Durable artifacts keep the stricter path redaction +/// of the host logging policy; this terminal layer mirrors only its +/// credential rules. fn redact_sensitive_fragments(input: &str) -> String { let mut redact_next = false; let mut sensitive_key_pending = false; @@ -80,8 +81,6 @@ fn redact_sensitive_fragments(input: &str) -> String { 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]")); } else if is_credential_value(trimmed) { output.push(redact_word(word, "[REDACTED]")); } else if !trimmed.contains(['?', '&']) @@ -184,64 +183,6 @@ fn safe_param_key(key: &str) -> bool { && !normalized.contains("id") } -fn is_private_absolute_path(word: &str) -> bool { - // A bare `/` is the separator in text such as `runtime 0.76.1 / ABI 0.1.71`; - // revealing the filesystem root is no leak. - (word.starts_with('/') && word != "/") - || word.to_ascii_lowercase().starts_with("file://") - || is_windows_absolute_path(word) - || word.contains(HOME_SENTINEL) -} - -/// Stands in for the operator's home directory from before the text is split -/// into words until the word that held it is redacted whole, so a home with a -/// space (`C:\Users\Jane Doe`) cannot fall across two words. A private-use -/// character: log text does not carry it, and punctuation trimming keeps it. -const HOME_SENTINEL: &str = "\u{E000}"; - -fn mask_operator_home(input: &str, home: Option<&str>) -> String { - let Some(home) = home.filter(|home| !home.is_empty()) else { - return input.to_owned(); - }; - // Windows paths compare regardless of case. ASCII folding keeps every - // byte offset, so matches found in the folded text map back to `input`. - let (text, needle) = if cfg!(windows) { - (input.to_ascii_lowercase(), home.to_ascii_lowercase()) - } else { - (input.to_owned(), home.to_owned()) - }; - let mut masked = String::with_capacity(input.len()); - let mut copied = 0; - for (start, _) in text.match_indices(&needle) { - masked.push_str(&input[copied..start]); - masked.push_str(HOME_SENTINEL); - copied = start + needle.len(); - } - masked.push_str(&input[copied..]); - masked -} - -/// The operator's home directory: `HOME`, or `USERPROFILE` on Windows, where -/// `HOME` is usually unset. Only an absolute path counts, so a Git Bash -/// `HOME` such as `/c/Users/name` falls through to `USERPROFILE`. -fn operator_home() -> Option { - ["HOME", "USERPROFILE"].into_iter().find_map(|variable| { - let home = std::env::var(variable).ok()?; - (!home.is_empty() && std::path::Path::new(&home).is_absolute()).then_some(home) - }) -} - -fn is_windows_absolute_path(value: &str) -> bool { - let bytes = value.as_bytes(); - let drive_root = bytes.len() >= 3 - && bytes[0].is_ascii_alphabetic() - && bytes[1] == b':' - && matches!(bytes[2], b'\\' | b'/'); - let unc_or_device = - value.starts_with("\\\\") || value.starts_with("//") || value.starts_with("\\??\\"); - 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. @@ -359,51 +300,52 @@ 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::{safe_native_params, sanitize_text}; use serde_json::json; #[test] - fn redacts_a_home_directory_that_contains_a_space() { + fn preserves_local_paths_including_homes_with_spaces() { + // 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 keeps_paths_after_benign_keys_while_redacting_after_sensitive_keys() { + let sanitized = sanitize_text("path=/home/operator/model.gguf token=supersecret"); + + assert!( + sanitized.contains("path=/home/operator/model.gguf"), + "{sanitized:?}" ); - assert!(!sanitized.contains("jane"), "{sanitized:?}"); + assert!(sanitized.contains("token=[REDACTED]"), "{sanitized:?}"); + assert!(!sanitized.contains("supersecret"), "{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 preserves_the_operators_own_paths_in_cli_guidance_and_errors() { + // 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); } } @@ -492,7 +434,7 @@ mod tests { } #[test] - fn redacts_unix_windows_unc_and_device_paths() { + fn preserves_unix_windows_unc_and_device_paths() { let cases = [ "/Users/operator/.mesh-llm/config.toml", r"C:\Users\operator\.mesh-llm\config.toml", @@ -501,32 +443,30 @@ 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() { 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 [REDACTED_PATH]" + "copied / to /srv/private/model.gguf" ); assert_eq!( sanitize_text("startup failed at (/home/operator/x)"), - "startup failed at ([REDACTED_PATH])" + "startup failed at (/home/operator/x)" ); } #[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 +484,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 +496,15 @@ 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() { + 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] 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..475a8c2fee 100644 --- a/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs +++ b/mesh/crates/mesh-llm-tui/src/output/tests/dashboard.rs @@ -804,7 +804,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..cfe0e8da8c 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 @@ -404,7 +404,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 ["private", "secret-token"] { assert!( !canonical_json.contains(forbidden), "canonical JSON leaked {forbidden:?}" @@ -414,6 +421,10 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ "canonical pretty leaked {forbidden:?}" ); } + assert!( + !canonical_pretty.contains(home.as_str()), + "canonical pretty line never renders the raw error text" + ); assert!(canonical_json.contains(&request_id_text)); assert!(canonical_pretty.contains(&request_id_text)); @@ -423,7 +434,6 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ for forbidden in [ "private", "secret-token", - home.as_str(), request_id_text.as_str(), "tokens", ] { @@ -433,6 +443,14 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ "pretty leaked {forbidden:?}" ); } + assert!( + json_line.contains(home.as_str()), + "native JSON projection should keep the operator's path visible: {json_line:?}" + ); + assert!( + pretty_line.contains(home.as_str()), + "native pretty projection should keep the operator's path visible: {pretty_line:?}" + ); assert!(pretty_line.chars().count() <= 1_100); } } diff --git a/mesh/docs/LOGGING.md b/mesh/docs/LOGGING.md index 6565255c77..c00ba2b71b 100644 --- a/mesh/docs/LOGGING.md +++ b/mesh/docs/LOGGING.md @@ -208,8 +208,12 @@ 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, retaining the surrounding diagnostic +category and the operator's local paths, which render verbatim on the +operator's own terminal; durable artifacts keep the stricter 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. From 0f098ef135ed721c142650c5de6e2df231d4c154 Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:45:15 +0530 Subject: [PATCH 2/5] test(tui): decode the JSON projection before asserting path visibility A Windows USERPROFILE contains backslashes, which the JSON serializer escapes, so a raw substring check against the serialized line fails even when the projection preserved the path. Parse the record and assert on the decoded message string instead; the pretty line keeps its direct comparison. --- .../src/output/tests/logging_projection.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) 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 cfe0e8da8c..27671113a0 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 @@ -443,9 +443,18 @@ 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_line.contains(home.as_str()), - "native JSON projection should keep the operator's path visible: {json_line:?}" + json_message.contains(home.as_str()), + "native JSON projection should keep the operator's path visible: {json_message:?}" ); assert!( pretty_line.contains(home.as_str()), From 06ac76dd6bb2be7b0b01af0c109a445d23c8c945 Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:51:44 +0530 Subject: [PATCH 3/5] fix(tui): redact terminal-output paths only when stderr is redirected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interactive sessions keep actionable errors: the operator's own command output already prints local paths verbatim, so paths stay visible when stderr is a terminal. Unattended contexts restore the redaction: when stderr is redirected — launchd's stderr.log, the systemd journal, container logs, CI capture — the reader is no longer the operator at the keyboard, and the operator's home-directory layout should not land there. Credential redaction is unconditional in both modes. The interactive dashboard redirects fd 2 into its capture pipe while it owns the screen, so the raw is_terminal probe alone would classify the operator's own Events panel as unattended; the probe also treats an installed console capture as attached. The attachment probe is thread-locally overridable in tests; every visibility assertion runs attached, the canonical test gains an unattended counterpart asserting [REDACTED_PATH] with the category text intact, and each mode-dependent test pins its side of the probe explicitly rather than riding on the harness's captured stderr. The canonical test stops deriving its path from the build account's HOME and uses a fixed synthetic path plus a payload word that cannot collide with any environment path. LOGGING.md and the --help-advanced logging line state the gate. --- .../mesh-llm-cli/src/parser/logging_help.rs | 2 +- .../src/output/console_capture.rs | 23 ++ .../src/output/logging_projection.rs | 2 +- .../src/output/logging_projection/privacy.rs | 210 ++++++++++++++++-- .../src/output/tests/dashboard.rs | 5 + .../src/output/tests/logging_projection.rs | 50 +++-- mesh/docs/LOGGING.md | 13 +- 7 files changed, 261 insertions(+), 44 deletions(-) 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 2f2953a0a7..e5166b0c6c 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 credentials and URL-embedded secrets 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 stderr is redirected (service journals).\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/logging_projection.rs b/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs index 2230625b10..8123e5677e 100644 --- a/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs +++ b/mesh/crates/mesh-llm-tui/src/output/logging_projection.rs @@ -1,4 +1,4 @@ -mod privacy; +pub(super) mod privacy; use super::OutputEvent; use super::formatting::OutputEventPresentation; 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 eb067a5d56..f0853e4fb1 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 @@ -30,13 +30,19 @@ pub(super) fn sanitize_map(mut fields: Map) -> Map } pub(super) fn sanitize_text(input: &str) -> String { - let normalized = redact_sensitive_fragments(&redact_url_query_values(input)); - if normalized.chars().count() <= MAX_PRESENTATION_CHARS { - normalized + let redact_paths = !interactive_output(); + let masked = if redact_paths { + mask_operator_home(input, operator_home().as_deref()) + } else { + input.to_owned() + }; + let sanitized = redact_sensitive_fragments(&redact_url_query_values(&masked), redact_paths); + if sanitized.chars().count() <= MAX_PRESENTATION_CHARS { + sanitized } else { format!( "{}... [TRUNCATED]", - normalized + sanitized .chars() .take(MAX_PRESENTATION_CHARS) .collect::() @@ -44,17 +50,74 @@ pub(super) fn sanitize_text(input: &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() -> bool { + #[cfg(test)] + if let Some(forced) = TEST_ATTACHMENT_OVERRIDE.with(std::cell::Cell::get) { + return forced; + } + std::io::IsTerminal::is_terminal(&std::io::stderr()) + || super::super::console_capture::capture_installed() +} + +#[cfg(test)] +thread_local! { + /// Test-only attachment override: `Some(attached)` while a test + /// forces the probe, `None` when unforced (the real stderr 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 { + super::TEST_ATTACHMENT_OVERRIDE.with(|cell| cell.set(Some(attached))); + 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 credential-shaped values. Terminal projections render on -/// the operator's own screen, where command output already prints local -/// paths verbatim (cache locations, config paths, keystores), so absolute -/// paths stay visible here too: redacting them only in event text turned -/// actionable guidance — a `--config` path the operator just typed, or the -/// corrected command the legacy-surface warning suggests — into -/// `[REDACTED_PATH]`. Durable artifacts keep the stricter path redaction -/// of the host logging policy; this terminal layer mirrors only its -/// credential rules. -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(); @@ -81,6 +144,8 @@ fn redact_sensitive_fragments(input: &str) -> String { if matches!(normalized.as_str(), "bearer" | "basic") { redact_next = true; output.push(word.to_owned()); + } else if redact_paths && is_private_absolute_path(trimmed) { + output.push(redact_word(word, "[REDACTED_PATH]")); } else if is_credential_value(trimmed) { output.push(redact_word(word, "[REDACTED]")); } else if !trimmed.contains(['?', '&']) @@ -183,6 +248,64 @@ fn safe_param_key(key: &str) -> bool { && !normalized.contains("id") } +fn is_private_absolute_path(word: &str) -> bool { + // A bare `/` is the separator in text such as `runtime 0.76.1 / ABI 0.1.71`; + // revealing the filesystem root is no leak. + (word.starts_with('/') && word != "/") + || word.to_ascii_lowercase().starts_with("file://") + || is_windows_absolute_path(word) + || word.contains(HOME_SENTINEL) +} + +/// Stands in for the operator's home directory from before the text is split +/// into words until the word that held it is redacted whole, so a home with a +/// space (`C:\Users\Jane Doe`) cannot fall across two words. A private-use +/// character: log text does not carry it, and punctuation trimming keeps it. +const HOME_SENTINEL: &str = "\u{E000}"; + +fn mask_operator_home(input: &str, home: Option<&str>) -> String { + let Some(home) = home.filter(|home| !home.is_empty()) else { + return input.to_owned(); + }; + // Windows paths compare regardless of case. ASCII folding keeps every + // byte offset, so matches found in the folded text map back to `input`. + let (text, needle) = if cfg!(windows) { + (input.to_ascii_lowercase(), home.to_ascii_lowercase()) + } else { + (input.to_owned(), home.to_owned()) + }; + let mut masked = String::with_capacity(input.len()); + let mut copied = 0; + for (start, _) in text.match_indices(&needle) { + masked.push_str(&input[copied..start]); + masked.push_str(HOME_SENTINEL); + copied = start + needle.len(); + } + masked.push_str(&input[copied..]); + masked +} + +/// The operator's home directory: `HOME`, or `USERPROFILE` on Windows, where +/// `HOME` is usually unset. Only an absolute path counts, so a Git Bash +/// `HOME` such as `/c/Users/name` falls through to `USERPROFILE`. +fn operator_home() -> Option { + ["HOME", "USERPROFILE"].into_iter().find_map(|variable| { + let home = std::env::var(variable).ok()?; + (!home.is_empty() && std::path::Path::new(&home).is_absolute()).then_some(home) + }) +} + +fn is_windows_absolute_path(value: &str) -> bool { + let bytes = value.as_bytes(); + let drive_root = bytes.len() >= 3 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && matches!(bytes[2], b'\\' | b'/'); + let unc_or_device = + value.starts_with("\\\\") || value.starts_with("//") || value.starts_with("\\??\\"); + 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. @@ -300,11 +423,13 @@ fn is_credential_value(value: &str) -> bool { #[cfg(test)] mod tests { + use super::test_support::AttachmentOverride; use super::{safe_native_params, sanitize_text}; use serde_json::json; #[test] - fn preserves_local_paths_including_homes_with_spaces() { + 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 @@ -320,6 +445,10 @@ mod tests { #[test] 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!( @@ -331,7 +460,8 @@ mod tests { } #[test] - fn preserves_the_operators_own_paths_in_cli_guidance_and_errors() { + 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 @@ -434,7 +564,8 @@ mod tests { } #[test] - fn preserves_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", @@ -449,7 +580,8 @@ mod tests { } #[test] - fn keeps_slash_separators_and_adjacent_paths() { + 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" @@ -464,6 +596,45 @@ mod tests { ); } + /// The same warning, unattended (stderr redirected — service + /// journal, container log, CI capture): the diagnostic category + /// survives, the operator's paths do not. + #[test] + fn forced_attached_mode_preserves_paths() { + // Before any override the probe consults the real stderr (a + // captured pipe under the test harness): either value is + // possible, so only assert the override once set. + let _guard = AttachmentOverride::set(true); + let attached_input = "startup failed at (/home/operator/x)"; + assert_eq!(sanitize_text(attached_input), attached_input); + drop(_guard); + } + + #[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" + ); + assert_eq!( + sanitize_text("copied / to /srv/private/model.gguf"), + "copied / to [REDACTED_PATH]" + ); + assert_eq!( + 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_credential_corpus() { let cases = [ @@ -496,7 +667,8 @@ mod tests { } #[test] - fn preserves_fatal_context_and_local_paths_while_redacting_credentials() { + 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, 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 475a8c2fee..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 { 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 27671113a0..c14f865888 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 @@ -363,16 +363,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 +377,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)), ], }; @@ -411,7 +408,7 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ // 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 ["private", "secret-token"] { + for forbidden in ["confidential-payload", "secret-token"] { assert!( !canonical_json.contains(forbidden), "canonical JSON leaked {forbidden:?}" @@ -422,7 +419,7 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ ); } assert!( - !canonical_pretty.contains(home.as_str()), + !canonical_pretty.contains(home), "canonical pretty line never renders the raw error text" ); assert!(canonical_json.contains(&request_id_text)); @@ -432,7 +429,7 @@ 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", request_id_text.as_str(), "tokens", @@ -453,15 +450,32 @@ fn canonical_projection_keeps_local_correlation_but_redacts_payloads_and_native_ .as_str() .expect("native JSON record to carry a message"); assert!( - json_message.contains(home.as_str()), + json_message.contains(home), "native JSON projection should keep the operator's path visible: {json_message:?}" ); assert!( - pretty_line.contains(home.as_str()), + 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 c00ba2b71b..be161110c1 100644 --- a/mesh/docs/LOGGING.md +++ b/mesh/docs/LOGGING.md @@ -209,11 +209,14 @@ TUI presentation stays on stderr. The projection retains only bounded local 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 -URL-embedded secrets selectively, retaining the surrounding diagnostic -category and the operator's local paths, which render verbatim on the -operator's own terminal; durable artifacts keep the stricter path -redaction of the host runtime's logging policy -(`mesh-llm-host-runtime`). These local correlation IDs do not cross mesh/network or +URL-embedded secrets selectively in every mode. The operator's local +paths render verbatim while stderr is attached to a terminal (an +installed dashboard console capture counts as attached — its Events +panel is the operator's screen), and are redacted (`[REDACTED_PATH]`) +when stderr is redirected — the mode a service journal, container +log, or CI capture reads. 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. From 6b2b9d2b5236d73d35aeac26454903509ab3f9a6 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 15:03:19 +1100 Subject: [PATCH 4/5] fix(tui): redact paths on redirected JSON output --- .../mesh-llm-cli/src/parser/logging_help.rs | 2 +- .../mesh-llm-tui/src/output/formatting.rs | 11 +++ .../src/output/logging_projection.rs | 15 ++-- .../src/output/logging_projection/privacy.rs | 88 +++++++++++++------ .../src/output/tests/logging_projection.rs | 20 +++++ mesh/docs/LOGGING.md | 10 +-- 6 files changed, 105 insertions(+), 41 deletions(-) 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 e5166b0c6c..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 credentials and URL-embedded secrets while retaining context. Paths render verbatim on an attached terminal and redact when stderr is redirected (service journals).\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/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 8123e5677e..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 @@ 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 f0853e4fb1..84ded58c5c 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,9 +37,18 @@ pub(super) fn sanitize_map(mut fields: Map) -> Map } pub(super) fn sanitize_text(input: &str) -> String { - let redact_paths = !interactive_output(); + sanitize_text_for_mode(input, LogFormat::Pretty) +} + +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, operator_home().as_deref()) + mask_operator_home(input, home) } else { input.to_owned() }; @@ -69,23 +85,25 @@ pub(super) fn sanitize_text(input: &str) -> String { /// "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() -> bool { +fn interactive_output(mode: LogFormat) -> bool { #[cfg(test)] - if let Some(forced) = TEST_ATTACHMENT_OVERRIDE.with(std::cell::Cell::get) { - return forced; + if let Some((pretty, json)) = TEST_ATTACHMENT_OVERRIDE.with(std::cell::Cell::get) { + return match mode { + LogFormat::Pretty => pretty, + LogFormat::Json => json, + }; } - std::io::IsTerminal::is_terminal(&std::io::stderr()) - || super::super::console_capture::capture_installed() + super::super::formatting::event_stream_is_terminal(mode) } #[cfg(test)] thread_local! { - /// Test-only attachment override: `Some(attached)` while a test - /// forces the probe, `None` when unforced (the real stderr probe + /// 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> = + static TEST_ATTACHMENT_OVERRIDE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } @@ -97,7 +115,11 @@ pub(in crate::output) mod test_support { impl AttachmentOverride { pub(in crate::output) fn set(attached: bool) -> Self { - super::TEST_ATTACHMENT_OVERRIDE.with(|cell| cell.set(Some(attached))); + 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 } } @@ -424,7 +446,8 @@ fn is_credential_value(value: &str) -> bool { #[cfg(test)] mod tests { use super::test_support::AttachmentOverride; - use super::{safe_native_params, sanitize_text}; + use super::{safe_native_params, sanitize_text, sanitize_text_with_home}; + use crate::output::LogFormat; use serde_json::json; #[test] @@ -558,7 +581,7 @@ 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)) ); } @@ -596,18 +619,25 @@ mod tests { ); } - /// The same warning, unattended (stderr redirected — service - /// journal, container log, CI capture): the diagnostic category - /// survives, the operator's paths do not. #[test] - fn forced_attached_mode_preserves_paths() { - // Before any override the probe consults the real stderr (a - // captured pipe under the test harness): either value is - // possible, so only assert the override once set. - let _guard = AttachmentOverride::set(true); - let attached_input = "startup failed at (/home/operator/x)"; - assert_eq!(sanitize_text(attached_input), attached_input); - drop(_guard); + 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] @@ -688,7 +718,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/logging_projection.rs b/mesh/crates/mesh-llm-tui/src/output/tests/logging_projection.rs index c14f865888..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( diff --git a/mesh/docs/LOGGING.md b/mesh/docs/LOGGING.md index be161110c1..2e5c436e38 100644 --- a/mesh/docs/LOGGING.md +++ b/mesh/docs/LOGGING.md @@ -210,11 +210,11 @@ 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 URL-embedded secrets selectively in every mode. The operator's local -paths render verbatim while stderr is attached to a terminal (an -installed dashboard console capture counts as attached — its Events -panel is the operator's screen), and are redacted (`[REDACTED_PATH]`) -when stderr is redirected — the mode a service journal, container -log, or CI capture reads. Durable artifacts +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 From 2cc7d46ef16cc29e56dcad1f8b608b3ce3e63ae9 Mon Sep 17 00:00:00 2001 From: James Dumay Date: Sun, 29 Nov 2026 15:24:52 +1100 Subject: [PATCH 5/5] fix(tui): preserve repeated spaces in attached paths --- .../src/output/logging_projection/privacy.rs | 71 ++++++++++++------- 1 file changed, 46 insertions(+), 25 deletions(-) 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 84ded58c5c..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 @@ -52,7 +52,7 @@ fn sanitize_text_with_home(input: &str, home: Option<&str>, redact_paths: bool) } else { input.to_owned() }; - let sanitized = redact_sensitive_fragments(&redact_url_query_values(&masked), redact_paths); + let sanitized = redact_sensitive_fragments(&masked, redact_paths); if sanitized.chars().count() <= MAX_PRESENTATION_CHARS { sanitized } else { @@ -143,33 +143,52 @@ 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()); + output.push_str(word); } else if redact_paths && is_private_absolute_path(trimmed) { - output.push(redact_word(word, "[REDACTED_PATH]")); + 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) @@ -179,22 +198,24 @@ fn redact_sensitive_fragments(input: &str, redact_paths: bool) -> 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 { @@ -328,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 { @@ -466,6 +477,16 @@ mod tests { } } + #[test] + 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]" + ); + } + #[test] fn keeps_paths_after_benign_keys_while_redacting_after_sensitive_keys() { // Attached-mode assertion: pin the probe so a build account whose