reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! WebSocket Authentication Middleware for MCP Server
//!
//! This module implements secure WebSocket authentication with:
//! - API key validation via header or first message
//! - Subscription tier enforcement (Free, Pro, Team, Enterprise)
//! - Active connection tracking per API key
//! - Rate limiting based on tier
//! - Secure connection upgrade handling
//!
//! # Security Features
//!
//! - Constant-time API key comparison to prevent timing attacks
//! - Connection limits per tier to prevent resource exhaustion
//! - Automatic connection cleanup on disconnect
//! - TLS enforcement in production (wss:// only)
//!
//! # Usage
//!
//! ```rust,ignore
//! use reasonkit::mcp::ws_auth::{WsAuthLayer, WsAuthState, SubscriptionTier};
//!
//! let auth_state = WsAuthState::new(api_key_validator);
//! let app = Router::new()
//!     .route("/ws", get(ws_handler))
//!     .layer(WsAuthLayer::new(auth_state));
//! ```

use axum::{
    body::Body,
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        ConnectInfo, State,
    },
    http::{header::HeaderMap, Request, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
// Note: StreamExt is used indirectly via WebSocket stream operations
#[allow(unused_imports)]
use futures_util::StreamExt;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    net::SocketAddr,
    sync::Arc,
    time::{Duration, Instant},
};
use thiserror::Error;
use tokio::sync::mpsc;
use tracing::{debug, error, info, instrument, warn};
use uuid::Uuid;

// Global nonce tracker for replay attack prevention
// Uses once_cell::sync::Lazy for thread-safe lazy initialization
static GLOBAL_NONCE_TRACKER: once_cell::sync::Lazy<NonceTracker> =
    once_cell::sync::Lazy::new(NonceTracker::new);

// ============================================================================
// Error Types
// ============================================================================

/// Authentication and connection errors
#[derive(Debug, Error)]
pub enum WsAuthError {
    #[error("Missing API key")]
    MissingApiKey,

    #[error("Invalid API key")]
    InvalidApiKey,

    #[error("API key expired")]
    ExpiredApiKey,

    #[error("Subscription tier '{0}' does not allow WebSocket access")]
    TierNotAllowed(String),

    #[error("Connection limit exceeded for tier '{0}': max {1} connections")]
    ConnectionLimitExceeded(String, usize),

    #[error("Rate limit exceeded: {0} requests per minute allowed")]
    RateLimitExceeded(u32),

    #[error("Authentication timeout: must authenticate within {0} seconds")]
    AuthTimeout(u64),

    #[error("Invalid authentication message format")]
    InvalidAuthMessage,

    #[error("Replay attack detected: nonce already used or timestamp invalid")]
    ReplayAttack,

    #[error("Internal authentication error: {0}")]
    Internal(String),
}

impl IntoResponse for WsAuthError {
    fn into_response(self) -> Response {
        let (status, message) = match &self {
            WsAuthError::MissingApiKey => (StatusCode::UNAUTHORIZED, self.to_string()),
            WsAuthError::InvalidApiKey => (StatusCode::UNAUTHORIZED, self.to_string()),
            WsAuthError::ExpiredApiKey => (StatusCode::UNAUTHORIZED, self.to_string()),
            WsAuthError::TierNotAllowed(_) => (StatusCode::FORBIDDEN, self.to_string()),
            WsAuthError::ConnectionLimitExceeded(_, _) => {
                (StatusCode::TOO_MANY_REQUESTS, self.to_string())
            }
            WsAuthError::RateLimitExceeded(_) => (StatusCode::TOO_MANY_REQUESTS, self.to_string()),
            WsAuthError::AuthTimeout(_) => (StatusCode::REQUEST_TIMEOUT, self.to_string()),
            WsAuthError::InvalidAuthMessage => (StatusCode::BAD_REQUEST, self.to_string()),
            WsAuthError::ReplayAttack => (StatusCode::UNAUTHORIZED, self.to_string()),
            WsAuthError::Internal(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal error".to_string(),
            ),
        };

        (status, message).into_response()
    }
}

// ============================================================================
// Subscription Tiers
// ============================================================================

/// Subscription tier levels with associated limits
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SubscriptionTier {
    /// Free tier: Limited features
    Free,
    /// Pro tier: Enhanced limits
    Pro,
    /// Team tier: Collaborative features
    Team,
    /// Enterprise tier: Unlimited access
    Enterprise,
}

impl SubscriptionTier {
    /// Maximum concurrent WebSocket connections allowed
    pub fn max_connections(&self) -> usize {
        match self {
            SubscriptionTier::Free => 1,
            SubscriptionTier::Pro => 5,
            SubscriptionTier::Team => 25,
            SubscriptionTier::Enterprise => 100,
        }
    }

    /// Maximum requests per minute
    pub fn rate_limit(&self) -> u32 {
        match self {
            SubscriptionTier::Free => 60,
            SubscriptionTier::Pro => 300,
            SubscriptionTier::Team => 1000,
            SubscriptionTier::Enterprise => 10000,
        }
    }

    /// Maximum message size in bytes
    pub fn max_message_size(&self) -> usize {
        match self {
            SubscriptionTier::Free => 64 * 1024,               // 64 KB
            SubscriptionTier::Pro => 1024 * 1024,              // 1 MB
            SubscriptionTier::Team => 10 * 1024 * 1024,        // 10 MB
            SubscriptionTier::Enterprise => 100 * 1024 * 1024, // 100 MB
        }
    }

    /// Session timeout duration
    pub fn session_timeout(&self) -> Duration {
        match self {
            SubscriptionTier::Free => Duration::from_secs(30 * 60), // 30 min
            SubscriptionTier::Pro => Duration::from_secs(2 * 60 * 60), // 2 hours
            SubscriptionTier::Team => Duration::from_secs(8 * 60 * 60), // 8 hours
            SubscriptionTier::Enterprise => Duration::from_secs(24 * 60 * 60), // 24 hours
        }
    }

    /// Whether WebSocket access is allowed
    pub fn allows_websocket(&self) -> bool {
        // All tiers allow WebSocket, but with different limits
        true
    }
}

impl std::fmt::Display for SubscriptionTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubscriptionTier::Free => write!(f, "free"),
            SubscriptionTier::Pro => write!(f, "pro"),
            SubscriptionTier::Team => write!(f, "team"),
            SubscriptionTier::Enterprise => write!(f, "enterprise"),
        }
    }
}

// ============================================================================
// API Key Types
// ============================================================================

/// Validated API key information
#[derive(Debug, Clone)]
pub struct ApiKeyInfo {
    /// Unique API key identifier (hashed or prefix)
    pub key_id: String,
    /// User or organization identifier
    pub owner_id: String,
    /// Subscription tier
    pub tier: SubscriptionTier,
    /// Key expiration timestamp (None = never expires)
    pub expires_at: Option<Instant>,
    /// Custom metadata
    pub metadata: HashMap<String, String>,
}

/// Trait for validating API keys
/// Implement this for your storage backend (database, Redis, etc.)
#[async_trait::async_trait]
pub trait ApiKeyValidator: Send + Sync + 'static {
    /// Validate an API key and return its info if valid
    async fn validate(&self, api_key: &str) -> Result<ApiKeyInfo, WsAuthError>;

    /// Revoke an API key (optional)
    async fn revoke(&self, key_id: &str) -> Result<(), WsAuthError> {
        let _ = key_id;
        Ok(())
    }
}

/// In-memory API key validator for development/testing
#[derive(Debug, Clone)]
pub struct InMemoryApiKeyValidator {
    keys: Arc<RwLock<HashMap<String, ApiKeyInfo>>>,
}

impl InMemoryApiKeyValidator {
    pub fn new() -> Self {
        Self {
            keys: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Add a new API key
    pub fn add_key(&self, api_key: String, info: ApiKeyInfo) {
        self.keys.write().insert(api_key, info);
    }

    /// Remove an API key
    pub fn remove_key(&self, api_key: &str) {
        self.keys.write().remove(api_key);
    }
}

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

#[async_trait::async_trait]
impl ApiKeyValidator for InMemoryApiKeyValidator {
    async fn validate(&self, api_key: &str) -> Result<ApiKeyInfo, WsAuthError> {
        let keys = self.keys.read();

        // Constant-time comparison for all keys to prevent timing attacks
        let mut found_info: Option<&ApiKeyInfo> = None;
        for (stored_key, info) in keys.iter() {
            if constant_time_compare(api_key, stored_key) {
                found_info = Some(info);
                break;
            }
        }

        match found_info {
            Some(info) => {
                // Check expiration
                if let Some(expires_at) = info.expires_at {
                    if Instant::now() > expires_at {
                        return Err(WsAuthError::ExpiredApiKey);
                    }
                }
                Ok(info.clone())
            }
            None => Err(WsAuthError::InvalidApiKey),
        }
    }

    async fn revoke(&self, key_id: &str) -> Result<(), WsAuthError> {
        let mut keys = self.keys.write();
        keys.retain(|_, v| v.key_id != key_id);
        Ok(())
    }
}

// ============================================================================
// Connection Tracking
// ============================================================================

/// Information about an active WebSocket connection
#[derive(Debug, Clone)]
pub struct ConnectionInfo {
    /// Unique connection ID
    pub connection_id: Uuid,
    /// API key ID (for grouping connections)
    pub key_id: String,
    /// Owner ID
    pub owner_id: String,
    /// Subscription tier
    pub tier: SubscriptionTier,
    /// Remote address
    pub remote_addr: SocketAddr,
    /// Connection established time
    pub connected_at: Instant,
    /// Last activity time
    pub last_activity: Instant,
    /// Request count for rate limiting
    pub request_count: u32,
    /// Rate limit window start
    pub rate_window_start: Instant,
}

/// Connection tracker for managing active WebSocket connections
#[derive(Debug)]
pub struct ConnectionTracker {
    /// Active connections by connection ID
    connections: RwLock<HashMap<Uuid, ConnectionInfo>>,
    /// Connection count by API key ID
    connection_counts: RwLock<HashMap<String, usize>>,
}

impl ConnectionTracker {
    pub fn new() -> Self {
        Self {
            connections: RwLock::new(HashMap::new()),
            connection_counts: RwLock::new(HashMap::new()),
        }
    }

    /// Register a new connection
    pub fn register(
        &self,
        key_info: &ApiKeyInfo,
        remote_addr: SocketAddr,
    ) -> Result<ConnectionInfo, WsAuthError> {
        let mut counts = self.connection_counts.write();
        let current_count = counts.get(&key_info.key_id).copied().unwrap_or(0);
        let max_connections = key_info.tier.max_connections();

        if current_count >= max_connections {
            return Err(WsAuthError::ConnectionLimitExceeded(
                key_info.tier.to_string(),
                max_connections,
            ));
        }

        let now = Instant::now();
        let conn_info = ConnectionInfo {
            connection_id: Uuid::new_v4(),
            key_id: key_info.key_id.clone(),
            owner_id: key_info.owner_id.clone(),
            tier: key_info.tier,
            remote_addr,
            connected_at: now,
            last_activity: now,
            request_count: 0,
            rate_window_start: now,
        };

        // Update counts
        *counts.entry(key_info.key_id.clone()).or_insert(0) += 1;

        // Store connection info
        self.connections
            .write()
            .insert(conn_info.connection_id, conn_info.clone());

        info!(
            connection_id = %conn_info.connection_id,
            key_id = %key_info.key_id,
            tier = %key_info.tier,
            "New WebSocket connection registered"
        );

        Ok(conn_info)
    }

    /// Unregister a connection
    pub fn unregister(&self, connection_id: Uuid) {
        let mut connections = self.connections.write();
        if let Some(conn_info) = connections.remove(&connection_id) {
            let mut counts = self.connection_counts.write();
            if let Some(count) = counts.get_mut(&conn_info.key_id) {
                *count = count.saturating_sub(1);
                if *count == 0 {
                    counts.remove(&conn_info.key_id);
                }
            }

            info!(
                connection_id = %connection_id,
                key_id = %conn_info.key_id,
                "WebSocket connection unregistered"
            );
        }
    }

    /// Check and update rate limit, returns true if allowed
    pub fn check_rate_limit(&self, connection_id: Uuid) -> Result<(), WsAuthError> {
        let mut connections = self.connections.write();

        if let Some(conn_info) = connections.get_mut(&connection_id) {
            let now = Instant::now();
            let rate_limit = conn_info.tier.rate_limit();

            // Reset window if more than 1 minute has passed
            if now.duration_since(conn_info.rate_window_start) > Duration::from_secs(60) {
                conn_info.rate_window_start = now;
                conn_info.request_count = 0;
            }

            conn_info.request_count += 1;
            conn_info.last_activity = now;

            if conn_info.request_count > rate_limit {
                return Err(WsAuthError::RateLimitExceeded(rate_limit));
            }
        }

        Ok(())
    }

    /// Get connection info
    pub fn get(&self, connection_id: Uuid) -> Option<ConnectionInfo> {
        self.connections.read().get(&connection_id).cloned()
    }

    /// Get all connections for an API key
    pub fn get_by_key(&self, key_id: &str) -> Vec<ConnectionInfo> {
        self.connections
            .read()
            .values()
            .filter(|c| c.key_id == key_id)
            .cloned()
            .collect()
    }

    /// Get total active connection count
    pub fn total_connections(&self) -> usize {
        self.connections.read().len()
    }

    /// Get connection count for a specific API key
    pub fn connection_count(&self, key_id: &str) -> usize {
        self.connection_counts
            .read()
            .get(key_id)
            .copied()
            .unwrap_or(0)
    }

    /// Clean up expired/stale connections
    pub fn cleanup_stale(&self, max_idle: Duration) {
        let now = Instant::now();
        let mut to_remove = Vec::new();

        {
            let connections = self.connections.read();
            for (id, info) in connections.iter() {
                if now.duration_since(info.last_activity) > max_idle {
                    to_remove.push(*id);
                }
            }
        }

        for id in to_remove {
            self.unregister(id);
            debug!(connection_id = %id, "Cleaned up stale connection");
        }
    }
}

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

// ============================================================================
// Authentication State
// ============================================================================

/// Shared authentication state for the WebSocket server
#[derive(Clone)]
pub struct WsAuthState<V: ApiKeyValidator> {
    /// API key validator
    pub validator: Arc<V>,
    /// Connection tracker
    pub tracker: Arc<ConnectionTracker>,
    /// Authentication timeout duration
    pub auth_timeout: Duration,
    /// Header name for API key (default: "Authorization")
    pub api_key_header: String,
    /// Whether to require TLS (wss://)
    pub require_tls: bool,
}

impl<V: ApiKeyValidator> WsAuthState<V> {
    pub fn new(validator: V) -> Self {
        Self {
            validator: Arc::new(validator),
            tracker: Arc::new(ConnectionTracker::new()),
            auth_timeout: Duration::from_secs(30),
            api_key_header: "Authorization".to_string(),
            require_tls: false,
        }
    }

    pub fn with_auth_timeout(mut self, timeout: Duration) -> Self {
        self.auth_timeout = timeout;
        self
    }

    pub fn with_api_key_header(mut self, header: impl Into<String>) -> Self {
        self.api_key_header = header.into();
        self
    }

    pub fn with_require_tls(mut self, require: bool) -> Self {
        self.require_tls = require;
        self
    }

    /// Extract API key from request headers
    pub fn extract_api_key_from_headers(&self, headers: &HeaderMap) -> Option<String> {
        headers
            .get(&self.api_key_header)
            .and_then(|v| v.to_str().ok())
            .map(|s| {
                // Handle "Bearer <token>" format
                s.strip_prefix("Bearer ").unwrap_or(s).to_string()
            })
    }
}

// ============================================================================
// WebSocket Handler
// ============================================================================

/// Authentication message sent by client in first WebSocket message
#[derive(Debug, Deserialize)]
pub struct WsAuthMessage {
    /// API key for authentication
    pub api_key: String,
    /// Request nonce (unique per request, prevents replay attacks)
    /// Format: Base64-encoded 16 random bytes
    #[serde(default)]
    pub nonce: Option<String>,
    /// Timestamp (Unix epoch seconds, must be within 5 minutes of server time)
    #[serde(default)]
    pub timestamp: Option<i64>,
    /// Optional client metadata
    #[serde(default)]
    pub client_info: HashMap<String, String>,
}

/// Authentication result sent to client
#[derive(Debug, Serialize)]
pub struct WsAuthResult {
    /// Whether authentication succeeded
    pub success: bool,
    /// Error message if failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Connection ID if succeeded
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_id: Option<String>,
    /// Subscription tier if succeeded
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    /// Rate limit (requests per minute)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate_limit: Option<u32>,
    /// Session timeout in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_timeout_secs: Option<u64>,
}

/// Authenticated WebSocket connection handle
pub struct AuthenticatedWsConnection {
    /// Connection info
    pub info: ConnectionInfo,
    /// WebSocket stream
    pub socket: WebSocket,
    /// State reference for rate limiting
    tracker: Arc<ConnectionTracker>,
}

impl AuthenticatedWsConnection {
    /// Send a message (with rate limit check)
    pub async fn send(&mut self, msg: Message) -> Result<(), WsAuthError> {
        self.tracker.check_rate_limit(self.info.connection_id)?;
        self.socket
            .send(msg)
            .await
            .map_err(|e| WsAuthError::Internal(e.to_string()))
    }

    /// Receive a message
    pub async fn recv(&mut self) -> Option<Result<Message, axum::Error>> {
        self.socket.recv().await
    }

    /// Get the connection ID
    pub fn connection_id(&self) -> Uuid {
        self.info.connection_id
    }

    /// Get the subscription tier
    pub fn tier(&self) -> SubscriptionTier {
        self.info.tier
    }
}

/// WebSocket upgrade handler with header-based authentication
#[instrument(skip(ws, state))]
pub async fn ws_handler_with_header_auth<V: ApiKeyValidator>(
    ws: WebSocketUpgrade,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(state): State<WsAuthState<V>>,
    headers: HeaderMap,
) -> Result<Response, WsAuthError> {
    // Try to extract API key from headers
    let api_key = state
        .extract_api_key_from_headers(&headers)
        .ok_or(WsAuthError::MissingApiKey)?;

    // Validate API key
    let key_info = state.validator.validate(&api_key).await?;

    // Check tier allows WebSocket
    if !key_info.tier.allows_websocket() {
        return Err(WsAuthError::TierNotAllowed(key_info.tier.to_string()));
    }

    // Register connection
    let conn_info = state.tracker.register(&key_info, addr)?;

    info!(
        connection_id = %conn_info.connection_id,
        tier = %key_info.tier,
        remote_addr = %addr,
        "WebSocket connection authenticated via header"
    );

    // Upgrade connection
    let tracker = Arc::clone(&state.tracker);

    Ok(ws.on_upgrade(move |socket| async move {
        handle_authenticated_socket(socket, conn_info, tracker).await;
    }))
}

/// WebSocket upgrade handler with first-message authentication
#[instrument(skip(ws, state))]
pub async fn ws_handler_with_message_auth<V: ApiKeyValidator>(
    ws: WebSocketUpgrade,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(state): State<WsAuthState<V>>,
    headers: HeaderMap,
) -> impl IntoResponse {
    // Check for API key in header first (preferred method)
    if let Some(api_key) = state.extract_api_key_from_headers(&headers) {
        match state.validator.validate(&api_key).await {
            Ok(key_info) => {
                if !key_info.tier.allows_websocket() {
                    return Err(WsAuthError::TierNotAllowed(key_info.tier.to_string()));
                }

                match state.tracker.register(&key_info, addr) {
                    Ok(conn_info) => {
                        let tracker = Arc::clone(&state.tracker);
                        return Ok(ws.on_upgrade(move |socket| async move {
                            handle_authenticated_socket(socket, conn_info, tracker).await;
                        }));
                    }
                    Err(e) => return Err(e),
                }
            }
            Err(_) => {
                // Fall through to message-based auth
            }
        }
    }

    // No valid header auth, require first-message authentication
    let validator = Arc::clone(&state.validator);
    let tracker = Arc::clone(&state.tracker);
    let auth_timeout = state.auth_timeout;

    Ok(ws.on_upgrade(move |socket| async move {
        handle_unauthenticated_upgrade(socket, addr, validator, tracker, auth_timeout).await;
    }))
}

/// Handle socket that requires first-message authentication
async fn handle_unauthenticated_upgrade<V: ApiKeyValidator>(
    mut socket: WebSocket,
    addr: SocketAddr,
    validator: Arc<V>,
    tracker: Arc<ConnectionTracker>,
    auth_timeout: Duration,
) {
    // Wait for authentication message with timeout
    let auth_result = tokio::time::timeout(auth_timeout, socket.recv()).await;

    let auth_msg = match auth_result {
        Ok(Some(Ok(Message::Text(text)))) => match serde_json::from_str::<WsAuthMessage>(&text) {
            Ok(msg) => msg,
            Err(e) => {
                let _ = send_auth_error(&mut socket, &WsAuthError::InvalidAuthMessage).await;
                warn!(error = %e, "Invalid auth message format");
                return;
            }
        },
        Ok(Some(Ok(_))) => {
            let _ = send_auth_error(&mut socket, &WsAuthError::InvalidAuthMessage).await;
            warn!("First message must be text auth message");
            return;
        }
        Ok(Some(Err(e))) => {
            warn!(error = %e, "WebSocket error during auth");
            return;
        }
        Ok(None) => {
            warn!("Connection closed before authentication");
            return;
        }
        Err(_) => {
            let _ = send_auth_error(
                &mut socket,
                &WsAuthError::AuthTimeout(auth_timeout.as_secs()),
            )
            .await;
            warn!(
                timeout_secs = auth_timeout.as_secs(),
                "Authentication timeout"
            );
            return;
        }
    };

    // Validate API key
    let key_info = match validator.validate(&auth_msg.api_key).await {
        Ok(info) => info,
        Err(e) => {
            let _ = send_auth_error(&mut socket, &e).await;
            warn!(error = %e, "API key validation failed");
            return;
        }
    };

    // SECURITY: Mandatory nonce validation to prevent replay attacks
    // Both nonce and timestamp are REQUIRED for authenticated connections
    let (nonce, timestamp) = match (auth_msg.nonce, auth_msg.timestamp) {
        (Some(n), Some(t)) => (n, t),
        (None, _) => {
            let err = WsAuthError::ReplayAttack;
            let _ = send_auth_error(&mut socket, &err).await;
            warn!("Authentication rejected: missing nonce (replay protection required)");
            return;
        }
        (_, None) => {
            let err = WsAuthError::ReplayAttack;
            let _ = send_auth_error(&mut socket, &err).await;
            warn!("Authentication rejected: missing timestamp (replay protection required)");
            return;
        }
    };

    // Validate and consume the nonce (prevents replay attacks)
    if let Err(e) = GLOBAL_NONCE_TRACKER.validate_and_consume(&nonce, timestamp) {
        let _ = send_auth_error(&mut socket, &WsAuthError::ReplayAttack).await;
        warn!(
            nonce = %nonce,
            timestamp = %timestamp,
            error = %e,
            "Replay attack prevention: nonce validation failed"
        );
        return;
    }

    debug!(
        nonce = %nonce,
        timestamp = %timestamp,
        "Nonce validated successfully - replay attack protection active"
    );

    // Check tier
    if !key_info.tier.allows_websocket() {
        let err = WsAuthError::TierNotAllowed(key_info.tier.to_string());
        let _ = send_auth_error(&mut socket, &err).await;
        return;
    }

    // Register connection
    let conn_info = match tracker.register(&key_info, addr) {
        Ok(info) => info,
        Err(e) => {
            let _ = send_auth_error(&mut socket, &e).await;
            return;
        }
    };

    // Send success response
    let auth_result = WsAuthResult {
        success: true,
        error: None,
        connection_id: Some(conn_info.connection_id.to_string()),
        tier: Some(conn_info.tier.to_string()),
        rate_limit: Some(conn_info.tier.rate_limit()),
        session_timeout_secs: Some(conn_info.tier.session_timeout().as_secs()),
    };

    if let Ok(json) = serde_json::to_string(&auth_result) {
        let _ = socket.send(Message::Text(json)).await;
    }

    info!(
        connection_id = %conn_info.connection_id,
        tier = %key_info.tier,
        remote_addr = %addr,
        "WebSocket connection authenticated via first message"
    );

    // Continue with authenticated handler
    handle_authenticated_socket(socket, conn_info, tracker).await;
}

/// Send authentication error response
async fn send_auth_error(socket: &mut WebSocket, error: &WsAuthError) -> Result<(), axum::Error> {
    let result = WsAuthResult {
        success: false,
        error: Some(error.to_string()),
        connection_id: None,
        tier: None,
        rate_limit: None,
        session_timeout_secs: None,
    };

    if let Ok(json) = serde_json::to_string(&result) {
        socket.send(Message::Text(json)).await?;
    }

    // Send close frame
    socket
        .send(Message::Close(Some(axum::extract::ws::CloseFrame {
            code: axum::extract::ws::close_code::POLICY,
            reason: error.to_string().into(),
        })))
        .await?;

    Ok(())
}

/// Handle an authenticated WebSocket connection
async fn handle_authenticated_socket(
    mut socket: WebSocket,
    conn_info: ConnectionInfo,
    tracker: Arc<ConnectionTracker>,
) {
    let connection_id = conn_info.connection_id;
    let tier = conn_info.tier;

    // Create a channel for the MCP message handler (for future bidirectional messaging)
    let (_tx, mut rx) = mpsc::channel::<Message>(100);

    // Spawn task to forward messages from channel to socket
    let send_task = tokio::spawn({
        let tracker = Arc::clone(&tracker);
        async move {
            while let Some(_msg) = rx.recv().await {
                // Check rate limit before sending
                if let Err(e) = tracker.check_rate_limit(connection_id) {
                    warn!(
                        connection_id = %connection_id,
                        error = %e,
                        "Rate limit exceeded"
                    );
                    // Send error and close
                    let _error_msg = serde_json::json!({
                        "jsonrpc": "2.0",
                        "error": {
                            "code": -32000,
                            "message": e.to_string()
                        }
                    });
                    // Ignore send errors during rate limit
                    break;
                }
            }
        }
    });

    // Process incoming messages
    while let Some(msg) = socket.recv().await {
        match msg {
            Ok(Message::Text(text)) => {
                debug!(
                    connection_id = %connection_id,
                    msg_len = text.len(),
                    "Received text message"
                );

                // Check message size limit
                if text.len() > tier.max_message_size() {
                    warn!(
                        connection_id = %connection_id,
                        size = text.len(),
                        max = tier.max_message_size(),
                        "Message size exceeds tier limit"
                    );
                    // Send error response
                    let error_msg = serde_json::json!({
                        "jsonrpc": "2.0",
                        "error": {
                            "code": -32000,
                            "message": format!("Message size {} exceeds limit {}", text.len(), tier.max_message_size())
                        }
                    });
                    if let Ok(json) = serde_json::to_string(&error_msg) {
                        let _ = socket.send(Message::Text(json)).await;
                    }
                    continue;
                }

                // TODO: Dispatch to MCP handler
                // For now, echo back
                let _ = socket.send(Message::Text(text)).await;
            }
            Ok(Message::Binary(data)) => {
                debug!(
                    connection_id = %connection_id,
                    size = data.len(),
                    "Received binary message"
                );

                // Check message size limit
                if data.len() > tier.max_message_size() {
                    warn!(
                        connection_id = %connection_id,
                        size = data.len(),
                        max = tier.max_message_size(),
                        "Binary message size exceeds tier limit"
                    );
                    continue;
                }

                // Echo back for now
                let _ = socket.send(Message::Binary(data)).await;
            }
            Ok(Message::Ping(data)) => {
                let _ = socket.send(Message::Pong(data)).await;
            }
            Ok(Message::Pong(_)) => {
                // Ignore pongs
            }
            Ok(Message::Close(_)) => {
                info!(connection_id = %connection_id, "Client initiated close");
                break;
            }
            Err(e) => {
                error!(
                    connection_id = %connection_id,
                    error = %e,
                    "WebSocket error"
                );
                break;
            }
        }
    }

    // Clean up
    send_task.abort();
    tracker.unregister(connection_id);
    info!(connection_id = %connection_id, "Connection closed");
}

// ============================================================================
// Axum Middleware Layer
// ============================================================================

/// Middleware for pre-upgrade authentication checks
pub async fn ws_auth_middleware<V: ApiKeyValidator>(
    State(state): State<WsAuthState<V>>,
    request: Request<Body>,
    next: Next,
) -> Result<Response, WsAuthError> {
    // Check if this is a WebSocket upgrade request
    let is_upgrade = request
        .headers()
        .get("upgrade")
        .and_then(|v| v.to_str().ok())
        .map(|v| v.eq_ignore_ascii_case("websocket"))
        .unwrap_or(false);

    if !is_upgrade {
        // Not a WebSocket request, pass through
        return Ok(next.run(request).await);
    }

    // TLS check in production
    if state.require_tls {
        let scheme = request.uri().scheme_str().unwrap_or("http");
        if scheme != "https" && scheme != "wss" {
            warn!("WebSocket connection rejected: TLS required");
            return Err(WsAuthError::Internal(
                "Secure connection (wss://) required".to_string(),
            ));
        }
    }

    // Continue to handler
    Ok(next.run(request).await)
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Constant-time string comparison to prevent timing attacks
fn constant_time_compare(a: &str, b: &str) -> bool {
    let a_bytes = a.as_bytes();
    let b_bytes = b.as_bytes();

    if a_bytes.len() != b_bytes.len() {
        // Still do a comparison to maintain constant time behavior
        let mut _dummy: u8 = 0;
        for byte in a_bytes.iter() {
            _dummy |= *byte;
        }
        return false;
    }

    let mut result: u8 = 0;
    for (x, y) in a_bytes.iter().zip(b_bytes.iter()) {
        result |= x ^ y;
    }

    result == 0
}

/// Generate a new API key (for development/testing)
pub fn generate_api_key() -> String {
    format!("rk_{}", Uuid::new_v4().to_string().replace('-', ""))
}

// ============================================================================
// Security Hardening: Nonce Tracking (Replay Attack Prevention)
// ============================================================================

/// Nonce tracker for preventing replay attacks
/// Stores used nonces with expiration time
#[derive(Debug)]
pub struct NonceTracker {
    /// Used nonces with expiration timestamps
    used_nonces: RwLock<HashMap<String, Instant>>,
    /// Nonce validity window (default: 5 minutes)
    validity_window: Duration,
}

impl NonceTracker {
    /// Create a new nonce tracker with default 5-minute window
    pub fn new() -> Self {
        Self {
            used_nonces: RwLock::new(HashMap::new()),
            validity_window: Duration::from_secs(300),
        }
    }

    /// Create with custom validity window
    pub fn with_validity(validity_window: Duration) -> Self {
        Self {
            used_nonces: RwLock::new(HashMap::new()),
            validity_window,
        }
    }

    /// Validate and consume a nonce
    /// Returns Ok(()) if nonce is valid and unused, Err(ReplayAttack) if:
    /// - Timestamp is outside validity window (potential replay with old message)
    /// - Nonce has already been used (definite replay attack)
    pub fn validate_and_consume(&self, nonce: &str, timestamp: i64) -> Result<(), WsAuthError> {
        // Check timestamp is within validity window
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let age_secs = (now - timestamp).abs();
        if age_secs > self.validity_window.as_secs() as i64 {
            warn!(
                timestamp = %timestamp,
                age_secs = %age_secs,
                validity_window_secs = %self.validity_window.as_secs(),
                "Replay attack detected: timestamp outside validity window"
            );
            return Err(WsAuthError::ReplayAttack);
        }

        let mut used = self.used_nonces.write();

        // Clean up expired nonces
        let expiry_threshold = Instant::now() - self.validity_window;
        used.retain(|_, &mut exp| exp > expiry_threshold);

        // Check if nonce was already used
        if used.contains_key(nonce) {
            warn!(nonce = %nonce, "Replay attack detected: nonce already used");
            return Err(WsAuthError::ReplayAttack);
        }

        // Mark nonce as used
        used.insert(nonce.to_string(), Instant::now());
        Ok(())
    }

    /// Generate a cryptographically secure nonce
    pub fn generate_nonce() -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let random = Uuid::new_v4();
        format!("{}:{}", timestamp, random)
    }
}

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

// ============================================================================
// Security Hardening: SSRF Protection
// ============================================================================

/// Check if a URL is safe to access (SSRF protection)
/// Blocks private IP ranges, localhost, and known dangerous schemes
pub fn is_url_safe(url: &str) -> Result<bool, WsAuthError> {
    use std::net::IpAddr;

    let parsed =
        url::Url::parse(url).map_err(|_| WsAuthError::Internal("Invalid URL".to_string()))?;

    // Only allow http/https
    match parsed.scheme() {
        "http" | "https" => {}
        scheme => {
            warn!(scheme = %scheme, "SSRF: Blocked scheme");
            return Ok(false);
        }
    }

    // Get host
    let host = match parsed.host_str() {
        Some(h) => h,
        None => return Ok(false),
    };

    // Block localhost variants
    let localhost_variants = ["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0", "0"];
    if localhost_variants
        .iter()
        .any(|&l| host.eq_ignore_ascii_case(l))
    {
        warn!(host = %host, "SSRF: Blocked localhost");
        return Ok(false);
    }

    // Try to parse as IP address
    if let Ok(ip) = host.parse::<IpAddr>() {
        if !is_public_ip(&ip) {
            warn!(ip = %ip, "SSRF: Blocked private/reserved IP");
            return Ok(false);
        }
    }

    // Block internal domains
    let blocked_suffixes = [
        ".internal",
        ".local",
        ".localhost",
        ".lan",
        ".corp",
        ".home",
    ];
    if blocked_suffixes
        .iter()
        .any(|&s| host.to_lowercase().ends_with(s))
    {
        warn!(host = %host, "SSRF: Blocked internal domain");
        return Ok(false);
    }

    // Block cloud metadata endpoints
    let blocked_hosts = [
        "169.254.169.254",          // AWS/GCP metadata
        "metadata.google.internal", // GCP
        "metadata",                 // Various cloud providers
    ];
    if blocked_hosts.iter().any(|&h| host.eq_ignore_ascii_case(h)) {
        warn!(host = %host, "SSRF: Blocked cloud metadata endpoint");
        return Ok(false);
    }

    Ok(true)
}

/// Check if an IP address is public (not private/reserved)
fn is_public_ip(ip: &std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(ipv4) => {
            // RFC 1918 private ranges
            !ipv4.is_private()
                && !ipv4.is_loopback()
                && !ipv4.is_link_local()
                && !ipv4.is_broadcast()
                && !ipv4.is_documentation()
                && !ipv4.is_unspecified()
                // 100.64.0.0/10 (CGNAT)
                && !(ipv4.octets()[0] == 100 && (ipv4.octets()[1] >= 64 && ipv4.octets()[1] <= 127))
                // 192.0.0.0/24 (IETF Protocol)
                && !(ipv4.octets()[0] == 192 && ipv4.octets()[1] == 0 && ipv4.octets()[2] == 0)
        }
        std::net::IpAddr::V6(ipv6) => {
            !ipv6.is_loopback()
                && !ipv6.is_unspecified()
                // Check for link-local (fe80::/10)
                && ((ipv6.segments()[0] & 0xffc0) != 0xfe80)
                // Check for unique local (fc00::/7)
                && ((ipv6.segments()[0] & 0xfe00) != 0xfc00)
        }
    }
}

// ============================================================================
// Security Hardening: API Key Rotation Support
// ============================================================================

/// API key rotation info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyRotationInfo {
    /// Old key ID (still valid during grace period)
    pub old_key_id: String,
    /// New key ID
    pub new_key_id: String,
    /// Grace period end timestamp
    pub grace_period_end: std::time::SystemTime,
    /// Whether old key has been used since rotation
    pub old_key_used: bool,
}

/// Extended API key info with rotation support
#[derive(Debug, Clone)]
pub struct ApiKeyInfoWithRotation {
    /// Base key info
    pub info: ApiKeyInfo,
    /// Rotation info if key is being rotated
    pub rotation: Option<KeyRotationInfo>,
    /// Whether this key accepts rotated-from requests
    pub accepts_rotated_key: bool,
}

/// Check if a key should be accepted during rotation grace period
pub fn validate_with_rotation_grace(
    provided_key_id: &str,
    current_key: &ApiKeyInfoWithRotation,
) -> bool {
    // Always accept current key
    if provided_key_id == current_key.info.key_id {
        return true;
    }

    // Check rotation grace period
    if let Some(ref rotation) = current_key.rotation {
        if provided_key_id == rotation.old_key_id {
            // Check if still within grace period
            if std::time::SystemTime::now() < rotation.grace_period_end {
                debug!(
                    old_key = %rotation.old_key_id,
                    new_key = %rotation.new_key_id,
                    "Accepting old key during rotation grace period"
                );
                return true;
            }
        }
    }

    false
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_subscription_tier_limits() {
        assert_eq!(SubscriptionTier::Free.max_connections(), 1);
        assert_eq!(SubscriptionTier::Pro.max_connections(), 5);
        assert_eq!(SubscriptionTier::Team.max_connections(), 25);
        assert_eq!(SubscriptionTier::Enterprise.max_connections(), 100);
    }

    #[test]
    fn test_subscription_tier_rate_limits() {
        assert_eq!(SubscriptionTier::Free.rate_limit(), 60);
        assert_eq!(SubscriptionTier::Pro.rate_limit(), 300);
        assert_eq!(SubscriptionTier::Team.rate_limit(), 1000);
        assert_eq!(SubscriptionTier::Enterprise.rate_limit(), 10000);
    }

    #[test]
    fn test_constant_time_compare() {
        assert!(constant_time_compare("secret", "secret"));
        assert!(!constant_time_compare("secret", "Secret"));
        assert!(!constant_time_compare("short", "longer"));
        assert!(!constant_time_compare("", "nonempty"));
    }

    #[test]
    fn test_generate_api_key() {
        let key = generate_api_key();
        assert!(key.starts_with("rk_"));
        assert_eq!(key.len(), 35); // "rk_" + 32 hex chars
    }

    #[tokio::test]
    async fn test_in_memory_validator() {
        let validator = InMemoryApiKeyValidator::new();

        let info = ApiKeyInfo {
            key_id: "key_123".to_string(),
            owner_id: "user_456".to_string(),
            tier: SubscriptionTier::Pro,
            expires_at: None,
            metadata: HashMap::new(),
        };

        validator.add_key("test_api_key".to_string(), info.clone());

        // Valid key
        let result = validator.validate("test_api_key").await;
        assert!(result.is_ok());
        let validated = result.unwrap();
        assert_eq!(validated.tier, SubscriptionTier::Pro);

        // Invalid key
        let result = validator.validate("wrong_key").await;
        assert!(matches!(result, Err(WsAuthError::InvalidApiKey)));
    }

    #[test]
    fn test_connection_tracker() {
        let tracker = ConnectionTracker::new();

        let key_info = ApiKeyInfo {
            key_id: "key_123".to_string(),
            owner_id: "user_456".to_string(),
            tier: SubscriptionTier::Free, // Only 1 connection allowed
            expires_at: None,
            metadata: HashMap::new(),
        };

        let addr: SocketAddr = "127.0.0.1:9100".parse().unwrap();

        // First connection should succeed
        let conn1 = tracker.register(&key_info, addr);
        assert!(conn1.is_ok());

        // Second connection should fail (Free tier = 1 max)
        let conn2 = tracker.register(&key_info, addr);
        assert!(matches!(
            conn2,
            Err(WsAuthError::ConnectionLimitExceeded(_, 1))
        ));

        // Unregister first connection
        tracker.unregister(conn1.unwrap().connection_id);

        // Now should be able to connect again
        let conn3 = tracker.register(&key_info, addr);
        assert!(conn3.is_ok());
    }

    #[test]
    fn test_rate_limiting() {
        let tracker = ConnectionTracker::new();

        let key_info = ApiKeyInfo {
            key_id: "key_123".to_string(),
            owner_id: "user_456".to_string(),
            tier: SubscriptionTier::Free, // 60 requests per minute
            expires_at: None,
            metadata: HashMap::new(),
        };

        let addr: SocketAddr = "127.0.0.1:9100".parse().unwrap();
        let conn = tracker.register(&key_info, addr).unwrap();

        // Should allow 60 requests
        for _ in 0..60 {
            assert!(tracker.check_rate_limit(conn.connection_id).is_ok());
        }

        // 61st request should fail
        assert!(matches!(
            tracker.check_rate_limit(conn.connection_id),
            Err(WsAuthError::RateLimitExceeded(60))
        ));
    }

    #[test]
    fn test_api_key_extraction() {
        let validator = InMemoryApiKeyValidator::new();
        let state = WsAuthState::new(validator);

        let mut headers = HeaderMap::new();

        // Test Bearer format
        headers.insert("Authorization", "Bearer my_api_key".parse().unwrap());
        assert_eq!(
            state.extract_api_key_from_headers(&headers),
            Some("my_api_key".to_string())
        );

        // Test raw format
        headers.insert("Authorization", "raw_api_key".parse().unwrap());
        assert_eq!(
            state.extract_api_key_from_headers(&headers),
            Some("raw_api_key".to_string())
        );

        // Test custom header
        let state = state.with_api_key_header("X-Api-Key");
        headers.insert("X-Api-Key", "custom_key".parse().unwrap());
        assert_eq!(
            state.extract_api_key_from_headers(&headers),
            Some("custom_key".to_string())
        );
    }
}