1use thiserror::Error;
57
58pub type Result<T, E = AuthError> = std::result::Result<T, E>;
64
65#[derive(Error, Debug)]
135pub enum AuthError {
136 #[error("Configuration error: {message}")]
141 Configuration {
142 message: String,
143 #[source]
144 source: Option<Box<dyn std::error::Error + Send + Sync>>,
145 help: Option<String>,
147 docs_url: Option<String>,
149 suggested_fix: Option<String>,
151 },
152
153 #[error("Authentication method '{method}' error: {message}")]
158 AuthMethod {
159 method: String,
160 message: String,
161 help: Option<String>,
163 docs_url: Option<String>,
165 suggested_fix: Option<String>,
167 },
168
169 #[error("Token error: {0}")]
171 Token(#[from] TokenError),
172
173 #[error("Permission error: {0}")]
175 Permission(#[from] PermissionError),
176
177 #[error("Storage error: {0}")]
179 Storage(#[from] StorageError),
180
181 #[error("Network error: {0}")]
183 Network(#[from] reqwest::Error),
184
185 #[error("JSON error: {0}")]
187 Json(#[from] serde_json::Error),
188
189 #[error("JWT error: {0}")]
191 Jwt(#[from] jsonwebtoken::errors::Error),
192
193 #[error("YAML error: {0}")]
195 Yaml(#[from] serde_yaml::Error),
196
197 #[error("TOML error: {0}")]
199 Toml(#[from] toml::ser::Error),
200
201 #[cfg(feature = "prometheus")]
203 #[error("Metrics error: {0}")]
204 Metrics(#[from] prometheus::Error),
205
206 #[error("IO error: {0}")]
208 Io(#[from] std::io::Error),
209
210 #[error("CLI error: {0}")]
212 Cli(String),
213
214 #[error("System time error: {0}")]
216 SystemTime(#[from] std::time::SystemTimeError),
217
218 #[error("Rate limit exceeded: {message}")]
220 RateLimit { message: String },
221
222 #[error("Too many concurrent sessions for user")]
224 TooManyConcurrentSessions,
225
226 #[error("MFA error: {0}")]
228 Mfa(#[from] MfaError),
229
230 #[error("Device flow error: {0}")]
232 DeviceFlow(#[from] DeviceFlowError),
233
234 #[error("OAuth provider error: {0}")]
236 OAuthProvider(#[from] OAuthProviderError),
237
238 #[error("Password verification failed: {0}")]
240 PasswordVerification(String),
241
242 #[error("Password hashing failed: {0}")]
244 PasswordHashing(String),
245
246 #[error("User not found")]
248 UserNotFound,
249
250 #[error("Invalid input: {0}")]
252 InvalidInput(String),
253
254 #[error("Hardware token error: {0}")]
256 HardwareToken(String),
257
258 #[error("Backup code verification failed: {0}")]
260 BackupCodeVerification(String),
261
262 #[error("Backup code hashing failed: {0}")]
264 BackupCodeHashing(String),
265
266 #[error("Invalid secret format")]
268 InvalidSecret,
269
270 #[error("User profile error: {message}")]
272 UserProfile { message: String },
273
274 #[error("Invalid credential: {credential_type} - {message}")]
276 InvalidCredential {
277 credential_type: String,
278 message: String,
279 },
280
281 #[error("Authentication timeout after {timeout_seconds} seconds")]
283 Timeout { timeout_seconds: u64 },
284
285 #[error("Provider '{provider}' is not configured or supported")]
287 ProviderNotConfigured { provider: String },
288
289 #[error("Cryptography error: {message}")]
291 Crypto { message: String },
292
293 #[error("Validation error: {message}")]
295 Validation { message: String },
296
297 #[error("Internal error: {message}")]
299 Internal { message: String },
300
301 #[error("Invalid request: {0}")]
303 InvalidRequest(String),
304
305 #[error(
307 "Step-up authentication required: current level '{current_level}', required level '{required_level}'"
308 )]
309 StepUpRequired {
310 current_level: String,
311 required_level: String,
312 step_up_url: String,
313 },
314
315 #[error("Session error: {0}")]
317 SessionError(String),
318
319 #[error("Unauthorized: {0}")]
321 Unauthorized(String),
322
323 #[error("Token generation error: {0}")]
325 TokenGeneration(String),
326
327 #[error("Invalid token: {0}")]
329 InvalidToken(String),
330
331 #[error("Unsupported provider: {0}")]
333 UnsupportedProvider(String),
334
335 #[error("Network error: {0}")]
337 NetworkError(String),
338
339 #[error("Parse error: {0}")]
341 ParseError(String),
342
343 #[error("Configuration error: {0}")]
345 ConfigurationError(String),
346}
347
348#[derive(Error, Debug)]
350pub enum TokenError {
351 #[error("Token has expired")]
352 Expired,
353
354 #[error("Token is invalid: {message}")]
355 Invalid { message: String },
356
357 #[error("Token not found")]
358 NotFound,
359
360 #[error("Token is missing")]
361 Missing,
362
363 #[error("Token creation failed: {message}")]
364 CreationFailed { message: String },
365
366 #[error("Token refresh failed: {message}")]
367 RefreshFailed { message: String },
368
369 #[error("Token revocation failed: {message}")]
370 RevocationFailed { message: String },
371}
372
373#[derive(Error, Debug)]
375pub enum PermissionError {
376 #[error("Access denied: missing permission '{permission}' for resource '{resource}'")]
377 AccessDenied {
378 permission: String,
379 resource: String,
380 },
381
382 #[error("Role '{role}' not found")]
383 RoleNotFound { role: String },
384
385 #[error("Permission '{permission}' not found")]
386 PermissionNotFound { permission: String },
387
388 #[error("Invalid permission format: {message}")]
389 InvalidFormat { message: String },
390
391 #[error("Permission denied: {message}")]
392 Denied {
393 action: String,
394 resource: String,
395 message: String,
396 },
397}
398
399#[derive(Error, Debug)]
401pub enum StorageError {
402 #[error("Connection failed: {message}")]
403 ConnectionFailed { message: String },
404
405 #[error("Operation failed: {message}")]
406 OperationFailed { message: String },
407
408 #[error("Serialization error: {message}")]
409 Serialization { message: String },
410
411 #[error("Storage backend not available")]
412 BackendUnavailable,
413}
414
415#[derive(Error, Debug)]
417pub enum MfaError {
418 #[error("MFA challenge expired")]
419 ChallengeExpired,
420
421 #[error("Invalid MFA code")]
422 InvalidCode,
423
424 #[error("MFA method not supported: {method}")]
425 MethodNotSupported { method: String },
426
427 #[error("MFA setup required")]
428 SetupRequired,
429
430 #[error("MFA verification failed: {message}")]
431 VerificationFailed { message: String },
432}
433
434#[derive(Error, Debug)]
436pub enum DeviceFlowError {
437 #[error("Authorization pending - user has not yet completed authorization")]
438 AuthorizationPending,
439
440 #[error("Slow down - polling too frequently")]
441 SlowDown,
442
443 #[error("Device code expired")]
444 ExpiredToken,
445
446 #[error("Access denied by user")]
447 AccessDenied,
448
449 #[error("Invalid device code")]
450 InvalidDeviceCode,
451
452 #[error("Unsupported grant type")]
453 UnsupportedGrantType,
454}
455
456#[derive(Error, Debug)]
458pub enum OAuthProviderError {
459 #[error("Invalid authorization code")]
460 InvalidAuthorizationCode,
461
462 #[error("Invalid redirect URI")]
463 InvalidRedirectUri,
464
465 #[error("Invalid client credentials")]
466 InvalidClientCredentials,
467
468 #[error("Insufficient scope: required '{required}', granted '{granted}'")]
469 InsufficientScope { required: String, granted: String },
470
471 #[error("Provider '{provider}' does not support '{feature}'")]
472 UnsupportedFeature { provider: String, feature: String },
473
474 #[error("Rate limited by provider: {message}")]
475 RateLimited { message: String },
476}
477
478impl AuthError {
479 pub fn config(message: impl Into<String>) -> Self {
481 Self::Configuration {
482 message: message.into(),
483 source: None,
484 help: None,
485 docs_url: None,
486 suggested_fix: None,
487 }
488 }
489
490 pub fn config_with_help(
492 message: impl Into<String>,
493 help: impl Into<String>,
494 suggested_fix: Option<String>,
495 ) -> Self {
496 Self::Configuration {
497 message: message.into(),
498 source: None,
499 help: Some(help.into()),
500 docs_url: Some(
501 "https://docs.rs/auth-framework/latest/auth_framework/config/".to_string(),
502 ),
503 suggested_fix,
504 }
505 }
506
507 pub fn jwt_secret_too_short(current_length: usize) -> Self {
509 Self::Configuration {
510 message: format!(
511 "JWT secret too short (got {} characters, need 32+ for security)",
512 current_length
513 ),
514 source: None,
515 help: Some("Use a cryptographically secure random string of at least 32 characters".to_string()),
516 docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/config/struct.SecurityConfig.html".to_string()),
517 suggested_fix: Some("Generate a secure secret: `openssl rand -hex 32`".to_string()),
518 }
519 }
520
521 pub fn production_memory_storage() -> Self {
523 Self::Configuration {
524 message: "Memory storage is not suitable for production environments".to_string(),
525 source: None,
526 help: Some("Use a persistent storage backend like PostgreSQL or Redis".to_string()),
527 docs_url: Some("https://docs.rs/auth-framework/latest/auth_framework/storage/".to_string()),
528 suggested_fix: Some("Configure PostgreSQL: .with_postgres(\"postgresql://...\") or Redis: .with_redis(\"redis://...\")".to_string()),
529 }
530 }
531
532 pub fn auth_method(method: impl Into<String>, message: impl Into<String>) -> Self {
534 Self::AuthMethod {
535 method: method.into(),
536 message: message.into(),
537 help: None,
538 docs_url: None,
539 suggested_fix: None,
540 }
541 }
542
543 pub fn auth_method_with_help(
545 method: impl Into<String>,
546 message: impl Into<String>,
547 help: impl Into<String>,
548 suggested_fix: Option<String>,
549 ) -> Self {
550 Self::AuthMethod {
551 method: method.into(),
552 message: message.into(),
553 help: Some(help.into()),
554 docs_url: Some(
555 "https://docs.rs/auth-framework/latest/auth_framework/methods/".to_string(),
556 ),
557 suggested_fix,
558 }
559 }
560
561 pub fn rate_limit(message: impl Into<String>) -> Self {
563 Self::RateLimit {
564 message: message.into(),
565 }
566 }
567
568 pub fn crypto(message: impl Into<String>) -> Self {
570 Self::Crypto {
571 message: message.into(),
572 }
573 }
574
575 pub fn validation(message: impl Into<String>) -> Self {
577 Self::Validation {
578 message: message.into(),
579 }
580 }
581
582 pub fn internal(message: impl Into<String>) -> Self {
584 Self::Internal {
585 message: message.into(),
586 }
587 }
588
589 pub fn authorization(message: impl Into<String>) -> Self {
591 Self::Permission(PermissionError::Denied {
592 action: "authorize".to_string(),
593 resource: "resource".to_string(),
594 message: message.into(),
595 })
596 }
597
598 pub fn access_denied(message: impl Into<String>) -> Self {
600 Self::Permission(PermissionError::Denied {
601 action: "access".to_string(),
602 resource: "resource".to_string(),
603 message: message.into(),
604 })
605 }
606
607 pub fn token(message: impl Into<String>) -> Self {
609 Self::Token(TokenError::Invalid {
610 message: message.into(),
611 })
612 }
613
614 pub fn device_flow(error: DeviceFlowError) -> Self {
616 Self::DeviceFlow(error)
617 }
618
619 pub fn oauth_provider(error: OAuthProviderError) -> Self {
621 Self::OAuthProvider(error)
622 }
623
624 pub fn user_profile(message: impl Into<String>) -> Self {
626 Self::UserProfile {
627 message: message.into(),
628 }
629 }
630
631 pub fn invalid_credential(
633 credential_type: impl Into<String>,
634 message: impl Into<String>,
635 ) -> Self {
636 Self::InvalidCredential {
637 credential_type: credential_type.into(),
638 message: message.into(),
639 }
640 }
641
642 pub fn timeout(timeout_seconds: u64) -> Self {
644 Self::Timeout { timeout_seconds }
645 }
646
647 pub fn provider_not_configured(provider: impl Into<String>) -> Self {
649 Self::ProviderNotConfigured {
650 provider: provider.into(),
651 }
652 }
653
654 pub fn rate_limited(message: impl Into<String>) -> Self {
656 Self::RateLimit {
657 message: message.into(),
658 }
659 }
660
661 pub fn configuration(message: impl Into<String>) -> Self {
663 Self::Configuration {
664 message: message.into(),
665 source: None,
666 help: None,
667 docs_url: None,
668 suggested_fix: None,
669 }
670 }
671}
672
673impl TokenError {
674 pub fn creation_failed(message: impl Into<String>) -> Self {
676 Self::CreationFailed {
677 message: message.into(),
678 }
679 }
680
681 pub fn refresh_failed(message: impl Into<String>) -> Self {
683 Self::RefreshFailed {
684 message: message.into(),
685 }
686 }
687
688 pub fn revocation_failed(message: impl Into<String>) -> Self {
690 Self::RevocationFailed {
691 message: message.into(),
692 }
693 }
694}
695
696impl PermissionError {
697 pub fn access_denied(permission: impl Into<String>, resource: impl Into<String>) -> Self {
699 Self::AccessDenied {
700 permission: permission.into(),
701 resource: resource.into(),
702 }
703 }
704
705 pub fn role_not_found(role: impl Into<String>) -> Self {
707 Self::RoleNotFound { role: role.into() }
708 }
709
710 pub fn permission_not_found(permission: impl Into<String>) -> Self {
712 Self::PermissionNotFound {
713 permission: permission.into(),
714 }
715 }
716
717 pub fn invalid_format(message: impl Into<String>) -> Self {
719 Self::InvalidFormat {
720 message: message.into(),
721 }
722 }
723}
724
725impl StorageError {
726 pub fn connection_failed(message: impl Into<String>) -> Self {
728 Self::ConnectionFailed {
729 message: message.into(),
730 }
731 }
732
733 pub fn operation_failed(message: impl Into<String>) -> Self {
735 Self::OperationFailed {
736 message: message.into(),
737 }
738 }
739
740 pub fn serialization(message: impl Into<String>) -> Self {
742 Self::Serialization {
743 message: message.into(),
744 }
745 }
746}
747
748impl MfaError {
749 pub fn method_not_supported(method: impl Into<String>) -> Self {
751 Self::MethodNotSupported {
752 method: method.into(),
753 }
754 }
755
756 pub fn verification_failed(message: impl Into<String>) -> Self {
758 Self::VerificationFailed {
759 message: message.into(),
760 }
761 }
762}
763
764#[cfg(feature = "actix-integration")]
766impl actix_web::ResponseError for AuthError {
767 fn error_response(&self) -> actix_web::HttpResponse {
768 match self {
769 AuthError::Token(_) => {
770 actix_web::HttpResponse::Unauthorized().json(serde_json::json!({
771 "error": "invalid_token",
772 "error_description": self.to_string()
773 }))
774 }
775 AuthError::Permission(_) => {
776 actix_web::HttpResponse::Forbidden().json(serde_json::json!({
777 "error": "insufficient_permissions",
778 "error_description": self.to_string()
779 }))
780 }
781 AuthError::RateLimit { .. } => {
782 actix_web::HttpResponse::TooManyRequests().json(serde_json::json!({
783 "error": "rate_limit_exceeded",
784 "error_description": self.to_string()
785 }))
786 }
787 AuthError::Configuration { .. }
788 | AuthError::Storage(_)
789 | AuthError::Internal { .. } => {
790 actix_web::HttpResponse::InternalServerError().json(serde_json::json!({
791 "error": "internal_error",
792 "error_description": "An internal error occurred"
793 }))
794 }
795 _ => actix_web::HttpResponse::BadRequest().json(serde_json::json!({
796 "error": "bad_request",
797 "error_description": self.to_string()
798 })),
799 }
800 }
801
802 fn status_code(&self) -> actix_web::http::StatusCode {
803 match self {
804 AuthError::Token(_) => actix_web::http::StatusCode::UNAUTHORIZED,
805 AuthError::Permission(_) => actix_web::http::StatusCode::FORBIDDEN,
806 AuthError::RateLimit { .. } => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
807 AuthError::Internal { .. }
808 | AuthError::Configuration { .. }
809 | AuthError::Storage(_) => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
810 _ => actix_web::http::StatusCode::BAD_REQUEST,
811 }
812 }
813}
814
815impl From<Box<dyn std::error::Error + Send + Sync>> for AuthError {
817 fn from(error: Box<dyn std::error::Error + Send + Sync>) -> Self {
818 AuthError::Cli(format!("Admin tool error: {}", error))
819 }
820}
821
822impl From<Box<dyn std::error::Error>> for AuthError {
823 fn from(error: Box<dyn std::error::Error>) -> Self {
824 AuthError::Cli(format!("Admin tool error: {}", error))
825 }
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831 use std::error::Error;
832
833 #[test]
834 fn test_auth_error_creation() {
835 let token_error = AuthError::token("Invalid JWT signature");
836 assert!(matches!(token_error, AuthError::Token(_)));
837 assert!(token_error.to_string().contains("Invalid JWT signature"));
838
839 let permission_error = AuthError::access_denied("Access denied");
840 assert!(matches!(permission_error, AuthError::Permission(_)));
841 assert!(permission_error.to_string().contains("Access denied"));
842
843 let config_error = AuthError::config("Database connection failed");
844 assert!(matches!(config_error, AuthError::Configuration { .. }));
845 assert!(
846 config_error
847 .to_string()
848 .contains("Database connection failed")
849 );
850 }
851
852 #[test]
853 fn test_auth_error_categorization() {
854 let errors = vec![
856 (AuthError::token("test"), "Token"),
857 (AuthError::access_denied("test"), "Permission"),
858 (AuthError::config("test"), "Configuration"),
859 (AuthError::crypto("test"), "Crypto"),
860 (AuthError::validation("test"), "Validation"),
861 ];
862
863 for (error, expected_category) in errors {
864 let error_string = format!("{:?}", error);
865 assert!(
866 error_string.contains(expected_category),
867 "Error {:?} should contain category {}",
868 error,
869 expected_category
870 );
871 }
872 }
873
874 #[test]
875 fn test_rate_limit_error() {
876 let rate_limit_error = AuthError::rate_limit("Too many requests");
877
878 match rate_limit_error {
879 AuthError::RateLimit { message } => {
880 assert_eq!(message, "Too many requests");
881 }
882 _ => panic!("Expected RateLimit error"),
883 }
884 }
885
886 #[test]
887 fn test_validation_error() {
888 let validation_error = AuthError::validation("username must not be empty");
889
890 match validation_error {
891 AuthError::Validation { message } => {
892 assert_eq!(message, "username must not be empty");
893 }
894 _ => panic!("Expected Validation error"),
895 }
896 }
897
898 #[test]
899 fn test_configuration_error() {
900 let config_error = AuthError::config("jwt_secret is required");
901
902 match config_error {
903 AuthError::Configuration { message, .. } => {
904 assert_eq!(message, "jwt_secret is required");
905 }
906 _ => panic!("Expected Configuration error"),
907 }
908 }
909
910 #[test]
911 fn test_error_chain() {
912 let root_cause = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
913 let auth_error = AuthError::internal(format!("Config file error: {}", root_cause));
914
915 assert!(auth_error.to_string().contains("File not found"));
917 assert!(auth_error.to_string().contains("Config file error"));
918 }
919
920 #[test]
921 fn test_error_source() {
922 let token_error = AuthError::token("JWT parsing failed");
923
924 assert!(token_error.source().is_some());
927
928 let error_msg = format!("{}", token_error);
930 assert!(error_msg.contains("JWT parsing failed"));
931 }
932
933 #[test]
934 fn test_from_conversions() {
935 let io_error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "Access denied");
937 let auth_error: AuthError = io_error.into();
938 assert!(matches!(auth_error, AuthError::Io(_)));
939
940 let json_str = r#"{"invalid": json"#;
942 let json_error: serde_json::Error =
943 serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();
944 let auth_error: AuthError = json_error.into();
945 assert!(matches!(auth_error, AuthError::Json(_)));
946 }
947
948 #[test]
949 fn test_error_equality() {
950 let error1 = AuthError::token("Same message");
951 let error2 = AuthError::token("Same message");
952 let error3 = AuthError::token("Different message");
953
954 assert_eq!(format!("{:?}", error1), format!("{:?}", error2));
956 assert_ne!(format!("{:?}", error1), format!("{:?}", error3));
957 }
958
959 #[test]
960 fn test_actix_web_integration() {
961 #[cfg(feature = "actix-web")]
962 {
963 use actix_web::ResponseError;
964
965 assert_eq!(
967 AuthError::token("test").status_code(),
968 actix_web::http::StatusCode::UNAUTHORIZED
969 );
970 assert_eq!(
971 AuthError::access_denied("test").status_code(),
972 actix_web::http::StatusCode::FORBIDDEN
973 );
974 assert_eq!(
975 AuthError::rate_limit("test").status_code(),
976 actix_web::http::StatusCode::TOO_MANY_REQUESTS
977 );
978 assert_eq!(
979 AuthError::internal("test").status_code(),
980 actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
981 );
982 }
983 }
984
985 #[test]
986 fn test_error_message_safety() {
987 let sensitive_data = "password123";
989 let safe_error = AuthError::token("Invalid credentials");
990
991 assert!(!safe_error.to_string().contains(sensitive_data));
993
994 let config_error = AuthError::config("connection failed");
996 assert!(!config_error.to_string().contains("password"));
997 assert!(!config_error.to_string().contains("secret"));
998 }
999
1000 #[test]
1001 fn test_cli_error_conversion() {
1002 let boxed_error: Box<dyn std::error::Error + Send + Sync> = "CLI operation failed".into();
1003 let auth_error: AuthError = boxed_error.into();
1004
1005 assert!(matches!(auth_error, AuthError::Cli(_)));
1006 assert!(auth_error.to_string().contains("CLI operation failed"));
1007 }
1008
1009 #[test]
1010 fn test_error_variants_coverage() {
1011 let test_errors = vec![
1013 AuthError::token("token error"),
1014 AuthError::access_denied("permission error"),
1015 AuthError::internal("internal error"),
1016 AuthError::crypto("crypto error"),
1017 AuthError::Cli("cli error".to_string()),
1018 AuthError::validation("validation error"),
1019 AuthError::config("config error"),
1020 AuthError::rate_limit("rate limit error"),
1021 ];
1022
1023 for error in test_errors {
1024 assert!(
1026 !error.to_string().is_empty(),
1027 "Error should have message: {:?}",
1028 error
1029 );
1030
1031 let debug_repr = format!("{:?}", error);
1033 assert!(
1034 !debug_repr.is_empty(),
1035 "Error should have debug representation: {:?}",
1036 error
1037 );
1038 }
1039 }
1040
1041 #[test]
1042 fn test_oauth_specific_errors() {
1043 let invalid_client = AuthError::auth_method("oauth", "Client authentication failed");
1045 assert!(
1046 invalid_client
1047 .to_string()
1048 .contains("Client authentication failed")
1049 );
1050
1051 let invalid_grant = AuthError::auth_method("oauth", "Authorization code expired");
1052 assert!(
1053 invalid_grant
1054 .to_string()
1055 .contains("Authorization code expired")
1056 );
1057 }
1058
1059 #[test]
1060 fn test_error_context_preservation() {
1061 let original_msg = "Original error message";
1063 let context_msg = "Additional context";
1064
1065 let base_error = AuthError::internal(original_msg);
1066 let contextual_error = AuthError::internal(format!("{}: {}", context_msg, base_error));
1067
1068 assert!(contextual_error.to_string().contains(original_msg));
1069 assert!(contextual_error.to_string().contains(context_msg));
1070 }
1071
1072 #[test]
1073 fn test_error_serialization() {
1074 let error = AuthError::validation("email invalid format");
1076
1077 let error_response = serde_json::json!({
1079 "error": "validation_failed",
1080 "message": error.to_string(),
1081 "field": "email"
1082 });
1083
1084 assert!(
1085 error_response["message"]
1086 .as_str()
1087 .unwrap()
1088 .contains("invalid format")
1089 );
1090 }
1091
1092 #[test]
1093 fn test_concurrent_error_creation() {
1094 use std::thread;
1095
1096 let handles: Vec<_> = (0..10)
1097 .map(|i| {
1098 thread::spawn(move || {
1099 let error = AuthError::token(format!("Concurrent error {}", i));
1100 assert!(
1101 error
1102 .to_string()
1103 .contains(&format!("Concurrent error {}", i))
1104 );
1105 error
1106 })
1107 })
1108 .collect();
1109
1110 for handle in handles {
1112 let error = handle.join().unwrap();
1113 assert!(!error.to_string().is_empty());
1114 }
1115 }
1116}