Skip to content

fix: file security and output hygiene - #103

Merged
lance0 merged 7 commits into
masterfrom
fix/file-security-hygiene
Jul 1, 2026
Merged

lance0 merged 7 commits into
masterfrom
fix/file-security-hygiene

Conversation

@lance0

@lance0 lance0 commented Jul 1, 2026

Copy link
Copy Markdown
Owner

Summary

Improves file security, prevents path traversal, and hardens output hygiene.

Changes

Testing

  • All 493 tests pass; cargo clippy --all-targets -- -D warnings clean.

Risk

Low — file I/O and output formatting only, no networking or probe-sending changes.

lance0 added 2 commits July 1, 2026 15:20
- Set prefs file to 0600 on Unix to protect PeeringDB API key (#14)
- Surface corrupt prefs parse errors as warnings instead of silent reset (#14)
- Sanitize target name in JSON export filename to prevent path traversal (#15)
- Quote CSV fields containing \r for RFC 4180 compliance (#24)
- Write PeeringDB cache atomically (temp file + rename) to prevent corruption (#25)
- Use scopeguard to reset refreshing flag even if refresh task panics (#26)
- Sanitize control characters in report target/interface output (#28)

All 493 tests pass; clippy clean.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens ttl’s on-disk and user-facing output handling by tightening file permissions, making cache writes more robust, and sanitizing/escaping exported or displayed strings to reduce path traversal and terminal/CSV injection risks.

Changes:

  • Harden preferences persistence: warn on corrupt prefs parse and restrict prefs file permissions (Unix).
  • Improve PeeringDB IX cache robustness: atomic-ish cache writes and refresh-flag reset safety via RAII.
  • Improve export/output hygiene: sanitize JSON export filenames, quote CSV fields containing \r, and strip control chars from report output.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/prefs.rs Logs parse warnings on corrupt prefs and attempts to enforce restrictive file permissions on save.
src/lookup/ix.rs Writes IX cache via temp file + rename and uses a scopeguard to ensure refresh state resets even on panic; adds a refresh gate test.
src/export/report.rs Strips control characters from target/interface strings before printing the text report.
src/export/json.rs Sanitizes the target component used in auto-generated JSON export filenames to reduce path traversal risk.
src/export/csv.rs Updates CSV escaping to also quote fields containing \r for RFC 4180 compliance.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/lookup/ix.rs Outdated
use anyhow::{Result, anyhow};
use ipnetwork::IpNetwork;
use parking_lot::RwLock;
use scopeguard;
Comment thread src/lookup/ix.rs Outdated
Comment on lines 408 to 415
let parent = self
.cache_path
.parent()
.ok_or_else(|| anyhow!("cache path has no parent directory"))?;
let temp = parent.join(".peeringdb_cache.tmp");
fs::write(&temp, &data)?;
fs::rename(&temp, &self.cache_path)?;
Ok(())
Comment thread src/prefs.rs Outdated
Comment on lines +60 to +61
/// Load preferences from disk. Logs a warning on corrupt files instead of
/// silently resetting — the caller decides whether to surface it.
Comment thread src/prefs.rs
Comment on lines +88 to +96
let data = toml::to_string_pretty(self)?;
fs::write(&path, data)?;

// Restrict file permissions to owner-only (protect API keys)
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
}
Comment thread src/export/csv.rs Outdated
@@ -91,7 +91,7 @@ pub fn export_csv<W: Write>(session: &Session, mut writer: W) -> Result<()> {

/// Escape a string for CSV (quote if contains comma, quote, or newline)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Comment thread src/lookup/ix.rs Outdated
Comment on lines +416 to +420
match fs::remove_file(&self.cache_path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
Comment thread src/export/report.rs Outdated
Comment on lines +8 to +13
let target_orig = session
.target
.original
.chars()
.filter(|c| !c.is_control())
.collect::<String>();
Comment thread src/export/report.rs Outdated
Comment on lines +26 to +27
let safe_iface: String = iface.chars().filter(|c| !c.is_control()).collect();
writeln!(writer, "Interface: {}", safe_iface)?;

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Comment thread src/prefs.rs
Comment on lines +64 to +77
Some(path) => match fs::read_to_string(&path) {
Ok(s) => match toml::from_str(&s) {
Ok(prefs) => prefs,
Err(e) => {
eprintln!(
"Warning: could not parse preferences at {}: {}",
path.display(),
e
);
Self::default()
}
},
Err(_) => Self::default(),
},
Comment thread src/prefs.rs
Comment on lines +95 to +105
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(&path)?;
file.write_all(data.as_bytes())?;

// Enforce owner-only permissions for existing files too.
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
}
Comment thread src/export/json.rs
Comment on lines +33 to +45
fn sanitize_filename(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii_control()
|| matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')
{
'_'
} else {
c
}
})
.collect()
}
Comment thread src/lookup/ix.rs Outdated
Comment on lines +29 to +33
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// Windows rename does not replace existing destinations.
fs::remove_file(dest)?;
fs::rename(temp, dest)?;
Ok(())

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Comment thread src/lookup/ix.rs
Comment on lines +29 to +34
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// Windows rename does not replace existing destinations.
fs::remove_file(dest)?;
fs::rename(temp, dest)?;
Ok(())
}

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Comment thread src/lookup/ix.rs
Comment on lines +658 to +661
// RAII guard ensures refreshing is reset even if the task panics
let _guard = scopeguard::guard((), |_| {
this.refreshing.store(false, Ordering::SeqCst);
});
Comment thread src/lookup/ix.rs Outdated
.cache_path
.parent()
.ok_or_else(|| anyhow!("cache path has no parent directory"))?;
let temp = parent.join(format!(".peeringdb_cache.{}.tmp", std::process::id()));
Comment thread src/lookup/ix.rs
Comment on lines +44 to +46
fs::rename(dest, &backup)?;
match fs::rename(temp, dest) {
Ok(()) => {
@lance0
lance0 merged commit d7dc62c into master Jul 1, 2026
5 checks passed
@lance0
lance0 deleted the fix/file-security-hygiene branch July 1, 2026 20:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants