1use std::fmt;
7
8pub type Result<T> = std::result::Result<T, Error>;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum ErrorCode {
18 InvalidMessage = 1001,
21 InvalidPayload = 1002,
23 UnsupportedVersion = 1003,
25 NoProposalChosen = 1004,
27 InvalidSyntax = 1005,
29
30 AuthenticationFailed = 2001,
33 CryptoError = 2002,
35 InvalidKeyLength = 2003,
37
38 InvalidState = 3001,
41 InvalidStateTransition = 3002,
43 SaNotFound = 3003,
45
46 ReplayDetected = 4001,
49
50 NetworkError = 5001,
53 NetworkTimeout = 5002,
55
56 InternalError = 9001,
59}
60
61impl ErrorCode {
62 pub fn as_u32(self) -> u32 {
64 self as u32
65 }
66
67 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#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum Error {
96 InvalidMessage(String),
98
99 InvalidPayload(String),
101
102 InvalidParameter(String),
104
105 UnsupportedVersion(u8),
107
108 UnsupportedExchangeType(u8),
110
111 NoProposalChosen,
113
114 InvalidProposal(String),
116
117 AuthenticationFailed(String),
119
120 SaNotFound(String),
122
123 CryptoError(String),
125
126 ReplayDetected(u64),
128
129 InvalidLength {
131 expected: usize,
133 actual: usize,
135 },
136
137 BufferTooShort {
139 required: usize,
141 available: usize,
143 },
144
145 MessageTooLarge(u32),
147
148 InvalidSpi(u32),
150
151 InvalidSequence(u64),
153
154 InvalidState(String),
156
157 InvalidStateTransition {
159 from: String,
161 to: String,
163 },
164
165 MissingPayload(String),
167
168 InvalidExchangeType,
170
171 InvalidMessageId {
173 expected: u32,
175 received: u32,
177 },
178
179 InvalidKeyLength {
181 expected: usize,
183 actual: usize,
185 },
186
187 InvalidIvLength {
189 expected: usize,
191 actual: usize,
193 },
194
195 Io(String),
197
198 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 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 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 other => other,
359 }
360 }
361
362 pub fn is_retryable(&self) -> bool {
367 matches!(self, Error::Io(_) | Error::CryptoError(_))
368 }
369
370 pub fn is_fatal(&self) -> bool {
374 matches!(
375 self,
376 Error::AuthenticationFailed(_)
377 | Error::InvalidState(_)
378 | Error::InvalidStateTransition { .. }
379 )
380 }
381}
382
383impl From<std::io::Error> for Error {
385 fn from(err: std::io::Error) -> Self {
386 Error::Io(err.to_string())
387 }
388}
389
390#[derive(Debug, Clone, PartialEq)]
394pub enum RecoveryAction {
395 Retry {
397 max_attempts: u32,
399 base_delay: std::time::Duration,
401 },
402
403 NotifyPeer {
405 notify_type: u16,
407 },
408
409 DeleteSa,
411
412 Reset,
414
415 Ignore,
417
418 Fail,
420}
421
422#[derive(Debug, Clone, PartialEq)]
446pub struct RetryPolicy {
447 max_attempts: u32,
449
450 base_delay: std::time::Duration,
452
453 backoff_multiplier: f32,
458
459 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 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 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 pub fn should_retry(&self, attempt: u32) -> bool {
519 attempt < self.max_attempts
520 }
521
522 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 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 if delay > self.max_delay {
546 self.max_delay
547 } else {
548 delay
549 }
550 }
551
552 pub fn max_attempts(&self) -> u32 {
554 self.max_attempts
555 }
556
557 pub fn base_delay(&self) -> std::time::Duration {
559 self.base_delay
560 }
561
562 pub fn backoff_multiplier(&self) -> f32 {
564 self.backoff_multiplier
565 }
566
567 pub fn max_delay(&self) -> std::time::Duration {
569 self.max_delay
570 }
571}
572
573#[derive(Debug, Clone)]
577pub struct ErrorHandler {
578 default_action: RecoveryAction,
580
581 default_retry: RetryPolicy,
583}
584
585impl Default for ErrorHandler {
586 fn default() -> Self {
587 Self::new()
588 }
589}
590
591impl ErrorHandler {
592 pub fn new() -> Self {
594 ErrorHandler {
595 default_action: RecoveryAction::Fail,
596 default_retry: RetryPolicy::default(),
597 }
598 }
599
600 pub fn with_default_action(action: RecoveryAction) -> Self {
602 ErrorHandler {
603 default_action: action,
604 default_retry: RetryPolicy::default(),
605 }
606 }
607
608 pub fn handle_error(&self, error: &Error) -> RecoveryAction {
618 match error {
619 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 Error::InvalidMessage(_)
627 | Error::InvalidPayload(_)
628 | Error::InvalidParameter(_)
629 | Error::UnsupportedVersion(_)
630 | Error::UnsupportedExchangeType(_) => RecoveryAction::NotifyPeer { notify_type: 7 }, Error::AuthenticationFailed(_) => RecoveryAction::DeleteSa,
634
635 Error::ReplayDetected(_) => RecoveryAction::Ignore,
637
638 Error::InvalidState(_) | Error::InvalidStateTransition { .. } => {
640 RecoveryAction::DeleteSa
641 }
642
643 Error::SaNotFound(_) => RecoveryAction::Ignore,
645
646 Error::NoProposalChosen => RecoveryAction::NotifyPeer { notify_type: 14 }, _ => self.default_action.clone(),
651 }
652 }
653
654 pub fn default_retry_policy(&self) -> &RetryPolicy {
656 &self.default_retry
657 }
658
659 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 #[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 #[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)); 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 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 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)); assert_eq!(policy.get_delay(5), std::time::Duration::from_secs(10)); }
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 #[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 let action = handler.handle_error(&Error::Io("network error".into()));
845 assert!(matches!(action, RecoveryAction::Retry { .. }));
846
847 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 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 #[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 #[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 assert!(Error::MessageTooLarge(1000).code().is_some() == false);
989 assert!(Error::InvalidSpi(123).code().is_some() == false);
990 }
991
992 #[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 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 #[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 #[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}