upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/sync/naughty_list.rs
blob: 35fcc0f97a292b8e5a6390765bf3e91cc96f1327 (plain)
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Naughty List Tracker for Remote Servers with Persistent Infrastructure Issues
//!
//! This module tracks remote servers (Nostr relays and git remote domains) with
//! persistent configuration/infrastructure problems (DNS failures, TLS certificate
//! errors, protocol violations) separately from transient network issues (timeouts,
//! connection refused).
//!
//! ## Failure Classification
//!
//! **Naughty List (12-hour expiration, log WARN on first occurrence, DEBUG on repeat):**
//! - `DnsLookupFailed`: Domain doesn't resolve or DNS errors
//! - `TlsCertificateInvalid`: Certificate errors (expired, mismatch, self-signed)
//! - `ProtocolError`: WebSocket/Nostr protocol violations
//!
//! **NOT Naughty (use existing HealthTracker backoff):**
//! - Connection timeouts (could be network congestion)
//! - Connection refused (could be temporary maintenance)
//!
//! ## Automatic Expiration
//!
//! Entries expire after 12 hours (configurable) to allow relays to recover from
//! infrastructure issues. After expiration, the relay is automatically retried.

use dashmap::DashMap;
use std::time::Instant;

/// Category of persistent remote server failure that qualifies for the naughty list
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NaughtyCategory {
    /// DNS lookup failures (domain doesn't resolve)
    DnsLookupFailed,
    /// TLS certificate errors (expired, invalid, mismatch)
    TlsCertificateInvalid,
    /// WebSocket or Nostr protocol violations (relay-specific, won't trigger for git)
    ProtocolError,
}

impl NaughtyCategory {
    /// Get string representation for metrics labels
    pub fn as_str(&self) -> &'static str {
        match self {
            NaughtyCategory::DnsLookupFailed => "dns_lookup_failed",
            NaughtyCategory::TlsCertificateInvalid => "tls_certificate_invalid",
            NaughtyCategory::ProtocolError => "protocol_error",
        }
    }
}

impl std::fmt::Display for NaughtyCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Naughty list entry for a remote server (relay URL or git domain) with persistent issues
#[derive(Debug, Clone)]
pub struct NaughtyEntry {
    /// Category of the persistent failure
    pub category: NaughtyCategory,
    /// Full error message
    pub reason: String,
    /// When this relay was first added to the naughty list
    pub first_seen: Instant,
    /// Most recent occurrence of the issue
    pub last_seen: Instant,
    /// Number of times we've seen this issue
    pub occurrence_count: u32,
}

/// Tracks remote servers with persistent infrastructure/configuration issues
///
/// Used for both:
/// - Nostr relay URLs (e.g., "wss://relay.example.com")
/// - Git remote domains (e.g., "git.example.com")
///
/// Separate from HealthTracker's backoff logic - this is specifically for
/// servers with configuration problems that are unlikely to be fixed quickly.
#[derive(Debug)]
pub struct NaughtyListTracker {
    /// Map of relay URL or git domain to naughty entry
    entries: DashMap<String, NaughtyEntry>,
    /// How many hours before removing a server from the naughty list
    expiration_hours: u64,
}

impl NaughtyListTracker {
    /// Create a new NaughtyListTracker with the specified expiration time
    ///
    /// # Arguments
    ///
    /// * `expiration_hours` - Hours before a naughty entry expires (default: 12)
    pub fn new(expiration_hours: u64) -> Self {
        Self {
            entries: DashMap::new(),
            expiration_hours,
        }
    }

    /// Create a new NaughtyListTracker with default 12-hour expiration
    pub fn with_defaults() -> Self {
        Self::new(12)
    }

    /// Classify an error string into a naughty category or return None for transient errors
    ///
    /// # Arguments
    ///
    /// * `error` - The error message string to classify
    ///
    /// # Returns
    ///
    /// - `Some(NaughtyCategory)` if the error indicates a persistent infrastructure issue
    /// - `None` if the error is a transient network issue (use HealthTracker backoff)
    pub fn classify_error(error: &str) -> Option<NaughtyCategory> {
        let error_lower = error.to_lowercase();

        // DNS lookup failures
        if error_lower.contains("failed to lookup address")
            || error_lower.contains("name or service not known")
            || error_lower.contains("nodename nor servname provided")
            || (error_lower.contains("dns") && !error_lower.contains("timeout"))
        {
            return Some(NaughtyCategory::DnsLookupFailed);
        }

        // TLS certificate errors
        if error_lower.contains("certificate")
            || error_lower.contains("ssl")
            || error_lower.contains("tls")
        {
            // Exclude timeout errors that mention TLS
            if !error_lower.contains("timeout") && !error_lower.contains("timed out") {
                return Some(NaughtyCategory::TlsCertificateInvalid);
            }
        }

        // Protocol errors
        if error_lower.contains("websocket")
            || error_lower.contains("protocol")
            || error_lower.contains("invalid frame")
        {
            // Exclude connection errors
            if !error_lower.contains("connection")
                && !error_lower.contains("timeout")
                && !error_lower.contains("refused")
            {
                return Some(NaughtyCategory::ProtocolError);
            }
        }

        // Everything else is transient (timeouts, refused, etc.)
        None
    }

    /// Record a naughty server (adds new entry or updates existing)
    ///
    /// # Arguments
    ///
    /// * `server_url_or_domain` - The relay URL or git domain
    /// * `category` - The naughty category
    /// * `reason` - The full error message
    ///
    /// # Returns
    ///
    /// `true` if this is a new naughty entry (first occurrence), `false` if updating existing
    pub fn record(
        &self,
        server_url_or_domain: &str,
        category: NaughtyCategory,
        reason: String,
    ) -> bool {
        let now = Instant::now();

        if let Some(mut entry) = self.entries.get_mut(server_url_or_domain) {
            // Update existing entry
            entry.last_seen = now;
            entry.occurrence_count = entry.occurrence_count.saturating_add(1);
            entry.reason = reason; // Update with latest error message
            false
        } else {
            // Create new entry
            self.entries.insert(
                server_url_or_domain.to_string(),
                NaughtyEntry {
                    category,
                    reason,
                    first_seen: now,
                    last_seen: now,
                    occurrence_count: 1,
                },
            );
            true
        }
    }

    /// Check if a server is on the naughty list (not expired)
    ///
    /// # Arguments
    ///
    /// * `server_url_or_domain` - The relay URL or git domain to check
    ///
    /// # Returns
    ///
    /// `true` if the server is currently on the naughty list
    pub fn is_naughty(&self, server_url_or_domain: &str) -> bool {
        if let Some(entry) = self.entries.get(server_url_or_domain) {
            let age = Instant::now().duration_since(entry.first_seen);
            let expiration = std::time::Duration::from_secs(self.expiration_hours * 3600);
            age < expiration
        } else {
            false
        }
    }

    /// Get a naughty entry if it exists and hasn't expired
    ///
    /// # Arguments
    ///
    /// * `server_url_or_domain` - The relay URL or git domain to look up
    ///
    /// # Returns
    ///
    /// A cloned `NaughtyEntry` if the server is on the naughty list and not expired
    pub fn get_entry(&self, server_url_or_domain: &str) -> Option<NaughtyEntry> {
        self.entries.get(server_url_or_domain).map(|e| e.clone())
    }

    /// Remove expired entries from the naughty list
    ///
    /// Entries older than `expiration_hours` are removed to allow servers
    /// to be retried after infrastructure issues are potentially fixed.
    ///
    /// # Returns
    ///
    /// Vector of server URLs/domains that were removed from the naughty list
    pub fn expire_old_entries(&self) -> Vec<String> {
        let now = Instant::now();
        let expiration = std::time::Duration::from_secs(self.expiration_hours * 3600);
        let mut expired = Vec::new();

        // Collect expired relay URLs
        self.entries.retain(|url, entry| {
            let age = now.duration_since(entry.first_seen);
            if age >= expiration {
                expired.push(url.clone());
                false // Remove this entry
            } else {
                true // Keep this entry
            }
        });

        expired
    }

    /// Get all naughty servers (for metrics and monitoring)
    ///
    /// # Returns
    ///
    /// Vector of (server_url_or_domain, entry) tuples for all servers currently on the naughty list
    pub fn get_all(&self) -> Vec<(String, NaughtyEntry)> {
        self.entries
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().clone()))
            .collect()
    }

    /// Get the count of servers in a specific category
    ///
    /// # Arguments
    ///
    /// * `category` - The category to count
    ///
    /// # Returns
    ///
    /// Number of servers in the specified category
    pub fn count_by_category(&self, category: NaughtyCategory) -> usize {
        self.entries
            .iter()
            .filter(|entry| entry.value().category == category)
            .count()
    }

    /// Get total number of servers on the naughty list
    pub fn total_count(&self) -> usize {
        self.entries.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_classify_dns_errors() {
        assert_eq!(
            NaughtyListTracker::classify_error("failed to lookup address information"),
            Some(NaughtyCategory::DnsLookupFailed)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("Name or service not known"),
            Some(NaughtyCategory::DnsLookupFailed)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("nodename nor servname provided"),
            Some(NaughtyCategory::DnsLookupFailed)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("dns error: NXDOMAIN"),
            Some(NaughtyCategory::DnsLookupFailed)
        );
    }

    #[test]
    fn test_classify_tls_errors() {
        assert_eq!(
            NaughtyListTracker::classify_error("certificate not valid for 'example.com'"),
            Some(NaughtyCategory::TlsCertificateInvalid)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("SSL certificate problem"),
            Some(NaughtyCategory::TlsCertificateInvalid)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("TLS handshake failed"),
            Some(NaughtyCategory::TlsCertificateInvalid)
        );

        // TLS timeout should NOT be classified as naughty
        assert_eq!(
            NaughtyListTracker::classify_error("TLS connection timed out"),
            None
        );
    }

    #[test]
    fn test_classify_protocol_errors() {
        assert_eq!(
            NaughtyListTracker::classify_error("websocket protocol error"),
            Some(NaughtyCategory::ProtocolError)
        );
        assert_eq!(
            NaughtyListTracker::classify_error("invalid frame header"),
            Some(NaughtyCategory::ProtocolError)
        );

        // WebSocket connection errors should NOT be classified as naughty
        assert_eq!(
            NaughtyListTracker::classify_error("websocket connection refused"),
            None
        );
    }

    #[test]
    fn test_classify_transient_errors() {
        // Timeouts are transient
        assert_eq!(
            NaughtyListTracker::classify_error("connection timed out"),
            None
        );
        assert_eq!(
            NaughtyListTracker::classify_error("operation timed out"),
            None
        );

        // Connection refused is transient
        assert_eq!(
            NaughtyListTracker::classify_error("connection refused"),
            None
        );

        // Generic network errors are transient
        assert_eq!(
            NaughtyListTracker::classify_error("network unreachable"),
            None
        );
    }

    #[test]
    fn test_record_new_entry() {
        let tracker = NaughtyListTracker::with_defaults();
        let url = "wss://bad-relay.example.com";

        let is_new = tracker.record(
            url,
            NaughtyCategory::DnsLookupFailed,
            "failed to lookup address".to_string(),
        );

        assert!(is_new);
        assert!(tracker.is_naughty(url));

        let entry = tracker.get_entry(url).unwrap();
        assert_eq!(entry.category, NaughtyCategory::DnsLookupFailed);
        assert_eq!(entry.occurrence_count, 1);
    }

    #[test]
    fn test_record_updates_existing() {
        let tracker = NaughtyListTracker::with_defaults();
        let url = "wss://bad-relay.example.com";

        // First occurrence
        let is_new1 = tracker.record(url, NaughtyCategory::DnsLookupFailed, "error 1".to_string());
        assert!(is_new1);

        // Second occurrence
        let is_new2 = tracker.record(url, NaughtyCategory::DnsLookupFailed, "error 2".to_string());
        assert!(!is_new2);

        let entry = tracker.get_entry(url).unwrap();
        assert_eq!(entry.occurrence_count, 2);
        assert_eq!(entry.reason, "error 2"); // Updated to latest
    }

    #[test]
    fn test_is_naughty() {
        let tracker = NaughtyListTracker::with_defaults();
        let url = "wss://bad-relay.example.com";

        assert!(!tracker.is_naughty(url));

        tracker.record(
            url,
            NaughtyCategory::TlsCertificateInvalid,
            "cert error".to_string(),
        );

        assert!(tracker.is_naughty(url));
    }

    #[test]
    fn test_get_all() {
        let tracker = NaughtyListTracker::with_defaults();

        tracker.record(
            "wss://relay1.example.com",
            NaughtyCategory::DnsLookupFailed,
            "dns error".to_string(),
        );
        tracker.record(
            "wss://relay2.example.com",
            NaughtyCategory::TlsCertificateInvalid,
            "tls error".to_string(),
        );

        let all = tracker.get_all();
        assert_eq!(all.len(), 2);
    }

    #[test]
    fn test_count_by_category() {
        let tracker = NaughtyListTracker::with_defaults();

        tracker.record(
            "wss://relay1.example.com",
            NaughtyCategory::DnsLookupFailed,
            "error".to_string(),
        );
        tracker.record(
            "wss://relay2.example.com",
            NaughtyCategory::DnsLookupFailed,
            "error".to_string(),
        );
        tracker.record(
            "wss://relay3.example.com",
            NaughtyCategory::TlsCertificateInvalid,
            "error".to_string(),
        );

        assert_eq!(
            tracker.count_by_category(NaughtyCategory::DnsLookupFailed),
            2
        );
        assert_eq!(
            tracker.count_by_category(NaughtyCategory::TlsCertificateInvalid),
            1
        );
        assert_eq!(tracker.count_by_category(NaughtyCategory::ProtocolError), 0);
    }

    #[test]
    fn test_total_count() {
        let tracker = NaughtyListTracker::with_defaults();
        assert_eq!(tracker.total_count(), 0);

        tracker.record(
            "wss://relay1.example.com",
            NaughtyCategory::DnsLookupFailed,
            "error".to_string(),
        );
        assert_eq!(tracker.total_count(), 1);

        tracker.record(
            "wss://relay2.example.com",
            NaughtyCategory::TlsCertificateInvalid,
            "error".to_string(),
        );
        assert_eq!(tracker.total_count(), 2);
    }

    #[test]
    fn test_expire_old_entries() {
        // Use very short expiration for testing
        let tracker = NaughtyListTracker::new(0); // Expire immediately (0 hours)

        tracker.record(
            "wss://relay1.example.com",
            NaughtyCategory::DnsLookupFailed,
            "error".to_string(),
        );

        // Entry should exist in the map
        assert_eq!(tracker.total_count(), 1);

        // But is_naughty should return false since it's already expired (0 hours)
        assert!(!tracker.is_naughty("wss://relay1.example.com"));

        // Sleep to ensure time passes
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Expire old entries (should remove the 0-hour expired entry)
        let expired = tracker.expire_old_entries();
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0], "wss://relay1.example.com");

        // Entry should be gone
        assert!(!tracker.is_naughty("wss://relay1.example.com"));
        assert_eq!(tracker.total_count(), 0);
    }

    #[test]
    fn test_category_display() {
        assert_eq!(
            NaughtyCategory::DnsLookupFailed.to_string(),
            "dns_lookup_failed"
        );
        assert_eq!(
            NaughtyCategory::TlsCertificateInvalid.to_string(),
            "tls_certificate_invalid"
        );
        assert_eq!(NaughtyCategory::ProtocolError.to_string(), "protocol_error");
    }

    #[test]
    fn test_category_as_str() {
        assert_eq!(
            NaughtyCategory::DnsLookupFailed.as_str(),
            "dns_lookup_failed"
        );
        assert_eq!(
            NaughtyCategory::TlsCertificateInvalid.as_str(),
            "tls_certificate_invalid"
        );
        assert_eq!(NaughtyCategory::ProtocolError.as_str(), "protocol_error");
    }
}