Windows: safety layer, rule engine fixes, and 30 built-in cleanup rules
- paths: platform-semantic comparisons. Component keys are lower-cased
and canonical \\?\\ verbatim prefixes folded away on Windows, so
is_within/same_path/depth_below/relative_below match how the OS
actually resolves paths; pretty() got the same treatment.
- safety: drive roots and UNC roots are hard-denied (is_root_like);
Windows hard-deny grows env-derived entries (SystemRoot, ProgramFiles,
ProgramData, USERPROFILE, ...); DENY_EXACT gains the AppData tree and
shell folders; OUTSIDE_HOME_OK becomes platform-supplied
(%ProgramData%, %PUBLIC% mirror /Applications); a path containing
$Recycle.Bin / System Volume Information / Recovery is always refused;
the canonicalize-vs-expected symlink probe now compares with
platform semantics instead of raw equality.
- rules: $VAR heads stop at backslashes too; ${VAR} resolves in every
occurrence; glob component matching is case-insensitive on Windows;
protect patterns normalise \\ to / so protections keep working there;
anchor_for keeps drive prefixes instead of bailing out, and folds
Prefix+RootDir into a rooted C:\ anchor.
- rules/windows.toml: 30 rules for Win10/11 (temp, WER/crash dumps,
browser caches, shell caches, dev caches, Windows.old, Package Cache)
embedded under cfg(windows) and parse-checked on every host.
main
parent
122e81cb4d
commit
5619b1467d
|
|
@ -1,8 +1,9 @@
|
|||
//! Path expansion helpers shared by the rule engine and the UI.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// Expand a leading `~` / `$HOME` and a few well known macOS anchors.
|
||||
/// Expand a leading `~` / `$HOME` (also `~\` on Windows) and stop there.
|
||||
///
|
||||
/// Rules are authored with `~` because the crate ships a data file, not
|
||||
/// hard-coded absolute paths, and the same rule file must work for the
|
||||
|
|
@ -17,14 +18,16 @@ pub fn expand_with(input: &str, home: &Path) -> PathBuf {
|
|||
if input == "~" || input == "$HOME" {
|
||||
return home.to_path_buf();
|
||||
}
|
||||
if let Some(rest) = input.strip_prefix("~/") {
|
||||
return home.join(rest);
|
||||
for prefix in ["~/", "~\\"] {
|
||||
if let Some(rest) = input.strip_prefix(prefix) {
|
||||
return home.join(rest.trim_start_matches(['/', '\\']));
|
||||
}
|
||||
}
|
||||
if let Some(rest) = input.strip_prefix("$HOME/") {
|
||||
return home.join(rest);
|
||||
}
|
||||
if let Some(rest) = input.strip_prefix("$HOME") {
|
||||
return home.join(rest.trim_start_matches('/'));
|
||||
return home.join(rest.trim_start_matches(['/', '\\']));
|
||||
}
|
||||
PathBuf::from(input)
|
||||
}
|
||||
|
|
@ -36,25 +39,121 @@ pub fn home_dir() -> PathBuf {
|
|||
/// Best-effort `/Volumes/...`-aware display shortening for the UI.
|
||||
pub fn pretty(path: &Path) -> String {
|
||||
let home = home_dir();
|
||||
match path.strip_prefix(&home) {
|
||||
Ok(rel) if rel.as_os_str().is_empty() => "~".to_string(),
|
||||
Ok(rel) => format!("~/{}", rel.display()),
|
||||
Err(_) => path.display().to_string(),
|
||||
if same_path(&home, path) {
|
||||
return "~".to_string();
|
||||
}
|
||||
match relative_below(&home, path) {
|
||||
Some(rel) => format!("~/{}", rel.display()),
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip the `\\?\` / `\??\` verbatim prefix `canonicalize` prepends on
|
||||
/// Windows so canonical paths can be compared with hand-built ones.
|
||||
#[cfg(windows)]
|
||||
fn strip_verbatim(path: &Path) -> PathBuf {
|
||||
let text = path.to_string_lossy();
|
||||
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
|
||||
return PathBuf::from(format!(r"\\{rest}"));
|
||||
}
|
||||
if text.starts_with(r"\\?\") || text.starts_with(r"\??\") {
|
||||
return PathBuf::from(text[4..].to_string());
|
||||
}
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn strip_verbatim(path: &Path) -> PathBuf {
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
/// Comparable spelling plus original text for every component of a path.
|
||||
///
|
||||
/// Windows path lookup is case-insensitive and `canonicalize` hands back
|
||||
/// verbatim `\\?\C:\…` paths whose drive letter casing can differ from a
|
||||
/// hand-built path, so all containment/equality decisions funnel through
|
||||
/// these lower-cased keys (with the drive root's `RootDir` folded into the
|
||||
/// `C:` prefix). On Unix the key is the literal component.
|
||||
fn parts(path: &Path) -> Vec<(String, OsString)> {
|
||||
normalized(&strip_verbatim(path))
|
||||
.components()
|
||||
.filter_map(|c| match c {
|
||||
Component::RootDir => {
|
||||
if cfg!(windows) {
|
||||
None
|
||||
} else {
|
||||
Some(("/".to_string(), OsString::from("/")))
|
||||
}
|
||||
}
|
||||
other => {
|
||||
let text = other.as_os_str().to_string_lossy().into_owned();
|
||||
Some((text.to_lowercase(), other.as_os_str().to_os_string()))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn keys_match(prefix: &[(String, OsString)], path: &[(String, OsString)]) -> bool {
|
||||
path.len() >= prefix.len()
|
||||
&& prefix
|
||||
.iter()
|
||||
.zip(path)
|
||||
.all(|(a, b)| a.0.eq_ignore_ascii_case(&b.0))
|
||||
}
|
||||
|
||||
/// True when `child` is strictly inside `parent`.
|
||||
///
|
||||
/// Comparison follows platform semantics: case-insensitive on Windows.
|
||||
pub fn is_within(parent: &Path, child: &Path) -> bool {
|
||||
child != parent && child.starts_with(parent)
|
||||
let (p, c) = (parts(parent), parts(child));
|
||||
c.len() > p.len() && keys_match(&p, &c)
|
||||
}
|
||||
|
||||
/// Path equality under platform semantics: case-insensitive on Windows,
|
||||
/// verbatim spellings folded, `C:\` equal to `C:`.
|
||||
pub fn same_path(a: &Path, b: &Path) -> bool {
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.len() == b.len() && keys_match(&a, &b)
|
||||
}
|
||||
|
||||
/// Filesystem roots: `/`, a drive root like `C:\`, or a UNC share root.
|
||||
pub fn is_root_like(path: &Path) -> bool {
|
||||
let p = parts(path);
|
||||
match p.len() {
|
||||
0 => true,
|
||||
1 => {
|
||||
let key = p[0].0.as_str();
|
||||
key == "/" || (cfg!(windows) && (key.ends_with(':') || key.starts_with(r"\\")))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `~/Library/Caches/com.foo.bar` under anchor `~/Library/Caches` has depth 1.
|
||||
pub fn depth_below(anchor: &Path, path: &Path) -> Option<usize> {
|
||||
path.strip_prefix(anchor).ok().map(|rel| {
|
||||
rel.components()
|
||||
.filter(|c| matches!(c, Component::Normal(_)))
|
||||
.count()
|
||||
})
|
||||
let (a, c) = (parts(anchor), parts(path));
|
||||
if keys_match(&a, &c) {
|
||||
Some(c.len() - a.len())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The remainder of `path` strictly below `anchor`, preserving the path's
|
||||
/// own casing; `None` when the path is the anchor or outside it.
|
||||
pub fn relative_below(anchor: &Path, path: &Path) -> Option<PathBuf> {
|
||||
let (a, c) = (parts(anchor), parts(path));
|
||||
if c.len() <= a.len() || !keys_match(&a, &c) {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
c[a.len()..]
|
||||
.iter()
|
||||
.fold(PathBuf::new(), |mut acc, (_, raw)| {
|
||||
acc.push(raw);
|
||||
acc
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Component-wise comparison that is stable for display and de-duplication.
|
||||
|
|
@ -108,4 +207,43 @@ mod tests {
|
|||
assert_eq!(depth_below(anchor, Path::new("/a/b/c/d")), Some(2));
|
||||
assert_eq!(depth_below(anchor, Path::new("/x/y")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_are_detected() {
|
||||
assert!(is_root_like(Path::new("/")));
|
||||
assert!(is_root_like(Path::new("")));
|
||||
assert!(!is_root_like(Path::new("/a")));
|
||||
assert!(same_path(Path::new("/a/b"), Path::new("/a/b")));
|
||||
assert!(!same_path(Path::new("/a/b"), Path::new("/a/b/c")));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_paths_compare_like_the_filesystem() {
|
||||
assert!(same_path(
|
||||
Path::new(r"C:\Users\Tester\AppData"),
|
||||
Path::new(r"c:\users\tester\appdata")
|
||||
));
|
||||
// `canonicalize` hands back verbatim spellings with real casing.
|
||||
assert!(same_path(
|
||||
Path::new(r"\\?\C:\Users\Tester"),
|
||||
Path::new(r"c:\users\tester")
|
||||
));
|
||||
// Drive root in both spellings is the volume root.
|
||||
assert!(is_root_like(Path::new(r"C:\")));
|
||||
assert!(is_root_like(Path::new(r"C:")));
|
||||
assert!(is_root_like(Path::new(r"\\nas\share")));
|
||||
assert!(!is_root_like(Path::new(r"C:\Users")));
|
||||
assert!(is_within(
|
||||
Path::new(r"C:\Users\Tester\AppData\Local"),
|
||||
Path::new(r"C:\users\tester\appdata\local\Temp\x")
|
||||
));
|
||||
assert_eq!(
|
||||
relative_below(
|
||||
Path::new(r"C:\Users\Tester\AppData\Local"),
|
||||
Path::new(r"C:\users\tester\appdata\local\Temp\x")
|
||||
),
|
||||
Some(PathBuf::from(r"Temp\x"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,35 @@ const DENY_EXACT: &[&str] = &[
|
|||
"~/.bash_history",
|
||||
];
|
||||
|
||||
/// Windows additions to the exact-deny list. The AppData tree is the
|
||||
/// Windows equivalent of `~/Library`: deleting the folder itself is how
|
||||
/// you destroy a profile, deleting one cache inside it is the job.
|
||||
#[cfg(windows)]
|
||||
const WINDOWS_DENY_EXACT: &[&str] = &[
|
||||
"~/AppData",
|
||||
"~/AppData/Local",
|
||||
"~/AppData/LocalLow",
|
||||
"~/AppData/Roaming",
|
||||
"~/AppData/Local/Packages",
|
||||
"~/OneDrive",
|
||||
"~/Links",
|
||||
"~/Favorites",
|
||||
"~/Contacts",
|
||||
"~/Saved Games",
|
||||
"~/Searches",
|
||||
];
|
||||
|
||||
/// System folders that exist per drive and must never be touched, no
|
||||
/// matter which drive the rule was anchored on.
|
||||
#[cfg(windows)]
|
||||
const WINDOWS_RESERVED_NAMES: &[&str] = &[
|
||||
"$Recycle.Bin",
|
||||
"$Extend",
|
||||
"System Volume Information",
|
||||
"Recovery",
|
||||
"PerfLogs",
|
||||
];
|
||||
|
||||
/// Folders outside the current user's home that a normal (non-root) user is
|
||||
/// still allowed to remove *entries from*.
|
||||
///
|
||||
|
|
@ -90,7 +119,57 @@ const DENY_EXACT: &[&str] = &[
|
|||
/// shared application folder is carved out here. Only its *contents* are
|
||||
/// reachable — `/Applications` itself is on the hard-deny list — and a bundle
|
||||
/// owned by root is still locked much earlier by `writable_by_us`.
|
||||
const OUTSIDE_HOME_OK: &[&str] = &["/Applications"];
|
||||
#[cfg(not(windows))]
|
||||
fn outside_home_ok() -> Vec<PathBuf> {
|
||||
["/Applications"].iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
/// Windows equivalent of `/Applications`: the machine-wide program data
|
||||
/// folders whose *contents* an ordinary user may delete from (they own
|
||||
/// the ACL), while the roots themselves are on the hard-deny list.
|
||||
#[cfg(windows)]
|
||||
fn outside_home_ok() -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = ["ProgramData", "PUBLIC"]
|
||||
.iter()
|
||||
.filter_map(std::env::var_os)
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
out.push(PathBuf::from(r"C:\ProgramData"));
|
||||
out.push(PathBuf::from(r"C:\Users\Public"));
|
||||
out
|
||||
}
|
||||
|
||||
/// System folders derived from the environment so the deny list follows
|
||||
/// non-default installs (Windows on D:, relocated Program Files, …).
|
||||
#[cfg(windows)]
|
||||
fn windows_hard_deny() -> Vec<PathBuf> {
|
||||
let mut out: Vec<PathBuf> = [
|
||||
"SystemRoot",
|
||||
"windir",
|
||||
"ProgramFiles",
|
||||
"ProgramFiles(x86)",
|
||||
"ProgramData",
|
||||
"PUBLIC",
|
||||
"USERPROFILE",
|
||||
]
|
||||
.iter()
|
||||
.filter_map(std::env::var_os)
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
out.extend(
|
||||
[
|
||||
r"C:\Windows",
|
||||
r"C:\Program Files",
|
||||
r"C:\Program Files (x86)",
|
||||
r"C:\Users",
|
||||
r"C:\ProgramData",
|
||||
r"C:\Users\Public",
|
||||
]
|
||||
.iter()
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SafetyPolicy {
|
||||
|
|
@ -104,17 +183,31 @@ pub struct SafetyPolicy {
|
|||
pub allow_system_paths: bool,
|
||||
/// Never descend into a symlink (default, and the right answer).
|
||||
pub follow_symlinks: bool,
|
||||
/// Roots whose contents a non-admin run may still reach — on Unix
|
||||
/// `/Applications`, on Windows `%ProgramData%` and `%PUBLIC%`.
|
||||
pub outside_home_ok: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for SafetyPolicy {
|
||||
fn default() -> Self {
|
||||
// mut is only exercised on Windows; keep both targets warning-free.
|
||||
#[cfg_attr(not(windows), allow(unused_mut))]
|
||||
let mut deny_exact: Vec<PathBuf> = DENY_EXACT.iter().map(|p| paths::expand(p)).collect();
|
||||
#[cfg_attr(not(windows), allow(unused_mut))]
|
||||
let mut hard_deny: Vec<PathBuf> = HARD_DENY.iter().map(PathBuf::from).collect();
|
||||
#[cfg(windows)]
|
||||
{
|
||||
deny_exact.extend(WINDOWS_DENY_EXACT.iter().map(|p| paths::expand(p)));
|
||||
hard_deny.extend(windows_hard_deny());
|
||||
}
|
||||
Self {
|
||||
deny_exact: DENY_EXACT.iter().map(|p| paths::expand(p)).collect(),
|
||||
hard_deny: HARD_DENY.iter().map(PathBuf::from).collect(),
|
||||
deny_exact,
|
||||
hard_deny,
|
||||
min_depth: 1,
|
||||
forbidden_mounts: Vec::new(),
|
||||
allow_system_paths: true,
|
||||
follow_symlinks: false,
|
||||
outside_home_ok: outside_home_ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -142,32 +235,43 @@ impl SafetyPolicy {
|
|||
}
|
||||
|
||||
fn is_exact_denied(&self, path: &Path) -> bool {
|
||||
let norm = paths::normalized(path);
|
||||
self.deny_exact.iter().any(|deny| {
|
||||
let d = paths::normalized(deny);
|
||||
// Trailing glob star entries deny the directory itself only.
|
||||
let d = d
|
||||
let d = deny
|
||||
.to_string_lossy()
|
||||
.trim_end_matches('*')
|
||||
.trim_end_matches('/')
|
||||
.trim_end_matches(['/', '\\'])
|
||||
.to_string();
|
||||
norm == Path::new(&d)
|
||||
paths::same_path(path, Path::new(&d))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_hard_denied(&self, path: &Path) -> bool {
|
||||
let norm = paths::normalized(path);
|
||||
if norm.as_os_str().is_empty() {
|
||||
if paths::is_root_like(path) {
|
||||
return true;
|
||||
}
|
||||
self.hard_deny
|
||||
.iter()
|
||||
.any(|deny| norm == *deny || norm == Path::new("/"))
|
||||
.any(|deny| paths::same_path(path, deny))
|
||||
}
|
||||
|
||||
/// Validate a removal target. `anchors` are the roots the rule claims to
|
||||
/// own; the target must live strictly below one of them.
|
||||
pub fn check(&self, path: &Path, anchors: &[PathBuf]) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let norm = paths::normalized(path);
|
||||
for comp in norm.components() {
|
||||
if let std::path::Component::Normal(name) = comp {
|
||||
if WINDOWS_RESERVED_NAMES
|
||||
.iter()
|
||||
.any(|r| name.to_string_lossy().eq_ignore_ascii_case(r))
|
||||
{
|
||||
return Err(SquidError::safety(path, "Windows system folder"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.is_hard_denied(path) {
|
||||
return Err(SquidError::safety(path, "protected system location"));
|
||||
}
|
||||
|
|
@ -175,7 +279,7 @@ impl SafetyPolicy {
|
|||
return Err(SquidError::safety(path, "protected user data folder"));
|
||||
}
|
||||
for mount in &self.forbidden_mounts {
|
||||
if paths::normalized(path) == paths::normalized(mount) {
|
||||
if paths::same_path(path, mount) {
|
||||
return Err(SquidError::safety(path, "volume root"));
|
||||
}
|
||||
}
|
||||
|
|
@ -201,9 +305,10 @@ impl SafetyPolicy {
|
|||
|
||||
if !self.allow_system_paths
|
||||
&& !paths::is_within(&paths::home_dir(), &norm)
|
||||
&& !OUTSIDE_HOME_OK
|
||||
&& !self
|
||||
.outside_home_ok
|
||||
.iter()
|
||||
.any(|allowed| paths::is_within(Path::new(allowed), &norm))
|
||||
.any(|allowed| paths::is_within(allowed, &norm))
|
||||
{
|
||||
return Err(SquidError::safety(
|
||||
path,
|
||||
|
|
@ -222,7 +327,7 @@ impl SafetyPolicy {
|
|||
let canonical = std::fs::canonicalize(parent).ok();
|
||||
if let Some(canonical) = canonical {
|
||||
let expected = paths::normalized(parent);
|
||||
if canonical != expected {
|
||||
if !paths::same_path(&canonical, &expected) {
|
||||
return Err(SquidError::safety(
|
||||
path,
|
||||
format!(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,296 @@
|
|||
# squid cleanup rules — Windows 10 / 11
|
||||
#
|
||||
# Every rule declares the anchor it owns (the longest literal prefix of each
|
||||
# pattern), so deletion is always validated against that anchor. Patterns use
|
||||
# `${VAR}` environment expansion (case-insensitive on Windows) and `\` as the
|
||||
# separator; `*` never crosses a path separator. Rules whose variable is not
|
||||
# set (or whose paths do not exist) silently match nothing, which keeps one
|
||||
# build safe on Home, Pro, and machines where the app was never installed.
|
||||
|
||||
# ─────────────────────────────────────────────── system junk / temp files ──
|
||||
[[rule]]
|
||||
id = "windows-temp"
|
||||
category = "system"
|
||||
title = "Temp files (%TEMP%)"
|
||||
patterns = ['${TEMP}\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
note = "Files still in use are skipped, not forced."
|
||||
|
||||
[[rule]]
|
||||
id = "recent-items"
|
||||
category = "system"
|
||||
title = "Recent Items shortcuts"
|
||||
patterns = ['${APPDATA}\Microsoft\Windows\Recent\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
select_by_default = false
|
||||
note = "Only the .lnk shortcuts, never the files they point at."
|
||||
|
||||
[[rule]]
|
||||
id = "windows-update-downloads"
|
||||
category = "system"
|
||||
title = "Windows Update download cache"
|
||||
patterns = ['${SystemRoot}\SoftwareDistribution\Download\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
note = "Safe: update payloads are re-downloaded if ever needed again."
|
||||
|
||||
[[rule]]
|
||||
id = "bits-transfer-cache"
|
||||
category = "system"
|
||||
title = "Delivery Optimization / BITS cache"
|
||||
patterns = ['${ProgramData}\Microsoft\Network\Downloader\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
|
||||
[[rule]]
|
||||
id = "prefetch"
|
||||
category = "system"
|
||||
title = "Prefetch files"
|
||||
patterns = ['${SystemRoot}\Prefetch\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
select_by_default = false
|
||||
note = "Freeing is tiny and boot speed drops until they rebuild."
|
||||
|
||||
# ─────────────────────────────────────────────── browser caches ─────────────
|
||||
[[rule]]
|
||||
id = "edge-caches"
|
||||
category = "browser-caches"
|
||||
title = "Microsoft Edge caches"
|
||||
patterns = ['${LOCALAPPDATA}\Microsoft\Edge\User Data\*\Cache', '${LOCALAPPDATA}\Microsoft\Edge\User Data\*\Code Cache']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["msedge.exe"]
|
||||
note = "Signed-in state is untouched; pages reload from the network."
|
||||
|
||||
[[rule]]
|
||||
id = "chrome-caches"
|
||||
category = "browser-caches"
|
||||
title = "Google Chrome caches"
|
||||
patterns = ['${LOCALAPPDATA}\Google\Chrome\User Data\*\Cache', '${LOCALAPPDATA}\Google\Chrome\User Data\*\Code Cache']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["chrome.exe"]
|
||||
|
||||
[[rule]]
|
||||
id = "firefox-cache"
|
||||
category = "browser-caches"
|
||||
title = "Firefox cache"
|
||||
patterns = ['${LOCALAPPDATA}\Mozilla\Firefox\Profiles\*\cache2']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["firefox.exe"]
|
||||
|
||||
[[rule]]
|
||||
id = "inet-cache"
|
||||
category = "browser-caches"
|
||||
title = "Legacy INetCache"
|
||||
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\INetCache\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
note = "Some entries stay locked while Explorer processes hold them."
|
||||
|
||||
# ─────────────────────────────────────────────── shell / app caches ─────────
|
||||
[[rule]]
|
||||
id = "icon-thumbnail-cache"
|
||||
category = "app-caches"
|
||||
title = "Icon & thumbnail cache"
|
||||
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\Explorer\iconcache_*', '${LOCALAPPDATA}\Microsoft\Windows\Explorer\thumbcache_*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["explorer.exe"]
|
||||
note = "Rebuilt automatically; thumbnails regenerate on browse."
|
||||
|
||||
[[rule]]
|
||||
id = "discord-cache"
|
||||
category = "app-caches"
|
||||
title = "Discord caches"
|
||||
patterns = ['${APPDATA}\discord\Cache', '${APPDATA}\discord\Code Cache', '${APPDATA}\discord\GPUCache']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["discord.exe"]
|
||||
|
||||
[[rule]]
|
||||
id = "slack-cache"
|
||||
category = "app-caches"
|
||||
title = "Slack caches"
|
||||
patterns = ['${APPDATA}\Slack\Cache', '${APPDATA}\Slack\Code Cache', '${APPDATA}\Slack\GPUCache']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["Slack.exe"]
|
||||
|
||||
[[rule]]
|
||||
id = "vscode-cache"
|
||||
category = "app-caches"
|
||||
title = "VS Code caches"
|
||||
patterns = ['${APPDATA}\Code\Cache', '${APPDATA}\Code\CachedData', '${APPDATA}\Code\Code Cache', '${APPDATA}\Code\GPUCache']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
skip_if_running = ["Code.exe"]
|
||||
|
||||
[[rule]]
|
||||
id = "vscode-logs"
|
||||
category = "logs"
|
||||
title = "VS Code logs"
|
||||
patterns = ['${APPDATA}\Code\logs\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
min_age_days = 7
|
||||
|
||||
# ─────────────────────────────────────────────── logs & crash reports ───────
|
||||
[[rule]]
|
||||
id = "user-error-reporting"
|
||||
category = "logs"
|
||||
title = "Windows Error Reporting (user)"
|
||||
patterns = ['${LOCALAPPDATA}\Microsoft\Windows\WER\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
|
||||
[[rule]]
|
||||
id = "system-error-reporting"
|
||||
category = "logs"
|
||||
title = "Windows Error Reporting (system)"
|
||||
patterns = ['${ProgramData}\Microsoft\Windows\WER\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
|
||||
[[rule]]
|
||||
id = "crash-dumps"
|
||||
category = "logs"
|
||||
title = 'Crash dumps (%LOCALAPPDATA%\CrashDumps)'
|
||||
patterns = ['${LOCALAPPDATA}\CrashDumps\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
min_age_days = 14
|
||||
note = "Keep two weeks so a recent crash can still be diagnosed."
|
||||
|
||||
[[rule]]
|
||||
id = "kernel-dumps"
|
||||
category = "logs"
|
||||
title = "Kernel / BSOD dumps"
|
||||
patterns = ['${SystemRoot}\Minidump\*', '${SystemRoot}\MEMORY.DMP']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
min_age_days = 30
|
||||
risky = true
|
||||
note = "MEMORY.DMP can be tens of GB; delete once BSODs are a solved problem."
|
||||
|
||||
[[rule]]
|
||||
id = "connected-devices-platform"
|
||||
category = "logs"
|
||||
title = "ConnectedDevicesPlatform logs"
|
||||
patterns = ['${LOCALAPPDATA}\ConnectedDevicesPlatform\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
|
||||
[[rule]]
|
||||
id = "onedrive-logs"
|
||||
category = "logs"
|
||||
title = "OneDrive logs"
|
||||
patterns = ['${LOCALAPPDATA}\Microsoft\OneDrive\logs\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
min_age_days = 7
|
||||
|
||||
[[rule]]
|
||||
id = "windows-setup-logs"
|
||||
category = "logs"
|
||||
title = "Windows setup / servicing logs"
|
||||
patterns = ['${SystemRoot}\Logs\*', '${ProgramData}\USOShared\Logs\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
min_age_days = 7
|
||||
|
||||
# ─────────────────────────────────────────────── developer caches ───────────
|
||||
[[rule]]
|
||||
id = "npm-cache"
|
||||
category = "developer"
|
||||
title = "npm cache"
|
||||
patterns = ['${LOCALAPPDATA}\npm-cache\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
note = "`npm install` refills it on demand."
|
||||
|
||||
[[rule]]
|
||||
id = "pip-cache"
|
||||
category = "developer"
|
||||
title = "pip wheel cache"
|
||||
patterns = ['${LOCALAPPDATA}\pip\Cache\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
|
||||
[[rule]]
|
||||
id = "cargo-cache"
|
||||
category = "developer"
|
||||
title = "cargo registry cache & sources"
|
||||
patterns = ['~/.cargo/registry/cache/*', '~/.cargo/registry/src/*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
note = "Re-downloaded on the next build; index metadata is kept."
|
||||
|
||||
[[rule]]
|
||||
id = "go-build-cache"
|
||||
category = "developer"
|
||||
title = "Go build cache"
|
||||
patterns = ['${LOCALAPPDATA}\go-build\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
note = "`go build` refills it; next build is slower."
|
||||
|
||||
[[rule]]
|
||||
id = "nuget-cache"
|
||||
category = "developer"
|
||||
title = "NuGet HTTP cache"
|
||||
patterns = ['${LOCALAPPDATA}\NuGet\v3-cache\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
|
||||
[[rule]]
|
||||
id = "gradle-cache"
|
||||
category = "developer"
|
||||
title = "Gradle module & transform caches"
|
||||
patterns = ['~/.gradle/caches/modules-*', '~/.gradle/caches/transforms-*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
|
||||
# ─────────────────────────────────────────────── leftovers ──────────────────
|
||||
[[rule]]
|
||||
id = "windows-old"
|
||||
category = "leftovers"
|
||||
title = "Previous Windows installations"
|
||||
patterns = ['C:\Windows.old\*', 'C:\$WINDOWS.~BT\*', 'C:\$WINDOWS.~WS\*', 'C:\$WinREAgent\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
risky = true
|
||||
note = "Removes the rollback target of your last major update."
|
||||
|
||||
[[rule]]
|
||||
id = "package-cache"
|
||||
category = "leftovers"
|
||||
title = 'Installer repair cache (%ProgramData%\Package Cache)'
|
||||
patterns = ['${ProgramData}\Package Cache\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
needs_admin = true
|
||||
risky = true
|
||||
select_by_default = false
|
||||
note = "Some installers need these payloads to repair or uninstall themselves."
|
||||
|
||||
[[rule]]
|
||||
id = "nvidia-installer-archives"
|
||||
category = "leftovers"
|
||||
title = "NVIDIA driver installer archives"
|
||||
patterns = ['C:\NVIDIA\*']
|
||||
mode = "path"
|
||||
os = ["windows"]
|
||||
select_by_default = false
|
||||
note = "Unpacked installer leftovers; the installed driver is untouched."
|
||||
|
|
@ -180,6 +180,9 @@ impl RuleSet {
|
|||
if cfg!(target_os = "macos") {
|
||||
set.parse_str(EMBEDDED_MACOS, "builtin:macos.toml");
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
|
|
@ -311,16 +314,21 @@ pub fn resolve_variables(pattern: &str) -> Option<String> {
|
|||
if text == "~" || text.starts_with("~/") || text.starts_with("~\\") {
|
||||
text = text.replacen('~', &paths::home_dir().to_string_lossy(), 1);
|
||||
}
|
||||
if let Some(pos) = text.find("${") {
|
||||
let mut cursor = 0usize;
|
||||
while let Some(offset) = text[cursor..].find("${") {
|
||||
let pos = cursor + offset;
|
||||
let rest = &text[pos + 2..];
|
||||
let end = rest.find('}')?;
|
||||
let name = rest[..end].to_string();
|
||||
let value = env_value(&name)?;
|
||||
text = format!("{}{}{}", &text[..pos], value, &rest[end + 1..]);
|
||||
// Continue after the substituted value so replacement text is never
|
||||
// re-scanned (an env var may itself contain `$`).
|
||||
cursor = pos + value.len();
|
||||
}
|
||||
if text.starts_with('$') {
|
||||
let head = text
|
||||
.find('/')
|
||||
.find(['/', '\\'])
|
||||
.map(|idx| text[1..idx].to_string())
|
||||
.unwrap_or_else(|| text[1..].to_string());
|
||||
let value = env_value(&head)?;
|
||||
|
|
@ -346,6 +354,9 @@ fn glob_matcher(component: &str) -> Option<GlobMatcher> {
|
|||
GlobBuilder::new(component)
|
||||
.literal_separator(true)
|
||||
.backslash_escape(true)
|
||||
// Windows filenames are matched case-insensitively by the OS; rules
|
||||
// must not silently miss entries that differ only in casing.
|
||||
.case_insensitive(cfg!(windows))
|
||||
.build()
|
||||
.ok()
|
||||
.map(|glob| glob.compile_matcher())
|
||||
|
|
@ -367,12 +378,25 @@ pub fn anchor_for(pattern: &str) -> Option<PathBuf> {
|
|||
for component in path.components() {
|
||||
let text = match component {
|
||||
Component::RootDir => {
|
||||
anchor.push("/");
|
||||
// Windows spells `C:\…` as Prefix("C:") then RootDir; fold
|
||||
// them into a rooted `C:\` anchor instead of drive-relative
|
||||
// `C:/`. On Unix this is the leading `/`.
|
||||
let existing = anchor.as_os_str().to_string_lossy().into_owned();
|
||||
if !existing.is_empty() && !existing.contains(['/', '\\']) {
|
||||
anchor = PathBuf::from(format!("{existing}\\", existing = existing));
|
||||
} else {
|
||||
anchor.push("/");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Component::CurDir => continue,
|
||||
// Drive/UNC prefixes are part of the anchor on Windows.
|
||||
Component::Prefix(prefix) => {
|
||||
anchor.push(prefix.as_os_str());
|
||||
continue;
|
||||
}
|
||||
Component::Normal(text) => text.to_string_lossy().into_owned(),
|
||||
Component::ParentDir | Component::Prefix(_) => return None,
|
||||
Component::ParentDir => return None,
|
||||
};
|
||||
if has_glob(&text) {
|
||||
saw_glob = true;
|
||||
|
|
@ -521,14 +545,28 @@ impl Protector {
|
|||
let mut absolute = Vec::new();
|
||||
let mut relative = Vec::new();
|
||||
for raw in &rule.protect {
|
||||
let resolved = resolve_variables(raw).unwrap_or_else(|| raw.clone());
|
||||
if resolved.starts_with('/') {
|
||||
#[cfg_attr(not(windows), allow(unused_mut))]
|
||||
let mut resolved = resolve_variables(raw).unwrap_or_else(|| raw.clone());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Matching below funnels through `/`-normalised text; make the
|
||||
// patterns speak the same language.
|
||||
resolved = resolved.replace('\\', "/");
|
||||
}
|
||||
let is_absolute = resolved.starts_with('/')
|
||||
|| (cfg!(windows)
|
||||
&& resolved.as_bytes().get(1) == Some(&b':')
|
||||
&& resolved.as_bytes()[0].is_ascii_alphabetic());
|
||||
if is_absolute {
|
||||
if let Some(matcher) = glob_matcher(&resolved) {
|
||||
absolute.push(matcher);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match Glob::new(&format!("**/{resolved}")) {
|
||||
match GlobBuilder::new(&format!("**/{resolved}"))
|
||||
.case_insensitive(cfg!(windows))
|
||||
.build()
|
||||
{
|
||||
Ok(glob) => relative.push(glob.compile_matcher()),
|
||||
Err(_) => {
|
||||
if let Some(matcher) = glob_matcher(raw) {
|
||||
|
|
@ -550,18 +588,21 @@ impl Protector {
|
|||
if self.absolute.is_empty() && self.relative.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let text = path.to_string_lossy();
|
||||
let text = path.to_string_lossy().into_owned();
|
||||
#[cfg(windows)]
|
||||
let text = text.replace('\\', "/");
|
||||
if self.absolute.iter().any(|m| m.is_match(&*text)) {
|
||||
return true;
|
||||
}
|
||||
for ancestor in path.ancestors() {
|
||||
let Ok(rel) = ancestor.strip_prefix(anchor) else {
|
||||
// Case-insensitive containment on Windows; `None` also covers the
|
||||
// anchor itself, whose next ancestor leaves the anchor anyway.
|
||||
let Some(rel) = paths::relative_below(anchor, ancestor) else {
|
||||
break;
|
||||
};
|
||||
if rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = rel.to_string_lossy().into_owned();
|
||||
#[cfg(windows)]
|
||||
let rel = rel.replace('\\', "/");
|
||||
if self.relative.iter().any(|m| m.is_match(&*rel)) {
|
||||
return true;
|
||||
}
|
||||
|
|
@ -625,6 +666,7 @@ pub fn globset_of(patterns: &[String]) -> Option<GlobSet> {
|
|||
}
|
||||
|
||||
const EMBEDDED_MACOS: &str = include_str!("../rules/macos.toml");
|
||||
const EMBEDDED_WINDOWS: &str = include_str!("../rules/windows.toml");
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
|
@ -689,7 +731,87 @@ mod tests {
|
|||
"{}: anchor {anchor:?} is not absolute",
|
||||
rule.id
|
||||
);
|
||||
assert_ne!(anchor, PathBuf::from("/"), "{}: anchors at /", rule.id);
|
||||
assert!(
|
||||
!paths::is_root_like(&anchor),
|
||||
"{}: anchors at a filesystem root",
|
||||
rule.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_rules_parse_on_every_host() {
|
||||
// The Windows host check only runs in CI's cross-check job, so the
|
||||
// TOML itself must at least parse on every platform.
|
||||
let mut set = RuleSet::default();
|
||||
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
|
||||
assert!(
|
||||
set.errors().is_empty(),
|
||||
"windows rules failed: {:?}",
|
||||
set.errors()
|
||||
);
|
||||
assert!(
|
||||
set.len() > 20,
|
||||
"expected dozens of rules, got {}",
|
||||
set.len()
|
||||
);
|
||||
let mut ids: Vec<&str> = set.rules().iter().map(|r| r.id.as_str()).collect();
|
||||
ids.sort();
|
||||
let count = ids.len();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), count, "duplicate rule ids");
|
||||
for rule in set.rules() {
|
||||
assert_eq!(
|
||||
rule.os,
|
||||
vec!["windows".to_string()],
|
||||
"{}: wrong os tag",
|
||||
rule.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_variables_resolve_case_insensitively_and_stop_at_separators() {
|
||||
std::env::set_var("SQUID_TEST_VAR", "C:\\Test Root");
|
||||
// `$VAR` at the head stops at the first separator, either flavour.
|
||||
assert_eq!(
|
||||
resolve_variables("$SQUID_TEST_VAR\\sub\\*").as_deref(),
|
||||
Some("C:\\Test Root\\sub\\*")
|
||||
);
|
||||
// Multiple `${VAR}` occurrences all resolve.
|
||||
assert_eq!(
|
||||
resolve_variables("${SQUID_TEST_VAR}\\a\\${SQUID_TEST_VAR}\\b").as_deref(),
|
||||
Some("C:\\Test Root\\a\\C:\\Test Root\\b")
|
||||
);
|
||||
assert!(resolve_variables("$SQUID_TEST_UNDEFINED\\x").is_none());
|
||||
std::env::remove_var("SQUID_TEST_VAR");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_anchors_are_never_at_a_drive_root() {
|
||||
let mut set = RuleSet::default();
|
||||
set.parse_str(EMBEDDED_WINDOWS, "builtin:windows.toml");
|
||||
for rule in set.rules() {
|
||||
for pattern in &rule.patterns {
|
||||
let anchor = anchor_for(pattern)
|
||||
.unwrap_or_else(|| panic!("{}: no anchor for {pattern}", rule.id));
|
||||
assert!(
|
||||
anchor.is_absolute(),
|
||||
"{}: anchor {anchor:?} is not absolute",
|
||||
rule.id
|
||||
);
|
||||
assert!(
|
||||
!paths::is_root_like(&anchor),
|
||||
"{}: anchors at a volume root: {anchor:?}",
|
||||
rule.id
|
||||
);
|
||||
assert!(
|
||||
anchor.components().count() >= 2,
|
||||
"{}: anchor too shallow: {anchor:?}",
|
||||
rule.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue