adler-core 0.6.0

Core engine for the Adler OSINT username-search tool.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Cross-run result cache.
//!
//! Re-running a scan minutes apart should not re-hit every site. The cache
//! persists `Found` / `NotFound` verdicts keyed by `(site name, username)`
//! and guarded by:
//!
//! - a **TTL**: entries older than the configured age are ignored (and
//!   pruned on load), and
//! - a **site signature**: a deterministic hash of the site's URL template
//!   and signal list. If the site definition changes, its old cache entries
//!   no longer match and are treated as misses.
//!
//! `Uncertain` outcomes are intentionally never cached — they're transient
//! (rate limits, network blips) and caching them would freeze a temporary
//! failure for the whole TTL window.
//!
//! Access pattern is bulk: [`Cache::load`] once at scan start, in-memory
//! [`Cache::get`] / [`Cache::put`] during the scan, [`Cache::save`] once at
//! the end. There are no concurrent disk writes, so a plain JSON file with
//! an atomic temp-then-rename save is enough — no embedded database needed.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::check::{CheckOutcome, MatchKind};
use crate::error::Result;
use crate::site::Site;
use crate::username::Username;

const CACHE_VERSION: u32 = 1;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

/// In-memory cache backed by a JSON file.
#[derive(Debug)]
pub struct Cache {
    path: PathBuf,
    ttl: Duration,
    entries: HashMap<(String, String), Entry>,
    dirty: bool,
}

#[derive(Debug, Clone)]
struct Entry {
    signature: u64,
    stored_at: u64,
    outcome: CheckOutcome,
}

#[derive(Serialize, Deserialize)]
struct StoredEntry {
    site: String,
    username: String,
    signature: u64,
    stored_at: u64,
    outcome: CheckOutcome,
}

#[derive(Serialize, Deserialize)]
struct CacheFile {
    version: u32,
    entries: Vec<StoredEntry>,
}

impl Cache {
    /// Load a cache from `path`, dropping entries older than `ttl`.
    ///
    /// Infallible: a missing, unreadable, or corrupt file yields an empty
    /// cache (a warning is logged). The cache should never be the reason a
    /// scan fails.
    pub fn load(path: PathBuf, ttl: Duration) -> Self {
        let mut cache = Self {
            path,
            ttl,
            entries: HashMap::new(),
            dirty: false,
        };
        let bytes = match std::fs::read(&cache.path) {
            Ok(b) => b,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return cache,
            Err(err) => {
                tracing::warn!(error = %err, path = %cache.path.display(), "cache read failed");
                return cache;
            }
        };
        let parsed: CacheFile = match serde_json::from_slice(&bytes) {
            Ok(f) => f,
            Err(err) => {
                tracing::warn!(error = %err, "cache file corrupt; starting empty");
                return cache;
            }
        };
        if parsed.version != CACHE_VERSION {
            tracing::info!(
                found = parsed.version,
                expected = CACHE_VERSION,
                "cache version mismatch; starting empty"
            );
            return cache;
        }
        let now = now_unix();
        let ttl_secs = ttl.as_secs();
        for stored in parsed.entries {
            if now.saturating_sub(stored.stored_at) > ttl_secs {
                cache.dirty = true; // expired entry pruned; persist the smaller file
                continue;
            }
            cache.entries.insert(
                (stored.site, stored.username),
                Entry {
                    signature: stored.signature,
                    stored_at: stored.stored_at,
                    outcome: stored.outcome,
                },
            );
        }
        cache
    }

    /// Look up a cached outcome for `site` + `username`.
    ///
    /// Returns `None` on a miss, a TTL expiry, or a site-signature mismatch
    /// (the site definition changed since the entry was stored).
    pub fn get(&self, site: &Site, username: &Username) -> Option<CheckOutcome> {
        let key = (site.name.clone(), username.as_str().to_owned());
        let entry = self.entries.get(&key)?;
        if entry.signature != signature(site) {
            return None;
        }
        if now_unix().saturating_sub(entry.stored_at) > self.ttl.as_secs() {
            return None;
        }
        Some(entry.outcome.clone())
    }

    /// Store an outcome. `Uncertain` outcomes are ignored (not cached).
    pub fn put(&mut self, site: &Site, username: &Username, outcome: CheckOutcome) {
        if matches!(outcome.kind, MatchKind::Uncertain) {
            return;
        }
        let key = (site.name.clone(), username.as_str().to_owned());
        self.entries.insert(
            key,
            Entry {
                signature: signature(site),
                stored_at: now_unix(),
                outcome,
            },
        );
        self.dirty = true;
    }

    /// Persist the cache to disk if anything changed since load. Writes
    /// atomically (temp file + rename) and creates parent directories.
    pub fn save(&self) -> Result<()> {
        if !self.dirty {
            return Ok(());
        }
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut entries: Vec<StoredEntry> = self
            .entries
            .iter()
            .map(|((site, username), entry)| StoredEntry {
                site: site.clone(),
                username: username.clone(),
                signature: entry.signature,
                stored_at: entry.stored_at,
                outcome: entry.outcome.clone(),
            })
            .collect();
        entries.sort_by(|a, b| {
            a.site
                .cmp(&b.site)
                .then_with(|| a.username.cmp(&b.username))
        });
        let file = CacheFile {
            version: CACHE_VERSION,
            entries,
        };
        let json = serde_json::to_string_pretty(&file)?;
        let tmp = self.path.with_extension("json.tmp");
        std::fs::write(&tmp, json)?;
        std::fs::rename(&tmp, &self.path)?;
        Ok(())
    }

    /// Number of live entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// True if the cache has no entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Delete the cache file at `path`. A missing file is not an error.
    pub fn clear(path: &Path) -> Result<()> {
        match std::fs::remove_file(path) {
            Ok(()) => Ok(()),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(err) => Err(err.into()),
        }
    }

    /// Default cache file location: `$XDG_CACHE_HOME/adler/cache.json`,
    /// falling back to `$HOME/.cache/adler/cache.json`, then a relative
    /// path if neither env var is set.
    pub fn default_path() -> PathBuf {
        if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") {
            return PathBuf::from(xdg).join("adler").join("cache.json");
        }
        if let Some(home) = std::env::var_os("HOME") {
            return PathBuf::from(home)
                .join(".cache")
                .join("adler")
                .join("cache.json");
        }
        PathBuf::from("adler-cache.json")
    }
}

/// Deterministic FNV-1a hash of a site's URL template and signal list.
///
/// Must be stable across processes, so we cannot use the std `DefaultHasher`
/// (it's randomly seeded). FNV-1a over the serialized signals + URL is
/// deterministic and collision-resistant enough for cache invalidation.
fn signature(site: &Site) -> u64 {
    let signals = serde_json::to_string(&site.signals).unwrap_or_default();
    let mut hash = FNV_OFFSET;
    for byte in site.url.as_str().bytes().chain(signals.bytes()) {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::site::{Signal, UrlTemplate};

    fn site(name: &str) -> Site {
        Site {
            name: name.into(),
            url: UrlTemplate::new("https://example.com/{username}").unwrap(),
            signals: vec![Signal::StatusFound { codes: vec![200] }],
            known_present: None,
            known_absent: None,
            extract: Vec::new(),
            tags: Vec::new(),
            request_headers: std::collections::BTreeMap::new(),
            regex_check: None,
            engine: None,
        }
    }

    fn outcome(kind: MatchKind) -> CheckOutcome {
        CheckOutcome {
            site: "Example".into(),
            url: "https://example.com/alice".into(),
            kind,
            reason: None,
            elapsed_ms: 5,
            enrichment: std::collections::BTreeMap::new(),
            evidence: Vec::new(),
        }
    }

    fn tmp_path(tag: &str) -> PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!(
            "adler-cache-test-{tag}-{}.json",
            std::process::id()
        ));
        p
    }

    fn empty_cache(ttl: Duration) -> Cache {
        Cache {
            path: tmp_path("mem"),
            ttl,
            entries: HashMap::new(),
            dirty: false,
        }
    }

    #[test]
    fn put_then_get_round_trips() {
        let mut cache = empty_cache(Duration::from_secs(3600));
        let s = site("Example");
        let user = Username::new("alice").unwrap();
        cache.put(&s, &user, outcome(MatchKind::Found));
        let got = cache.get(&s, &user).unwrap();
        assert_eq!(got.kind, MatchKind::Found);
    }

    #[test]
    fn uncertain_is_not_cached() {
        let mut cache = empty_cache(Duration::from_secs(3600));
        let s = site("Example");
        let user = Username::new("alice").unwrap();
        cache.put(&s, &user, outcome(MatchKind::Uncertain));
        assert!(cache.get(&s, &user).is_none());
        assert!(cache.is_empty());
    }

    #[test]
    fn get_misses_on_different_username() {
        let mut cache = empty_cache(Duration::from_secs(3600));
        let s = site("Example");
        cache.put(
            &s,
            &Username::new("alice").unwrap(),
            outcome(MatchKind::Found),
        );
        assert!(cache.get(&s, &Username::new("bob").unwrap()).is_none());
    }

    #[test]
    fn get_misses_when_signature_changes() {
        let mut cache = empty_cache(Duration::from_secs(3600));
        let s = site("Example");
        let user = Username::new("alice").unwrap();
        cache.put(&s, &user, outcome(MatchKind::Found));

        // Same name, different signals → different signature → miss.
        let mut changed = site("Example");
        changed.signals = vec![Signal::StatusNotFound { codes: vec![404] }];
        assert!(cache.get(&changed, &user).is_none());
    }

    #[test]
    fn get_misses_on_expired_entry() {
        let mut cache = empty_cache(Duration::from_secs(0));
        let s = site("Example");
        let user = Username::new("alice").unwrap();
        // stored_at = now, ttl = 0 → already expired (now - stored_at > 0 is
        // false at the same second, so force an old timestamp).
        cache.entries.insert(
            ("Example".into(), "alice".into()),
            Entry {
                signature: signature(&s),
                stored_at: now_unix().saturating_sub(10),
                outcome: outcome(MatchKind::Found),
            },
        );
        assert!(cache.get(&s, &user).is_none());
    }

    #[test]
    fn save_and_load_round_trip() {
        let path = tmp_path("roundtrip");
        let _ = std::fs::remove_file(&path);
        let s = site("Example");
        let user = Username::new("alice").unwrap();
        {
            let mut cache = Cache::load(path.clone(), Duration::from_secs(3600));
            cache.put(&s, &user, outcome(MatchKind::Found));
            cache.save().unwrap();
        }
        let reloaded = Cache::load(path.clone(), Duration::from_secs(3600));
        let got = reloaded.get(&s, &user).unwrap();
        assert_eq!(got.kind, MatchKind::Found);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn load_drops_expired_entries() {
        let path = tmp_path("expiry");
        // Write a cache file by hand with a stored_at two hours in the past.
        let file = CacheFile {
            version: CACHE_VERSION,
            entries: vec![StoredEntry {
                site: "Example".into(),
                username: "alice".into(),
                signature: signature(&site("Example")),
                stored_at: now_unix().saturating_sub(7200),
                outcome: outcome(MatchKind::Found),
            }],
        };
        std::fs::write(&path, serde_json::to_string(&file).unwrap()).unwrap();
        // TTL of 1 hour → the 2-hour-old entry is pruned.
        let reloaded = Cache::load(path.clone(), Duration::from_secs(3600));
        assert!(reloaded.is_empty());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn corrupt_file_yields_empty_cache() {
        let path = tmp_path("corrupt");
        std::fs::write(&path, b"this is not json {{{").unwrap();
        let cache = Cache::load(path.clone(), Duration::from_secs(3600));
        assert!(cache.is_empty());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn clear_removes_file_and_tolerates_missing() {
        let path = tmp_path("clear");
        std::fs::write(&path, b"{}").unwrap();
        Cache::clear(&path).unwrap();
        assert!(!path.exists());
        // Second clear on a missing file is fine.
        Cache::clear(&path).unwrap();
    }

    #[test]
    fn signature_is_deterministic() {
        let s = site("Example");
        assert_eq!(signature(&s), signature(&s));
    }
}