Skip to main content

seer_core/
watchlist.rs

1//! Domain watchlist for monitoring expiration and health.
2//!
3//! Loads a list of domains from `~/.seer/watchlist.toml` and checks their
4//! SSL certificates, domain expiration, and HTTP status.
5
6use std::path::PathBuf;
7
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11use crate::error::{Result, SeerError};
12use crate::status::StatusClient;
13
14/// Persistent list of domains to monitor.
15#[derive(Debug, Clone, Default, Serialize, Deserialize)]
16pub struct Watchlist {
17    #[serde(default)]
18    pub domains: Vec<String>,
19}
20
21/// Status result for a single watched domain.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct WatchResult {
24    pub domain: String,
25    pub ssl_days_remaining: Option<i64>,
26    pub domain_days_remaining: Option<i64>,
27    pub registrar: Option<String>,
28    pub http_status: Option<u16>,
29    pub issues: Vec<String>,
30}
31
32/// Aggregated report from checking all watched domains.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct WatchReport {
35    pub checked_at: DateTime<Utc>,
36    pub results: Vec<WatchResult>,
37    pub total: usize,
38    pub warnings: usize,
39    pub critical: usize,
40}
41
42impl Watchlist {
43    /// Returns the path to the watchlist file (`~/.seer/watchlist.toml`).
44    pub fn path() -> Option<PathBuf> {
45        dirs::home_dir().map(|h| h.join(".seer").join("watchlist.toml"))
46    }
47
48    /// Loads the watchlist from disk, returning an empty list on any failure.
49    ///
50    /// When the file exists but fails to parse, it is renamed to
51    /// `<path>.corrupt` (preserving the user's data for recovery/forensics)
52    /// and a warning is logged — previously the file was silently
53    /// overwritten on the next save, dropping the user's watchlist.
54    pub fn load() -> Self {
55        let Some(path) = Self::path() else {
56            return Self::default();
57        };
58        Self::load_from_path(&path)
59    }
60
61    /// Like [`Self::load`] but reads from an explicit path. Split out so
62    /// tests can exercise the corrupt-file handling without depending on
63    /// the real `~/.seer/watchlist.toml` location.
64    pub(crate) fn load_from_path(path: &std::path::Path) -> Self {
65        if !path.exists() {
66            return Self::default();
67        }
68        match std::fs::read_to_string(path) {
69            Ok(content) => match toml::from_str::<Watchlist>(&content) {
70                Ok(w) => w,
71                Err(e) => {
72                    let backup = path.with_extension("corrupt");
73                    if let Err(rename_err) = std::fs::rename(path, &backup) {
74                        tracing::error!(
75                            path = %path.display(),
76                            error = %rename_err,
77                            "failed to back up corrupt watchlist",
78                        );
79                    } else {
80                        tracing::warn!(
81                            path = %path.display(),
82                            backup = %backup.display(),
83                            error = %e,
84                            "watchlist file corrupt; moved to backup",
85                        );
86                    }
87                    Watchlist::default()
88                }
89            },
90            Err(_) => Self::default(),
91        }
92    }
93
94    /// Persists the watchlist to disk via write-and-rename so a crash mid-write
95    /// cannot leave the file truncated (the next `load()` would see corrupt
96    /// TOML and silently fall back to the default empty watchlist, losing
97    /// the user's domains). Mirrors `LookupHistory::save`.
98    ///
99    /// The temp filename is suffixed with the current PID so two concurrent
100    /// `seer` processes don't write to the same intermediate path and race
101    /// each other's `rename`s.
102    pub fn save(&self) -> Result<()> {
103        let path = Self::path()
104            .ok_or_else(|| SeerError::ConfigError("Cannot determine home directory".to_string()))?;
105        if let Some(parent) = path.parent() {
106            std::fs::create_dir_all(parent).map_err(|e| SeerError::ConfigError(e.to_string()))?;
107            #[cfg(unix)]
108            {
109                use std::os::unix::fs::PermissionsExt;
110                let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
111            }
112        }
113        let content =
114            toml::to_string_pretty(self).map_err(|e| SeerError::ConfigError(e.to_string()))?;
115        let tmp_path = path.with_extension(format!("toml.{}.tmp", std::process::id()));
116        std::fs::write(&tmp_path, content).map_err(|e| SeerError::ConfigError(e.to_string()))?;
117        #[cfg(unix)]
118        {
119            use std::os::unix::fs::PermissionsExt;
120            let _ = std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600));
121        }
122        std::fs::rename(&tmp_path, &path).map_err(|e| {
123            let _ = std::fs::remove_file(&tmp_path);
124            SeerError::ConfigError(e.to_string())
125        })?;
126        Ok(())
127    }
128
129    /// Adds a domain to the watchlist. Returns `Ok(true)` if the domain was newly added.
130    pub fn add(&mut self, domain: &str) -> Result<bool> {
131        let domain = crate::validation::normalize_domain(domain)?;
132        if self.domains.contains(&domain) {
133            return Ok(false);
134        }
135        self.domains.push(domain);
136        self.domains.sort();
137        Ok(true)
138    }
139
140    /// Removes a domain from the watchlist. Returns `true` if the domain was present.
141    pub fn remove(&mut self, domain: &str) -> bool {
142        let domain =
143            crate::validation::normalize_domain(domain).unwrap_or_else(|_| domain.to_lowercase());
144        let len_before = self.domains.len();
145        self.domains.retain(|d| d != &domain);
146        self.domains.len() < len_before
147    }
148}
149
150/// Checks all given domains concurrently and produces a [`WatchReport`].
151pub async fn check_watchlist(domains: &[String]) -> WatchReport {
152    use futures::stream::{self, StreamExt};
153
154    let client = StatusClient::new();
155
156    let results: Vec<WatchResult> = stream::iter(domains)
157        .map(|domain| {
158            let client = &client;
159            async move {
160                let mut watch_result = WatchResult {
161                    domain: domain.clone(),
162                    ssl_days_remaining: None,
163                    domain_days_remaining: None,
164                    registrar: None,
165                    http_status: None,
166                    issues: vec![],
167                };
168
169                match client.check(domain).await {
170                    Ok(status) => {
171                        watch_result.http_status = status.http_status;
172
173                        if let Some(ref cert) = status.certificate {
174                            watch_result.ssl_days_remaining = Some(cert.days_until_expiry);
175                            if cert.days_until_expiry < 30 {
176                                watch_result.issues.push(format!(
177                                    "SSL expires in {} days",
178                                    cert.days_until_expiry
179                                ));
180                            }
181                            if !cert.is_valid {
182                                watch_result
183                                    .issues
184                                    .push("SSL certificate invalid".to_string());
185                            }
186                        }
187
188                        if let Some(ref exp) = status.domain_expiration {
189                            watch_result.domain_days_remaining = Some(exp.days_until_expiry);
190                            watch_result.registrar = exp.registrar.clone();
191                            if exp.days_until_expiry < 90 {
192                                watch_result.issues.push(format!(
193                                    "Domain expires in {} days",
194                                    exp.days_until_expiry
195                                ));
196                            }
197                        }
198
199                        if let Some(status_code) = status.http_status {
200                            if !(200..300).contains(&status_code) {
201                                watch_result
202                                    .issues
203                                    .push(format!("HTTP status {}", status_code));
204                            }
205                        }
206                    }
207                    Err(e) => {
208                        watch_result.issues.push(format!("Check failed: {}", e));
209                    }
210                }
211
212                watch_result
213            }
214        })
215        .buffer_unordered(10)
216        .collect()
217        .await;
218
219    let total = results.len();
220    // A result counts as critical if ANY of: SSL expires within 30 days,
221    // domain registration expires within 30 days, or an issue string mentions
222    // "invalid" / "failed". Flat OR of three predicates, evaluated
223    // independently — the previous version nested the numeric checks inside
224    // an `any()` over issue strings, which made the critical count depend
225    // on iteration order over `issues` and could short-circuit incorrectly.
226    let critical = results
227        .iter()
228        .filter(|r| {
229            let bad_ssl = r.ssl_days_remaining.is_some_and(|d| d < 30);
230            let bad_domain = r.domain_days_remaining.is_some_and(|d| d < 30);
231            let bad_issue = r
232                .issues
233                .iter()
234                .any(|i| i.contains("invalid") || i.contains("failed"));
235            bad_ssl || bad_domain || bad_issue
236        })
237        .count();
238    let warnings = results.iter().filter(|r| !r.issues.is_empty()).count();
239
240    WatchReport {
241        checked_at: Utc::now(),
242        results,
243        total,
244        warnings,
245        critical,
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_watchlist_default() {
255        let wl = Watchlist::default();
256        assert!(wl.domains.is_empty());
257    }
258
259    #[test]
260    fn test_watchlist_add_remove() {
261        let mut wl = Watchlist::default();
262        assert!(wl.add("example.com").unwrap());
263        assert!(!wl.add("example.com").unwrap()); // duplicate
264        assert_eq!(wl.domains.len(), 1);
265
266        assert!(wl.add("test.org").unwrap());
267        assert_eq!(wl.domains.len(), 2);
268        // Should be sorted
269        assert_eq!(wl.domains[0], "example.com");
270        assert_eq!(wl.domains[1], "test.org");
271
272        assert!(wl.remove("example.com"));
273        assert!(!wl.remove("example.com")); // already removed
274        assert_eq!(wl.domains.len(), 1);
275    }
276
277    #[test]
278    fn test_watchlist_add_normalizes_case() {
279        let mut wl = Watchlist::default();
280        wl.add("EXAMPLE.COM").unwrap();
281        assert_eq!(wl.domains[0], "example.com");
282    }
283
284    #[test]
285    fn test_watchlist_serialization() {
286        let mut wl = Watchlist::default();
287        wl.add("a.com").unwrap();
288        wl.add("b.org").unwrap();
289        let toml_str = toml::to_string_pretty(&wl).unwrap();
290        assert!(toml_str.contains("a.com"));
291        assert!(toml_str.contains("b.org"));
292
293        let parsed: Watchlist = toml::from_str(&toml_str).unwrap();
294        assert_eq!(parsed.domains.len(), 2);
295    }
296
297    /// Creates a unique temporary file path for a load-from-disk test.
298    fn unique_temp_watchlist_path(tag: &str) -> PathBuf {
299        let mut dir = std::env::temp_dir();
300        dir.push(format!(
301            "seer-watchlist-test-{}-{}",
302            tag,
303            std::process::id()
304        ));
305        let _ = std::fs::create_dir_all(&dir);
306        dir.push("watchlist.toml");
307        dir
308    }
309
310    #[test]
311    fn load_from_path_returns_default_and_backs_up_corrupt_file() {
312        let path = unique_temp_watchlist_path("corrupt");
313        let backup = path.with_extension("corrupt");
314
315        let _ = std::fs::remove_file(&path);
316        let _ = std::fs::remove_file(&backup);
317
318        // TOML parsers reject stray garbage on the value side of `=`.
319        std::fs::write(&path, b"domains = not-an-array-\n").expect("seed corrupt watchlist file");
320
321        let loaded = Watchlist::load_from_path(&path);
322        assert!(
323            loaded.domains.is_empty(),
324            "corrupt watchlist must load as empty default"
325        );
326        assert!(
327            !path.exists(),
328            "original corrupt file should have been renamed away"
329        );
330        assert!(
331            backup.exists(),
332            "backup .corrupt file should exist at {}",
333            backup.display()
334        );
335
336        let _ = std::fs::remove_file(&backup);
337        if let Some(parent) = path.parent() {
338            let _ = std::fs::remove_dir_all(parent);
339        }
340    }
341
342    #[test]
343    fn load_from_path_returns_default_when_missing() {
344        let path = unique_temp_watchlist_path("missing");
345        let _ = std::fs::remove_file(&path);
346
347        let loaded = Watchlist::load_from_path(&path);
348        assert!(loaded.domains.is_empty());
349
350        if let Some(parent) = path.parent() {
351            let _ = std::fs::remove_dir_all(parent);
352        }
353    }
354
355    #[test]
356    fn test_watch_result_serialization() {
357        let result = WatchResult {
358            domain: "example.com".to_string(),
359            ssl_days_remaining: Some(45),
360            domain_days_remaining: Some(120),
361            registrar: Some("Test Registrar".to_string()),
362            http_status: Some(200),
363            issues: vec![],
364        };
365        let json = serde_json::to_string(&result).unwrap();
366        assert!(json.contains("example.com"));
367        assert!(json.contains("45"));
368    }
369}