Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Redact sensitive auth probe output and restrict log permissions (#4604)

Maximilian Roos899b6c6aa636
diff --git a/src/command_log.rs b/src/command_log.rs
index 8a25e4406..53396b4ce 100644
--- a/src/command_log.rs
+++ b/src/command_log.rs
@@ -9,7 +9,7 @@
//! renamed to `commands.jsonl.old` and a fresh file is started. This bounds
//! storage to ~2MB worst case.
-use std::fs::{self, File, OpenOptions};
+use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
@@ -24,15 +24,22 @@ const MAX_CMD_LENGTH: usize = 2000;
static COMMAND_LOG: OnceLock<Mutex<CommandLog>> = OnceLock::new();
struct CommandLog {
- log_path: PathBuf,
+ log_dir: PathBuf,
file: Option<File>,
wt_command: String,
}
impl CommandLog {
fn new(log_dir: &Path, wt_command: &str) -> Self {
+ // Existing audit logs need private permissions even when this command
+ // writes no audit entry or never reaches the rotation threshold.
+ for filename in ["commands.jsonl", "commands.jsonl.old"] {
+ if log_dir.join(filename).exists() {
+ let _ = crate::utils::prepare_log_file(log_dir, Path::new(filename));
+ }
+ }
Self {
- log_path: log_dir.join("commands.jsonl"),
+ log_dir: log_dir.to_path_buf(),
file: None,
wt_command: wt_command.to_string(),
}
@@ -45,25 +52,25 @@ impl CommandLog {
exit_code: Option<i32>,
duration: Option<Duration>,
) {
+ // Restrict an existing file before it can become the rotated log.
+ if self.file.is_none() {
+ self.file =
+ crate::utils::open_log_file(&self.log_dir, Path::new("commands.jsonl"), true).ok();
+ }
+ if self.file.is_none() {
+ return;
+ }
+
// Rotate if needed
- if let Ok(metadata) = fs::metadata(&self.log_path)
+ if let Ok(metadata) = fs::metadata(self.log_dir.join("commands.jsonl"))
&& metadata.len() > MAX_LOG_SIZE
{
- let old_path = self.log_path.with_extension("jsonl.old");
- let _ = fs::rename(&self.log_path, &old_path);
- self.file = None; // Force re-open after rotation
- }
-
- // Lazily open the file on first write (or after rotation)
- if self.file.is_none() {
- if let Some(parent) = self.log_path.parent() {
- let _ = fs::create_dir_all(parent);
- }
- self.file = OpenOptions::new()
- .create(true)
- .append(true)
- .open(&self.log_path)
- .ok();
+ let _ = fs::rename(
+ self.log_dir.join("commands.jsonl"),
+ self.log_dir.join("commands.jsonl.old"),
+ );
+ self.file =
+ crate::utils::open_log_file(&self.log_dir, Path::new("commands.jsonl"), true).ok();
}
let cmd_display = truncate_cmd(command);
@@ -233,6 +240,19 @@ mod tests {
assert_eq!(parsed["wt"], "wt test");
}
+ #[test]
+ fn test_write_tolerates_unavailable_log_directory() {
+ let dir = tempfile::tempdir().unwrap();
+ let blocked = dir.path().join("not-a-directory");
+ fs::write(&blocked, "preserved contents").unwrap();
+ let mut logger = CommandLog::new(&blocked, "wt test");
+
+ logger.write("test", "echo hi", Some(0), None);
+
+ assert!(logger.file.is_none());
+ assert_eq!(fs::read_to_string(blocked).unwrap(), "preserved contents");
+ }
+
#[test]
fn test_write_appends_multiple_entries() {
let dir = tempfile::tempdir().unwrap();
@@ -259,10 +279,13 @@ mod tests {
// Write a file just over MAX_LOG_SIZE
let filler = "x".repeat(MAX_LOG_SIZE as usize + 1);
fs::write(&log_path, &filler).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&log_path, fs::Permissions::from_mode(0o644)).unwrap();
+ }
let mut logger = CommandLog::new(dir.path(), "wt test");
- // Open the existing oversized file so the logger has a handle
- logger.file = OpenOptions::new().append(true).open(&log_path).ok();
logger.write(
"rotated",
@@ -280,5 +303,15 @@ mod tests {
let content = fs::read_to_string(&log_path).unwrap();
let parsed: serde_json::Value = serde_json::from_str(content.trim()).unwrap();
assert_eq!(parsed["label"], "rotated");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for path in [&log_path, &old_path] {
+ assert_eq!(
+ fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+ }
}
}
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 1de4d7080..84a3c8230 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -116,27 +116,15 @@ fn create_detach_log(
hook_log: &HookLog,
) -> anyhow::Result<(PathBuf, fs::File)> {
let log_dir = repo.wt_logs_dir();
- let log_path = hook_log.path(&log_dir, branch);
-
- // Create the full ancestor chain (e.g., {log_dir}/{branch}/{source}/{hook-type}/).
- // log_path always has a parent here because HookLog::path() always appends at
- // least one segment beyond log_dir.
- let parent = log_path
- .parent()
- .expect("HookLog::path always includes a parent");
- fs::create_dir_all(parent).with_context(|| {
- format!(
- "Failed to create log directory {}",
- format_path_for_display(parent)
- )
- })?;
-
- let log_file = fs::File::create(&log_path).with_context(|| {
- format!(
- "Failed to create log file {}",
- format_path_for_display(&log_path)
- )
- })?;
+ let relative_path = hook_log.path(Path::new(""), branch);
+ let log_path = log_dir.join(&relative_path);
+ let log_file =
+ worktrunk::utils::open_log_file(&log_dir, &relative_path, false).with_context(|| {
+ format!(
+ "Failed to create log file {}",
+ format_path_for_display(&log_path)
+ )
+ })?;
Ok((log_path, log_file))
}
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 76a8b7559..8fff4b1f5 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -112,8 +112,6 @@ pub fn run_pipeline() -> anyhow::Result<()> {
Repository::at(&spec.worktree_path).context("failed to open repository for pipeline")?;
let log_dir = repo.wt_logs_dir();
- fs::create_dir_all(&log_dir)
- .with_context(|| format!("failed to create log directory: {}", log_dir.display()))?;
let error_wrapper = hook_error_wrapper(spec.hook_type, spec.source, true);
let mut cmd_index = 0usize;
@@ -299,13 +297,15 @@ fn command_log_name(name: Option<&str>, index: usize) -> String {
}
/// Create a per-command log file in the repository's log directory.
-///
-/// Caller must ensure `log_dir` exists (created once at pipeline startup).
fn create_command_log(spec: &PipelineSpec, log_dir: &Path, name: &str) -> anyhow::Result<fs::File> {
let hook_log = HookLog::hook(spec.source, spec.hook_type, name);
- let path = hook_log.path(log_dir, &spec.branch);
- fs::File::create(&path)
- .with_context(|| format!("failed to create log file: {}", path.display()))
+ let relative_path = hook_log.path(Path::new(""), &spec.branch);
+ worktrunk::utils::open_log_file(log_dir, &relative_path, false).with_context(|| {
+ format!(
+ "failed to create log file: {}",
+ log_dir.join(relative_path).display()
+ )
+ })
}
#[cfg(all(test, unix))]
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 5094460ae..95a135b24 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -296,10 +296,11 @@ impl DiagnosticReport {
/// Returns the path if successful, None if write failed.
pub fn write_diagnostic_file(&self, repo: &Repository) -> Option<PathBuf> {
let log_dir = repo.wt_logs_dir();
- std::fs::create_dir_all(&log_dir).ok()?;
-
let path = log_dir.join("diagnostic.md");
- std::fs::write(&path, &self.content).ok()?;
+ let mut file =
+ worktrunk::utils::open_log_file(&log_dir, std::path::Path::new("diagnostic.md"), false)
+ .ok()?;
+ std::io::Write::write_all(&mut file, self.content.as_bytes()).ok()?;
Some(path)
}
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rs
index 0793d51bb..ce6291706 100644
--- a/src/git/remote_ref/github.rs
+++ b/src/git/remote_ref/github.rs
@@ -224,6 +224,7 @@ pub fn is_authed_for(host: &str) -> bool {
Cmd::new("gh")
.args(["auth", "token", "--hostname", host])
.env("GH_PROMPT_DISABLED", "1")
+ .sensitive_output()
.run()
.map(|o| o.status.success())
.unwrap_or(false)
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 0cc375a2f..b675a478d 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -28,6 +28,7 @@ use super::{
CliApiRequest, PlatformData, RemoteRefInfo, cli_api_error, cli_config_value, run_cli_api,
};
use crate::git::{ForgeKind, Repository};
+use crate::shell_exec::Cmd;
/// Raw JSON response from `glab api projects/:id/merge_requests/<number>`.
#[derive(Debug, Deserialize)]
@@ -252,7 +253,13 @@ fn fetch_project_urls(
/// nothing for a host without a token. Returns `false` if `glab` is not
/// installed.
pub fn is_authed_for(host: &str) -> bool {
- cli_config_value("glab", &["token", "--host", host]).is_some_and(|token| !token.is_empty())
+ Cmd::new("glab")
+ .args(["config", "get", "token", "--host", host])
+ .sensitive_output()
+ .run()
+ .is_ok_and(|output| {
+ output.status.success() && !String::from_utf8_lossy(&output.stdout).trim().is_empty()
+ })
}
/// Get the git protocol configured in `glab` (GitLab CLI).
diff --git a/src/log_files.rs b/src/log_files.rs
index 7da69054f..4480c01e8 100644
--- a/src/log_files.rs
+++ b/src/log_files.rs
@@ -38,7 +38,7 @@
//! ones) route to the file layers only — `-vv` is a strict superset
//! of `-v` on stderr.
-use std::fs::{File, OpenOptions};
+use std::fs::File;
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
@@ -196,14 +196,9 @@ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SubprocessMakeWriter {
fn try_create(filename: &str) -> Option<(PathBuf, File)> {
let repo = worktrunk::git::Repository::current().ok()?;
let log_dir = repo.wt_logs_dir();
- std::fs::create_dir_all(&log_dir).ok()?;
let path = log_dir.join(filename);
- let file = OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .open(&path)
- .ok()?;
+ let file =
+ worktrunk::utils::open_log_file(&log_dir, std::path::Path::new(filename), false).ok()?;
Some((path, file))
}
diff --git a/src/logging.rs b/src/logging.rs
index c575cbab9..322696870 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -492,10 +492,8 @@ pub(crate) fn init(verbose_level: u8) {
// gate `log_enabled!` checks before a `log::*` record evaluates its
// format args. Worktrunk's own emit sites are native `tracing::*`, gated
// by the global level hint the layer filters now expose (see
- // `target_filter`), so this cap is specifically for the two `log`-API
- // consumers that hint can't reach: the `log::*` records forwarded from
- // dependencies, and the `log::log_enabled!` deep-logging guard in
- // `shell_exec::log_output`.
+ // `target_filter`), so this cap governs `log::*` records forwarded from
+ // dependencies.
//
// Mirror the env-wins-when-set semantics the layer filters use (PR #2901):
// if `RUST_LOG` is set, its level wins; otherwise the verbosity flag
@@ -675,7 +673,8 @@ where
}
/// `subprocess.log` layer: only `SUBPROCESS_FULL_TARGET` records (raw bodies
-/// and their `$ cmd … seq=N` headers), written through verbatim.
+/// and their `$ cmd … seq=N` headers), written through verbatim. The Debug
+/// baseline and `RUST_LOG` overrides match the trace file layers.
fn build_subprocess_layer<S>(verbose_level: u8) -> Option<impl Layer<S>>
where
S: Subscriber + for<'a> LookupSpan<'a>,
@@ -683,12 +682,15 @@ where
if verbose_level < 2 || !log_files::SUBPROCESS.is_active() {
return None;
}
+ let env_filter = EnvFilter::builder()
+ .with_default_directive(LevelFilter::DEBUG.into())
+ .from_env_lossy();
let only_full = target_filter(|meta| meta.target() == SUBPROCESS_FULL_TARGET);
let layer = tracing_subscriber::fmt::layer()
.with_writer(SubprocessMakeWriter)
.with_ansi(false)
.event_format(SubprocessFileFormat)
- .with_filter(only_full);
+ .with_filter(env_filter.and(only_full));
Some(layer)
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index f906be893..2d7b87ec7 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -909,20 +909,32 @@ fn command_header(cmd: &str, context: Option<&str>) -> String {
///
/// `output` is `None` for a command that never produced any (spawn or wait
/// failure); its header and stdin still emit, so the input survives in the deep
-/// log even when nothing ran.
+/// log even when nothing ran. Sensitive commands emit only a redaction marker
+/// to each target, regardless of outcome.
///
/// Below Debug both targets are disabled and this is a no-op.
-fn log_output(trace: &CommandTrace, stdin: Option<&[u8]>, output: Option<&std::process::Output>) {
- // `log::max_level` (held at the verbosity/`RUST_LOG` ceiling by the
- // `LogTracer` cap in `logging::init`) is the coarse "deep logging on at
- // all?" gate that skips building the full *and* bounded output strings
- // when nothing consumes them. It stays a `log::*` check on purpose: this
- // body feeds both `SUBPROCESS_FULL_TARGET` and `SUBPROCESS_BOUNDED_TARGET`,
- // so the gate must fire whenever *either* deep sink is live — exactly the
- // verbosity cap. A per-target `tracing::enabled!(SUBPROCESS_FULL_TARGET …)`
- // would wrongly skip the bounded preview in the rare case where `-vv`
- // opened `trace.log` but `subprocess.log` failed to open.
- if !log::log_enabled!(log::Level::Debug) {
+fn log_output(
+ trace: &CommandTrace,
+ stdin: Option<&[u8]>,
+ output: Option<&std::process::Output>,
+ sensitive: bool,
+) {
+ // Either sink can be active without the other (for example, if opening
+ // subprocess.log failed). Avoid formatting bytes unless one consumes them.
+ if !tracing::enabled!(target: SUBPROCESS_FULL_TARGET, tracing::Level::DEBUG)
+ && !tracing::enabled!(target: SUBPROCESS_BOUNDED_TARGET, tracing::Level::DEBUG)
+ {
+ return;
+ }
+ if sensitive {
+ tracing::debug!(
+ target: SUBPROCESS_FULL_TARGET,
+ "{} [seq={} tid={}]\n [redacted]",
+ command_header(trace.cmd(), trace.context()),
+ trace.seq(),
+ trace.tid(),
+ );
+ tracing::debug!(target: SUBPROCESS_BOUNDED_TARGET, " [redacted]");
return;
}
let stdin = stdin.unwrap_or_default();
@@ -1270,6 +1282,8 @@ pub struct Cmd {
current_dir: Option<std::path::PathBuf>,
context: Option<String>,
stdin_data: Option<Vec<u8>>,
+ /// Redact captured stdin/stdout/stderr in both subprocess log targets.
+ sensitive_output: bool,
timeout: Option<std::time::Duration>,
/// Environment mutations in call order: `Some(value)` sets, `None`
/// removes. One ordered list rather than a set list plus a remove list, so
@@ -1340,14 +1354,14 @@ fn record_captured(
trace: &mut CommandTrace,
stdin: Option<&[u8]>,
result: &std::io::Result<std::process::Output>,
+ sensitive: bool,
) {
match result {
Ok(output) => trace.complete(output.status.success()),
Err(e) => trace.fail(e),
}
- // stdin is logged either way; stdout/stderr only when the command produced
- // output — a command that failed to spawn still leaves its input behind.
- log_output(trace, stdin, result.as_ref().ok());
+ // Redact every stream together, including input when spawning failed.
+ log_output(trace, stdin, result.as_ref().ok(), sensitive);
}
/// A child from [`Cmd::spawn_captured`], traced from spawn until
@@ -1355,6 +1369,7 @@ fn record_captured(
struct CapturedChild {
child: std::process::Child,
trace: CommandTrace,
+ sensitive_output: bool,
_tracked: Option<BackgroundPid>,
}
@@ -1363,10 +1378,11 @@ impl CapturedChild {
let CapturedChild {
child,
mut trace,
+ sensitive_output,
_tracked,
} = self;
let result = child.wait_with_output();
- record_captured(&mut trace, None, &result);
+ record_captured(&mut trace, None, &result, sensitive_output);
result
}
}
@@ -1595,6 +1611,7 @@ impl Cmd {
current_dir: None,
context: None,
stdin_data: None,
+ sensitive_output: false,
timeout: None,
env_ops: Vec::new(),
shell_wrap,
@@ -1776,6 +1793,16 @@ impl Cmd {
self
}
+ /// Redact captured stdin, stdout, and stderr from debug logs.
+ ///
+ /// Status and timing are still traced, and callers receive the original
+ /// output. In a pipeline, both commands' captured output is redacted.
+ /// Command arguments remain visible; streaming output is unaffected.
+ pub fn sensitive_output(mut self) -> Self {
+ self.sensitive_output = true;
+ self
+ }
+
/// Set a timeout for command execution (only applies to `.run()`).
///
/// Note: Timeout is not supported by `.stream()` since streaming commands
@@ -1994,7 +2021,12 @@ impl Cmd {
}
})();
- record_captured(&mut trace, self.stdin_data.as_deref(), &result);
+ record_captured(
+ &mut trace,
+ self.stdin_data.as_deref(),
+ &result,
+ self.sensitive_output,
+ );
let exit_code = result.as_ref().ok().and_then(|output| output.status.code());
external_log.record(exit_code);
@@ -2069,6 +2101,7 @@ impl Cmd {
Ok(CapturedChild {
child,
trace,
+ sensitive_output: self.sensitive_output,
_tracked: tracked,
})
}
@@ -2131,6 +2164,7 @@ impl Cmd {
let first_cmd_str = self.command_string();
let second_cmd_str = next.command_string();
+ let sensitive = self.sensitive_output || next.sensitive_output;
self.log_run_start(&first_cmd_str);
next.log_run_start(&second_cmd_str);
@@ -2235,7 +2269,7 @@ impl Cmd {
// source's stdout (the OS pipe), not its own input, so it is logged
// with `None` — the intermediate stream stays out of the deep log.
let second_result = second_child.wait_with_output();
- record_captured(&mut second_trace, None, &second_result);
+ record_captured(&mut second_trace, None, &second_result, sensitive);
// Reap `first`. Its stderr is already being drained; combine
// the captured stderr with the exit status into an Output.
@@ -2252,7 +2286,12 @@ impl Cmd {
// The source's own stdin (the commit list) is logged under ` < `,
// symmetric with `run`. Only the intermediate diff stream — the
// source's stdout, routed to the sink via OS pipe — stays out.
- record_captured(&mut first_trace, source_stdin.as_deref(), &first_result);
+ record_captured(
+ &mut first_trace,
+ source_stdin.as_deref(),
+ &first_result,
+ sensitive,
+ );
(first_result, second_result)
});
@@ -3192,6 +3231,92 @@ print(*counts)
// Cmd and timeout tests
// ========================================================================
+ /// Captured secrets reach callers, never either debug target. The plain
+ /// command is a positive control for the scoped subscriber's output capture.
+ #[test]
+ #[cfg(all(feature = "cli", unix))]
+ fn test_sensitive_captured_output() {
+ const SECRET: &str = "fake-captured-token-4b8ad2";
+ for mode in ["run", "timeout", "concurrent", "source", "sink"] {
+ let log = tempfile::NamedTempFile::new().unwrap();
+ let subscriber = tracing_subscriber::fmt()
+ .without_time()
+ .with_ansi(false)
+ .with_max_level(tracing::Level::DEBUG)
+ .with_writer(Arc::new(log.reopen().unwrap()))
+ .finish();
+ tracing::subscriber::with_default(subscriber, || {
+ let command = || {
+ Cmd::new("sh")
+ .args(["-c", "cat; printf '%s' \"$TOKEN\" >&2; exit 1"])
+ .env("TOKEN", SECRET)
+ };
+ // Log ordinary I/O first, then clear it before testing redaction.
+ command().stdin_bytes(SECRET).run().unwrap();
+ assert!(
+ std::fs::read_to_string(log.path())
+ .unwrap()
+ .contains(SECRET)
+ );
+ log.as_file().set_len(0).unwrap();
+
+ let output = match mode {
+ "run" => command().stdin_bytes(SECRET).sensitive_output().run(),
+ "timeout" => command()
+ .stdin_bytes(SECRET)
+ .sensitive_output()
+ .timeout(Duration::from_secs(10))
+ .run(),
+ "concurrent" => Cmd::run_concurrently(&[command().sensitive_output()])
+ .pop()
+ .unwrap(),
+ "source" => {
+ let (source, sink) = command()
+ .stdin_bytes(SECRET)
+ .sensitive_output()
+ .pipe_into(Cmd::new("cat"))
+ .unwrap();
+ assert_eq!(sink.stdout, SECRET.as_bytes());
+ Ok(source)
+ }
+ "sink" => {
+ let (source, sink) = Cmd::new("cat")
+ .stdin_bytes(SECRET)
+ .pipe_into(command().sensitive_output())
+ .unwrap();
+ assert!(source.status.success());
+ Ok(sink)
+ }
+ _ => unreachable!(),
+ }
+ .unwrap();
+ assert_eq!(output.status.code(), Some(1), "{mode}");
+ assert_eq!(output.stderr, SECRET.as_bytes(), "{mode}");
+ if matches!(mode, "run" | "timeout" | "sink") {
+ assert_eq!(output.stdout, SECRET.as_bytes(), "{mode}");
+ }
+ // Spawn failure still has input, which must also be redacted.
+ assert!(
+ Cmd::new("/no/such/sensitive-program")
+ .stdin_bytes(SECRET)
+ .sensitive_output()
+ .run()
+ .is_err()
+ );
+ });
+ let captured = std::fs::read_to_string(log.path()).unwrap();
+ assert!(!captured.contains(SECRET), "{mode}: {captured}");
+ for target in [SUBPROCESS_FULL_TARGET, SUBPROCESS_BOUNDED_TARGET] {
+ assert!(
+ captured.lines().any(|line| line.contains(target)),
+ "{mode}: missing {target}: {captured}"
+ );
+ }
+ assert!(captured.contains("[redacted]"), "{mode}: {captured}");
+ assert!(captured.contains("dur_us="), "{mode}: {captured}");
+ }
+ }
+
#[test]
fn test_cmd_completes_fast_command() {
let result = Cmd::new("echo")
diff --git a/src/utils.rs b/src/utils.rs
index 9d4e55061..da48fb209 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -171,6 +171,62 @@ pub fn write_new_atomically(path: &Path, content: &str) -> io::Result<()> {
write_atomically_with(path, content, false)
}
+/// Prepare a regenerable log or diagnostic path without opening the file.
+///
+/// `relative_path` names a file within `log_dir`. On Unix, new directories
+/// are owner-only; every directory from the file's parent through `log_dir`
+/// is restricted to 0700 and an existing regular file to 0600. Log-file
+/// symlinks and special files are left alone: repair must not change a file's
+/// symlink target or block on a FIFO even without a log write.
+pub fn prepare_log_file(log_dir: &Path, relative_path: &Path) -> io::Result<std::path::PathBuf> {
+ let path = log_dir.join(relative_path);
+ let parent = path
+ .parent()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Log file needs a directory"))?;
+ let mut directory = std::fs::DirBuilder::new();
+ directory.recursive(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
+ directory.mode(0o700);
+ directory.create(parent)?;
+ for ancestor in parent
+ .ancestors()
+ .take_while(|dir| dir.starts_with(log_dir))
+ {
+ std::fs::set_permissions(ancestor, std::fs::Permissions::from_mode(0o700))?;
+ }
+ if std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file()) {
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
+ }
+ }
+ #[cfg(not(unix))]
+ directory.create(parent)?;
+ Ok(path)
+}
+
+/// Open a log file after preparing its directory and existing permissions.
+/// Newly created files are owner-only on Unix.
+pub fn open_log_file(
+ log_dir: &Path,
+ relative_path: &Path,
+ append: bool,
+) -> io::Result<std::fs::File> {
+ let path = prepare_log_file(log_dir, relative_path)?;
+ let mut options = std::fs::OpenOptions::new();
+ options
+ .write(true)
+ .create(true)
+ .append(append)
+ .truncate(!append);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ options.open(&path)
+}
+
fn write_atomically_with(path: &Path, content: &str, overwrite: bool) -> io::Result<()> {
let target = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
// A bare filename's parent is `Some("")`, which no directory call accepts.
diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rs
index 125a72f47..f32c1d4f7 100644
--- a/tests/integration_tests/diagnostic.rs
+++ b/tests/integration_tests/diagnostic.rs
@@ -15,10 +15,241 @@
use std::fs;
use std::path::PathBuf;
+use ansi_str::AnsiStr;
use insta::assert_snapshot;
use rstest::rstest;
-use crate::common::{TestRepo, repo, setup_snapshot_settings};
+use crate::common::{
+ TestRepo,
+ mock_commands::{MockConfig, MockResponse, mock_calls},
+ repo, setup_snapshot_settings,
+};
+
+/// Authentication probes must preserve their result without exposing credentials
+/// through either subprocess log route or the diagnostic that embeds the trace.
+#[rstest]
+#[case::github("gh", "github.com", "auth token --hostname github.com", 0)]
+#[case::github_failed("gh", "github.com", "auth token --hostname github.com", 1)]
+#[case::gitlab("glab", "gitlab.com", "config get token --host gitlab.com", 0)]
+fn test_auth_probe_output_is_redacted(
+ mut repo: TestRepo,
+ #[case] tool: &str,
+ #[case] host: &str,
+ #[case] probe: &str,
+ #[case] probe_exit_code: i32,
+) {
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ &format!("https://{host}/test-owner/test-repo.git"),
+ ]);
+ repo.setup_mock_gh_with_ci_data("[]");
+
+ let stdout_token = "fake-credential-on-stdout";
+ let stderr_token = "fake-credential-on-stderr";
+ // Mock playback matches at most the first three arguments.
+ let probe_key = probe
+ .split_whitespace()
+ .take(3)
+ .collect::<Vec<_>>()
+ .join(" ");
+ MockConfig::new(tool)
+ .version(&format!("{tool} version 2.0.0 (mock)"))
+ .command(
+ &probe_key,
+ MockResponse::output(stdout_token)
+ .with_stderr(stderr_token)
+ .with_exit_code(probe_exit_code),
+ )
+ .command("_default", MockResponse::output("[]"))
+ .write(repo.mock_bin_path().unwrap());
+
+ let call_log = tempfile::tempdir().unwrap();
+ let output = repo
+ .wt_command()
+ .args(["config", "show", "--full", "-vv"])
+ .env("RUST_LOG", "debug")
+ .env("NO_COLOR", "1")
+ .env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path())
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert!(
+ mock_calls(call_log.path(), tool)
+ .iter()
+ .any(|call| call == probe)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout)
+ .ansi_strip()
+ .into_owned();
+ assert_eq!(
+ stdout.contains(&format!("{tool} installed & authenticated")),
+ probe_exit_code == 0,
+ "probe must retain its authentication result: {stdout}"
+ );
+
+ let logs_dir = repo.root_path().join(".git/wt/logs");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ for token in [stdout_token, stderr_token] {
+ assert!(!stderr.contains(token), "stderr exposed {token}");
+ }
+ for filename in [
+ "trace.log",
+ "trace.jsonl",
+ "subprocess.log",
+ "diagnostic.md",
+ ] {
+ let content = fs::read_to_string(logs_dir.join(filename)).unwrap();
+ for token in [stdout_token, stderr_token] {
+ assert!(!content.contains(token), "{filename} exposed {token}");
+ }
+ if filename == "trace.log" || filename == "subprocess.log" {
+ assert!(
+ content.contains("[redacted]"),
+ "{filename} must record redaction"
+ );
+ }
+ }
+ assert!(
+ stderr.contains("[redacted]"),
+ "RUST_LOG=debug must record redaction on stderr"
+ );
+}
+
+/// Debug artifacts are private on creation and when replacing older logs whose
+/// permissions were set before Worktrunk restricted its log files.
+#[cfg(unix)]
+#[rstest]
+#[case::new(None)]
+#[case::existing(Some(0o644))]
+#[case::readonly(Some(0o444))]
+fn test_debug_artifacts_have_private_permissions(repo: TestRepo, #[case] mode: Option<u32>) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let logs_dir = repo.root_path().join(".git/wt/logs");
+ let filenames = [
+ "trace.log",
+ "trace.jsonl",
+ "subprocess.log",
+ "diagnostic.md",
+ ];
+ let audit_files = ["commands.jsonl", "commands.jsonl.old"];
+ if let Some(mode) = mode {
+ fs::create_dir_all(&logs_dir).unwrap();
+ fs::set_permissions(&logs_dir, fs::Permissions::from_mode(0o755)).unwrap();
+ for filename in filenames {
+ let path = logs_dir.join(filename);
+ fs::write(&path, "old log").unwrap();
+ fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap();
+ }
+ for filename in audit_files {
+ let path = logs_dir.join(filename);
+ fs::write(&path, "old audit entry").unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
+ }
+ }
+
+ let output = repo.wt_command().args(["list", "-vv"]).output().unwrap();
+ assert!(output.status.success());
+ assert_eq!(
+ fs::metadata(&logs_dir).unwrap().permissions().mode() & 0o777,
+ 0o700
+ );
+ for filename in filenames {
+ let path = logs_dir.join(filename);
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600,
+ "{filename}"
+ );
+ }
+ for filename in audit_files {
+ let path = logs_dir.join(filename);
+ if mode.is_some() {
+ assert_eq!(fs::read_to_string(&path).unwrap(), "old audit entry");
+ assert_eq!(
+ fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ } else {
+ assert!(!path.exists());
+ }
+ }
+}
+
+/// Preparing audit permissions must not open a FIFO when no audit entry is written.
+#[cfg(unix)]
+#[rstest]
+fn test_audit_permission_repair_does_not_open_fifo(repo: TestRepo) {
+ use nix::sys::stat::Mode;
+ use nix::unistd::mkfifo;
+ use std::os::unix::fs::{FileTypeExt, PermissionsExt};
+
+ let logs_dir = repo.root_path().join(".git/wt/logs");
+ fs::create_dir_all(&logs_dir).unwrap();
+ fs::set_permissions(&logs_dir, fs::Permissions::from_mode(0o755)).unwrap();
+ for filename in ["commands.jsonl", "commands.jsonl.old"] {
+ mkfifo(&logs_dir.join(filename), Mode::S_IRUSR | Mode::S_IWUSR).unwrap();
+ }
+ let mut command = repo.wt_command();
+ command
+ .args(["list", "-vv"])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null());
+ let child = worktrunk::shell_exec::spawn_shared_child(&mut command).unwrap();
+ let result = worktrunk::shell_exec::wait_shared_child(
+ &child,
+ Some(std::time::Instant::now() + std::time::Duration::from_secs(30)),
+ );
+ if result.is_err() {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ }
+ let status = result.unwrap();
+ assert!(status.success());
+ assert_eq!(
+ fs::metadata(&logs_dir).unwrap().permissions().mode() & 0o777,
+ 0o700
+ );
+ for filename in ["commands.jsonl", "commands.jsonl.old"] {
+ assert!(
+ fs::metadata(logs_dir.join(filename))
+ .unwrap()
+ .file_type()
+ .is_fifo()
+ );
+ }
+}
+
+/// Inspect the log entry itself so permission repair cannot chmod its symlink target.
+#[cfg(unix)]
+#[rstest]
+fn test_audit_permission_repair_preserves_symlink_target(repo: TestRepo) {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+
+ let logs_dir = repo.root_path().join(".git/wt/logs");
+ fs::create_dir_all(&logs_dir).unwrap();
+ let target = repo.home_path().join("unrelated-file");
+ fs::write(&target, "preserved contents").unwrap();
+ fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
+ let rotated = logs_dir.join("commands.jsonl.old");
+ symlink(&target, &rotated).unwrap();
+
+ let output = repo.wt_command().args(["list", "-vv"]).output().unwrap();
+ assert!(output.status.success());
+ assert_eq!(fs::read_to_string(&target).unwrap(), "preserved contents");
+ assert_eq!(
+ fs::metadata(target).unwrap().permissions().mode() & 0o777,
+ 0o755
+ );
+ assert!(
+ fs::symlink_metadata(rotated)
+ .unwrap()
+ .file_type()
+ .is_symlink()
+ );
+}
/// Helper to corrupt a worktree's HEAD file to trigger git errors.
///
@@ -741,6 +972,23 @@ fn test_rust_log_overrides_verbose_flag(repo: TestRepo) {
env_stderr.contains("init_logging"),
"RUST_LOG=debug at -v should surface trace records on stderr: {env_stderr}"
);
+
+ // Lowering the filter must also suppress raw subprocess bodies at -vv.
+ let errors_only = repo
+ .wt_command()
+ .args(["list", "-vv"])
+ .env("RUST_LOG", "error")
+ .output()
+ .unwrap();
+ assert!(errors_only.status.success());
+ let logs_dir = repo.root_path().join(".git/wt/logs");
+ for filename in ["trace.log", "subprocess.log"] {
+ assert!(
+ fs::read_to_string(logs_dir.join(filename))
+ .unwrap()
+ .is_empty()
+ );
+ }
}
/// `RUST_LOG=debug` at `-v 0` activates Debug logging without creating the
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 32b19e63c..96dda8d17 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -961,6 +961,111 @@ approved-commands = ["echo 'stdout output' && echo 'stderr output' >&2"]
");
}
+/// Both the detached runner and its command logs restrict every directory in
+/// their branch subtree, including directories left by older versions.
+#[cfg(unix)]
+#[rstest]
+#[case::new(false)]
+#[case::existing(true)]
+fn test_post_start_logs_have_private_permissions(repo: TestRepo, #[case] existing: bool) {
+ use std::os::unix::fs::PermissionsExt;
+
+ repo.write_project_config(
+ r#"[post-start]
+capture = "echo captured-output"
+"#,
+ );
+ let log_dir = resolve_git_common_dir(repo.root_path()).join("wt/logs");
+ let hook_dir = log_dir.join("main/project/post-start");
+ let directories = [
+ log_dir.clone(),
+ log_dir.join("main"),
+ log_dir.join("main/project"),
+ hook_dir.clone(),
+ ];
+ let files = [hook_dir.join("runner.log"), hook_dir.join("capture.log")];
+ if existing {
+ fs::create_dir_all(&hook_dir).unwrap();
+ for directory in &directories {
+ fs::set_permissions(directory, fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ for file in &files {
+ fs::write(file, "old log").unwrap();
+ fs::set_permissions(file, fs::Permissions::from_mode(0o644)).unwrap();
+ }
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["hook", "post-start", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ // Old content must not satisfy the background completion condition.
+ crate::common::wait_for("captured background output", || {
+ fs::read_to_string(&files[1]).is_ok_and(|content| content == "captured-output\n")
+ });
+ for directory in &directories {
+ assert_eq!(
+ fs::metadata(directory).unwrap().permissions().mode() & 0o777,
+ 0o700,
+ "{}",
+ directory.display()
+ );
+ }
+ for file in &files {
+ assert_eq!(
+ fs::metadata(file).unwrap().permissions().mode() & 0o777,
+ 0o600,
+ "{}",
+ file.display()
+ );
+ }
+}
+
+/// A background command whose output log cannot open reports the path in its
+/// runner log and leaves the command unexecuted.
+#[rstest]
+fn test_post_start_reports_unavailable_command_log(repo: TestRepo) {
+ repo.write_project_config(
+ r#"[post-start]
+capture = "echo executed > should-not-exist.txt"
+"#,
+ );
+ let hook_dir = resolve_git_common_dir(repo.root_path())
+ .join("wt")
+ .join("logs")
+ .join("main")
+ .join("project")
+ .join("post-start");
+ let blocked_log = hook_dir.join("capture.log");
+ fs::create_dir_all(&blocked_log).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["hook", "post-start", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "background spawn should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let runner_log = hook_dir.join("runner.log");
+ crate::common::wait_for("background command log failure", || {
+ fs::read_to_string(&runner_log).is_ok_and(|content| {
+ content.contains("failed to create log file:")
+ && content.contains(&blocked_log.display().to_string())
+ })
+ });
+ assert!(blocked_log.is_dir());
+ assert!(!repo.root_path().join("should-not-exist.txt").exists());
+}
+
#[rstest]
fn test_post_start_invalid_command_handling(repo: TestRepo) {
// Create command with syntax error (missing quote)
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index a3377dbe9..0a2b4c734 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -2225,10 +2225,7 @@ fn test_removal_runs_post_remove_after_cleanup_spawn_failure(
repo.git_output(&["rev-parse", "main"])
);
} else {
- assert!(
- stderr.contains("Failed to create log directory"),
- "{stderr}"
- );
+ assert!(stderr.contains("Failed to create log file"), "{stderr}");
}
// The trash entry may already be gone: `wt remove`'s sweep starts a drain
// under the shared log, which the blocked branch log doesn't stop.