Skip to main content

fynx_proto/ipsec/
error.rs

1//! Error types for IPSec protocol operations
2//!
3//! This module defines a unified error type for all IPSec operations,
4//! covering IKEv2 and ESP protocols.
5
6use std::fmt;
7
8/// Result type for IPSec operations
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Error codes for programmatic handling
12///
13/// Provides stable error codes that can be used for programmatic error handling,
14/// logging, and monitoring. Error codes are grouped by category (1000s = protocol,
15/// 2000s = crypto, 3000s = state, etc.)
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum ErrorCode {
18    // Protocol errors (1000-1999)
19    /// Invalid message format (1001)
20    InvalidMessage = 1001,
21    /// Invalid payload (1002)
22    InvalidPayload = 1002,
23    /// Unsupported version (1003)
24    UnsupportedVersion = 1003,
25    /// No proposal chosen (1004)
26    NoProposalChosen = 1004,
27    /// Invalid syntax (1005)
28    InvalidSyntax = 1005,
29
30    // Crypto errors (2000-2999)
31    /// Authentication failed (2001)
32    AuthenticationFailed = 2001,
33    /// Cryptographic operation failed (2002)
34    CryptoError = 2002,
35    /// Invalid key length (2003)
36    InvalidKeyLength = 2003,
37
38    // State errors (3000-3999)
39    /// Invalid state (3001)
40    InvalidState = 3001,
41    /// Invalid state transition (3002)
42    InvalidStateTransition = 3002,
43    /// Security Association not found (3003)
44    SaNotFound = 3003,
45
46    // Security errors (4000-4999)
47    /// Replay attack detected (4001)
48    ReplayDetected = 4001,
49
50    // Network errors (5000-5999)
51    /// Network I/O error (5001)
52    NetworkError = 5001,
53    /// Network timeout (5002)
54    NetworkTimeout = 5002,
55
56    // Internal errors (9000-9999)
57    /// Internal error (9001)
58    InternalError = 9001,
59}
60
61impl ErrorCode {
62    /// Get error code as u32
63    pub fn as_u32(self) -> u32 {
64        self as u32
65    }
66
67    /// Get error code category name
68    pub fn category(self) -> &'static str {
69        match self {
70            ErrorCode::InvalidMessage
71            | ErrorCode::InvalidPayload
72            | ErrorCode::UnsupportedVersion
73            | ErrorCode::NoProposalChosen
74            | ErrorCode::InvalidSyntax => "Protocol",
75
76            ErrorCode::AuthenticationFailed
77            | ErrorCode::CryptoError
78            | ErrorCode::InvalidKeyLength => "Crypto",
79
80            ErrorCode::InvalidState | ErrorCode::InvalidStateTransition | ErrorCode::SaNotFound => {
81                "State"
82            }
83
84            ErrorCode::ReplayDetected => "Security",
85
86            ErrorCode::NetworkError | ErrorCode::NetworkTimeout => "Network",
87
88            ErrorCode::InternalError => "Internal",
89        }
90    }
91}
92
93/// IPSec protocol errors
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum Error {
96    /// Invalid IKEv2 message format
97    InvalidMessage(String),
98
99    /// Invalid IKEv2 payload
100    InvalidPayload(String),
101
102    /// Invalid parameter value
103    InvalidParameter(String),
104
105    /// Unsupported protocol version
106    UnsupportedVersion(u8),
107
108    /// Unsupported exchange type
109    UnsupportedExchangeType(u8),
110
111    /// No acceptable proposal found
112    NoProposalChosen,
113
114    /// Invalid proposal
115    InvalidProposal(String),
116
117    /// Authentication failed
118    AuthenticationFailed(String),
119
120    /// Security Association not found
121    SaNotFound(String),
122
123    /// Cryptographic operation failed
124    CryptoError(String),
125
126    /// Replay attack detected
127    ReplayDetected(u64),
128
129    /// Invalid packet length
130    InvalidLength {
131        /// Expected length
132        expected: usize,
133        /// Actual length
134        actual: usize,
135    },
136
137    /// Buffer too short for operation
138    BufferTooShort {
139        /// Required length
140        required: usize,
141        /// Available length
142        available: usize,
143    },
144
145    /// Message too large
146    MessageTooLarge(u32),
147
148    /// Invalid Security Parameter Index
149    InvalidSpi(u32),
150
151    /// Invalid sequence number
152    InvalidSequence(u64),
153
154    /// State machine error
155    InvalidState(String),
156
157    /// Invalid state transition
158    InvalidStateTransition {
159        /// Current state
160        from: String,
161        /// Target state
162        to: String,
163    },
164
165    /// Missing required payload
166    MissingPayload(String),
167
168    /// Invalid exchange type
169    InvalidExchangeType,
170
171    /// Invalid message ID
172    InvalidMessageId {
173        /// Expected message ID
174        expected: u32,
175        /// Received message ID
176        received: u32,
177    },
178
179    /// Invalid key length
180    InvalidKeyLength {
181        /// Expected length
182        expected: usize,
183        /// Actual length
184        actual: usize,
185    },
186
187    /// Invalid IV length
188    InvalidIvLength {
189        /// Expected length
190        expected: usize,
191        /// Actual length
192        actual: usize,
193    },
194
195    /// I/O error
196    Io(String),
197
198    /// Internal error (should not happen)
199    Internal(String),
200}
201
202impl fmt::Display for Error {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        match self {
205            Error::InvalidMessage(msg) => write!(f, "Invalid IKE message: {}", msg),
206            Error::InvalidPayload(msg) => write!(f, "Invalid IKE payload: {}", msg),
207            Error::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg),
208            Error::UnsupportedVersion(v) => {
209                write!(f, "Unsupported IKE version: 0x{:02x}", v)
210            }
211            Error::UnsupportedExchangeType(t) => {
212                write!(f, "Unsupported exchange type: {}", t)
213            }
214            Error::NoProposalChosen => {
215                write!(f, "No acceptable proposal found in negotiation")
216            }
217            Error::InvalidProposal(msg) => {
218                write!(f, "Invalid proposal: {}", msg)
219            }
220            Error::AuthenticationFailed(msg) => {
221                write!(f, "Authentication failed: {}", msg)
222            }
223            Error::SaNotFound(id) => write!(f, "Security Association not found: {}", id),
224            Error::CryptoError(msg) => write!(f, "Cryptographic error: {}", msg),
225            Error::ReplayDetected(seq) => {
226                write!(f, "Replay attack detected (sequence: {})", seq)
227            }
228            Error::InvalidLength { expected, actual } => {
229                write!(f, "Invalid length: expected {}, got {}", expected, actual)
230            }
231            Error::BufferTooShort {
232                required,
233                available,
234            } => {
235                write!(
236                    f,
237                    "Buffer too short: need {} bytes, have {}",
238                    required, available
239                )
240            }
241            Error::MessageTooLarge(size) => {
242                write!(f, "IKE message too large: {} bytes", size)
243            }
244            Error::InvalidSpi(spi) => write!(f, "Invalid SPI: 0x{:08x}", spi),
245            Error::InvalidSequence(seq) => write!(f, "Invalid sequence number: {}", seq),
246            Error::InvalidState(msg) => write!(f, "Invalid state: {}", msg),
247            Error::InvalidStateTransition { from, to } => {
248                write!(f, "Invalid state transition from {} to {}", from, to)
249            }
250            Error::MissingPayload(name) => write!(f, "Missing required payload: {}", name),
251            Error::InvalidExchangeType => write!(f, "Invalid exchange type"),
252            Error::InvalidMessageId { expected, received } => {
253                write!(
254                    f,
255                    "Invalid message ID: expected {}, received {}",
256                    expected, received
257                )
258            }
259            Error::InvalidKeyLength { expected, actual } => {
260                write!(
261                    f,
262                    "Invalid key length: expected {} bytes, got {}",
263                    expected, actual
264                )
265            }
266            Error::InvalidIvLength { expected, actual } => {
267                write!(
268                    f,
269                    "Invalid IV length: expected {} bytes, got {}",
270                    expected, actual
271                )
272            }
273            Error::Io(msg) => write!(f, "I/O error: {}", msg),
274            Error::Internal(msg) => write!(f, "Internal error: {}", msg),
275        }
276    }
277}
278
279impl std::error::Error for Error {}
280
281impl Error {
282    /// Get error code for programmatic handling
283    ///
284    /// Returns a stable error code that can be used for:
285    /// - Programmatic error handling
286    /// - Monitoring and alerting
287    /// - Error categorization
288    ///
289    /// # Returns
290    ///
291    /// `Some(ErrorCode)` if this error has a defined code, `None` otherwise.
292    pub fn code(&self) -> Option<ErrorCode> {
293        match self {
294            Error::InvalidMessage(_) => Some(ErrorCode::InvalidMessage),
295            Error::InvalidPayload(_) => Some(ErrorCode::InvalidPayload),
296            Error::InvalidParameter(_) => Some(ErrorCode::InvalidSyntax),
297            Error::UnsupportedVersion(_) => Some(ErrorCode::UnsupportedVersion),
298            Error::UnsupportedExchangeType(_) => Some(ErrorCode::InvalidSyntax),
299            Error::NoProposalChosen => Some(ErrorCode::NoProposalChosen),
300            Error::InvalidProposal(_) => Some(ErrorCode::InvalidSyntax),
301            Error::AuthenticationFailed(_) => Some(ErrorCode::AuthenticationFailed),
302            Error::SaNotFound(_) => Some(ErrorCode::SaNotFound),
303            Error::CryptoError(_) => Some(ErrorCode::CryptoError),
304            Error::ReplayDetected(_) => Some(ErrorCode::ReplayDetected),
305            Error::InvalidState(_) => Some(ErrorCode::InvalidState),
306            Error::InvalidStateTransition { .. } => Some(ErrorCode::InvalidStateTransition),
307            Error::InvalidKeyLength { .. } => Some(ErrorCode::InvalidKeyLength),
308            Error::Io(_) => Some(ErrorCode::NetworkError),
309            Error::Internal(_) => Some(ErrorCode::InternalError),
310            _ => None,
311        }
312    }
313
314    /// Add context to error message
315    ///
316    /// Wraps the error with additional context information.
317    /// Useful for adding operation context to errors propagated from lower layers.
318    ///
319    /// # Arguments
320    ///
321    /// * `context` - Context description
322    ///
323    /// # Returns
324    ///
325    /// New error with context prepended to the message.
326    ///
327    /// # Example
328    ///
329    /// ```
330    /// use fynx_proto::ipsec::error::Error;
331    ///
332    /// let err = Error::CryptoError("invalid key".to_string());
333    /// let err_with_context = err.with_context("ESP encryption");
334    ///
335    /// assert_eq!(
336    ///     err_with_context.to_string(),
337    ///     "Cryptographic error: ESP encryption: invalid key"
338    /// );
339    /// ```
340    pub fn with_context(self, context: &str) -> Self {
341        match self {
342            Error::InvalidMessage(msg) => Error::InvalidMessage(format!("{}: {}", context, msg)),
343            Error::InvalidPayload(msg) => Error::InvalidPayload(format!("{}: {}", context, msg)),
344            Error::InvalidParameter(msg) => {
345                Error::InvalidParameter(format!("{}: {}", context, msg))
346            }
347            Error::InvalidProposal(msg) => Error::InvalidProposal(format!("{}: {}", context, msg)),
348            Error::AuthenticationFailed(msg) => {
349                Error::AuthenticationFailed(format!("{}: {}", context, msg))
350            }
351            Error::SaNotFound(msg) => Error::SaNotFound(format!("{}: {}", context, msg)),
352            Error::CryptoError(msg) => Error::CryptoError(format!("{}: {}", context, msg)),
353            Error::InvalidState(msg) => Error::InvalidState(format!("{}: {}", context, msg)),
354            Error::MissingPayload(msg) => Error::MissingPayload(format!("{}: {}", context, msg)),
355            Error::Io(msg) => Error::Io(format!("{}: {}", context, msg)),
356            Error::Internal(msg) => Error::Internal(format!("{}: {}", context, msg)),
357            // For other variants, leave as-is (they have structured data, not just messages)
358            other => other,
359        }
360    }
361
362    /// Check if error is retryable
363    ///
364    /// Returns `true` if this error represents a transient condition
365    /// that may succeed on retry.
366    pub fn is_retryable(&self) -> bool {
367        matches!(self, Error::Io(_) | Error::CryptoError(_))
368    }
369
370    /// Check if error is fatal
371    ///
372    /// Returns `true` if this error indicates an unrecoverable condition.
373    pub fn is_fatal(&self) -> bool {
374        matches!(
375            self,
376            Error::AuthenticationFailed(_)
377                | Error::InvalidState(_)
378                | Error::InvalidStateTransition { .. }
379        )
380    }
381}
382
383// Convert from std::io::Error
384impl From<std::io::Error> for Error {
385    fn from(err: std::io::Error) -> Self {
386        Error::Io(err.to_string())
387    }
388}
389
390/// Error Recovery Action
391///
392/// Defines what action to take when an error occurs.
393#[derive(Debug, Clone, PartialEq)]
394pub enum RecoveryAction {
395    /// Retry the operation with specified policy
396    Retry {
397        /// Maximum retry attempts
398        max_attempts: u32,
399        /// Base delay between retries
400        base_delay: std::time::Duration,
401    },
402
403    /// Send NOTIFY error to peer
404    NotifyPeer {
405        /// Notify message type
406        notify_type: u16,
407    },
408
409    /// Delete the Security Association
410    DeleteSa,
411
412    /// Reset connection (restart IKE_SA_INIT)
413    Reset,
414
415    /// Ignore the error (log and continue)
416    Ignore,
417
418    /// Fail immediately (propagate error)
419    Fail,
420}
421
422/// Retry Policy
423///
424/// Configures automatic retry behavior with exponential backoff.
425///
426/// # Example
427///
428/// ```rust,ignore
429/// use fynx_proto::ipsec::error::RetryPolicy;
430/// use std::time::Duration;
431///
432/// let policy = RetryPolicy::new(3, Duration::from_secs(1), 2.0, Duration::from_secs(60));
433///
434/// // Check if should retry
435/// assert!(policy.should_retry(0));
436/// assert!(policy.should_retry(1));
437/// assert!(policy.should_retry(2));
438/// assert!(!policy.should_retry(3)); // Max attempts reached
439///
440/// // Get retry delay (exponential backoff)
441/// assert_eq!(policy.get_delay(0), Duration::from_secs(1));  // 1s
442/// assert_eq!(policy.get_delay(1), Duration::from_secs(2));  // 2s
443/// assert_eq!(policy.get_delay(2), Duration::from_secs(4));  // 4s
444/// ```
445#[derive(Debug, Clone, PartialEq)]
446pub struct RetryPolicy {
447    /// Maximum retry attempts (0 = no retries)
448    max_attempts: u32,
449
450    /// Base delay between retries
451    base_delay: std::time::Duration,
452
453    /// Exponential backoff multiplier
454    ///
455    /// Each retry delay = base_delay * (multiplier ^ attempt)
456    /// Typical values: 2.0 (exponential doubling)
457    backoff_multiplier: f32,
458
459    /// Maximum delay cap
460    ///
461    /// Prevents delays from growing too large
462    max_delay: std::time::Duration,
463}
464
465impl Default for RetryPolicy {
466    fn default() -> Self {
467        RetryPolicy {
468            max_attempts: 3,
469            base_delay: std::time::Duration::from_secs(1),
470            backoff_multiplier: 2.0,
471            max_delay: std::time::Duration::from_secs(60),
472        }
473    }
474}
475
476impl RetryPolicy {
477    /// Create new retry policy
478    ///
479    /// # Arguments
480    ///
481    /// * `max_attempts` - Maximum retry attempts
482    /// * `base_delay` - Initial delay between retries
483    /// * `backoff_multiplier` - Exponential backoff multiplier (e.g., 2.0)
484    /// * `max_delay` - Maximum delay cap
485    pub fn new(
486        max_attempts: u32,
487        base_delay: std::time::Duration,
488        backoff_multiplier: f32,
489        max_delay: std::time::Duration,
490    ) -> Self {
491        RetryPolicy {
492            max_attempts,
493            base_delay,
494            backoff_multiplier,
495            max_delay,
496        }
497    }
498
499    /// Create no-retry policy
500    pub fn no_retry() -> Self {
501        RetryPolicy {
502            max_attempts: 0,
503            base_delay: std::time::Duration::from_secs(0),
504            backoff_multiplier: 1.0,
505            max_delay: std::time::Duration::from_secs(0),
506        }
507    }
508
509    /// Check if should retry given attempt number
510    ///
511    /// # Arguments
512    ///
513    /// * `attempt` - Current attempt number (0-based)
514    ///
515    /// # Returns
516    ///
517    /// `true` if attempt < max_attempts
518    pub fn should_retry(&self, attempt: u32) -> bool {
519        attempt < self.max_attempts
520    }
521
522    /// Get retry delay for given attempt
523    ///
524    /// Uses exponential backoff: `delay = base_delay * (multiplier ^ attempt)`
525    ///
526    /// # Arguments
527    ///
528    /// * `attempt` - Current attempt number (0-based)
529    ///
530    /// # Returns
531    ///
532    /// Delay duration, capped at max_delay
533    pub fn get_delay(&self, attempt: u32) -> std::time::Duration {
534        if self.max_attempts == 0 {
535            return std::time::Duration::from_secs(0);
536        }
537
538        // Calculate exponential backoff: base * (multiplier ^ attempt)
539        let multiplier_pow = self.backoff_multiplier.powi(attempt as i32);
540        let delay_secs = self.base_delay.as_secs_f32() * multiplier_pow;
541
542        let delay = std::time::Duration::from_secs_f32(delay_secs);
543
544        // Cap at max_delay
545        if delay > self.max_delay {
546            self.max_delay
547        } else {
548            delay
549        }
550    }
551
552    /// Get maximum attempts
553    pub fn max_attempts(&self) -> u32 {
554        self.max_attempts
555    }
556
557    /// Get base delay
558    pub fn base_delay(&self) -> std::time::Duration {
559        self.base_delay
560    }
561
562    /// Get backoff multiplier
563    pub fn backoff_multiplier(&self) -> f32 {
564        self.backoff_multiplier
565    }
566
567    /// Get maximum delay
568    pub fn max_delay(&self) -> std::time::Duration {
569        self.max_delay
570    }
571}
572
573/// Error Handler
574///
575/// Maps error types to recovery actions.
576#[derive(Debug, Clone)]
577pub struct ErrorHandler {
578    /// Default recovery action
579    default_action: RecoveryAction,
580
581    /// Default retry policy
582    default_retry: RetryPolicy,
583}
584
585impl Default for ErrorHandler {
586    fn default() -> Self {
587        Self::new()
588    }
589}
590
591impl ErrorHandler {
592    /// Create new error handler with default policies
593    pub fn new() -> Self {
594        ErrorHandler {
595            default_action: RecoveryAction::Fail,
596            default_retry: RetryPolicy::default(),
597        }
598    }
599
600    /// Create error handler with custom default action
601    pub fn with_default_action(action: RecoveryAction) -> Self {
602        ErrorHandler {
603            default_action: action,
604            default_retry: RetryPolicy::default(),
605        }
606    }
607
608    /// Handle error and determine recovery action
609    ///
610    /// # Arguments
611    ///
612    /// * `error` - The error to handle
613    ///
614    /// # Returns
615    ///
616    /// Appropriate recovery action for the error type
617    pub fn handle_error(&self, error: &Error) -> RecoveryAction {
618        match error {
619            // Transient errors - retry
620            Error::Io(_) | Error::CryptoError(_) => RecoveryAction::Retry {
621                max_attempts: self.default_retry.max_attempts(),
622                base_delay: self.default_retry.base_delay(),
623            },
624
625            // Protocol errors - notify peer
626            Error::InvalidMessage(_)
627            | Error::InvalidPayload(_)
628            | Error::InvalidParameter(_)
629            | Error::UnsupportedVersion(_)
630            | Error::UnsupportedExchangeType(_) => RecoveryAction::NotifyPeer { notify_type: 7 }, // INVALID_SYNTAX
631
632            // Authentication errors - delete SA
633            Error::AuthenticationFailed(_) => RecoveryAction::DeleteSa,
634
635            // Replay attacks - ignore (already handled)
636            Error::ReplayDetected(_) => RecoveryAction::Ignore,
637
638            // State errors - depends on severity
639            Error::InvalidState(_) | Error::InvalidStateTransition { .. } => {
640                RecoveryAction::DeleteSa
641            }
642
643            // Missing SA - ignore (may be already deleted)
644            Error::SaNotFound(_) => RecoveryAction::Ignore,
645
646            // No proposal chosen - notify peer
647            Error::NoProposalChosen => RecoveryAction::NotifyPeer { notify_type: 14 }, // NO_PROPOSAL_CHOSEN
648
649            // All other errors - use default
650            _ => self.default_action.clone(),
651        }
652    }
653
654    /// Get default retry policy
655    pub fn default_retry_policy(&self) -> &RetryPolicy {
656        &self.default_retry
657    }
658
659    /// Set default retry policy
660    pub fn set_default_retry_policy(&mut self, policy: RetryPolicy) {
661        self.default_retry = policy;
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn test_error_display() {
671        let err = Error::InvalidMessage("test".to_string());
672        assert_eq!(err.to_string(), "Invalid IKE message: test");
673
674        let err = Error::UnsupportedVersion(0x10);
675        assert_eq!(err.to_string(), "Unsupported IKE version: 0x10");
676
677        let err = Error::InvalidLength {
678            expected: 10,
679            actual: 5,
680        };
681        assert_eq!(err.to_string(), "Invalid length: expected 10, got 5");
682    }
683
684    #[test]
685    fn test_error_clone() {
686        let err1 = Error::NoProposalChosen;
687        let err2 = err1.clone();
688        assert_eq!(err1, err2);
689    }
690
691    #[test]
692    fn test_io_error_conversion() {
693        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
694        let err: Error = io_err.into();
695        match err {
696            Error::Io(msg) => assert!(msg.contains("file not found")),
697            _ => panic!("Expected Io error"),
698        }
699    }
700
701    #[test]
702    fn test_buffer_too_short() {
703        let err = Error::BufferTooShort {
704            required: 100,
705            available: 50,
706        };
707        assert!(err.to_string().contains("Buffer too short"));
708        assert!(err.to_string().contains("100"));
709        assert!(err.to_string().contains("50"));
710    }
711
712    // Recovery Action tests
713
714    #[test]
715    fn test_recovery_action_retry() {
716        let action = RecoveryAction::Retry {
717            max_attempts: 3,
718            base_delay: std::time::Duration::from_secs(1),
719        };
720        assert!(matches!(action, RecoveryAction::Retry { .. }));
721    }
722
723    #[test]
724    fn test_recovery_action_notify_peer() {
725        let action = RecoveryAction::NotifyPeer { notify_type: 7 };
726        assert!(matches!(action, RecoveryAction::NotifyPeer { .. }));
727    }
728
729    // RetryPolicy tests
730
731    #[test]
732    fn test_retry_policy_default() {
733        let policy = RetryPolicy::default();
734        assert_eq!(policy.max_attempts(), 3);
735        assert_eq!(policy.base_delay(), std::time::Duration::from_secs(1));
736        assert_eq!(policy.backoff_multiplier(), 2.0);
737        assert_eq!(policy.max_delay(), std::time::Duration::from_secs(60));
738    }
739
740    #[test]
741    fn test_retry_policy_new() {
742        let policy = RetryPolicy::new(
743            5,
744            std::time::Duration::from_secs(2),
745            1.5,
746            std::time::Duration::from_secs(30),
747        );
748        assert_eq!(policy.max_attempts(), 5);
749        assert_eq!(policy.base_delay(), std::time::Duration::from_secs(2));
750        assert_eq!(policy.backoff_multiplier(), 1.5);
751        assert_eq!(policy.max_delay(), std::time::Duration::from_secs(30));
752    }
753
754    #[test]
755    fn test_retry_policy_no_retry() {
756        let policy = RetryPolicy::no_retry();
757        assert_eq!(policy.max_attempts(), 0);
758        assert!(!policy.should_retry(0));
759    }
760
761    #[test]
762    fn test_retry_policy_should_retry() {
763        let policy = RetryPolicy::new(
764            3,
765            std::time::Duration::from_secs(1),
766            2.0,
767            std::time::Duration::from_secs(60),
768        );
769
770        assert!(policy.should_retry(0));
771        assert!(policy.should_retry(1));
772        assert!(policy.should_retry(2));
773        assert!(!policy.should_retry(3)); // Max attempts reached
774        assert!(!policy.should_retry(4));
775    }
776
777    #[test]
778    fn test_retry_policy_get_delay_exponential() {
779        let policy = RetryPolicy::new(
780            5,
781            std::time::Duration::from_secs(1),
782            2.0,
783            std::time::Duration::from_secs(100),
784        );
785
786        // Exponential backoff: 1, 2, 4, 8, 16 seconds
787        assert_eq!(policy.get_delay(0), std::time::Duration::from_secs(1));
788        assert_eq!(policy.get_delay(1), std::time::Duration::from_secs(2));
789        assert_eq!(policy.get_delay(2), std::time::Duration::from_secs(4));
790        assert_eq!(policy.get_delay(3), std::time::Duration::from_secs(8));
791        assert_eq!(policy.get_delay(4), std::time::Duration::from_secs(16));
792    }
793
794    #[test]
795    fn test_retry_policy_get_delay_capped() {
796        let policy = RetryPolicy::new(
797            10,
798            std::time::Duration::from_secs(1),
799            2.0,
800            std::time::Duration::from_secs(10),
801        );
802
803        // Should cap at max_delay (10 seconds)
804        assert_eq!(policy.get_delay(0), std::time::Duration::from_secs(1));
805        assert_eq!(policy.get_delay(1), std::time::Duration::from_secs(2));
806        assert_eq!(policy.get_delay(2), std::time::Duration::from_secs(4));
807        assert_eq!(policy.get_delay(3), std::time::Duration::from_secs(8));
808        assert_eq!(policy.get_delay(4), std::time::Duration::from_secs(10)); // Capped
809        assert_eq!(policy.get_delay(5), std::time::Duration::from_secs(10)); // Capped
810    }
811
812    #[test]
813    fn test_retry_policy_get_delay_no_retry() {
814        let policy = RetryPolicy::no_retry();
815        assert_eq!(policy.get_delay(0), std::time::Duration::from_secs(0));
816        assert_eq!(policy.get_delay(1), std::time::Duration::from_secs(0));
817    }
818
819    // ErrorHandler tests
820
821    #[test]
822    fn test_error_handler_new() {
823        let handler = ErrorHandler::new();
824        assert!(matches!(
825            handler.handle_error(&Error::Internal("test".into())),
826            RecoveryAction::Fail
827        ));
828    }
829
830    #[test]
831    fn test_error_handler_with_default_action() {
832        let handler = ErrorHandler::with_default_action(RecoveryAction::Ignore);
833        assert!(matches!(
834            handler.handle_error(&Error::Internal("test".into())),
835            RecoveryAction::Ignore
836        ));
837    }
838
839    #[test]
840    fn test_error_handler_transient_errors() {
841        let handler = ErrorHandler::new();
842
843        // I/O errors should retry
844        let action = handler.handle_error(&Error::Io("network error".into()));
845        assert!(matches!(action, RecoveryAction::Retry { .. }));
846
847        // Crypto errors should retry
848        let action = handler.handle_error(&Error::CryptoError("hash failed".into()));
849        assert!(matches!(action, RecoveryAction::Retry { .. }));
850    }
851
852    #[test]
853    fn test_error_handler_protocol_errors() {
854        let handler = ErrorHandler::new();
855
856        // Protocol errors should notify peer
857        let action = handler.handle_error(&Error::InvalidMessage("bad format".into()));
858        assert!(matches!(
859            action,
860            RecoveryAction::NotifyPeer { notify_type: 7 }
861        ));
862
863        let action = handler.handle_error(&Error::UnsupportedVersion(99));
864        assert!(matches!(action, RecoveryAction::NotifyPeer { .. }));
865    }
866
867    #[test]
868    fn test_error_handler_authentication_errors() {
869        let handler = ErrorHandler::new();
870
871        let action = handler.handle_error(&Error::AuthenticationFailed("bad sig".into()));
872        assert!(matches!(action, RecoveryAction::DeleteSa));
873    }
874
875    #[test]
876    fn test_error_handler_replay_attacks() {
877        let handler = ErrorHandler::new();
878
879        let action = handler.handle_error(&Error::ReplayDetected(12345));
880        assert!(matches!(action, RecoveryAction::Ignore));
881    }
882
883    #[test]
884    fn test_error_handler_state_errors() {
885        let handler = ErrorHandler::new();
886
887        let action = handler.handle_error(&Error::InvalidState("bad state".into()));
888        assert!(matches!(action, RecoveryAction::DeleteSa));
889
890        let action = handler.handle_error(&Error::InvalidStateTransition {
891            from: "Idle".into(),
892            to: "Established".into(),
893        });
894        assert!(matches!(action, RecoveryAction::DeleteSa));
895    }
896
897    #[test]
898    fn test_error_handler_sa_not_found() {
899        let handler = ErrorHandler::new();
900
901        let action = handler.handle_error(&Error::SaNotFound("SA-123".into()));
902        assert!(matches!(action, RecoveryAction::Ignore));
903    }
904
905    #[test]
906    fn test_error_handler_no_proposal_chosen() {
907        let handler = ErrorHandler::new();
908
909        let action = handler.handle_error(&Error::NoProposalChosen);
910        assert!(matches!(
911            action,
912            RecoveryAction::NotifyPeer { notify_type: 14 }
913        ));
914    }
915
916    #[test]
917    fn test_error_handler_set_retry_policy() {
918        let mut handler = ErrorHandler::new();
919
920        let custom_policy = RetryPolicy::new(
921            5,
922            std::time::Duration::from_secs(2),
923            1.5,
924            std::time::Duration::from_secs(30),
925        );
926
927        handler.set_default_retry_policy(custom_policy.clone());
928        assert_eq!(handler.default_retry_policy(), &custom_policy);
929    }
930
931    // ErrorCode tests
932
933    #[test]
934    fn test_error_code_values() {
935        assert_eq!(ErrorCode::InvalidMessage as u32, 1001);
936        assert_eq!(ErrorCode::AuthenticationFailed as u32, 2001);
937        assert_eq!(ErrorCode::InvalidState as u32, 3001);
938        assert_eq!(ErrorCode::ReplayDetected as u32, 4001);
939        assert_eq!(ErrorCode::NetworkError as u32, 5001);
940        assert_eq!(ErrorCode::InternalError as u32, 9001);
941    }
942
943    #[test]
944    fn test_error_code_as_u32() {
945        assert_eq!(ErrorCode::InvalidMessage.as_u32(), 1001);
946        assert_eq!(ErrorCode::NoProposalChosen.as_u32(), 1004);
947    }
948
949    #[test]
950    fn test_error_code_category() {
951        assert_eq!(ErrorCode::InvalidMessage.category(), "Protocol");
952        assert_eq!(ErrorCode::AuthenticationFailed.category(), "Crypto");
953        assert_eq!(ErrorCode::InvalidState.category(), "State");
954        assert_eq!(ErrorCode::ReplayDetected.category(), "Security");
955        assert_eq!(ErrorCode::NetworkError.category(), "Network");
956        assert_eq!(ErrorCode::InternalError.category(), "Internal");
957    }
958
959    // Error::code() tests
960
961    #[test]
962    fn test_error_code_mapping() {
963        assert_eq!(
964            Error::InvalidMessage("test".into()).code(),
965            Some(ErrorCode::InvalidMessage)
966        );
967        assert_eq!(
968            Error::AuthenticationFailed("bad auth".into()).code(),
969            Some(ErrorCode::AuthenticationFailed)
970        );
971        assert_eq!(
972            Error::NoProposalChosen.code(),
973            Some(ErrorCode::NoProposalChosen)
974        );
975        assert_eq!(
976            Error::ReplayDetected(123).code(),
977            Some(ErrorCode::ReplayDetected)
978        );
979        assert_eq!(
980            Error::Io("timeout".into()).code(),
981            Some(ErrorCode::NetworkError)
982        );
983    }
984
985    #[test]
986    fn test_error_code_none_for_some_variants() {
987        // Some error variants don't have codes
988        assert!(Error::MessageTooLarge(1000).code().is_some() == false);
989        assert!(Error::InvalidSpi(123).code().is_some() == false);
990    }
991
992    // Error::with_context() tests
993
994    #[test]
995    fn test_error_with_context() {
996        let err = Error::CryptoError("invalid key".to_string());
997        let err_with_context = err.with_context("ESP encryption");
998
999        assert_eq!(
1000            err_with_context.to_string(),
1001            "Cryptographic error: ESP encryption: invalid key"
1002        );
1003    }
1004
1005    #[test]
1006    fn test_error_with_context_multiple() {
1007        let err = Error::InvalidMessage("bad format".to_string());
1008        let err1 = err.with_context("IKE_SA_INIT");
1009        let err2 = err1.with_context("handshake");
1010
1011        assert!(err2
1012            .to_string()
1013            .contains("handshake: IKE_SA_INIT: bad format"));
1014    }
1015
1016    #[test]
1017    fn test_error_with_context_structured() {
1018        // Structured errors (non-string) should return unchanged
1019        let err = Error::InvalidLength {
1020            expected: 10,
1021            actual: 5,
1022        };
1023        let err_with_context = err.clone().with_context("test");
1024
1025        assert_eq!(err, err_with_context);
1026    }
1027
1028    // Error::is_retryable() tests
1029
1030    #[test]
1031    fn test_error_is_retryable() {
1032        assert!(Error::Io("timeout".into()).is_retryable());
1033        assert!(Error::CryptoError("hash failed".into()).is_retryable());
1034
1035        assert!(!Error::AuthenticationFailed("bad sig".into()).is_retryable());
1036        assert!(!Error::InvalidState("bad state".into()).is_retryable());
1037        assert!(!Error::NoProposalChosen.is_retryable());
1038    }
1039
1040    // Error::is_fatal() tests
1041
1042    #[test]
1043    fn test_error_is_fatal() {
1044        assert!(Error::AuthenticationFailed("bad auth".into()).is_fatal());
1045        assert!(Error::InvalidState("bad state".into()).is_fatal());
1046        assert!(Error::InvalidStateTransition {
1047            from: "A".into(),
1048            to: "B".into()
1049        }
1050        .is_fatal());
1051
1052        assert!(!Error::Io("timeout".into()).is_fatal());
1053        assert!(!Error::NoProposalChosen.is_fatal());
1054        assert!(!Error::ReplayDetected(123).is_fatal());
1055    }
1056}