From ea1465d1929da8eef75238dd3e4fc9bc286e79cb Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Sun, 22 Nov 2026 15:44:07 +0800 Subject: [PATCH] Release Squid 0.1.11 with security allowlist --- Cargo.lock | 16 +- Cargo.toml | 2 +- crates/squid-core/src/settings.rs | 66 +++++ crates/squid-guard/src/allowlist.rs | 138 ++++++++++ crates/squid-guard/src/lib.rs | 1 + package.json | 2 +- src-tauri/Cargo.lock | 14 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/lib.rs | 2 + src-tauri/src/security.rs | 337 +++++++++++++++++++++--- src-tauri/tauri.conf.json | 2 +- src/components/SecuritySettingsCard.tsx | 66 +++++ src/hooks/useSecurityWorkspace.ts | 18 +- src/lib/api.ts | 7 + src/pages/ApplicationsPage.tsx | 4 - src/pages/CleanupPage.tsx | 4 - src/pages/HistoryPage.tsx | 4 - src/pages/OverviewPage.tsx | 4 - src/pages/PermissionsPage.tsx | 12 - src/pages/PurgePage.tsx | 4 - src/pages/SecurityPage.tsx | 196 ++++++++++---- src/pages/SettingsPage.tsx | 4 - src/pages/StartupPage.tsx | 4 - src/pages/StoragePage.tsx | 4 - src/pages/SystemPage.tsx | 4 - src/styles.css | 25 +- src/types.ts | 9 + 27 files changed, 794 insertions(+), 157 deletions(-) create mode 100644 crates/squid-guard/src/allowlist.rs diff --git a/Cargo.lock b/Cargo.lock index 566b8bf..f843721 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3594,7 +3594,7 @@ dependencies = [ [[package]] name = "squid-cli" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", @@ -3614,7 +3614,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", @@ -3633,7 +3633,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", @@ -3653,7 +3653,7 @@ dependencies = [ [[package]] name = "squid-guard" -version = "0.1.10" +version = "0.1.11" dependencies = [ "chrono", "hex", @@ -3669,7 +3669,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.10" +version = "0.1.11" dependencies = [ "dirs", "file_icon_provider", @@ -3689,7 +3689,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.10" +version = "0.1.11" dependencies = [ "globset", "serde", @@ -3701,7 +3701,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.10" +version = "0.1.11" dependencies = [ "chrono", "libc", @@ -3714,7 +3714,7 @@ dependencies = [ [[package]] name = "squid-tui" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 67148c5..26a5a8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.10" +version = "0.1.11" edition = "2021" rust-version = "1.95" license = "GPL-3.0-only" diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs index b6b920a..b9d7128 100644 --- a/crates/squid-core/src/settings.rs +++ b/crates/squid-core/src/settings.rs @@ -106,6 +106,10 @@ pub struct SecuritySettings { pub scan_exclusions: Vec, /// Findings the user dismissed, as `confidence|path` fingerprints. pub ignored_findings: Vec, + /// Software the user trusts. Matching findings stay visible in the trusted + /// filter but stop counting as outstanding. Confirmed threats are never + /// matched, whatever is in here. + pub allowlist: Vec, } impl Default for SecuritySettings { @@ -119,6 +123,7 @@ impl Default for SecuritySettings { update_rules: true, scan_exclusions: Vec::new(), ignored_findings: Vec::new(), + allowlist: Vec::new(), } } } @@ -161,6 +166,55 @@ impl SecuritySettings { self.ignored_findings.retain(|kept| kept != fingerprint); self.ignored_findings.len() != before } + + pub fn allow(&mut self, kind: AllowKind, value: impl Into) -> bool { + let value = value.into().trim().to_string(); + if value.is_empty() { + return false; + } + if self + .allowlist + .iter() + .any(|entry| entry.kind == kind && entry.value.eq_ignore_ascii_case(&value)) + { + return false; + } + self.allowlist.push(AllowEntry { kind, value }); + true + } + + pub fn remove_allow(&mut self, kind: AllowKind, value: &str) -> bool { + let before = self.allowlist.len(); + self.allowlist + .retain(|entry| !(entry.kind == kind && entry.value.eq_ignore_ascii_case(value))); + self.allowlist.len() != before + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AllowKind { + Publisher, + Path, + Evidence, +} + +impl AllowKind { + pub fn parse(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "publisher" => Some(AllowKind::Publisher), + "path" | "folder" => Some(AllowKind::Path), + "evidence" | "kind" => Some(AllowKind::Evidence), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AllowEntry { + pub kind: AllowKind, + pub value: String, } impl Default for Settings { @@ -644,5 +698,17 @@ mod tests { let older = "history_keep = 60\n"; let restored: Settings = toml::from_str(older).unwrap(); assert!(!restored.desktop_setup_reviewed); + assert!(restored.security.allowlist.is_empty()); + } + + #[test] + fn trust_rules_are_deduplicated_and_removable() { + let mut security = SecuritySettings::default(); + assert!(security.allow(AllowKind::Publisher, " Example Ltd ")); + assert!(!security.allow(AllowKind::Publisher, "example ltd")); + assert!(security.allow(AllowKind::Path, "/Applications/Example.app")); + assert_eq!(security.allowlist.len(), 2); + assert!(security.remove_allow(AllowKind::Publisher, "EXAMPLE LTD")); + assert_eq!(security.allowlist.len(), 1); } } diff --git a/crates/squid-guard/src/allowlist.rs b/crates/squid-guard/src/allowlist.rs new file mode 100644 index 0000000..b4d719d --- /dev/null +++ b/crates/squid-guard/src/allowlist.rs @@ -0,0 +1,138 @@ +//! User trust rules for findings that are not threats. +//! +//! The scanner is intentionally conservative: an unsigned login item is worth +//! telling a person about. A real machine also has hundreds of those from +//! ordinary software, so the answer cannot be to lower the detector until it +//! stops seeing them. It is to let the user name the publisher, folder or +//! advisory class they trust. +//! +//! Two limits are deliberate. A confirmed finding is never matched, and an +//! evidence-class rule only applies to advisory findings. Trust can quiet a +//! note; it cannot hide a published threat. + +use crate::findings::{Confidence, Evidence, Finding}; +use squid_core::paths; +use squid_core::settings::{AllowEntry, AllowKind}; + +/// Evidence classes that describe ordinary software rather than a published +/// threat. These are the only classes an evidence rule may quiet. +pub const TRUSTABLE_EVIDENCE: [&str; 4] = ["startup", "unsigned", "writable", "missing"]; + +pub fn evidence_kind(evidence: &Evidence) -> Option<&'static str> { + let key = evidence.key(); + let kind = key.split(':').next()?; + TRUSTABLE_EVIDENCE + .iter() + .copied() + .find(|known| *known == kind) +} + +pub fn is_allowlisted(finding: &Finding, allowlist: &[AllowEntry]) -> bool { + if finding.confidence == Confidence::Confirmed { + return false; + } + allowlist.iter().any(|entry| match entry.kind { + AllowKind::Publisher => finding + .signed + .then_some(finding.publisher.as_deref()) + .flatten() + .is_some_and(|publisher| publisher.trim().eq_ignore_ascii_case(entry.value.trim())), + AllowKind::Path => finding.path.as_deref().is_some_and(|path| { + let trusted = paths::expand(&entry.value); + paths::same_path(&trusted, path) || paths::is_within(&trusted, path) + }), + AllowKind::Evidence => { + finding.confidence == Confidence::Advisory + && finding + .evidence + .iter() + .filter_map(evidence_kind) + .any(|kind| kind == entry.value.trim().to_ascii_lowercase()) + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + fn finding(confidence: Confidence) -> Finding { + Finding { + id: "scan#1".into(), + confidence, + path: Some(PathBuf::from( + "/Applications/Example.app/Contents/MacOS/Example", + )), + display_path: Some("/Applications/Example.app".into()), + name: "Example".into(), + title: "Example".into(), + description: String::new(), + evidence: vec![Evidence::Unsigned { + path: PathBuf::from("/Applications/Example.app/Contents/MacOS/Example"), + note: None, + }], + size: 1, + sha256: None, + signed: true, + publisher: Some("Example Software Ltd".into()), + found_at_ms: 0, + quarantined: false, + ignored: false, + } + } + + fn rule(kind: AllowKind, value: &str) -> AllowEntry { + AllowEntry { + kind, + value: value.into(), + } + } + + #[test] + fn a_publisher_or_bundle_folder_quiets_an_advisory() { + let finding = finding(Confidence::Advisory); + assert!(is_allowlisted( + &finding, + &[rule(AllowKind::Publisher, "example software ltd")] + )); + assert!(is_allowlisted( + &finding, + &[rule(AllowKind::Path, "/Applications/Example.app")] + )); + assert!(is_allowlisted( + &finding, + &[rule(AllowKind::Evidence, "unsigned")] + )); + assert!(!is_allowlisted( + &finding, + &[rule(AllowKind::Path, "/Applications/Other.app")] + )); + } + + #[test] + fn an_evidence_rule_never_hides_a_suspicious_or_confirmed_finding() { + assert!(!is_allowlisted( + &finding(Confidence::Suspicious), + &[rule(AllowKind::Evidence, "unsigned")] + )); + assert!(!is_allowlisted( + &finding(Confidence::Confirmed), + &[ + rule(AllowKind::Evidence, "unsigned"), + rule(AllowKind::Publisher, "Example Software Ltd"), + rule(AllowKind::Path, "/Applications"), + ] + )); + } + + #[test] + fn a_publisher_rule_requires_a_signed_file() { + let mut unsigned = finding(Confidence::Advisory); + unsigned.signed = false; + assert!(!is_allowlisted( + &unsigned, + &[rule(AllowKind::Publisher, "Example Software Ltd")] + )); + } +} diff --git a/crates/squid-guard/src/lib.rs b/crates/squid-guard/src/lib.rs index 0e3826e..68526b8 100644 --- a/crates/squid-guard/src/lib.rs +++ b/crates/squid-guard/src/lib.rs @@ -24,6 +24,7 @@ //! - heuristics answer "would a careful person look at this twice" //! (`suspicious`/`advisory`) and never quarantine on their own. +pub mod allowlist; pub mod coverage; pub mod findings; pub mod heuristics; diff --git a/package.json b/package.json index baa0a3c..f227f1f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.10", + "version": "0.1.11", "type": "module", "scripts": { "dev": "vite --port 1420 --strictPort", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index e32dc47..deb46ba 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4760,7 +4760,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", @@ -4779,7 +4779,7 @@ dependencies = [ [[package]] name = "squid-desktop" -version = "0.1.10" +version = "0.1.11" dependencies = [ "base64 0.22.1", "chrono", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.10" +version = "0.1.11" dependencies = [ "anyhow", "chrono", @@ -4826,7 +4826,7 @@ dependencies = [ [[package]] name = "squid-guard" -version = "0.1.10" +version = "0.1.11" dependencies = [ "chrono", "hex", @@ -4842,7 +4842,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.10" +version = "0.1.11" dependencies = [ "dirs 6.0.0", "file_icon_provider", @@ -4862,7 +4862,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.10" +version = "0.1.11" dependencies = [ "globset", "serde", @@ -4874,7 +4874,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.10" +version = "0.1.11" dependencies = [ "chrono", "libc", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 010193e..cdadb58 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.10" +version = "0.1.11" description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." authors = ["squid contributors"] edition = "2021" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5854efa..f4aefa2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -294,6 +294,8 @@ pub fn run() { security::security_restore, security::security_delete_quarantine, security::security_ignore, + security::security_trust, + security::security_untrust, security::security_exclusions, security::security_settings_save, security::security_update_rules, diff --git a/src-tauri/src/security.rs b/src-tauri/src/security.rs index fe834fb..b84c101 100644 --- a/src-tauri/src/security.rs +++ b/src-tauri/src/security.rs @@ -14,6 +14,7 @@ use crate::app::{AppState, ProgressReporter}; use chrono::{DateTime, Local}; use serde::{Deserialize, Serialize}; use squid_core::progress::{CancelToken, Progress}; +use squid_core::settings::{AllowEntry, AllowKind}; use squid_core::{paths, Settings}; use squid_guard::intel::IntelStatus; use squid_guard::quarantine::{Quarantine, QuarantineEntry}; @@ -69,7 +70,27 @@ pub(crate) fn outstanding() -> (usize, usize, bool) { .map(|entry| (entry.id.clone(), entry.original_path.clone())) .collect(); store.mark_quarantined(&pairs); - let (confirmed, suspicious, _) = store.counts(); + let (settings, _) = Settings::load(); + let (confirmed, suspicious, _) = store + .scan() + .map(|scan| { + let mut counts = (0, 0, 0); + for finding in &scan.findings { + if finding.ignored + || finding.quarantined + || squid_guard::allowlist::is_allowlisted(finding, &settings.security.allowlist) + { + continue; + } + match finding.confidence { + Confidence::Confirmed => counts.0 += 1, + Confidence::Suspicious => counts.1 += 1, + Confidence::Advisory => counts.2 += 1, + } + } + counts + }) + .unwrap_or((0, 0, 0)); (confirmed, suspicious, scanned) } @@ -122,10 +143,11 @@ pub struct FindingView { found_at_ms: u64, quarantined: bool, ignored: bool, + allowlisted: bool, } -impl From<&Finding> for FindingView { - fn from(finding: &Finding) -> FindingView { +impl FindingView { + fn new(finding: &Finding, allowlist: &[AllowEntry]) -> FindingView { FindingView { id: finding.id.clone(), confidence: finding.confidence, @@ -145,6 +167,7 @@ impl From<&Finding> for FindingView { found_at_ms: finding.found_at_ms, quarantined: finding.quarantined, ignored: finding.ignored, + allowlisted: squid_guard::allowlist::is_allowlisted(finding, allowlist), } } } @@ -174,7 +197,12 @@ pub struct ScanView { } impl ScanView { - fn new(report: &ScanReport) -> ScanView { + fn new(report: &ScanReport, allowlist: &[AllowEntry]) -> ScanView { + let findings: Vec = report + .findings + .iter() + .map(|finding| FindingView::new(finding, allowlist)) + .collect(); ScanView { scan_id: report.scan_id.clone(), mode: report.mode.as_str().to_string(), @@ -197,23 +225,25 @@ impl ScanView { .unwrap_or_else(|| gap.outcome.as_str().into()), }) .collect(), - findings: report.findings.iter().map(FindingView::from).collect(), + findings: findings.clone(), system_advisories: report .system_advisories .iter() - .map(FindingView::from) + .map(|finding| FindingView::new(finding, allowlist)) .collect(), - confirmed: report.confirmed(), - suspicious: report.suspicious(), - advisory: report.advisory(), + confirmed: count_open(&findings, Confidence::Confirmed), + suspicious: count_open(&findings, Confidence::Suspicious), + advisory: count_open(&findings, Confidence::Advisory), clean: report.clean_and_complete(), } } - fn from_stored(scan: &StoredScan) -> ScanView { - // Counted by the record itself, so the badge, the tray and this view can - // never disagree about what "still needs a decision" means. - let (confirmed, suspicious, advisory) = scan.counts(); + fn from_stored(scan: &StoredScan, allowlist: &[AllowEntry]) -> ScanView { + let findings: Vec = scan + .findings + .iter() + .map(|finding| FindingView::new(finding, allowlist)) + .collect(); ScanView { scan_id: scan.scan_id.clone(), mode: scan.mode.clone(), @@ -232,16 +262,28 @@ impl ScanView { reason: reason.clone(), }) .collect(), - findings: scan.findings.iter().map(FindingView::from).collect(), + confirmed: count_open(&findings, Confidence::Confirmed), + suspicious: count_open(&findings, Confidence::Suspicious), + advisory: count_open(&findings, Confidence::Advisory), + findings, system_advisories: Vec::new(), clean: scan.findings.is_empty() && scan.coverage_complete && !scan.cancelled, - confirmed, - suspicious, - advisory, } } } +fn count_open(findings: &[FindingView], confidence: Confidence) -> usize { + findings + .iter() + .filter(|finding| { + finding.confidence == confidence + && !finding.ignored + && !finding.allowlisted + && !finding.quarantined + }) + .count() +} + /// The security half of the settings file, in the shape the UI binds to. #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -252,6 +294,7 @@ pub struct SecuritySettingsView { update_rules: bool, scan_exclusions: Vec, ignored_findings: Vec, + allowlist: Vec, /// Absolute paths a scan covers, so the UI can promise only what it can show. quick_roots: Vec, full_roots: Vec, @@ -269,6 +312,7 @@ impl SecuritySettingsView { update_rules: settings.security.update_rules, scan_exclusions: settings.security.scan_exclusions.clone(), ignored_findings: settings.security.ignored_findings.clone(), + allowlist: settings.security.allowlist.clone(), quick_roots: display_list(&squid_guard::scan::quick_roots()), full_roots: display_list(&squid_guard::scan::full_roots()), quarantined: held, @@ -358,6 +402,7 @@ pub struct SecurityPaths { #[tauri::command] pub async fn security_status() -> Result { tauri::async_runtime::spawn_blocking(|| { + let (settings, _) = Settings::load(); let mut store = squid_guard::store::Store::new(); let mut held = Quarantine::new(); // The ledger, not the frontend, decides what counts as handled. @@ -367,7 +412,9 @@ pub async fn security_status() -> Result { .map(|entry| (entry.id.clone(), entry.original_path.clone())) .collect(); store.mark_quarantined(&pairs); - let scan = store.scan().map(ScanView::from_stored); + let scan = store + .scan() + .map(|scan| ScanView::from_stored(scan, &settings.security.allowlist)); let (confirmed, suspicious) = scan .as_ref() .map(|view| (view.confirmed, view.suspicious)) @@ -561,8 +608,8 @@ fn run_scan( // has the ledger folded into it. Ok(store .scan() - .map(ScanView::from_stored) - .unwrap_or_else(|| ScanView::new(&report))) + .map(|scan| ScanView::from_stored(scan, &settings.security.allowlist)) + .unwrap_or_else(|| ScanView::new(&report, &settings.security.allowlist))) } /// Everything that follows a finished scan once the ledger has been folded in: @@ -741,6 +788,184 @@ pub async fn security_ignore(finding_id: String, ignored: bool) -> Result Result { + tauri::async_runtime::spawn_blocking(move || { + let finding = { + let store = squid_guard::store::Store::new(); + store + .finding(&finding_id) + .cloned() + .ok_or_else(|| "This finding is no longer in the last scan.".to_string())? + }; + let entry = trust_entry_for(&finding, &scope)?; + let message = match entry.kind { + AllowKind::Publisher => format!("Trusted publisher {}", entry.value), + AllowKind::Path => format!("Trusted {}", paths::pretty(&paths::expand(&entry.value))), + AllowKind::Evidence => format!("No longer reporting {} advisories", entry.value), + }; + let (mut settings, _) = Settings::load(); + settings.security.allow(entry.kind, entry.value); + settings + .save() + .map_err(|error| format!("Could not save settings: {error}"))?; + let mut store = squid_guard::store::Store::new(); + store.note("trust", message.clone(), finding.path.clone()); + Ok(ActionResult { + message, + status: status_now(), + }) + }) + .await + .map_err(|error| error.to_string())? +} + +/// Remove a trust rule. The next status is rebuilt from the stored scan, so the +/// findings it covered become actionable again without waiting for a rescan. +#[tauri::command] +pub async fn security_untrust(kind: String, value: String) -> Result { + tauri::async_runtime::spawn_blocking(move || { + let kind = + AllowKind::parse(&kind).ok_or_else(|| format!("Unknown trust rule kind {kind}."))?; + let (mut settings, _) = Settings::load(); + if !settings.security.remove_allow(kind, value.trim()) { + return Err("That trust rule was not present.".into()); + } + settings + .save() + .map_err(|error| format!("Could not save settings: {error}"))?; + Ok(ActionResult { + message: "This software will be reported again.".into(), + status: status_now(), + }) + }) + .await + .map_err(|error| error.to_string())? +} + +fn trust_entry_for(finding: &Finding, scope: &str) -> Result { + if finding.confidence == Confidence::Confirmed { + return Err("Confirmed threats cannot be trusted.".into()); + } + match scope { + "publisher" => { + let publisher = finding + .signed + .then_some(finding.publisher.as_deref()) + .flatten() + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "This finding has no verified publisher to trust.".to_string())?; + Ok(AllowEntry { + kind: AllowKind::Publisher, + value: publisher.to_string(), + }) + } + "folder" => { + let path = finding + .path + .as_deref() + .ok_or_else(|| "This finding has no file to trust.".to_string())?; + let root = trust_root(path).ok_or_else(|| { + "This file is too close to a broad system folder to trust by path.".to_string() + })?; + Ok(AllowEntry { + kind: AllowKind::Path, + value: root.to_string_lossy().into_owned(), + }) + } + "evidence" => { + if finding.confidence != Confidence::Advisory { + return Err("Only advisory notes can be hidden by type.".into()); + } + let mut kinds: Vec<&str> = finding + .evidence + .iter() + .filter_map(squid_guard::allowlist::evidence_kind) + .collect(); + kinds.sort_unstable(); + kinds.dedup(); + match kinds.as_slice() { + [kind] => Ok(AllowEntry { + kind: AllowKind::Evidence, + value: (*kind).to_string(), + }), + [] => Err("This finding has no trustable advisory class.".into()), + _ => Err( + "This finding has several advisory classes; trust its folder or publisher instead." + .into(), + ), + } + } + other => Err(format!("Unknown trust scope {other}.")), + } +} + +/// The app bundle when there is one, otherwise the containing folder. Broad +/// folders are refused: one click must not trust every app on the machine. +fn trust_root(path: &std::path::Path) -> Option { + let mut bundle = None; + let mut prefix = PathBuf::new(); + for component in path.components() { + prefix.push(component.as_os_str()); + if component + .as_os_str() + .to_string_lossy() + .to_ascii_lowercase() + .ends_with(".app") + { + bundle = Some(prefix.clone()); + } + } + let root = bundle.or_else(|| path.parent().map(std::path::Path::to_path_buf))?; + if paths::is_root_like(&root) { + return None; + } + let home = squid_platform::startup::home_dir(); + let mut broad = vec![ + home.clone(), + home.join("Applications"), + home.join("Desktop"), + home.join("Documents"), + home.join("Downloads"), + home.join("Library"), + home.join("Library/Application Support"), + home.join("Library/Caches"), + home.join("Library/LaunchAgents"), + home.join("Library/LaunchDaemons"), + home.join("Library/Preferences"), + PathBuf::from("/Applications"), + PathBuf::from("/Library"), + PathBuf::from("/Library/Application Support"), + PathBuf::from("/Library/LaunchAgents"), + PathBuf::from("/Library/LaunchDaemons"), + PathBuf::from("/Users/Shared"), + PathBuf::from("/System"), + PathBuf::from("/usr"), + PathBuf::from("/private"), + PathBuf::from("/tmp"), + PathBuf::from("/var"), + ]; + for key in [ + "LOCALAPPDATA", + "APPDATA", + "ProgramData", + "ProgramFiles", + "ProgramFiles(x86)", + ] { + if let Some(path) = std::env::var_os(key) { + broad.push(PathBuf::from(path)); + } + } + if broad.iter().any(|broad| paths::same_path(broad, &root)) { + return None; + } + Some(root) +} + /// Add or drop a scan exclusion. Separate from the cleanup whitelist on purpose, /// and the UI says so: protecting a folder from *cleaning* must not stop a /// malware finding from being reported there. @@ -1032,7 +1257,7 @@ pub fn last_scan_label() -> Option { mod tests { use super::*; use squid_guard::findings::Evidence; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; fn finding(id: &str, confidence: Confidence, ignored: bool, quarantined: bool) -> Finding { Finding { @@ -1078,12 +1303,15 @@ mod tests { // The tray badge and the page must agree, and both must stop counting a // file that has been quarantined or ignored. Otherwise "3 issues found" // follows a user who has already handled all three. - let view = ScanView::from_stored(&scan_with(vec![ - finding("confirmed-open", Confidence::Confirmed, false, false), - finding("confirmed-held", Confidence::Confirmed, false, true), - finding("confirmed-dismissed", Confidence::Confirmed, true, false), - finding("suspicious-open", Confidence::Suspicious, false, false), - ])); + let view = ScanView::from_stored( + &scan_with(vec![ + finding("confirmed-open", Confidence::Confirmed, false, false), + finding("confirmed-held", Confidence::Confirmed, false, true), + finding("confirmed-dismissed", Confidence::Confirmed, true, false), + finding("suspicious-open", Confidence::Suspicious, false, false), + ]), + &[], + ); assert_eq!( view.confirmed, 1, "only the unhandled confirmed finding counts" @@ -1098,17 +1326,66 @@ mod tests { #[test] fn a_scan_with_gaps_is_never_called_clean() { let mut stored = scan_with(Vec::new()); - assert!(ScanView::from_stored(&stored).clean); + assert!(ScanView::from_stored(&stored, &[]).clean); stored.coverage_complete = false; stored.gaps = vec![("/protected".into(), "permission denied".into())]; - let view = ScanView::from_stored(&stored); + let view = ScanView::from_stored(&stored, &[]); assert!( !view.clean, "an unreadable folder is not the same as a clean one" ); assert_eq!(view.gaps.len(), 1); stored.cancelled = true; - assert!(!ScanView::from_stored(&stored).clean); + assert!(!ScanView::from_stored(&stored, &[]).clean); + } + + #[test] + fn a_trusted_finding_stops_counting_without_hiding_confirmed_ones() { + let stored = scan_with(vec![ + finding("advisory-trusted", Confidence::Advisory, false, false), + finding("confirmed-trusted", Confidence::Confirmed, false, false), + ]); + let allowlist = vec![AllowEntry { + kind: AllowKind::Path, + value: "/tmp".into(), + }]; + let view = ScanView::from_stored(&stored, &allowlist); + assert_eq!(view.advisory, 0, "the trusted advisory is handled"); + assert_eq!( + view.confirmed, 1, + "a confirmed finding is never hidden by trust" + ); + assert_eq!( + view.findings + .iter() + .filter(|finding| finding.allowlisted) + .count(), + 1 + ); + } + + #[test] + fn trust_by_path_stops_at_the_bundle_and_refuses_broad_folders() { + assert_eq!( + trust_root(Path::new( + "/Applications/Example.app/Contents/MacOS/Example" + )), + Some(PathBuf::from("/Applications/Example.app")) + ); + assert_eq!( + trust_root(Path::new("/Applications")), + None, + "one click must not trust every app" + ); + assert_eq!(trust_root(Path::new("/tmp/example")), None); + } + + #[test] + fn trust_refuses_confirmed_findings_and_suspicious_evidence_rules() { + let confirmed = finding("confirmed", Confidence::Confirmed, false, false); + assert!(trust_entry_for(&confirmed, "folder").is_err()); + let suspicious = finding("suspicious", Confidence::Suspicious, false, false); + assert!(trust_entry_for(&suspicious, "evidence").is_err()); } #[test] diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 66ab362..4d40c28 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Squid", - "version": "0.1.10", + "version": "0.1.11", "identifier": "app.nex.squid", "mainBinaryName": "squid-desktop", "build": { diff --git a/src/components/SecuritySettingsCard.tsx b/src/components/SecuritySettingsCard.tsx index 7ef23d5..f280eda 100644 --- a/src/components/SecuritySettingsCard.tsx +++ b/src/components/SecuritySettingsCard.tsx @@ -22,6 +22,13 @@ const SCHEDULES: [ScanSchedule, string, string][] = [ ["weekly", "Weekly while Squid is in the tray", "驻留托盘时每周一次"], ]; +const EVIDENCE_LABELS: Record = { + startup: ["Startup items", "登录启动项"], + unsigned: ["Unsigned files", "未签名文件"], + writable: ["Writable locations", "可写位置"], + missing: ["Missing targets", "目标缺失"], +}; + /** * The security half of Settings. * @@ -91,6 +98,17 @@ export function SecuritySettingsCard({ } }; + const untrust = async (kind: "publisher" | "path" | "evidence", value: string) => { + setBusy(true); + try { + push(await security.untrust(kind, value), "success"); + } catch (reason) { + push(messageFrom(reason), "danger"); + } finally { + setBusy(false); + } + }; + return (
@@ -282,6 +300,54 @@ export function SecuritySettingsCard({
+ {settings.allowlist.length ? ( +
+
+ {t("Trusted software", "已信任的软件")} + + {t( + `${settings.allowlist.length} rules quiet ordinary advisories. Confirmed threats are never trusted.`, + `${settings.allowlist.length} 条规则用于静默普通提示,已确认威胁永远不会被信任。`, + )} + +
+
+ {settings.allowlist.map((entry) => ( +
+ + + + + {entry.kind === "publisher" + ? t("Publisher", "发布者") + : entry.kind === "path" + ? t("Folder", "文件夹") + : t("Note type", "提示类型")} + + + {entry.kind === "evidence" + ? t( + EVIDENCE_LABELS[entry.value]?.[0] ?? entry.value, + EVIDENCE_LABELS[entry.value]?.[1] ?? entry.value, + ) + : entry.kind === "path" + ? shortPath(entry.value, 88) + : entry.value} + + +
+ ))} +
+
+ ) : null} + {settings.ignoredFindings.length ? (
diff --git a/src/hooks/useSecurityWorkspace.ts b/src/hooks/useSecurityWorkspace.ts index f964a04..943ff3b 100644 --- a/src/hooks/useSecurityWorkspace.ts +++ b/src/hooks/useSecurityWorkspace.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { api, type SecurityPatch } from "../lib/api"; import { isCancelled, messageFrom } from "../lib/format"; -import type { JobProgress, ScanMode, SecurityStatus } from "../types"; +import type { AllowKind, JobProgress, ScanMode, SecurityStatus } from "../types"; function jobId(): string { return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; @@ -21,6 +21,11 @@ export interface SecurityWorkspace { restore: (id: string) => Promise; purge: (id: string) => Promise; dismiss: (findingId: string, ignored: boolean) => Promise; + trust: ( + findingId: string, + scope: "publisher" | "folder" | "evidence", + ) => Promise; + untrust: (kind: AllowKind, value: string) => Promise; exclude: (action: "add" | "remove", path: string) => Promise; updateRules: () => Promise; rollbackRules: () => Promise; @@ -158,6 +163,15 @@ export function useSecurityWorkspace(active: boolean): SecurityWorkspace { (findingId: string, ignored: boolean) => apply(() => api.securityIgnore(findingId, ignored)), [apply], ); + const trust = useCallback( + (findingId: string, scope: "publisher" | "folder" | "evidence") => + apply(() => api.securityTrust(findingId, scope)), + [apply], + ); + const untrust = useCallback( + (kind: AllowKind, value: string) => apply(() => api.securityUntrust(kind, value)), + [apply], + ); const exclude = useCallback( async (action: "add" | "remove", path: string) => { @@ -203,6 +217,8 @@ export function useSecurityWorkspace(active: boolean): SecurityWorkspace { restore, purge, dismiss, + trust, + untrust, exclude, updateRules, rollbackRules, diff --git a/src/lib/api.ts b/src/lib/api.ts index 166289d..c82eccb 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -18,6 +18,7 @@ import type { ScanResult, SettingsView, SecurityAction, + AllowKind, SecurityScan, SecuritySettings, SecurityStatus, @@ -131,6 +132,12 @@ export const api = { invoke("security_delete_quarantine", { id }), securityIgnore: (findingId: string, ignored: boolean) => invoke("security_ignore", { findingId, ignored }), + securityTrust: ( + findingId: string, + scope: "publisher" | "folder" | "evidence", + ) => invoke("security_trust", { findingId, scope }), + securityUntrust: (kind: AllowKind, value: string) => + invoke("security_untrust", { kind, value }), securityExclusions: (action: "add" | "remove", path: string) => invoke("security_exclusions", { action, path }), securitySettingsSave: (patch: SecurityPatch) => diff --git a/src/pages/ApplicationsPage.tsx b/src/pages/ApplicationsPage.tsx index 8e68ab0..b0e1c95 100644 --- a/src/pages/ApplicationsPage.tsx +++ b/src/pages/ApplicationsPage.tsx @@ -152,10 +152,6 @@ export function ApplicationsPage({
@@ -88,10 +84,6 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace } @@ -150,10 +142,6 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace } onClick={run}> {t("Start deep scan", "开始深度扫描")} diff --git a/src/pages/SecurityPage.tsx b/src/pages/SecurityPage.tsx index b13780f..5d07dbe 100644 --- a/src/pages/SecurityPage.tsx +++ b/src/pages/SecurityPage.tsx @@ -1,11 +1,13 @@ import { AlertTriangle, Ban, + BadgeCheck, CheckCircle2, Download, Eye, EyeOff, FolderOpen, + FolderCheck, FolderSearch, FolderX, HardDriveDownload, @@ -16,7 +18,7 @@ import { Trash2, Undo2, } from "lucide-react"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; @@ -35,7 +37,7 @@ import { useToast, } from "../components/ui"; -type Filter = "all" | Confidence | "quarantined"; +type Filter = "all" | Confidence | "quarantined" | "trusted"; const CONFIDENCE_META: Record = { confirmed: { tone: "danger", en: "Confirmed", zh: "已确认" }, @@ -43,6 +45,23 @@ const CONFIDENCE_META: Record = { + startup: ["Hide all startup notes", "隐藏所有登录启动提示"], + unsigned: ["Hide all unsigned notes", "隐藏所有未签名提示"], + writable: ["Hide all writable-location notes", "隐藏所有可写位置提示"], + missing: ["Hide all missing-target notes", "隐藏所有目标缺失提示"], +}; + +function trustableEvidenceKey(finding: Finding): string | null { + if (finding.confidence !== "advisory") return null; + const kinds = new Set(finding.evidence.map((item) => item.key.split(":")[0])); + if (kinds.size !== 1) return null; + const [kind] = [...kinds]; + return TRUSTABLE_EVIDENCE.has(kind) ? kind : null; +} + /** * Security: what protects this machine, what squid found, and what it is holding. * @@ -71,9 +90,17 @@ export function SecurityPage({ const findings = useMemo(() => { const all = scan?.findings ?? []; - if (filter === "all") return all.filter((finding) => !finding.ignored); + if (filter === "all") { + return all.filter((finding) => !finding.ignored && !finding.allowlisted); + } + if (filter === "trusted") { + return all.filter((finding) => !finding.ignored && finding.allowlisted); + } if (filter === "quarantined") return all.filter((finding) => finding.quarantined); - return all.filter((finding) => finding.confidence === filter && !finding.ignored); + return all.filter( + (finding) => + finding.confidence === filter && !finding.ignored && !finding.allowlisted, + ); }, [filter, scan]); /** @@ -84,16 +111,32 @@ export function SecurityPage({ */ const counts = useMemo(() => { const all = scan?.findings ?? []; - const open = all.filter((finding) => !finding.ignored); + const open = all.filter((finding) => !finding.ignored && !finding.allowlisted); return { all: open.length, confirmed: open.filter((f) => f.confidence === "confirmed").length, suspicious: open.filter((f) => f.confidence === "suspicious").length, advisory: open.filter((f) => f.confidence === "advisory").length, quarantined: all.filter((f) => f.quarantined).length, + trusted: all.filter((f) => !f.ignored && f.allowlisted).length, }; }, [scan]); + const filterOptions: [Filter, string, number][] = [ + ["all", t("All", "全部"), counts.all], + ["confirmed", t("Confirmed", "已确认"), counts.confirmed], + ["suspicious", t("Suspicious", "可疑"), counts.suspicious], + ["advisory", t("Advisory", "提示"), counts.advisory], + ["quarantined", t("Quarantined", "已隔离"), counts.quarantined], + ]; + if (counts.trusted > 0) { + filterOptions.push(["trusted", t("Trusted", "已信任"), counts.trusted]); + } + + useEffect(() => { + if (filter === "trusted" && counts.trusted === 0) setFilter("all"); + }, [counts.trusted, filter]); + const run = async (mode: "quick" | "full") => { try { await security.start(mode); @@ -130,15 +173,17 @@ export function SecurityPage({ } }; + const trust = (finding: Finding, scope: "publisher" | "folder" | "evidence") => { + setDetail(null); + void act(() => security.trust(finding.id, scope)); + }; + const detailEvidence = detail ? trustableEvidenceKey(detail) : null; + if (!status) { return (
{security.error ? : null}
@@ -153,10 +198,6 @@ export function SecurityPage({ ? t("The last scan, and what to do about it", "上次扫描的结果,以及下一步") : t("Nothing has been scanned yet", "还没有扫描过这台电脑") } - description={t( - "Scans run when you ask. Real-time protection stays with the system.", - "扫描只在你要求时运行,实时防护仍由系统负责。", - )} actions={ <> + detail && !detail.quarantined && !detail.allowlisted ? ( +
+ {!detail.allowlisted && detail.confidence !== "confirmed" ? ( + <> + {detail.signed && detail.publisher ? ( + + ) : null} + {detail.path ? ( + + ) : null} + {detailEvidence ? ( + + ) : null} + + ) : null} + {!detail.quarantined && detail.confidence === "confirmed" ? ( + + ) : null} +
) : null } > @@ -698,6 +787,7 @@ function FindingRow({ onOpen, onQuarantine, onDismiss, + onTrust, onExclude, onReveal, }: { @@ -706,13 +796,18 @@ function FindingRow({ onOpen: () => void; onQuarantine: () => void; onDismiss: (ignored: boolean) => void; + onTrust: () => void; onExclude: () => void; onReveal: () => void; }) { const { t } = useI18n(); const meta = CONFIDENCE_META[finding.confidence]; return ( -
  • +
  • - - {t(meta.en, meta.zh)} + + {finding.allowlisted ? t("Trusted", "已信任") : t(meta.en, meta.zh)} {finding.quarantined ? ` · ${t("held", "已隔离")}` : ""}
    @@ -736,8 +831,17 @@ function FindingRow({ ) : null} - {finding.quarantined ? null : ( + {finding.quarantined || finding.allowlisted ? null : ( <> + {finding.confidence !== "confirmed" && finding.path ? ( + + ) : null}