fraiseql-core 2.2.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Security-specific error types for comprehensive error handling.
//!
//! This module defines all security-related error types used throughout
//! the framework. No `PyO3` decorators - all types are pure Rust.
//!
//! Note: The `PyO3` FFI wrappers for Python are in `py/src/ffi/errors.rs`

use std::fmt;

/// Main security error type for all security operations.
///
/// Covers rate limiting, query validation, CORS, CSRF, audit logging,
/// and security configuration errors.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SecurityError {
    /// Rate limiting exceeded - client has made too many requests.
    ///
    /// Contains:
    /// - `retry_after`: Seconds to wait before retrying
    /// - `limit`: Maximum allowed requests
    /// - `window_secs`: Time window in seconds
    RateLimitExceeded {
        /// Seconds to wait before retrying
        retry_after: u64,
        /// Maximum allowed requests
        limit:       usize,
        /// Time window in seconds
        window_secs: u64,
    },

    /// Query validation: depth exceeds maximum allowed.
    ///
    /// GraphQL queries can nest arbitrarily deep, which can cause
    /// excessive database queries or resource consumption.
    QueryTooDeep {
        /// Actual query depth
        depth:     usize,
        /// Maximum allowed depth
        max_depth: usize,
    },

    /// Query validation: complexity exceeds configured limit.
    ///
    /// Complexity is calculated as a weighted sum of field costs,
    /// accounting for pagination and nested selections.
    QueryTooComplex {
        /// Actual query complexity score
        complexity:     usize,
        /// Maximum allowed complexity
        max_complexity: usize,
    },

    /// Query validation: size exceeds maximum allowed bytes.
    ///
    /// Very large queries can consume memory or cause `DoS`.
    QueryTooLarge {
        /// Actual query size in bytes
        size:     usize,
        /// Maximum allowed size in bytes
        max_size: usize,
    },

    /// CORS origin not in allowed list.
    OriginNotAllowed(String),

    /// CORS HTTP method not allowed.
    MethodNotAllowed(String),

    /// CORS header not in allowed list.
    HeaderNotAllowed(String),

    /// CSRF token validation failed.
    InvalidCSRFToken(String),

    /// CSRF token session ID mismatch.
    CSRFSessionMismatch,

    /// Audit log write failure.
    ///
    /// Audit logging to the database failed. The underlying
    /// reason is captured in the error string.
    AuditLogFailure(String),

    /// Security configuration error.
    ///
    /// The security configuration is invalid or incomplete.
    SecurityConfigError(String),

    /// TLS/HTTPS required but connection is not secure.
    ///
    /// The security profile requires all connections to be HTTPS/TLS,
    /// but an HTTP connection was received.
    TlsRequired {
        /// Description of what was required
        detail: String,
    },

    /// TLS version is below the minimum required version.
    ///
    /// The connection uses TLS but the version is too old. For example,
    /// if TLS 1.3 is required but the connection uses TLS 1.2.
    TlsVersionTooOld {
        /// The TLS version actually used
        current:  crate::security::TlsVersion,
        /// The minimum TLS version required
        required: crate::security::TlsVersion,
    },

    /// Mutual TLS (client certificate) required but not provided.
    ///
    /// The security profile requires mTLS, meaning clients must present
    /// a valid X.509 certificate, but none was provided.
    MtlsRequired {
        /// Description of what was required
        detail: String,
    },

    /// Client certificate validation failed.
    ///
    /// A client certificate was presented, but it failed validation.
    /// This could be due to an invalid signature, expired certificate,
    /// revoked certificate, or other validation errors.
    InvalidClientCert {
        /// Description of why validation failed
        detail: String,
    },

    /// Authentication is required but none was provided.
    ///
    /// Used in auth middleware when authentication is required
    /// (configured or policy enforces it) but no valid credentials
    /// were found in the request.
    AuthRequired,

    /// Authentication token is invalid or malformed.
    ///
    /// The provided authentication token (e.g., JWT) failed to parse
    /// or validate. Could be due to invalid signature, bad format, etc.
    InvalidToken,

    /// JWT signature verification failed.
    ///
    /// The token's signature does not match the configured signing secret.
    /// Most commonly caused by a wrong or rotated `FRAISEQL_JWT_SECRET`.
    JwtSignatureInvalid,

    /// JWT issuer claim does not match the expected issuer.
    ///
    /// The token was issued by a different service than expected.
    /// Check `[security.jwt] issuer` in fraiseql.toml.
    JwtIssuerMismatch {
        /// The expected issuer from configuration
        expected: String,
    },

    /// JWT audience claim does not match the expected audience.
    ///
    /// The token was issued for a different service or audience.
    /// Check `[security.jwt] audience` in fraiseql.toml.
    JwtAudienceMismatch {
        /// The expected audience from configuration
        expected: String,
    },

    /// Authentication token has expired.
    ///
    /// The authentication token has an 'exp' claim and that timestamp
    /// has passed. The user needs to re-authenticate.
    TokenExpired {
        /// The time when the token expired
        expired_at: chrono::DateTime<chrono::Utc>,
    },

    /// Authentication token is missing a required claim.
    ///
    /// The authentication token doesn't have a required claim like 'sub', 'exp', etc.
    TokenMissingClaim {
        /// The name of the claim that's missing
        claim: String,
    },

    /// Authentication token algorithm doesn't match expected algorithm.
    ///
    /// The token was signed with a different algorithm than expected
    /// (e.g., token used HS256 but system expects RS256).
    InvalidTokenAlgorithm {
        /// The algorithm used in the token
        algorithm: String,
    },

    /// JWT token has been replayed — its `jti` (JWT ID) was already used.
    ///
    /// A previously-validated token is being reused. This indicates a
    /// stolen-token replay attack. The token should be rejected and the event
    /// should trigger a security alert.
    TokenReplayed,

    /// GraphQL introspection query is not allowed.
    ///
    /// The security policy disallows introspection queries (__schema, __type),
    /// typically in production to prevent schema information leakage.
    IntrospectionDisabled {
        /// Description of why introspection is disabled
        detail: String,
    },

    /// Query contains too many aliases (alias amplification attack).
    ///
    /// Alias amplification is a `DoS` technique where many aliases resolve the same
    /// expensive field, multiplying backend work with a small query string.
    TooManyAliases {
        /// Actual number of aliases in the query
        alias_count: usize,
        /// Maximum allowed alias count
        max_aliases: usize,
    },

    /// Query is not valid GraphQL syntax.
    ///
    /// The query string could not be parsed by the GraphQL parser.
    MalformedQuery(String),
}

/// Convenience type alias for security operation results.
///
/// Use `Result<T>` in security modules for consistent error handling.
pub(crate) type Result<T> = std::result::Result<T, SecurityError>;

impl fmt::Display for SecurityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RateLimitExceeded {
                retry_after,
                limit,
                window_secs,
            } => {
                write!(
                    f,
                    "Rate limit exceeded. Limit: {limit} per {window_secs} seconds. Retry after: {retry_after} seconds"
                )
            },
            Self::QueryTooDeep { depth, max_depth } => {
                write!(f, "Query too deep: {depth} levels (max: {max_depth})")
            },
            Self::QueryTooComplex {
                complexity,
                max_complexity,
            } => {
                write!(f, "Query too complex: {complexity} (max: {max_complexity})")
            },
            Self::QueryTooLarge { size, max_size } => {
                write!(f, "Query too large: {size} bytes (max: {max_size})")
            },
            Self::OriginNotAllowed(origin) => {
                write!(f, "CORS origin not allowed: {origin}")
            },
            Self::MethodNotAllowed(method) => {
                write!(f, "CORS method not allowed: {method}")
            },
            Self::HeaderNotAllowed(header) => {
                write!(f, "CORS header not allowed: {header}")
            },
            Self::InvalidCSRFToken(reason) => {
                write!(f, "Invalid CSRF token: {reason}")
            },
            Self::CSRFSessionMismatch => {
                write!(f, "CSRF token session mismatch")
            },
            Self::AuditLogFailure(reason) => {
                write!(f, "Audit logging failed: {reason}")
            },
            Self::SecurityConfigError(reason) => {
                write!(f, "Security configuration error: {reason}")
            },
            Self::TlsRequired { detail } => {
                write!(f, "TLS/HTTPS required: {detail}")
            },
            Self::TlsVersionTooOld { current, required } => {
                write!(f, "TLS version too old: {current} (required: {required})")
            },
            Self::MtlsRequired { detail } => {
                write!(f, "Mutual TLS required: {detail}")
            },
            Self::InvalidClientCert { detail } => {
                write!(f, "Invalid client certificate: {detail}")
            },
            Self::AuthRequired => {
                write!(f, "Authentication required")
            },
            Self::InvalidToken => {
                write!(f, "Invalid authentication token")
            },
            Self::JwtSignatureInvalid => {
                write!(
                    f,
                    "JWT signature invalid — verify FRAISEQL_JWT_SECRET matches the secret \
                     used to sign the token"
                )
            },
            Self::JwtIssuerMismatch { expected } => {
                write!(
                    f,
                    "JWT issuer does not match expected '{expected}' — \
                     check [security.jwt] issuer in fraiseql.toml"
                )
            },
            Self::JwtAudienceMismatch { expected } => {
                write!(
                    f,
                    "JWT audience does not match expected '{expected}' — \
                     check [security.jwt] audience in fraiseql.toml"
                )
            },
            Self::TokenExpired { expired_at } => {
                write!(f, "Token expired at {expired_at}")
            },
            Self::TokenMissingClaim { claim } => {
                write!(f, "Token missing required claim: {claim}")
            },
            Self::InvalidTokenAlgorithm { algorithm } => {
                write!(f, "Invalid token algorithm: {algorithm}")
            },
            Self::TokenReplayed => {
                write!(f, "Token has already been used (replay detected)")
            },
            Self::IntrospectionDisabled { detail } => {
                write!(f, "Introspection disabled: {detail}")
            },
            Self::TooManyAliases {
                alias_count,
                max_aliases,
            } => {
                write!(f, "Query contains too many aliases: {alias_count} > {max_aliases}")
            },
            Self::MalformedQuery(msg) => {
                write!(f, "Malformed GraphQL query: {msg}")
            },
        }
    }
}

impl std::error::Error for SecurityError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        // All SecurityError variants carry textual descriptions only;
        // none wrap a boxed source error, so the causal chain terminates here.
        // If a variant is added that wraps a cause, add a match arm returning it.
        None
    }
}

impl PartialEq for SecurityError {
    #[allow(clippy::match_same_arms)] // Reason: each arm binds distinct enum variant fields; combining would lose per-variant clarity
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::RateLimitExceeded {
                    retry_after: r1,
                    limit: l1,
                    window_secs: w1,
                },
                Self::RateLimitExceeded {
                    retry_after: r2,
                    limit: l2,
                    window_secs: w2,
                },
            ) => r1 == r2 && l1 == l2 && w1 == w2,
            (
                Self::QueryTooDeep {
                    depth: d1,
                    max_depth: m1,
                },
                Self::QueryTooDeep {
                    depth: d2,
                    max_depth: m2,
                },
            ) => d1 == d2 && m1 == m2,
            (
                Self::QueryTooComplex {
                    complexity: c1,
                    max_complexity: m1,
                },
                Self::QueryTooComplex {
                    complexity: c2,
                    max_complexity: m2,
                },
            ) => c1 == c2 && m1 == m2,
            (
                Self::QueryTooLarge {
                    size: s1,
                    max_size: m1,
                },
                Self::QueryTooLarge {
                    size: s2,
                    max_size: m2,
                },
            ) => s1 == s2 && m1 == m2,
            (Self::OriginNotAllowed(o1), Self::OriginNotAllowed(o2)) => o1 == o2,
            (Self::MethodNotAllowed(m1), Self::MethodNotAllowed(m2)) => m1 == m2,
            (Self::HeaderNotAllowed(h1), Self::HeaderNotAllowed(h2)) => h1 == h2,
            (Self::InvalidCSRFToken(r1), Self::InvalidCSRFToken(r2)) => r1 == r2,
            (Self::CSRFSessionMismatch, Self::CSRFSessionMismatch) => true,
            (Self::AuditLogFailure(r1), Self::AuditLogFailure(r2)) => r1 == r2,
            (Self::SecurityConfigError(r1), Self::SecurityConfigError(r2)) => r1 == r2,
            (Self::TlsRequired { detail: d1 }, Self::TlsRequired { detail: d2 }) => d1 == d2,
            (
                Self::TlsVersionTooOld {
                    current: c1,
                    required: r1,
                },
                Self::TlsVersionTooOld {
                    current: c2,
                    required: r2,
                },
            ) => c1 == c2 && r1 == r2,
            (Self::MtlsRequired { detail: d1 }, Self::MtlsRequired { detail: d2 }) => d1 == d2,
            (Self::InvalidClientCert { detail: d1 }, Self::InvalidClientCert { detail: d2 }) => {
                d1 == d2
            },
            (Self::AuthRequired, Self::AuthRequired) => true,
            (Self::InvalidToken, Self::InvalidToken) => true,
            (Self::JwtSignatureInvalid, Self::JwtSignatureInvalid) => true,
            (
                Self::JwtIssuerMismatch { expected: e1 },
                Self::JwtIssuerMismatch { expected: e2 },
            ) => e1 == e2,
            (
                Self::JwtAudienceMismatch { expected: e1 },
                Self::JwtAudienceMismatch { expected: e2 },
            ) => e1 == e2,
            (Self::TokenExpired { expired_at: e1 }, Self::TokenExpired { expired_at: e2 }) => {
                e1 == e2
            },
            (Self::TokenMissingClaim { claim: c1 }, Self::TokenMissingClaim { claim: c2 }) => {
                c1 == c2
            },
            (
                Self::InvalidTokenAlgorithm { algorithm: a1 },
                Self::InvalidTokenAlgorithm { algorithm: a2 },
            ) => a1 == a2,
            (Self::TokenReplayed, Self::TokenReplayed) => true,
            (
                Self::IntrospectionDisabled { detail: d1 },
                Self::IntrospectionDisabled { detail: d2 },
            ) => d1 == d2,
            (
                Self::TooManyAliases {
                    alias_count: a1,
                    max_aliases: m1,
                },
                Self::TooManyAliases {
                    alias_count: a2,
                    max_aliases: m2,
                },
            ) => a1 == a2 && m1 == m2,
            (Self::MalformedQuery(m1), Self::MalformedQuery(m2)) => m1 == m2,
            _ => false,
        }
    }
}

impl Eq for SecurityError {}

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

    #[test]
    fn test_rate_limit_error_display() {
        let err = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };

        assert!(err.to_string().contains("Rate limit exceeded"));
        assert!(err.to_string().contains("100"));
        assert!(err.to_string().contains("60"));
    }

    #[test]
    fn test_query_too_deep_display() {
        let err = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };

        assert!(err.to_string().contains("Query too deep"));
        assert!(err.to_string().contains("20"));
        assert!(err.to_string().contains("10"));
    }

    #[test]
    fn test_query_too_complex_display() {
        let err = SecurityError::QueryTooComplex {
            complexity:     500,
            max_complexity: 100,
        };

        assert!(err.to_string().contains("Query too complex"));
        assert!(err.to_string().contains("500"));
        assert!(err.to_string().contains("100"));
    }

    #[test]
    fn test_query_too_large_display() {
        let err = SecurityError::QueryTooLarge {
            size:     100_000,
            max_size: 10_000,
        };

        assert!(err.to_string().contains("Query too large"));
        assert!(err.to_string().contains("100000"));
        assert!(err.to_string().contains("10000"));
    }

    #[test]
    fn test_cors_errors() {
        let origin_err = SecurityError::OriginNotAllowed("https://evil.com".to_string());
        assert!(origin_err.to_string().contains("CORS origin"));

        let method_err = SecurityError::MethodNotAllowed("DELETE".to_string());
        assert!(method_err.to_string().contains("CORS method"));

        let header_err = SecurityError::HeaderNotAllowed("X-Custom".to_string());
        assert!(header_err.to_string().contains("CORS header"));
    }

    #[test]
    fn test_csrf_errors() {
        let invalid = SecurityError::InvalidCSRFToken("expired".to_string());
        assert!(invalid.to_string().contains("Invalid CSRF token"));

        let mismatch = SecurityError::CSRFSessionMismatch;
        assert!(mismatch.to_string().contains("session mismatch"));
    }

    #[test]
    fn test_audit_error() {
        let err = SecurityError::AuditLogFailure("connection timeout".to_string());
        assert!(err.to_string().contains("Audit logging failed"));
    }

    #[test]
    fn test_config_error() {
        let err = SecurityError::SecurityConfigError("missing config key".to_string());
        assert!(err.to_string().contains("Security configuration error"));
    }

    #[test]
    fn test_error_equality() {
        let err1 = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };
        let err2 = SecurityError::QueryTooDeep {
            depth:     20,
            max_depth: 10,
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::QueryTooDeep {
            depth:     30,
            max_depth: 10,
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_rate_limit_equality() {
        let err1 = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };
        let err2 = SecurityError::RateLimitExceeded {
            retry_after: 60,
            limit:       100,
            window_secs: 60,
        };
        assert_eq!(err1, err2);
    }

    // ============================================================================
    // TLS Error Tests
    // ============================================================================

    #[test]
    fn test_tls_required_error_display() {
        let err = SecurityError::TlsRequired {
            detail: "HTTPS required".to_string(),
        };

        assert!(err.to_string().contains("TLS/HTTPS required"));
        assert!(err.to_string().contains("HTTPS required"));
    }

    #[test]
    fn test_tls_version_too_old_error_display() {
        use crate::security::tls_enforcer::TlsVersion;

        let err = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };

        assert!(err.to_string().contains("TLS version too old"));
        assert!(err.to_string().contains("1.2"));
        assert!(err.to_string().contains("1.3"));
    }

    #[test]
    fn test_mtls_required_error_display() {
        let err = SecurityError::MtlsRequired {
            detail: "Client certificate required".to_string(),
        };

        assert!(err.to_string().contains("Mutual TLS required"));
        assert!(err.to_string().contains("Client certificate"));
    }

    #[test]
    fn test_invalid_client_cert_error_display() {
        let err = SecurityError::InvalidClientCert {
            detail: "Certificate validation failed".to_string(),
        };

        assert!(err.to_string().contains("Invalid client certificate"));
        assert!(err.to_string().contains("validation failed"));
    }

    #[test]
    fn test_auth_required_error_display() {
        let err = SecurityError::AuthRequired;
        assert!(err.to_string().contains("Authentication required"));
    }

    #[test]
    fn test_invalid_token_error_display() {
        let err = SecurityError::InvalidToken;
        assert!(err.to_string().contains("Invalid authentication token"));
    }

    #[test]
    fn test_token_expired_error_display() {
        use chrono::{Duration, Utc};

        let expired_at = Utc::now() - Duration::hours(1);
        let err = SecurityError::TokenExpired { expired_at };

        assert!(err.to_string().contains("Token expired"));
    }

    #[test]
    fn test_token_missing_claim_error_display() {
        let err = SecurityError::TokenMissingClaim {
            claim: "sub".to_string(),
        };

        assert!(err.to_string().contains("Token missing required claim"));
        assert!(err.to_string().contains("sub"));
    }

    #[test]
    fn test_invalid_token_algorithm_error_display() {
        let err = SecurityError::InvalidTokenAlgorithm {
            algorithm: "HS256".to_string(),
        };

        assert!(err.to_string().contains("Invalid token algorithm"));
        assert!(err.to_string().contains("HS256"));
    }

    #[test]
    fn test_introspection_disabled_error_display() {
        let err = SecurityError::IntrospectionDisabled {
            detail: "Introspection not allowed in production".to_string(),
        };

        assert!(err.to_string().contains("Introspection disabled"));
        assert!(err.to_string().contains("production"));
    }

    // ============================================================================
    // TLS Error Equality Tests
    // ============================================================================

    #[test]
    fn test_tls_required_equality() {
        let err1 = SecurityError::TlsRequired {
            detail: "test".to_string(),
        };
        let err2 = SecurityError::TlsRequired {
            detail: "test".to_string(),
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::TlsRequired {
            detail: "different".to_string(),
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_tls_version_too_old_equality() {
        use crate::security::tls_enforcer::TlsVersion;

        let err1 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };
        let err2 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_2,
            required: TlsVersion::V1_3,
        };
        assert_eq!(err1, err2);

        let err3 = SecurityError::TlsVersionTooOld {
            current:  TlsVersion::V1_1,
            required: TlsVersion::V1_3,
        };
        assert_ne!(err1, err3);
    }

    #[test]
    fn test_mtls_required_equality() {
        let err1 = SecurityError::MtlsRequired {
            detail: "test".to_string(),
        };
        let err2 = SecurityError::MtlsRequired {
            detail: "test".to_string(),
        };
        assert_eq!(err1, err2);
    }

    #[test]
    fn test_invalid_token_equality() {
        assert_eq!(SecurityError::InvalidToken, SecurityError::InvalidToken);
    }

    #[test]
    fn test_auth_required_equality() {
        assert_eq!(SecurityError::AuthRequired, SecurityError::AuthRequired);
    }
}