Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33b027bce2 | ||
|
|
a81e43d98e |
No files matched your search
@@ -16,8 +16,6 @@ pub struct Config {
|
||||
pub telemetry: TelemetryConfig,
|
||||
#[serde(default)]
|
||||
pub hooks: HooksConfig,
|
||||
#[serde(default)]
|
||||
pub limits: LimitsConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
@@ -96,39 +94,6 @@ impl Default for TelemetryConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct LimitsConfig {
|
||||
/// Max total grep results to show (default: 200)
|
||||
pub grep_max_results: usize,
|
||||
/// Max matches per file in grep output (default: 25)
|
||||
pub grep_max_per_file: usize,
|
||||
/// Max staged/modified files shown in git status (default: 15)
|
||||
pub status_max_files: usize,
|
||||
/// Max untracked files shown in git status (default: 10)
|
||||
pub status_max_untracked: usize,
|
||||
/// Max chars for parser passthrough fallback (default: 2000)
|
||||
pub passthrough_max_chars: usize,
|
||||
}
|
||||
|
||||
impl Default for LimitsConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
grep_max_results: 200,
|
||||
grep_max_per_file: 25,
|
||||
status_max_files: 15,
|
||||
status_max_untracked: 10,
|
||||
passthrough_max_chars: 2000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get limits config. Falls back to defaults if config can't be loaded.
|
||||
pub fn limits() -> LimitsConfig {
|
||||
Config::load()
|
||||
.map(|c| c.limits)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
|
||||
pub fn telemetry_enabled() -> Option<bool> {
|
||||
Config::load().ok().map(|c| c.telemetry.enabled)
|
||||
|
||||
+10
-64
@@ -42,13 +42,6 @@ fn docker_ps(_verbose: u8) -> Result<()> {
|
||||
.output()
|
||||
.context("Failed to run docker ps")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprint!("{}", stderr);
|
||||
timer.track("docker ps", "rtk docker ps", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let mut rtk = String::new();
|
||||
|
||||
@@ -102,13 +95,6 @@ fn docker_images(_verbose: u8) -> Result<()> {
|
||||
.output()
|
||||
.context("Failed to run docker images")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprint!("{}", stderr);
|
||||
timer.track("docker images", "rtk docker images", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let lines: Vec<&str> = stdout.lines().collect();
|
||||
let mut rtk = String::new();
|
||||
@@ -183,19 +169,6 @@ fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("docker logs {}", container),
|
||||
"rtk docker logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("🐳 Logs for {}:\n{}", container, analyzed);
|
||||
println!("{}", rtk);
|
||||
@@ -221,15 +194,6 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
@@ -240,12 +204,15 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
let items = json["items"].as_array();
|
||||
if items.is_none() || items.unwrap().is_empty() {
|
||||
rtk.push_str("☸️ No pods found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
return Ok(());
|
||||
};
|
||||
}
|
||||
|
||||
let pods = items.unwrap();
|
||||
let (mut running, mut pending, mut failed, mut restarts_total) = (0, 0, 0, 0i64);
|
||||
let mut issues: Vec<String> = Vec::new();
|
||||
|
||||
@@ -328,15 +295,6 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
@@ -347,12 +305,15 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
let items = json["items"].as_array();
|
||||
if items.is_none() || items.unwrap().is_empty() {
|
||||
rtk.push_str("☸️ No services found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
return Ok(());
|
||||
};
|
||||
}
|
||||
|
||||
let services = items.unwrap();
|
||||
rtk.push_str(&format!("☸️ {} services:\n", services.len()));
|
||||
|
||||
for svc in services.iter().take(15) {
|
||||
@@ -412,21 +373,6 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
|
||||
let output = cmd.output().context("Failed to run kubectl logs")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("kubectl logs {}", pod),
|
||||
"rtk kubectl logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("☸️ Logs for {}:\n{}", pod, analyzed);
|
||||
println!("{}", rtk);
|
||||
|
||||
+28
-111
@@ -1,4 +1,3 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
@@ -112,21 +111,6 @@ fn run_diff(
|
||||
let output = cmd.output().context("Failed to run git diff")?;
|
||||
let stat_stdout = String::from_utf8_lossy(&output.stdout);
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
let raw = stat_stdout.to_string();
|
||||
timer.track(
|
||||
&format!("git diff {}", args.join(" ")),
|
||||
&format!("rtk git diff {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("Git diff summary:");
|
||||
}
|
||||
@@ -608,46 +592,33 @@ fn format_status_output(porcelain: &str) -> String {
|
||||
}
|
||||
|
||||
// Build summary
|
||||
let limits = config::limits();
|
||||
let max_files = limits.status_max_files;
|
||||
let max_untracked = limits.status_max_untracked;
|
||||
|
||||
if staged > 0 {
|
||||
output.push_str(&format!("✅ Staged: {} files\n", staged));
|
||||
for f in staged_files.iter().take(max_files) {
|
||||
for f in staged_files.iter().take(5) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if staged_files.len() > max_files {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
staged_files.len() - max_files
|
||||
));
|
||||
if staged_files.len() > 5 {
|
||||
output.push_str(&format!(" ... +{} more\n", staged_files.len() - 5));
|
||||
}
|
||||
}
|
||||
|
||||
if modified > 0 {
|
||||
output.push_str(&format!("📝 Modified: {} files\n", modified));
|
||||
for f in modified_files.iter().take(max_files) {
|
||||
for f in modified_files.iter().take(5) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if modified_files.len() > max_files {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
modified_files.len() - max_files
|
||||
));
|
||||
if modified_files.len() > 5 {
|
||||
output.push_str(&format!(" ... +{} more\n", modified_files.len() - 5));
|
||||
}
|
||||
}
|
||||
|
||||
if untracked > 0 {
|
||||
output.push_str(&format!("❓ Untracked: {} files\n", untracked));
|
||||
for f in untracked_files.iter().take(max_untracked) {
|
||||
for f in untracked_files.iter().take(3) {
|
||||
output.push_str(&format!(" {}\n", f));
|
||||
}
|
||||
if untracked_files.len() > max_untracked {
|
||||
output.push_str(&format!(
|
||||
" ... +{} more\n",
|
||||
untracked_files.len() - max_untracked
|
||||
));
|
||||
if untracked_files.len() > 3 {
|
||||
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - 3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -709,20 +680,6 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
let raw = stdout.to_string();
|
||||
timer.track(
|
||||
&format!("git status {}", args.join(" ")),
|
||||
&format!("rtk git status {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
if verbose > 0 || !stderr.is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
@@ -902,14 +859,13 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
"ok (nothing to commit)",
|
||||
);
|
||||
} else {
|
||||
eprintln!("FAILED: git commit");
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
eprintln!("{}", stderr);
|
||||
}
|
||||
if !stdout.trim().is_empty() {
|
||||
eprint!("{}", stdout);
|
||||
eprintln!("{}", stdout);
|
||||
}
|
||||
timer.track(&original_cmd, "rtk git commit", &raw_output, &raw_output);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1147,20 +1103,6 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let raw = stdout.to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("git branch {}", args.join(" ")),
|
||||
&format!("rtk git branch {}", args.join(" ")),
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let filtered = filter_branch_output(&stdout);
|
||||
println!("{}", filtered);
|
||||
|
||||
@@ -1748,48 +1690,23 @@ A added.rs
|
||||
|
||||
#[test]
|
||||
fn test_format_status_output_truncation() {
|
||||
// Test that >15 staged files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=20 {
|
||||
porcelain.push_str(&format!("M file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("✅ Staged: 20 files"));
|
||||
// Test that >5 staged files show "... +N more"
|
||||
let porcelain = r#"## main
|
||||
M file1.rs
|
||||
M file2.rs
|
||||
M file3.rs
|
||||
M file4.rs
|
||||
M file5.rs
|
||||
M file6.rs
|
||||
M file7.rs
|
||||
"#;
|
||||
let result = format_status_output(porcelain);
|
||||
assert!(result.contains("✅ Staged: 7 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file15.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file16.rs"));
|
||||
assert!(!result.contains("file20.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_status_modified_truncation() {
|
||||
// Test that >15 modified files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=20 {
|
||||
porcelain.push_str(&format!(" M file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("📝 Modified: 20 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file15.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file16.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_status_untracked_truncation() {
|
||||
// Test that >10 untracked files show "... +N more"
|
||||
let mut porcelain = String::from("## main\n");
|
||||
for i in 1..=15 {
|
||||
porcelain.push_str(&format!("?? file{}.rs\n", i));
|
||||
}
|
||||
let result = format_status_output(&porcelain);
|
||||
assert!(result.contains("❓ Untracked: 15 files"));
|
||||
assert!(result.contains("file1.rs"));
|
||||
assert!(result.contains("file10.rs"));
|
||||
assert!(result.contains("... +5 more"));
|
||||
assert!(!result.contains("file11.rs"));
|
||||
assert!(result.contains("file5.rs"));
|
||||
assert!(result.contains("... +2 more"));
|
||||
assert!(!result.contains("file6.rs"));
|
||||
assert!(!result.contains("file7.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+4
-17
@@ -1,4 +1,3 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::{resolved_command, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
@@ -79,21 +78,9 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
&filtered,
|
||||
);
|
||||
|
||||
// golangci-lint: exit 0 = clean, exit 1 = lint issues, exit 2+ = config/build error
|
||||
// None = killed by signal (OOM, SIGKILL) — always fatal
|
||||
match output.status.code() {
|
||||
Some(0) | Some(1) => Ok(()),
|
||||
Some(code) => {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr.trim());
|
||||
}
|
||||
std::process::exit(code);
|
||||
}
|
||||
None => {
|
||||
eprintln!("golangci-lint: killed by signal");
|
||||
std::process::exit(130);
|
||||
}
|
||||
}
|
||||
// golangci-lint returns exit code 1 when issues found (expected behavior)
|
||||
// Don't exit with error code in that case
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Filter golangci-lint JSON output - group by linter and file
|
||||
@@ -107,7 +94,7 @@ fn filter_golangci_json(output: &str) -> String {
|
||||
return format!(
|
||||
"golangci-lint (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
truncate(output, 500)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
+15
-22
@@ -1,4 +1,3 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
@@ -78,13 +77,6 @@ pub fn run(
|
||||
let mut by_file: HashMap<String, Vec<(usize, String)>> = HashMap::new();
|
||||
let mut total = 0;
|
||||
|
||||
// Compile context regex once (instead of per-line in clean_line)
|
||||
let context_re = if context_only {
|
||||
Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
for line in stdout.lines() {
|
||||
let parts: Vec<&str> = line.splitn(3, ':').collect();
|
||||
|
||||
@@ -99,7 +91,7 @@ pub fn run(
|
||||
};
|
||||
|
||||
total += 1;
|
||||
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), pattern);
|
||||
let cleaned = clean_line(content, max_line_len, context_only, pattern);
|
||||
by_file.entry(file).or_default().push((line_num, cleaned));
|
||||
}
|
||||
|
||||
@@ -118,8 +110,7 @@ pub fn run(
|
||||
let file_display = compact_path(file);
|
||||
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
|
||||
|
||||
let per_file = config::limits().grep_max_per_file;
|
||||
for (line_num, content) in matches.iter().take(per_file) {
|
||||
for (line_num, content) in matches.iter().take(10) {
|
||||
rtk_output.push_str(&format!(" {:>4}: {}\n", line_num, content));
|
||||
shown += 1;
|
||||
if shown >= max_results {
|
||||
@@ -127,8 +118,8 @@ pub fn run(
|
||||
}
|
||||
}
|
||||
|
||||
if matches.len() > per_file {
|
||||
rtk_output.push_str(&format!(" +{}\n", matches.len() - per_file));
|
||||
if matches.len() > 10 {
|
||||
rtk_output.push_str(&format!(" +{}\n", matches.len() - 10));
|
||||
}
|
||||
rtk_output.push('\n');
|
||||
}
|
||||
@@ -152,14 +143,16 @@ pub fn run(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_line(line: &str, max_len: usize, context_re: Option<&Regex>, pattern: &str) -> String {
|
||||
fn clean_line(line: &str, max_len: usize, context_only: bool, pattern: &str) -> String {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if let Some(re) = context_re {
|
||||
if let Some(m) = re.find(trimmed) {
|
||||
let matched = m.as_str();
|
||||
if matched.len() <= max_len {
|
||||
return matched.to_string();
|
||||
if context_only {
|
||||
if let Ok(re) = Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))) {
|
||||
if let Some(m) = re.find(trimmed) {
|
||||
let matched = m.as_str();
|
||||
if matched.len() <= max_len {
|
||||
return matched.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -223,7 +216,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_clean_line() {
|
||||
let line = " const result = someFunction();";
|
||||
let cleaned = clean_line(line, 50, None, "result");
|
||||
let cleaned = clean_line(line, 50, false, "result");
|
||||
assert!(!cleaned.starts_with(' '));
|
||||
assert!(cleaned.len() <= 50);
|
||||
}
|
||||
@@ -247,7 +240,7 @@ mod tests {
|
||||
fn test_clean_line_multibyte() {
|
||||
// Thai text that exceeds max_len in bytes
|
||||
let line = " สวัสดีครับ นี่คือข้อความที่ยาวมากสำหรับทดสอบ ";
|
||||
let cleaned = clean_line(line, 20, None, "ครับ");
|
||||
let cleaned = clean_line(line, 20, false, "ครับ");
|
||||
// Should not panic
|
||||
assert!(!cleaned.is_empty());
|
||||
}
|
||||
@@ -255,7 +248,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_clean_line_emoji() {
|
||||
let line = "🎉🎊🎈🎁🎂🎄 some text 🎃🎆🎇✨";
|
||||
let cleaned = clean_line(line, 15, None, "text");
|
||||
let cleaned = clean_line(line, 15, false, "text");
|
||||
assert!(!cleaned.is_empty());
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -1,4 +1,3 @@
|
||||
use crate::config;
|
||||
use crate::mypy_cmd;
|
||||
use crate::ruff_cmd;
|
||||
use crate::tracking;
|
||||
@@ -235,7 +234,7 @@ fn filter_eslint_json(output: &str) -> String {
|
||||
return format!(
|
||||
"ESLint output (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
truncate(output, 500)
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -327,7 +326,7 @@ fn filter_pylint_json(output: &str) -> String {
|
||||
return format!(
|
||||
"Pylint output (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
truncate(output, 500)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
+12
-16
@@ -1,23 +1,11 @@
|
||||
use crate::tracking;
|
||||
use anyhow::Result;
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::{self, BufRead};
|
||||
use std::path::Path;
|
||||
|
||||
lazy_static! {
|
||||
static ref TIMESTAMP_RE: Regex =
|
||||
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
|
||||
static ref UUID_RE: Regex =
|
||||
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
.unwrap();
|
||||
static ref HEX_RE: Regex = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
|
||||
static ref NUM_RE: Regex = Regex::new(r"\b\d{4,}\b").unwrap();
|
||||
static ref PATH_RE: Regex = Regex::new(r"/[\w./\-]+").unwrap();
|
||||
}
|
||||
|
||||
/// Filter and deduplicate log output
|
||||
pub fn run_file(file: &Path, verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
@@ -70,14 +58,22 @@ fn analyze_logs(content: &str) -> String {
|
||||
let mut unique_errors: Vec<String> = Vec::new();
|
||||
let mut unique_warnings: Vec<String> = Vec::new();
|
||||
|
||||
// Use module-level lazy_static regexes for normalization
|
||||
// Patterns to normalize log messages
|
||||
let timestamp_re =
|
||||
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
|
||||
let uuid_re =
|
||||
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
.unwrap();
|
||||
let hex_re = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
|
||||
let num_re = Regex::new(r"\b\d{4,}\b").unwrap();
|
||||
let path_re = Regex::new(r"/[\w./\-]+").unwrap();
|
||||
|
||||
for line in content.lines() {
|
||||
let line_lower = line.to_lowercase();
|
||||
|
||||
// Normalize for deduplication
|
||||
let normalized =
|
||||
normalize_log_line(line, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE);
|
||||
normalize_log_line(line, ×tamp_re, &uuid_re, &hex_re, &num_re, &path_re);
|
||||
|
||||
// Categorize
|
||||
if line_lower.contains("error")
|
||||
@@ -132,7 +128,7 @@ fn analyze_logs(content: &str) -> String {
|
||||
let original = unique_errors
|
||||
.iter()
|
||||
.find(|e| {
|
||||
&normalize_log_line(e, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
|
||||
&normalize_log_line(e, ×tamp_re, &uuid_re, &hex_re, &num_re, &path_re)
|
||||
== *normalized
|
||||
})
|
||||
.map(|s| s.as_str())
|
||||
@@ -172,7 +168,7 @@ fn analyze_logs(content: &str) -> String {
|
||||
let original = unique_warnings
|
||||
.iter()
|
||||
.find(|w| {
|
||||
&normalize_log_line(w, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
|
||||
&normalize_log_line(w, ×tamp_re, &uuid_re, &hex_re, &num_re, &path_re)
|
||||
== *normalized
|
||||
})
|
||||
.map(|s| s.as_str())
|
||||
|
||||
+3
-26
@@ -56,7 +56,6 @@ mod telemetry;
|
||||
mod toml_filter;
|
||||
mod tracking;
|
||||
mod tree;
|
||||
mod trust;
|
||||
mod tsc_cmd;
|
||||
mod utils;
|
||||
mod verify_cmd;
|
||||
@@ -306,7 +305,7 @@ enum Commands {
|
||||
#[arg(short = 'l', long, default_value = "80")]
|
||||
max_len: usize,
|
||||
/// Max results to show
|
||||
#[arg(short, long, default_value = "200")]
|
||||
#[arg(short, long, default_value = "50")]
|
||||
max: usize,
|
||||
/// Show only match context (not full line)
|
||||
#[arg(short, long)]
|
||||
@@ -574,16 +573,6 @@ enum Commands {
|
||||
args: Vec<OsString>,
|
||||
},
|
||||
|
||||
/// Trust project-local TOML filters in current directory
|
||||
Trust {
|
||||
/// List all trusted projects
|
||||
#[arg(long)]
|
||||
list: bool,
|
||||
},
|
||||
|
||||
/// Revoke trust for project-local TOML filters
|
||||
Untrust,
|
||||
|
||||
/// Verify hook integrity and run TOML filter inline tests
|
||||
Verify {
|
||||
/// Run tests only for this filter name
|
||||
@@ -1017,10 +1006,6 @@ const RTK_META_COMMANDS: &[&str] = &[
|
||||
"hook-audit",
|
||||
"cc-economics",
|
||||
"verify",
|
||||
"trust",
|
||||
"untrust",
|
||||
"session",
|
||||
"rewrite",
|
||||
];
|
||||
|
||||
fn run_fallback(parse_error: clap::Error) -> Result<()> {
|
||||
@@ -2103,14 +2088,6 @@ fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
Commands::Trust { list } => {
|
||||
trust::run_trust(list)?;
|
||||
}
|
||||
|
||||
Commands::Untrust => {
|
||||
trust::run_untrust()?;
|
||||
}
|
||||
|
||||
Commands::Verify {
|
||||
filter,
|
||||
require_all,
|
||||
@@ -2394,8 +2371,8 @@ mod tests {
|
||||
// RTK meta-commands should produce parse errors (not fall through to raw execution).
|
||||
// Skip "proxy" because it uses trailing_var_arg (accepts any args by design).
|
||||
for cmd in RTK_META_COMMANDS {
|
||||
if matches!(*cmd, "proxy" | "rewrite" | "session") {
|
||||
continue; // these use trailing_var_arg (accept any args by design)
|
||||
if *cmd == "proxy" {
|
||||
continue;
|
||||
}
|
||||
let result = Cli::try_parse_from(["rtk", cmd, "--nonexistent-flag-xyz"]);
|
||||
assert!(
|
||||
|
||||
+1
-4
@@ -43,10 +43,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
&filtered,
|
||||
);
|
||||
|
||||
if !output.status.success() {
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
Ok(())
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
struct MypyError {
|
||||
|
||||
@@ -70,7 +70,7 @@ impl OutputParser for VitestParser {
|
||||
)
|
||||
} else {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_output(input, 2000))
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-7
@@ -89,18 +89,12 @@ pub trait OutputParser: Sized {
|
||||
let result = Self::parse(input);
|
||||
if result.tier() > max_tier {
|
||||
// Force degradation to passthrough if exceeds max tier
|
||||
return ParseResult::Passthrough(truncate_passthrough(input));
|
||||
return ParseResult::Passthrough(truncate_output(input, 500));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Truncate output using configured passthrough limit
|
||||
pub fn truncate_passthrough(output: &str) -> String {
|
||||
let max_chars = crate::config::limits().passthrough_max_chars;
|
||||
truncate_output(output, max_chars)
|
||||
}
|
||||
|
||||
/// Truncate output to max length with ellipsis
|
||||
pub fn truncate_output(output: &str, max_chars: usize) -> String {
|
||||
let chars: Vec<char> = output.chars().collect();
|
||||
|
||||
@@ -5,7 +5,7 @@ use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, FormatMode, OutputParser,
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_output, FormatMode, OutputParser,
|
||||
ParseResult, TestFailure, TestResult, TokenFormatter,
|
||||
};
|
||||
|
||||
@@ -110,7 +110,7 @@ impl OutputParser for PlaywrightParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-7
@@ -6,7 +6,7 @@ use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, Dependency,
|
||||
emit_degradation_warning, emit_passthrough_warning, truncate_output, Dependency,
|
||||
DependencyState, FormatMode, OutputParser, ParseResult, TokenFormatter,
|
||||
};
|
||||
|
||||
@@ -75,7 +75,7 @@ impl OutputParser for PnpmListParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,7 @@ impl OutputParser for PnpmOutdatedParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,8 +307,7 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprint!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
anyhow::bail!("pnpm list failed: {}", stderr);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
@@ -432,8 +431,7 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
eprint!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
anyhow::bail!("pnpm install failed: {}", stderr);
|
||||
}
|
||||
|
||||
let combined = format!("{}{}", stdout, stderr);
|
||||
|
||||
+20
-38
@@ -54,24 +54,18 @@ fn run_generate(args: &[String], verbose: u8) -> Result<()> {
|
||||
.output()
|
||||
.context("Failed to run prisma generate (try: npm install -g prisma)")?;
|
||||
|
||||
let exit_code = output.status.code().unwrap_or(1);
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("prisma generate failed: {}", stderr);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stdout.trim().is_empty() {
|
||||
eprint!("{}", stdout);
|
||||
}
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("prisma generate", "rtk prisma generate", &raw, &raw);
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
let filtered = filter_prisma_generate(&raw);
|
||||
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track("prisma generate", "rtk prisma generate", &raw, &filtered);
|
||||
|
||||
Ok(())
|
||||
@@ -111,22 +105,15 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
|
||||
|
||||
let output = cmd.output().context("Failed to run prisma migrate")?;
|
||||
|
||||
let exit_code = output.status.code().unwrap_or(1);
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("prisma migrate failed: {}", stderr);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stdout.trim().is_empty() {
|
||||
eprint!("{}", stdout);
|
||||
}
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &raw);
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
let filtered = match subcommand {
|
||||
MigrateSubcommand::Dev { .. } => filter_migrate_dev(&raw),
|
||||
MigrateSubcommand::Status => filter_migrate_status(&raw),
|
||||
@@ -134,6 +121,7 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
|
||||
};
|
||||
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &filtered);
|
||||
|
||||
Ok(())
|
||||
@@ -155,24 +143,18 @@ fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
|
||||
|
||||
let output = cmd.output().context("Failed to run prisma db push")?;
|
||||
|
||||
let exit_code = output.status.code().unwrap_or(1);
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
anyhow::bail!("prisma db push failed: {}", stderr);
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stdout.trim().is_empty() {
|
||||
eprint!("{}", stdout);
|
||||
}
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("prisma db push", "rtk prisma db push", &raw, &raw);
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
let filtered = filter_db_push(&raw);
|
||||
|
||||
println!("{}", filtered);
|
||||
|
||||
timer.track("prisma db push", "rtk prisma db push", &raw, &filtered);
|
||||
|
||||
Ok(())
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
use crate::config;
|
||||
use crate::tracking;
|
||||
use crate::utils::{resolved_command, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
@@ -122,7 +121,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
|
||||
return format!(
|
||||
"Ruff check (JSON parse failed: {})\n{}",
|
||||
e,
|
||||
truncate(output, config::limits().passthrough_max_chars)
|
||||
truncate(output, 500)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
+13
-44
@@ -181,29 +181,11 @@ impl TomlFilterRegistry {
|
||||
fn load() -> Self {
|
||||
let mut filters = Vec::new();
|
||||
|
||||
// Priority 1: project-local .rtk/filters.toml (trust-gated)
|
||||
let project_filter_path = std::path::Path::new(".rtk/filters.toml");
|
||||
if project_filter_path.exists() {
|
||||
let trust_status = crate::trust::check_trust(project_filter_path)
|
||||
.unwrap_or(crate::trust::TrustStatus::Untrusted);
|
||||
|
||||
match trust_status {
|
||||
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
|
||||
if let Ok(content) = std::fs::read_to_string(project_filter_path) {
|
||||
match Self::parse_and_compile(&content, "project") {
|
||||
Ok(f) => filters.extend(f),
|
||||
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::trust::TrustStatus::Untrusted => {
|
||||
eprintln!("[rtk] WARNING: untrusted project filters (.rtk/filters.toml)");
|
||||
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to review and enable.");
|
||||
}
|
||||
crate::trust::TrustStatus::ContentChanged { .. } => {
|
||||
eprintln!("[rtk] WARNING: .rtk/filters.toml changed since trusted.");
|
||||
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to re-review.");
|
||||
}
|
||||
// Priority 1: project-local .rtk/filters.toml
|
||||
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
|
||||
match Self::parse_and_compile(&content, "project") {
|
||||
Ok(f) => filters.extend(f),
|
||||
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,27 +529,14 @@ pub fn run_filter_tests(filter_name_opt: Option<&str>) -> VerifyResults {
|
||||
&mut tested_filter_names,
|
||||
);
|
||||
|
||||
// Trust-gated: only verify project-local filters if trusted (SA-2025-RTK-002)
|
||||
let project_path = std::path::Path::new(".rtk/filters.toml");
|
||||
if project_path.exists() {
|
||||
let trust_status =
|
||||
crate::trust::check_trust(project_path).unwrap_or(crate::trust::TrustStatus::Untrusted);
|
||||
match trust_status {
|
||||
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
|
||||
if let Ok(content) = std::fs::read_to_string(project_path) {
|
||||
collect_test_outcomes(
|
||||
&content,
|
||||
filter_name_opt,
|
||||
&mut outcomes,
|
||||
&mut all_filter_names,
|
||||
&mut tested_filter_names,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("[rtk] WARNING: untrusted project filters skipped in verify");
|
||||
}
|
||||
}
|
||||
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
|
||||
collect_test_outcomes(
|
||||
&content,
|
||||
filter_name_opt,
|
||||
&mut outcomes,
|
||||
&mut all_filter_names,
|
||||
&mut tested_filter_names,
|
||||
);
|
||||
}
|
||||
|
||||
let filters_without_tests = all_filter_names
|
||||
|
||||
@@ -251,12 +251,6 @@ impl Tracker {
|
||||
}
|
||||
|
||||
let conn = Connection::open(&db_path)?;
|
||||
// WAL mode + busy_timeout for concurrent access (multiple Claude Code instances).
|
||||
// Non-fatal: NFS/read-only filesystems may not support WAL.
|
||||
let _ = conn.execute_batch(
|
||||
"PRAGMA journal_mode=WAL;
|
||||
PRAGMA busy_timeout=5000;",
|
||||
);
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS commands (
|
||||
id INTEGER PRIMARY KEY,
|
||||
|
||||
-510
@@ -1,510 +0,0 @@
|
||||
//! Trust boundary for project-local TOML filters (SA-2025-RTK-002).
|
||||
//!
|
||||
//! `.rtk/filters.toml` is loaded from CWD with highest priority. An attacker
|
||||
//! can commit this file to a public repo to control what an LLM sees — hiding
|
||||
//! malicious code, suppressing security scanner output, or rewriting command
|
||||
//! output entirely via `replace` and `match_output` primitives.
|
||||
//!
|
||||
//! This module implements a trust-before-load model:
|
||||
//! - Untrusted filters are **skipped** (not "loaded with warning")
|
||||
//! - `rtk trust` stores the SHA-256 hash after user review
|
||||
//! - Content changes invalidate trust (re-review required)
|
||||
//! - `RTK_TRUST_PROJECT_FILTERS=1` overrides for CI pipelines
|
||||
|
||||
use crate::integrity;
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
struct TrustStore {
|
||||
version: u32,
|
||||
trusted: HashMap<String, TrustEntry>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub struct TrustEntry {
|
||||
pub sha256: String,
|
||||
pub trusted_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum TrustStatus {
|
||||
Trusted,
|
||||
Untrusted,
|
||||
ContentChanged { expected: String, actual: String },
|
||||
EnvOverride,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Store path
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn store_path() -> Result<PathBuf> {
|
||||
let data_dir = dirs::data_local_dir().context("Cannot determine local data directory")?;
|
||||
Ok(data_dir.join("rtk").join("trusted_filters.json"))
|
||||
}
|
||||
|
||||
fn read_store() -> Result<TrustStore> {
|
||||
let path = store_path()?;
|
||||
if !path.exists() {
|
||||
return Ok(TrustStore::default());
|
||||
}
|
||||
let content = std::fs::read_to_string(&path)
|
||||
.with_context(|| format!("Failed to read trust store: {}", path.display()))?;
|
||||
serde_json::from_str(&content)
|
||||
.with_context(|| format!("Failed to parse trust store: {}", path.display()))
|
||||
}
|
||||
|
||||
fn write_store(store: &TrustStore) -> Result<()> {
|
||||
let path = store_path()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("Failed to create directory: {}", parent.display()))?;
|
||||
}
|
||||
let content = serde_json::to_string_pretty(store).context("Failed to serialize trust store")?;
|
||||
std::fs::write(&path, content)
|
||||
.with_context(|| format!("Failed to write trust store: {}", path.display()))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Canonical path helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn canonical_key(filter_path: &Path) -> Result<String> {
|
||||
// Resolve symlinks and produce an absolute path. No fallback — if we can't
|
||||
// canonicalize, we can't safely key the trust entry (fail-closed).
|
||||
let canonical = std::fs::canonicalize(filter_path)
|
||||
.with_context(|| format!("Cannot resolve path: {}", filter_path.display()))?;
|
||||
Ok(canonical.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Check if a project-local filter file is trusted.
|
||||
///
|
||||
/// Priority: env var > hash match > untrusted.
|
||||
/// All errors are soft — if anything fails, returns Untrusted (fail-secure).
|
||||
pub fn check_trust(filter_path: &Path) -> Result<TrustStatus> {
|
||||
// Fast path: env var override for CI pipelines only.
|
||||
// Requires a known CI env var to be set to prevent .envrc injection attacks.
|
||||
if std::env::var("RTK_TRUST_PROJECT_FILTERS").as_deref() == Ok("1") {
|
||||
let in_ci = std::env::var("CI").is_ok()
|
||||
|| std::env::var("GITHUB_ACTIONS").is_ok()
|
||||
|| std::env::var("GITLAB_CI").is_ok()
|
||||
|| std::env::var("JENKINS_URL").is_ok()
|
||||
|| std::env::var("BUILDKITE").is_ok();
|
||||
if in_ci {
|
||||
return Ok(TrustStatus::EnvOverride);
|
||||
}
|
||||
eprintln!(
|
||||
"[rtk] WARNING: RTK_TRUST_PROJECT_FILTERS=1 ignored (CI environment not detected)"
|
||||
);
|
||||
}
|
||||
|
||||
let key = canonical_key(filter_path)?;
|
||||
let store = match read_store() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[rtk] WARNING: trust store unreadable ({}), treating all filters as untrusted",
|
||||
e
|
||||
);
|
||||
TrustStore::default()
|
||||
}
|
||||
};
|
||||
|
||||
let entry = match store.trusted.get(&key) {
|
||||
Some(e) => e,
|
||||
None => return Ok(TrustStatus::Untrusted),
|
||||
};
|
||||
|
||||
let actual_hash = integrity::compute_hash(filter_path)
|
||||
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
|
||||
|
||||
if actual_hash == entry.sha256 {
|
||||
Ok(TrustStatus::Trusted)
|
||||
} else {
|
||||
Ok(TrustStatus::ContentChanged {
|
||||
expected: entry.sha256.clone(),
|
||||
actual: actual_hash,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Store current SHA-256 hash as trusted (computes hash from file).
|
||||
pub fn trust_filter(filter_path: &Path) -> Result<()> {
|
||||
let hash = integrity::compute_hash(filter_path)
|
||||
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
|
||||
trust_filter_with_hash(filter_path, &hash)
|
||||
}
|
||||
|
||||
/// Store a pre-computed SHA-256 hash as trusted (avoids TOCTOU re-read).
|
||||
pub fn trust_filter_with_hash(filter_path: &Path, hash: &str) -> Result<()> {
|
||||
let key = canonical_key(filter_path)?;
|
||||
|
||||
let mut store = read_store().unwrap_or_default();
|
||||
store.version = 1;
|
||||
store.trusted.insert(
|
||||
key,
|
||||
TrustEntry {
|
||||
sha256: hash.to_string(),
|
||||
trusted_at: chrono::Utc::now().to_rfc3339(),
|
||||
},
|
||||
);
|
||||
write_store(&store)
|
||||
}
|
||||
|
||||
/// Remove trust entry for a filter path.
|
||||
pub fn untrust_filter(filter_path: &Path) -> Result<bool> {
|
||||
let key = canonical_key(filter_path)?;
|
||||
let mut store = read_store().unwrap_or_default();
|
||||
let removed = store.trusted.remove(&key).is_some();
|
||||
if removed {
|
||||
write_store(&store)?;
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// List all trusted projects.
|
||||
pub fn list_trusted() -> Result<HashMap<String, TrustEntry>> {
|
||||
let store = read_store().unwrap_or_default();
|
||||
Ok(store.trusted)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CLI commands
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Run `rtk trust` — review and trust project-local filters.
|
||||
pub fn run_trust(list: bool) -> Result<()> {
|
||||
if list {
|
||||
let trusted = list_trusted()?;
|
||||
if trusted.is_empty() {
|
||||
println!("No trusted project filters.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("Trusted project filters:");
|
||||
println!("{}", "═".repeat(60));
|
||||
for (path, entry) in &trusted {
|
||||
let date = entry.trusted_at.get(..10).unwrap_or(&entry.trusted_at);
|
||||
println!(" {} (trusted {})", path, date);
|
||||
println!(" sha256:{}", entry.sha256);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let filter_path = Path::new(".rtk/filters.toml");
|
||||
if !filter_path.exists() {
|
||||
anyhow::bail!("No .rtk/filters.toml found in current directory");
|
||||
}
|
||||
|
||||
// Read ONCE to prevent TOCTOU: display + hash from same buffer
|
||||
let content_bytes = std::fs::read(filter_path).context("Failed to read .rtk/filters.toml")?;
|
||||
let content = String::from_utf8_lossy(&content_bytes);
|
||||
|
||||
println!("=== .rtk/filters.toml ===");
|
||||
println!("{}", content);
|
||||
println!("=========================");
|
||||
println!();
|
||||
|
||||
// Risk summary
|
||||
print_risk_summary(&content);
|
||||
|
||||
// Hash the in-memory buffer (not a second file read)
|
||||
let hash = {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut h = Sha256::new();
|
||||
h.update(&content_bytes);
|
||||
format!("{:x}", h.finalize())
|
||||
};
|
||||
|
||||
// Store trust with pre-computed hash
|
||||
trust_filter_with_hash(filter_path, &hash)?;
|
||||
println!();
|
||||
println!(
|
||||
"Trusted .rtk/filters.toml (sha256:{})",
|
||||
hash.get(..16).unwrap_or(&hash)
|
||||
);
|
||||
println!("Project-local filters will now be applied.");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run `rtk untrust` — revoke trust for project-local filters.
|
||||
pub fn run_untrust() -> Result<()> {
|
||||
let filter_path = Path::new(".rtk/filters.toml");
|
||||
// If file doesn't exist, untrust by canonical path lookup won't work.
|
||||
// Try anyway (file may have been deleted after trust), fallback gracefully.
|
||||
let removed = untrust_filter(filter_path).unwrap_or(false);
|
||||
if removed {
|
||||
println!("Trust revoked for .rtk/filters.toml");
|
||||
println!("Project-local filters will no longer be applied.");
|
||||
} else {
|
||||
println!("No trust entry found for current directory.");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Risk analysis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn print_risk_summary(content: &str) {
|
||||
let filter_count = content.matches("[filters.").count();
|
||||
let has_replace = content.contains("replace");
|
||||
let has_match_output = content.contains("match_output");
|
||||
let has_dot_pattern = content.contains("pattern = \".\"") || content.contains("pattern = '.'");
|
||||
|
||||
println!("Risk summary:");
|
||||
println!(" Filters: {}", filter_count);
|
||||
|
||||
if has_replace {
|
||||
println!(" ⚠ Contains 'replace' rules (can rewrite output)");
|
||||
}
|
||||
if has_match_output {
|
||||
println!(" ⚠ Contains 'match_output' rules (can replace entire output)");
|
||||
}
|
||||
if has_dot_pattern {
|
||||
println!(" ⚠ Contains catch-all pattern '.' (matches everything)");
|
||||
}
|
||||
if !has_replace && !has_match_output && !has_dot_pattern {
|
||||
println!(" No high-risk patterns detected.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// Helper: create a temporary trust store in a temp dir.
|
||||
/// Overrides the store path via a scoped env var (not possible with
|
||||
/// the real function), so we test the logic by calling internal fns.
|
||||
fn setup_test_env(temp: &TempDir) -> PathBuf {
|
||||
let store_file = temp.path().join("trusted_filters.json");
|
||||
store_file
|
||||
}
|
||||
|
||||
fn check_trust_with_store(filter_path: &Path, store_file: &Path) -> Result<TrustStatus> {
|
||||
// Note: env var check is NOT included here to avoid test interference.
|
||||
// The env var path is tested separately in test_env_override.
|
||||
let key = canonical_key(filter_path)?;
|
||||
|
||||
let store: TrustStore = if store_file.exists() {
|
||||
let content = std::fs::read_to_string(store_file)?;
|
||||
serde_json::from_str(&content)?
|
||||
} else {
|
||||
TrustStore::default()
|
||||
};
|
||||
|
||||
let entry = match store.trusted.get(&key) {
|
||||
Some(e) => e,
|
||||
None => return Ok(TrustStatus::Untrusted),
|
||||
};
|
||||
|
||||
let actual_hash = integrity::compute_hash(filter_path)?;
|
||||
|
||||
if actual_hash == entry.sha256 {
|
||||
Ok(TrustStatus::Trusted)
|
||||
} else {
|
||||
Ok(TrustStatus::ContentChanged {
|
||||
expected: entry.sha256.clone(),
|
||||
actual: actual_hash,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn trust_with_store(filter_path: &Path, store_file: &Path) -> Result<()> {
|
||||
let key = canonical_key(filter_path)?;
|
||||
let hash = integrity::compute_hash(filter_path)?;
|
||||
|
||||
let mut store: TrustStore = if store_file.exists() {
|
||||
let content = std::fs::read_to_string(store_file)?;
|
||||
serde_json::from_str(&content)?
|
||||
} else {
|
||||
TrustStore::default()
|
||||
};
|
||||
|
||||
store.version = 1;
|
||||
store.trusted.insert(
|
||||
key,
|
||||
TrustEntry {
|
||||
sha256: hash,
|
||||
trusted_at: chrono::Utc::now().to_rfc3339(),
|
||||
},
|
||||
);
|
||||
|
||||
if let Some(parent) = store_file.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let content = serde_json::to_string_pretty(&store)?;
|
||||
std::fs::write(store_file, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn untrust_with_store(filter_path: &Path, store_file: &Path) -> Result<bool> {
|
||||
let key = canonical_key(filter_path)?;
|
||||
|
||||
let mut store: TrustStore = if store_file.exists() {
|
||||
let content = std::fs::read_to_string(store_file)?;
|
||||
serde_json::from_str(&content)?
|
||||
} else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
let removed = store.trusted.remove(&key).is_some();
|
||||
if removed {
|
||||
let content = serde_json::to_string_pretty(&store)?;
|
||||
std::fs::write(store_file, content)?;
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untrusted_by_default() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = setup_test_env(&temp);
|
||||
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
assert_eq!(status, TrustStatus::Untrusted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_trust_then_check() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = setup_test_env(&temp);
|
||||
|
||||
trust_with_store(&filter, &store_file).unwrap();
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
assert_eq!(status, TrustStatus::Trusted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_change_detected() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = setup_test_env(&temp);
|
||||
|
||||
trust_with_store(&filter, &store_file).unwrap();
|
||||
|
||||
// Modify the filter file
|
||||
std::fs::write(
|
||||
&filter,
|
||||
"[filters.evil]\nmatch_command = \".*\"\nmatch_output = \"password\"",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
match status {
|
||||
TrustStatus::ContentChanged { expected, actual } => {
|
||||
assert_ne!(expected, actual);
|
||||
assert_eq!(expected.len(), 64);
|
||||
assert_eq!(actual.len(), 64);
|
||||
}
|
||||
other => panic!("Expected ContentChanged, got {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_untrust_revokes() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = setup_test_env(&temp);
|
||||
|
||||
trust_with_store(&filter, &store_file).unwrap();
|
||||
let removed = untrust_with_store(&filter, &store_file).unwrap();
|
||||
assert!(removed);
|
||||
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
assert_eq!(status, TrustStatus::Untrusted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_env_override_with_ci() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
|
||||
// Both env vars must be set: trust override + CI indicator
|
||||
#[allow(deprecated)]
|
||||
std::env::set_var("RTK_TRUST_PROJECT_FILTERS", "1");
|
||||
#[allow(deprecated)]
|
||||
std::env::set_var("CI", "true");
|
||||
let status = check_trust(&filter).unwrap();
|
||||
#[allow(deprecated)]
|
||||
std::env::remove_var("RTK_TRUST_PROJECT_FILTERS");
|
||||
#[allow(deprecated)]
|
||||
std::env::remove_var("CI");
|
||||
|
||||
assert_eq!(status, TrustStatus::EnvOverride);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_env_override_without_ci_is_ignored() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = setup_test_env(&temp);
|
||||
|
||||
// Trust override WITHOUT CI env → should be Untrusted, not EnvOverride
|
||||
// (protects against .envrc injection)
|
||||
// Note: we use check_trust_with_store which skips env var check,
|
||||
// so this tests the store path when env var would be ignored
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
assert_eq!(status, TrustStatus::Untrusted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_store_is_untrusted() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
|
||||
let store_file = temp.path().join("nonexistent").join("store.json");
|
||||
|
||||
let status = check_trust_with_store(&filter, &store_file).unwrap();
|
||||
assert_eq!(status, TrustStatus::Untrusted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_risk_summary_detects_replace() {
|
||||
let content = "[filters.evil]\nmatch_command = \"git\"\nreplace = [[\"secret\", \"\"]]";
|
||||
// Just verify it doesn't panic — output goes to stdout
|
||||
print_risk_summary(content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_risk_summary_detects_match_output() {
|
||||
let content = "[filters.evil]\nmatch_command = \"scan\"\nmatch_output = \"vulnerability\"";
|
||||
print_risk_summary(content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_canonical_key_works() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let filter = temp.path().join("filters.toml");
|
||||
std::fs::write(&filter, "test").unwrap();
|
||||
|
||||
let key = canonical_key(&filter).unwrap();
|
||||
assert!(key.contains("filters.toml"));
|
||||
// Should be an absolute path
|
||||
assert!(key.starts_with('/') || key.contains(':'));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -3,7 +3,7 @@ use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::parser::{
|
||||
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_passthrough,
|
||||
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_output,
|
||||
FormatMode, OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
|
||||
};
|
||||
use crate::tracking;
|
||||
@@ -88,7 +88,7 @@ impl OutputParser for VitestParser {
|
||||
}
|
||||
None => {
|
||||
// Tier 3: Passthrough
|
||||
ParseResult::Passthrough(truncate_passthrough(input))
|
||||
ParseResult::Passthrough(truncate_output(input, 500))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-20
@@ -41,16 +41,10 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
println!("{}", msg);
|
||||
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
|
||||
} else {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("wget {}", url),
|
||||
"rtk wget",
|
||||
&raw_output,
|
||||
&raw_output,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
let error = parse_error(&stderr, &stdout);
|
||||
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
|
||||
println!("{}", msg);
|
||||
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -109,16 +103,10 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
|
||||
);
|
||||
} else {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("wget -O - {}", url),
|
||||
"rtk wget -o",
|
||||
&stderr,
|
||||
&stderr,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
let error = parse_error(&stderr, "");
|
||||
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
|
||||
println!("{}", msg);
|
||||
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
Reference in new issue
Block a user