ant-quic 0.24.3

QUIC transport protocol with advanced NAT traversal for P2P networks
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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright 2024 Saorsa Labs Ltd.
//
// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
//
// Full details available at https://saorsalabs.com/licenses
#![allow(missing_docs)]

//! Certificate Type Negotiation Protocol Implementation
//!
//! This module implements the complete certificate type negotiation protocol
//! as defined in RFC 7250, including state management, caching, and integration
//! with both client and server sides of TLS connections.

use std::{
    collections::HashMap,
    hash::{Hash, Hasher},
    sync::Arc,
    time::{Duration, Instant},
};

use parking_lot::{Mutex, RwLock};

use tracing::{Level, debug, info, span, warn};

use super::tls_extensions::{
    CertificateTypeList, CertificateTypePreferences, NegotiationResult, TlsExtensionError,
};

/// Negotiation state for a single TLS connection
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NegotiationState {
    /// Negotiation not yet started
    Pending,
    /// Extensions sent, waiting for response
    Waiting {
        sent_at: Instant,
        our_preferences: CertificateTypePreferences,
    },
    /// Negotiation completed successfully
    Completed {
        result: NegotiationResult,
        completed_at: Instant,
    },
    /// Negotiation failed
    Failed {
        /// The error message
        error: String,
        /// When the failure occurred
        failed_at: Instant,
    },
    /// Timed out waiting for response
    TimedOut {
        /// When the timeout occurred
        timeout_at: Instant,
    },
}

impl NegotiationState {
    /// Check if negotiation is complete (either succeeded or failed)
    pub fn is_complete(&self) -> bool {
        matches!(
            self,
            Self::Completed { .. } | Self::Failed { .. } | Self::TimedOut { .. }
        )
    }

    /// Check if negotiation succeeded
    pub fn is_successful(&self) -> bool {
        matches!(self, Self::Completed { .. })
    }

    /// Get the negotiation result if successful
    pub fn get_result(&self) -> Option<&NegotiationResult> {
        match self {
            Self::Completed { result, .. } => Some(result),
            _ => None,
        }
    }

    /// Get error message if failed
    pub fn get_error(&self) -> Option<&str> {
        match self {
            Self::Failed { error, .. } => Some(error),
            _ => None,
        }
    }
}

/// Configuration for certificate type negotiation
#[derive(Debug, Clone)]
pub struct NegotiationConfig {
    /// Timeout for waiting for negotiation response
    pub timeout: Duration,
    /// Whether to cache negotiation results
    pub enable_caching: bool,
    /// Maximum cache size
    pub max_cache_size: usize,
    /// Whether to allow fallback to X.509 if RPK negotiation fails
    pub allow_fallback: bool,
    /// Default preferences if none specified
    pub default_preferences: CertificateTypePreferences,
}

impl Default for NegotiationConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(10),
            enable_caching: true,
            max_cache_size: 1000,
            allow_fallback: true,
            default_preferences: CertificateTypePreferences::prefer_raw_public_key(),
        }
    }
}

/// Unique identifier for a negotiation session
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NegotiationId(u64);

impl Default for NegotiationId {
    fn default() -> Self {
        Self::new()
    }
}

impl NegotiationId {
    /// Generate a new unique negotiation ID
    pub fn new() -> Self {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self(COUNTER.fetch_add(1, Ordering::Relaxed))
    }

    /// Get the raw ID value
    pub fn as_u64(self) -> u64 {
        self.0
    }
}

/// Cache key for negotiation results
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct CacheKey {
    /// Our certificate type preferences
    local_preferences: String, // Serialized preferences for hashing
    /// Remote certificate type preferences  
    remote_preferences: String, // Serialized preferences for hashing
}

impl CacheKey {
    /// Create a cache key from preferences
    fn new(
        local: &CertificateTypePreferences,
        remote_client: Option<&CertificateTypeList>,
        remote_server: Option<&CertificateTypeList>,
    ) -> Self {
        use std::collections::hash_map::DefaultHasher;

        let mut hasher = DefaultHasher::new();
        local.hash(&mut hasher);
        let local_hash = hasher.finish();

        let mut hasher = DefaultHasher::new();
        if let Some(types) = remote_client {
            types.hash(&mut hasher);
        }
        if let Some(types) = remote_server {
            types.hash(&mut hasher);
        }
        let remote_hash = hasher.finish();

        Self {
            local_preferences: format!("{local_hash:x}"),
            remote_preferences: format!("{remote_hash:x}"),
        }
    }
}

/// Hash implementation for CertificateTypePreferences
impl Hash for CertificateTypePreferences {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.client_types.types.hash(state);
        self.server_types.types.hash(state);
        self.require_extensions.hash(state);
        self.fallback_client.hash(state);
        self.fallback_server.hash(state);
    }
}

/// Hash implementation for CertificateTypeList  
impl Hash for CertificateTypeList {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.types.hash(state);
    }
}

/// Certificate type negotiation manager
pub struct CertificateNegotiationManager {
    /// Configuration for negotiation behavior
    config: NegotiationConfig,
    /// Active negotiation sessions
    sessions: RwLock<HashMap<NegotiationId, NegotiationState>>,
    /// Result cache for performance optimization
    cache: Arc<Mutex<HashMap<CacheKey, (NegotiationResult, Instant)>>>,
    /// Negotiation statistics
    stats: Arc<Mutex<NegotiationStats>>,
}

/// Statistics for certificate type negotiation
#[derive(Debug, Default, Clone)]
pub struct NegotiationStats {
    /// Total number of negotiations attempted
    pub total_attempts: u64,
    /// Number of successful negotiations
    pub successful: u64,
    /// Number of failed negotiations
    pub failed: u64,
    /// Number of timed out negotiations
    pub timed_out: u64,
    /// Number of cache hits
    pub cache_hits: u64,
    /// Number of cache misses
    pub cache_misses: u64,
    /// Average negotiation time
    pub avg_negotiation_time: Duration,
}

impl CertificateNegotiationManager {
    /// Create a new negotiation manager
    pub fn new(config: NegotiationConfig) -> Self {
        Self {
            config,
            sessions: RwLock::new(HashMap::new()),
            cache: Arc::new(Mutex::new(HashMap::new())),
            stats: Arc::new(Mutex::new(NegotiationStats::default())),
        }
    }

    /// Start a new certificate type negotiation
    pub fn start_negotiation(
        &self,
        preferences: CertificateTypePreferences,
    ) -> Result<NegotiationId, TlsExtensionError> {
        let id = NegotiationId::new();
        let state = NegotiationState::Waiting {
            sent_at: Instant::now(),
            our_preferences: preferences,
        };

        let mut sessions = self.sessions.write();
        sessions.insert(id, state);

        let mut stats = self.stats.lock();
        stats.total_attempts += 1;

        debug!("Started certificate type negotiation: {:?}", id);
        Ok(id)
    }

    /// Complete a negotiation with remote preferences
    pub fn complete_negotiation(
        &self,
        id: NegotiationId,
        remote_client_types: Option<CertificateTypeList>,
        remote_server_types: Option<CertificateTypeList>,
    ) -> Result<NegotiationResult, TlsExtensionError> {
        let _span = span!(Level::DEBUG, "complete_negotiation", id = id.as_u64()).entered();

        let mut sessions = self.sessions.write();
        let state = sessions.get(&id).ok_or_else(|| {
            TlsExtensionError::InvalidExtensionData(format!("Unknown negotiation ID: {id:?}"))
        })?;

        let our_preferences = match state {
            NegotiationState::Waiting {
                our_preferences, ..
            } => our_preferences.clone(),
            _ => {
                return Err(TlsExtensionError::InvalidExtensionData(
                    "Negotiation not in waiting state".to_string(),
                ));
            }
        };

        // Check cache first if enabled
        if self.config.enable_caching {
            let cache_key = CacheKey::new(
                &our_preferences,
                remote_client_types.as_ref(),
                remote_server_types.as_ref(),
            );

            let mut cache = self.cache.lock();
            if let Some((cached_result, cached_at)) = cache.get(&cache_key) {
                // Check if cache entry is still valid (not expired)
                if cached_at.elapsed() < Duration::from_secs(300) {
                    // 5 minute cache
                    let mut stats = self.stats.lock();
                    stats.cache_hits += 1;

                    // Update session state
                    sessions.insert(
                        id,
                        NegotiationState::Completed {
                            result: cached_result.clone(),
                            completed_at: Instant::now(),
                        },
                    );

                    debug!("Cache hit for negotiation: {:?}", id);
                    return Ok(cached_result.clone());
                } else {
                    // Remove expired entry
                    cache.remove(&cache_key);
                }
            }

            let mut stats = self.stats.lock();
            stats.cache_misses += 1;
        }

        // Perform actual negotiation
        let negotiation_start = Instant::now();
        let result =
            our_preferences.negotiate(remote_client_types.as_ref(), remote_server_types.as_ref());

        match result {
            Ok(negotiation_result) => {
                let completed_at = Instant::now();
                let negotiation_time = negotiation_start.elapsed();

                // Update session state
                sessions.insert(
                    id,
                    NegotiationState::Completed {
                        result: negotiation_result.clone(),
                        completed_at,
                    },
                );

                // Update statistics
                let mut stats = self.stats.lock();
                stats.successful += 1;

                // Update average negotiation time (simple moving average)
                let total_completed = stats.successful + stats.failed;
                stats.avg_negotiation_time = if total_completed == 1 {
                    negotiation_time
                } else {
                    Duration::from_nanos(
                        (stats.avg_negotiation_time.as_nanos() as u64 * (total_completed - 1)
                            + negotiation_time.as_nanos() as u64)
                            / total_completed,
                    )
                };

                // Cache the result if caching is enabled
                if self.config.enable_caching {
                    let cache_key = CacheKey::new(
                        &our_preferences,
                        remote_client_types.as_ref(),
                        remote_server_types.as_ref(),
                    );

                    let mut cache = self.cache.lock();

                    // Evict old entries if cache is full
                    if cache.len() >= self.config.max_cache_size {
                        // Simple eviction: remove oldest entries
                        let mut entries: Vec<_> =
                            cache.iter().map(|(k, (_, t))| (k.clone(), *t)).collect();
                        entries.sort_by_key(|(_, timestamp)| *timestamp);

                        let to_remove = cache.len() - self.config.max_cache_size + 1;
                        let keys_to_remove: Vec<_> = entries
                            .iter()
                            .take(to_remove)
                            .map(|(key, _)| key.clone())
                            .collect();

                        for key in keys_to_remove {
                            cache.remove(&key);
                        }
                    }

                    cache.insert(cache_key, (negotiation_result.clone(), completed_at));
                }

                info!(
                    "Certificate type negotiation completed successfully: {:?} -> client={}, server={}",
                    id, negotiation_result.client_cert_type, negotiation_result.server_cert_type
                );

                Ok(negotiation_result)
            }
            Err(error) => {
                // Update session state
                sessions.insert(
                    id,
                    NegotiationState::Failed {
                        error: error.to_string(),
                        failed_at: Instant::now(),
                    },
                );

                // Update statistics
                let mut stats = self.stats.lock();
                stats.failed += 1;

                warn!("Certificate type negotiation failed: {:?} -> {}", id, error);
                Err(error)
            }
        }
    }

    /// Fail a negotiation with an error
    pub fn fail_negotiation(&self, id: NegotiationId, error: String) {
        let mut sessions = self.sessions.write();
        sessions.insert(
            id,
            NegotiationState::Failed {
                error,
                failed_at: Instant::now(),
            },
        );

        let mut stats = self.stats.lock();
        stats.failed += 1;

        warn!("Certificate type negotiation failed: {:?}", id);
    }

    /// Get the current state of a negotiation
    pub fn get_negotiation_state(&self, id: NegotiationId) -> Option<NegotiationState> {
        let sessions = self.sessions.read();
        sessions.get(&id).cloned()
    }

    /// Check for and handle timed out negotiations
    pub fn handle_timeouts(&self) {
        let mut sessions = self.sessions.write();
        let mut timed_out_ids = Vec::new();

        for (id, state) in sessions.iter() {
            if let NegotiationState::Waiting { sent_at, .. } = state {
                if sent_at.elapsed() > self.config.timeout {
                    timed_out_ids.push(*id);
                }
            }
        }

        for id in timed_out_ids {
            sessions.insert(
                id,
                NegotiationState::TimedOut {
                    timeout_at: Instant::now(),
                },
            );

            let mut stats = self.stats.lock();
            stats.timed_out += 1;

            warn!("Certificate type negotiation timed out: {:?}", id);
        }
    }

    /// Clean up completed negotiations older than the specified duration
    pub fn cleanup_old_sessions(&self, max_age: Duration) {
        let mut sessions = self.sessions.write();
        let cutoff = Instant::now() - max_age;

        sessions.retain(|id, state| {
            let should_retain = match state {
                NegotiationState::Completed { completed_at, .. } => *completed_at > cutoff,
                NegotiationState::Failed { failed_at, .. } => *failed_at > cutoff,
                NegotiationState::TimedOut { timeout_at, .. } => *timeout_at > cutoff,
                _ => true, // Keep pending and waiting sessions
            };

            if !should_retain {
                debug!("Cleaned up old negotiation session: {:?}", id);
            }

            should_retain
        });
    }

    /// Get current negotiation statistics
    pub fn get_stats(&self) -> NegotiationStats {
        self.stats.lock().clone()
    }

    /// Clear all cached results
    pub fn clear_cache(&self) {
        let mut cache = self.cache.lock();
        cache.clear();
        debug!("Cleared certificate type negotiation cache");
    }

    /// Get cache statistics
    pub fn get_cache_stats(&self) -> (usize, usize) {
        let cache = self.cache.lock();
        (cache.len(), self.config.max_cache_size)
    }
}

impl Default for CertificateNegotiationManager {
    fn default() -> Self {
        Self::new(NegotiationConfig::default())
    }
}

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

    #[test]
    fn test_negotiation_id_generation() {
        let id1 = NegotiationId::new();
        let id2 = NegotiationId::new();

        assert_ne!(id1, id2);
        assert!(id1.as_u64() > 0);
        assert!(id2.as_u64() > 0);
    }

    #[test]
    fn test_negotiation_state_checks() {
        let pending = NegotiationState::Pending;
        assert!(!pending.is_complete());
        assert!(!pending.is_successful());

        let completed = NegotiationState::Completed {
            result: NegotiationResult::new(CertificateType::RawPublicKey, CertificateType::X509),
            completed_at: Instant::now(),
        };
        assert!(completed.is_complete());
        assert!(completed.is_successful());
        assert!(completed.get_result().is_some());

        let failed = NegotiationState::Failed {
            error: "Test error".to_string(),
            failed_at: Instant::now(),
        };
        assert!(failed.is_complete());
        assert!(!failed.is_successful());
        assert_eq!(failed.get_error().unwrap(), "Test error");
    }

    #[test]
    fn test_negotiation_manager_basic_flow() {
        let manager = CertificateNegotiationManager::default();
        let preferences = CertificateTypePreferences::prefer_raw_public_key();

        // Start negotiation
        let id = manager.start_negotiation(preferences).unwrap();

        let state = manager.get_negotiation_state(id).unwrap();
        assert!(matches!(state, NegotiationState::Waiting { .. }));

        // Complete negotiation
        let remote_types = CertificateTypeList::raw_public_key_only();
        let result = manager
            .complete_negotiation(id, Some(remote_types.clone()), Some(remote_types))
            .unwrap();

        assert_eq!(result.client_cert_type, CertificateType::RawPublicKey);
        assert_eq!(result.server_cert_type, CertificateType::RawPublicKey);

        let state = manager.get_negotiation_state(id).unwrap();
        assert!(state.is_successful());
    }

    #[test]
    fn test_negotiation_caching() {
        let config = NegotiationConfig {
            enable_caching: true,
            ..Default::default()
        };
        let manager = CertificateNegotiationManager::new(config);
        let preferences = CertificateTypePreferences::prefer_raw_public_key();

        // First negotiation
        let id1 = manager.start_negotiation(preferences.clone()).unwrap();
        let remote_types = CertificateTypeList::raw_public_key_only();
        let result1 = manager
            .complete_negotiation(id1, Some(remote_types.clone()), Some(remote_types.clone()))
            .unwrap();

        // Second negotiation with same preferences should hit cache
        let id2 = manager.start_negotiation(preferences).unwrap();
        let result2 = manager
            .complete_negotiation(id2, Some(remote_types.clone()), Some(remote_types))
            .unwrap();

        assert_eq!(result1, result2);

        let stats = manager.get_stats();
        assert_eq!(stats.cache_hits, 1);
        assert_eq!(stats.cache_misses, 1);
    }

    #[test]
    fn test_negotiation_timeout_handling() {
        let config = NegotiationConfig {
            timeout: Duration::from_millis(1),
            ..Default::default()
        };
        let manager = CertificateNegotiationManager::new(config);
        let preferences = CertificateTypePreferences::prefer_raw_public_key();

        let id = manager.start_negotiation(preferences).unwrap();

        // Wait for timeout
        std::thread::sleep(Duration::from_millis(10));
        manager.handle_timeouts();

        let state = manager.get_negotiation_state(id).unwrap();
        assert!(matches!(state, NegotiationState::TimedOut { .. }));

        let stats = manager.get_stats();
        assert_eq!(stats.timed_out, 1);
    }
}