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        }
108        let content =
109            toml::to_string_pretty(self).map_err(|e| SeerError::ConfigError(e.to_string()))?;
110        let tmp_path = path.with_extension(format!("toml.{}.tmp", std::process::id()));
111        std::fs::write(&tmp_path, content).map_err(|e| SeerError::ConfigError(e.to_string()))?;
112        std::fs::rename(&tmp_path, &path).map_err(|e| {
113            let _ = std::fs::remove_file(&tmp_path);
114            SeerError::ConfigError(e.to_string())
115        })?;
116        Ok(())
117    }
118
119    /// Adds a domain to the watchlist. Returns `Ok(true)` if the domain was newly added.
120    pub fn add(&mut self, domain: &str) -> Result<bool> {
121        let domain = crate::validation::normalize_domain(domain)?;
122        if self.domains.contains(&domain) {
123            return Ok(false);
124        }
125        self.domains.push(domain);
126        self.domains.sort();
127        Ok(true)
128    }
129
130    /// Removes a domain from the watchlist. Returns `true` if the domain was present.
131    pub fn remove(&mut self, domain: &str) -> bool {
132        let domain =
133            crate::validation::normalize_domain(domain).unwrap_or_else(|_| domain.to_lowercase());
134        let len_before = self.domains.len();
135        self.domains.retain(|d| d != &domain);
136        self.domains.len() < len_before
137    }
138}
139
140/// Checks all given domains concurrently and produces a [`WatchReport`].
141pub async fn check_watchlist(domains: &[String]) -> WatchReport {
142    use futures::stream::{self, StreamExt};
143
144    let client = StatusClient::new();
145
146    let results: Vec<WatchResult> = stream::iter(domains)
147        .map(|domain| {
148            let client = &client;
149            async move {
150                let mut watch_result = WatchResult {
151                    domain: domain.clone(),
152                    ssl_days_remaining: None,
153                    domain_days_remaining: None,
154                    registrar: None,
155                    http_status: None,
156                    issues: vec![],
157                };
158
159                match client.check(domain).await {
160                    Ok(status) => {
161                        watch_result.http_status = status.http_status;
162
163                        if let Some(ref cert) = status.certificate {
164                            watch_result.ssl_days_remaining = Some(cert.days_until_expiry);
165                            if cert.days_until_expiry < 30 {
166                                watch_result.issues.push(format!(
167                                    "SSL expires in {} days",
168                                    cert.days_until_expiry
169                                ));
170                            }
171                            if !cert.is_valid {
172                                watch_result
173                                    .issues
174                                    .push("SSL certificate invalid".to_string());
175                            }
176                        }
177
178                        if let Some(ref exp) = status.domain_expiration {
179                            watch_result.domain_days_remaining = Some(exp.days_until_expiry);
180                            watch_result.registrar = exp.registrar.clone();
181                            if exp.days_until_expiry < 90 {
182                                watch_result.issues.push(format!(
183                                    "Domain expires in {} days",
184                                    exp.days_until_expiry
185                                ));
186                            }
187                        }
188
189                        if let Some(status_code) = status.http_status {
190                            if !(200..300).contains(&status_code) {
191                                watch_result
192                                    .issues
193                                    .push(format!("HTTP status {}", status_code));
194                            }
195                        }
196                    }
197                    Err(e) => {
198                        watch_result.issues.push(format!("Check failed: {}", e));
199                    }
200                }
201
202                watch_result
203            }
204        })
205        .buffer_unordered(10)
206        .collect()
207        .await;
208
209    let total = results.len();
210    // A result counts as critical if ANY of: SSL expires within 30 days,
211    // domain registration expires within 30 days, or an issue string mentions
212    // "invalid" / "failed". Flat OR of three predicates, evaluated
213    // independently — the previous version nested the numeric checks inside
214    // an `any()` over issue strings, which made the critical count depend
215    // on iteration order over `issues` and could short-circuit incorrectly.
216    let critical = results
217        .iter()
218        .filter(|r| {
219            let bad_ssl = r.ssl_days_remaining.is_some_and(|d| d < 30);
220            let bad_domain = r.domain_days_remaining.is_some_and(|d| d < 30);
221            let bad_issue = r
222                .issues
223                .iter()
224                .any(|i| i.contains("invalid") || i.contains("failed"));
225            bad_ssl || bad_domain || bad_issue
226        })
227        .count();
228    let warnings = results.iter().filter(|r| !r.issues.is_empty()).count();
229
230    WatchReport {
231        checked_at: Utc::now(),
232        results,
233        total,
234        warnings,
235        critical,
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    #[test]
244    fn test_watchlist_default() {
245        let wl = Watchlist::default();
246        assert!(wl.domains.is_empty());
247    }
248
249    #[test]
250    fn test_watchlist_add_remove() {
251        let mut wl = Watchlist::default();
252        assert!(wl.add("example.com").unwrap());
253        assert!(!wl.add("example.com").unwrap()); // duplicate
254        assert_eq!(wl.domains.len(), 1);
255
256        assert!(wl.add("test.org").unwrap());
257        assert_eq!(wl.domains.len(), 2);
258        // Should be sorted
259        assert_eq!(wl.domains[0], "example.com");
260        assert_eq!(wl.domains[1], "test.org");
261
262        assert!(wl.remove("example.com"));
263        assert!(!wl.remove("example.com")); // already removed
264        assert_eq!(wl.domains.len(), 1);
265    }
266
267    #[test]
268    fn test_watchlist_add_normalizes_case() {
269        let mut wl = Watchlist::default();
270        wl.add("EXAMPLE.COM").unwrap();
271        assert_eq!(wl.domains[0], "example.com");
272    }
273
274    #[test]
275    fn test_watchlist_serialization() {
276        let mut wl = Watchlist::default();
277        wl.add("a.com").unwrap();
278        wl.add("b.org").unwrap();
279        let toml_str = toml::to_string_pretty(&wl).unwrap();
280        assert!(toml_str.contains("a.com"));
281        assert!(toml_str.contains("b.org"));
282
283        let parsed: Watchlist = toml::from_str(&toml_str).unwrap();
284        assert_eq!(parsed.domains.len(), 2);
285    }
286
287    /// Creates a unique temporary file path for a load-from-disk test.
288    fn unique_temp_watchlist_path(tag: &str) -> PathBuf {
289        let mut dir = std::env::temp_dir();
290        dir.push(format!(
291            "seer-watchlist-test-{}-{}",
292            tag,
293            std::process::id()
294        ));
295        let _ = std::fs::create_dir_all(&dir);
296        dir.push("watchlist.toml");
297        dir
298    }
299
300    #[test]
301    fn load_from_path_returns_default_and_backs_up_corrupt_file() {
302        let path = unique_temp_watchlist_path("corrupt");
303        let backup = path.with_extension("corrupt");
304
305        let _ = std::fs::remove_file(&path);
306        let _ = std::fs::remove_file(&backup);
307
308        // TOML parsers reject stray garbage on the value side of `=`.
309        std::fs::write(&path, b"domains = not-an-array-\n").expect("seed corrupt watchlist file");
310
311        let loaded = Watchlist::load_from_path(&path);
312        assert!(
313            loaded.domains.is_empty(),
314            "corrupt watchlist must load as empty default"
315        );
316        assert!(
317            !path.exists(),
318            "original corrupt file should have been renamed away"
319        );
320        assert!(
321            backup.exists(),
322            "backup .corrupt file should exist at {}",
323            backup.display()
324        );
325
326        let _ = std::fs::remove_file(&backup);
327        if let Some(parent) = path.parent() {
328            let _ = std::fs::remove_dir_all(parent);
329        }
330    }
331
332    #[test]
333    fn load_from_path_returns_default_when_missing() {
334        let path = unique_temp_watchlist_path("missing");
335        let _ = std::fs::remove_file(&path);
336
337        let loaded = Watchlist::load_from_path(&path);
338        assert!(loaded.domains.is_empty());
339
340        if let Some(parent) = path.parent() {
341            let _ = std::fs::remove_dir_all(parent);
342        }
343    }
344
345    #[test]
346    fn test_watch_result_serialization() {
347        let result = WatchResult {
348            domain: "example.com".to_string(),
349            ssl_days_remaining: Some(45),
350            domain_days_remaining: Some(120),
351            registrar: Some("Test Registrar".to_string()),
352            http_status: Some(200),
353            issues: vec![],
354        };
355        let json = serde_json::to_string(&result).unwrap();
356        assert!(json.contains("example.com"));
357        assert!(json.contains("45"));
358    }
359}