Repository navigation
fix: file security and output hygiene - #103
Merged
Merged
Conversation
- 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.
There was a problem hiding this comment.
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.
| use anyhow::{Result, anyhow}; | ||
| use ipnetwork::IpNetwork; | ||
| use parking_lot::RwLock; | ||
| use scopeguard; |
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 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 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))?; | ||
| } |
| @@ -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) | |||
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 on lines
+8
to
+13
| let target_orig = session | ||
| .target | ||
| .original | ||
| .chars() | ||
| .filter(|c| !c.is_control()) | ||
| .collect::<String>(); |
Comment on lines
+26
to
+27
| let safe_iface: String = iface.chars().filter(|c| !c.is_control()).collect(); | ||
| writeln!(writer, "Interface: {}", safe_iface)?; |
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 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 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 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(()) |
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(()) | ||
| } |
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); | ||
| }); |
| .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 on lines
+44
to
+46
| fs::rename(dest, &backup)?; | ||
| match fs::rename(temp, dest) { | ||
| Ok(()) => { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Improves file security, prevents path traversal, and hardens output hygiene.
Changes
sanitize_filenamereplaces path separators, control chars, and unsafe filename chars with_), preventing path traversal via crafted target names or replay files.\rfor RFC 4180 line-break compliance (was only checking,,",\n).scopeguardto reset therefreshingflag even if the refresh task panics, preventing permanent refresh lockout.Testing
cargo clippy --all-targets -- -D warningsclean.Risk
Low — file I/O and output formatting only, no networking or probe-sending changes.