hiver-security 0.1.0-alpha.6

Security framework for Hiver Framework. Hiver框架的安全框架。 Equivalent to: Spring Security (@PreAuthorize, @Secured, @RolesAllowed)
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
//! JWT (JSON Web Token) authentication module
//! JWT (JSON Web Token) 认证模块
//!
//! # Equivalent to Spring Boot / 等价于 Spring Boot
//!
//! - `JwtUtil` - JWT utility class
//! - `JwtAuthenticationFilter` - JWT authentication filter
//! - `JwtTokenProvider` - JWT token provider
//!
//! # Example / 示例
//!
//! ```rust,no_run,ignore
//! use hiver_security::jwt::{JwtUtil, JwtClaims};
//! use hiver_security::User;
//!
//! // Create JWT token for user
//! let user = User::with_roles("alice", "password", &[Role::User]);
//! let token = JwtUtil::create_token(user.id, &user.username, &user.authorities)?;
//!
//! // Verify JWT token
//! let claims = JwtUtil::verify_token(&token)?;
//! println!("User ID: {}", claims.sub);
//! ```

use crate::{Authority, Role, SecurityError, SecurityResult};
use chrono::{Duration, Utc};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;

/// JWT claims
/// JWT 声明
///
/// Contains all standard JWT claims (RFC 7519) plus application-specific fields.
/// 包含所有标准JWT声明(RFC 7519)加应用特定字段。
///
/// # Standard Claims / 标准声明
///
/// - `iss` (Issuer) / 签发者
/// - `sub` (Subject) / 主题
/// - `aud` (Audience) / 受众
/// - `exp` (Expiration) / 过期时间
/// - `nbf` (Not Before) / 生效时间
/// - `iat` (Issued At) / 签发时间
/// - `jti` (JWT ID) / JWT标识符
///
/// # Spring Equivalent / Spring等价物
///
/// ```java
/// public class JwtClaims {
///     private String iss;      // Issuer
///     private String sub;      // Subject (user ID)
///     private String aud;      // Audience
///     private long exp;        // Expiration
///     private long nbf;        // Not Before
///     private long iat;        // Issued at
///     private String jti;      // JWT ID
///     private String username; // Username
///     private List<String> authorities; // Roles/permissions
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtClaims {
    /// Subject (user ID)
    /// 主体(用户ID)
    pub sub: String,

    /// Username
    /// 用户名
    pub username: String,

    /// Authorities/roles
    /// 权限/角色
    pub authorities: Vec<String>,

    /// Issued at (seconds since epoch)
    /// 签发时间(自纪元以来的秒数)
    pub iat: i64,

    /// Expiration (seconds since epoch)
    /// 过期时间(自纪元以来的秒数)
    pub exp: i64,

    /// Issuer
    /// 签发者
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iss: Option<String>,

    /// Audience (recipient(s) the JWT is intended for)
    /// 受众(JWT的预期接收者)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aud: Option<serde_json::Value>,

    /// Not Before (seconds since epoch; token is not valid before this time)
    /// 生效时间(自纪元以来的秒数;此时间之前令牌无效)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<i64>,

    /// JWT ID (unique identifier for the token)
    /// JWT标识符(令牌的唯一标识符)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<String>,

    /// Custom claims (application-specific key-value pairs)
    /// 自定义声明(应用特定的键值对)
    #[serde(flatten)]
    pub custom: HashMap<String, serde_json::Value>,
}

impl JwtClaims {
    /// Create new JWT claims
    /// 创建新的JWT声明
    pub fn new(
        user_id: impl Into<String>,
        username: impl Into<String>,
        authorities: &[Authority],
        expiration_hours: i64,
    ) -> Self {
        let now = Utc::now();
        let expiration = now + Duration::hours(expiration_hours);

        Self {
            sub: user_id.into(),
            username: username.into(),
            authorities: authorities.iter().map(ToString::to_string).collect(),
            iat: now.timestamp(),
            exp: expiration.timestamp(),
            iss: Some("hiver-security".to_string()),
            aud: None,
            nbf: None,
            jti: None,
            custom: HashMap::new(),
        }
    }

    /// Create a JwtClaims builder for advanced configuration
    /// 创建JwtClaims构建器用于高级配置
    pub fn builder(user_id: impl Into<String>, username: impl Into<String>) -> JwtClaimsBuilder {
        JwtClaimsBuilder {
            sub: user_id.into(),
            username: username.into(),
            authorities: Vec::new(),
            expiration_hours: 24,
            issuer: Some("hiver-security".to_string()),
            audience: None,
            not_before: None,
            jwt_id: None,
            custom: HashMap::new(),
        }
    }

    /// Set the issuer claim
    /// 设置签发者声明
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.iss = Some(issuer.into());
        self
    }

    /// Set the audience claim
    /// 设置受众声明
    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
        self.aud = Some(serde_json::Value::String(audience.into()));
        self
    }

    /// Set multiple audiences
    /// 设置多个受众
    pub fn with_audiences(mut self, audiences: Vec<String>) -> Self {
        self.aud = Some(serde_json::Value::Array(
            audiences
                .into_iter()
                .map(serde_json::Value::String)
                .collect(),
        ));
        self
    }

    /// Set the not-before claim
    /// 设置生效时间声明
    pub fn with_not_before(mut self, nbf: i64) -> Self {
        self.nbf = Some(nbf);
        self
    }

    /// Set the JWT ID claim
    /// 设置JWT标识符声明
    pub fn with_jwt_id(mut self, jti: impl Into<String>) -> Self {
        self.jti = Some(jti.into());
        self
    }

    /// Add a custom claim
    /// 添加自定义声明
    pub fn with_custom_claim(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.custom.insert(key.into(), value);
        self
    }

    /// Check if token is expired
    /// 检查token是否过期
    pub fn is_expired(&self) -> bool {
        Utc::now().timestamp() > self.exp
    }

    /// Get time until expiration
    /// 获取剩余有效时间
    pub fn time_until_expiration(&self) -> Duration {
        let now = Utc::now().timestamp();
        let seconds_left = self.exp - now;
        Duration::seconds(seconds_left)
    }

    /// Convert authorities to Authority enum
    /// 将authorities转换为Authority枚举
    pub fn get_authorities(&self) -> Vec<Authority> {
        self.authorities
            .iter()
            .filter_map(|a| Authority::from_string(a))
            .collect()
    }

    /// Check if has authority
    /// 检查是否有权限
    pub fn has_authority(&self, authority: &Authority) -> bool {
        self.get_authorities().contains(authority)
    }

    /// Check if has role
    /// 检查是否有角色
    pub fn has_role(&self, role: &Role) -> bool {
        self.get_authorities()
            .contains(&Authority::Role(role.clone()))
    }

    /// Get the audience as a list of strings
    /// 获取受众字符串列表
    pub fn audiences(&self) -> Vec<String> {
        match &self.aud {
            Some(serde_json::Value::String(s)) => vec![s.clone()],
            Some(serde_json::Value::Array(arr)) => arr
                .iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect(),
            _ => Vec::new(),
        }
    }

    /// Check if a specific audience is present
    /// 检查是否包含特定受众
    pub fn has_audience(&self, audience: &str) -> bool {
        self.audiences().iter().any(|a| a == audience)
    }
}

/// Builder for constructing JwtClaims with all optional fields
/// 用于构建包含所有可选字段的JwtClaims的构建器
#[derive(Debug)]
pub struct JwtClaimsBuilder {
    sub: String,
    username: String,
    authorities: Vec<String>,
    expiration_hours: i64,
    issuer: Option<String>,
    audience: Option<String>,
    not_before: Option<i64>,
    jwt_id: Option<String>,
    custom: HashMap<String, serde_json::Value>,
}

impl JwtClaimsBuilder {
    /// Set authorities
    /// 设置权限
    pub fn authorities(mut self, auths: &[Authority]) -> Self {
        self.authorities = auths.iter().map(ToString::to_string).collect();
        self
    }

    /// Set expiration in hours
    /// 设置过期时间(小时)
    pub fn expiration_hours(mut self, hours: i64) -> Self {
        self.expiration_hours = hours;
        self
    }

    /// Set issuer
    /// 设置签发者
    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Set audience
    /// 设置受众
    pub fn audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }

    /// Set not-before timestamp
    /// 设置生效时间戳
    pub fn not_before(mut self, nbf: i64) -> Self {
        self.not_before = Some(nbf);
        self
    }

    /// Set JWT ID
    /// 设置JWT标识符
    pub fn jwt_id(mut self, jti: impl Into<String>) -> Self {
        self.jwt_id = Some(jti.into());
        self
    }

    /// Add a custom claim
    /// 添加自定义声明
    pub fn custom_claim(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.custom.insert(key.into(), value);
        self
    }

    /// Build the JwtClaims
    /// 构建JwtClaims
    pub fn build(self) -> JwtClaims {
        let now = Utc::now();
        let expiration = now + Duration::hours(self.expiration_hours);

        JwtClaims {
            sub: self.sub,
            username: self.username,
            authorities: self.authorities,
            iat: now.timestamp(),
            exp: expiration.timestamp(),
            iss: self.issuer,
            aud: self.audience.map(serde_json::Value::String),
            nbf: self.not_before,
            jti: self.jwt_id,
            custom: self.custom,
        }
    }
}

/// Supported JWT signing algorithms
/// 支持的JWT签名算法
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JwtAlgorithm {
    /// HMAC using SHA-256
    #[default]
    Hs256,
    /// HMAC using SHA-384
    Hs384,
    /// HMAC using SHA-512
    Hs512,
    /// RSASSA-PKCS1-v1_5 using SHA-256
    Rs256,
}

impl JwtAlgorithm {
    /// Convert to jsonwebtoken Algorithm
    /// 转换为jsonwebtoken库的Algorithm
    pub fn to_algorithm(&self) -> jsonwebtoken::Algorithm {
        match self {
            JwtAlgorithm::Hs256 => jsonwebtoken::Algorithm::HS256,
            JwtAlgorithm::Hs384 => jsonwebtoken::Algorithm::HS384,
            JwtAlgorithm::Hs512 => jsonwebtoken::Algorithm::HS512,
            JwtAlgorithm::Rs256 => jsonwebtoken::Algorithm::RS256,
        }
    }
}

/// JWT utility
/// JWT 工具类
///
/// Equivalent to Spring's `JwtUtil` class.
/// `等价于Spring的JwtUtil类`。
///
/// # Spring Equivalent / Spring等价物
///
/// ```java
/// public class JwtUtil {
///     public static String createJWT(String subject) { ... }
///     public static Claims parseJWT(String jwt) { ... }
/// }
/// ```
pub struct JwtUtil;

impl JwtUtil {
    /// Get JWT secret key from environment or use default
    /// 从环境变量获取JWT密钥或使用默认值
    fn get_secret() -> String {
        env::var("JWT_SECRET")
            .unwrap_or_else(|_| "hiver-jwt-secret-key-change-in-production-2024".to_string())
    }

    /// Get default token expiration in hours
    /// 获取默认token过期时间(小时)
    fn get_default_expiration() -> i64 {
        env::var("JWT_EXPIRATION_HOURS")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(24) // Default: 24 hours
    }

    /// Create JWT token for user
    /// 为用户创建JWT token
    ///
    /// # Arguments / 参数
    ///
    /// * `user_id` - User ID / 用户ID
    /// * `username` - Username / 用户名
    /// * `authorities` - User authorities / 用户权限
    ///
    /// # Returns / 返回
    ///
    /// JWT token string / JWT token字符串
    ///
    /// # Example / 示例
    ///
    /// ```rust,ignore
    /// let token = JwtUtil::create_token(
    ///     "123",
    ///     "alice",
    ///     &[Authority::Role(Role::User)]
    /// )?;
    /// ```
    pub fn create_token(
        user_id: impl Into<String>,
        username: impl Into<String>,
        authorities: &[Authority],
    ) -> SecurityResult<String> {
        let expiration_hours = Self::get_default_expiration();
        Self::create_token_with_expiration(user_id, username, authorities, expiration_hours)
    }

    /// Create JWT token with custom expiration
    /// 创建带自定义过期时间的JWT token
    ///
    /// # Arguments / 参数
    ///
    /// * `user_id` - User ID / 用户ID
    /// * `username` - Username / 用户名
    /// * `authorities` - User authorities / 用户权限
    /// * `expiration_hours` - Token expiration in hours / token过期时间(小时)
    pub fn create_token_with_expiration(
        user_id: impl Into<String>,
        username: impl Into<String>,
        authorities: &[Authority],
        expiration_hours: i64,
    ) -> SecurityResult<String> {
        let claims = JwtClaims::new(user_id, username, authorities, expiration_hours);

        let secret = Self::get_secret();
        let encoding_key = EncodingKey::from_secret(secret.as_ref());

        encode(&Header::default(), &claims, &encoding_key)
            .map_err(|e| SecurityError::TokenError(format!("Failed to encode token: {}", e)))
    }

    /// Verify and parse JWT token
    /// 验证并解析JWT token
    ///
    /// # Arguments / 参数
    ///
    /// * `token` - JWT token string / JWT token字符串
    ///
    /// # Returns / 返回
    ///
    /// Parsed JWT claims / 解析后的JWT声明
    ///
    /// # Errors / 错误
    ///
    /// Returns error if token is invalid or expired / 如果token无效或过期则返回错误
    pub fn verify_token(token: &str) -> SecurityResult<JwtClaims> {
        let secret = Self::get_secret();
        let decoding_key = DecodingKey::from_secret(secret.as_ref());
        let validation = Validation::new(jsonwebtoken::Algorithm::HS256);

        decode::<JwtClaims>(token, &decoding_key, &validation)
            .map(|data| {
                let claims = data.claims;

                // Check expiration manually for better error messages
                if claims.is_expired() {
                    return Err(SecurityError::TokenExpired("Token has expired".to_string()));
                }

                Ok(claims)
            })
            .map_err(|e| match e.kind() {
                jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
                    SecurityError::TokenExpired("Token signature has expired".to_string())
                },
                _ => SecurityError::InvalidToken(format!("Invalid token: {}", e)),
            })?
    }

    /// Refresh JWT token
    /// 刷新JWT token
    ///
    /// Creates a new token with the same user information but extended expiration.
    /// 创建具有相同用户信息但延长过期时间的新token。
    ///
    /// # Arguments / 参数
    ///
    /// * `token` - Old JWT token / 旧的JWT token
    pub fn refresh_token(token: &str) -> SecurityResult<String> {
        let claims = Self::verify_token(token)?;

        // Parse authorities back from strings
        let authorities: Vec<Authority> = claims
            .authorities
            .iter()
            .filter_map(|s| Authority::from_string(s))
            .collect();

        Self::create_token(&claims.sub, &claims.username, &authorities)
    }

    /// Parse token without verification (for debugging/testing only)
    /// 解析token但不验证(仅用于调试/测试)
    ///
    /// # Warning / 警告
    ///
    /// This should NOT be used in production for authentication.
    /// 这不应该在生产环境中用于身份验证。
    #[cfg(test)]
    pub fn parse_token_unsafe(token: &str) -> SecurityResult<JwtClaims> {
        Self::decode_without_validation(token)
    }

    /// Decode token without any signature or claim validation
    /// 不进行任何签名或声明验证地解码令牌
    ///
    /// Reads the claims payload from the token without checking the signature,
    /// expiration, or any other validation rules. Useful for inspecting token
    /// contents in non-security contexts.
    /// 从令牌中读取声明负载而不检查签名、过期时间或任何其他验证规则。
    /// 适用于在非安全上下文中检查令牌内容。
    ///
    /// # Warning / 警告
    ///
    /// Do NOT use this for authentication decisions.
    /// 不要将此用于身份验证决策。
    pub fn decode_without_validation(token: &str) -> SecurityResult<JwtClaims> {
        use base64::Engine;
        let parts: Vec<&str> = token.split('.').collect();
        if parts.len() != 3 {
            return Err(SecurityError::InvalidToken(
                "Invalid token format: expected 3 parts".to_string(),
            ));
        }

        let payload = parts
            .get(1)
            .ok_or_else(|| SecurityError::InvalidToken("Token payload part missing".to_string()))?;
        let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(payload)
            .map_err(|_| {
                SecurityError::InvalidToken("Failed to decode token payload".to_string())
            })?;

        let claims: JwtClaims = serde_json::from_slice(&decoded)
            .map_err(|e| SecurityError::InvalidToken(format!("Failed to parse claims: {}", e)))?;

        Ok(claims)
    }

    /// Fully validate and decode a JWT token
    /// 完全验证并解码JWT令牌
    ///
    /// Performs signature verification and validates all standard claims:
    /// 执行签名验证并验证所有标准声明:
    /// - Signature is valid for the given secret
    /// - `exp` (expiration) has not passed
    /// - `nbf` (not-before) has passed if present
    ///
    /// Optionally validates `iss` (issuer) and `aud` (audience) if provided.
    /// 如果提供了`iss`(签发者)和`aud`(受众),则可选地验证它们。
    pub fn decode_and_validate(
        token: &str,
        secret: &str,
        algorithm: &JwtAlgorithm,
        issuer: Option<&str>,
        audience: Option<&str>,
    ) -> SecurityResult<JwtClaims> {
        let decoding_key = DecodingKey::from_secret(secret.as_ref());
        let mut validation = Validation::new(algorithm.to_algorithm());

        if let Some(iss) = issuer {
            validation.set_issuer(&[iss]);
        }
        if let Some(aud) = audience {
            validation.set_audience(&[aud]);
        }

        decode::<JwtClaims>(token, &decoding_key, &validation)
            .map(|data| data.claims)
            .map_err(|e| match e.kind() {
                jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
                    SecurityError::TokenExpired("Token has expired".to_string())
                },
                jsonwebtoken::errors::ErrorKind::InvalidToken => {
                    SecurityError::InvalidToken("Token is invalid".to_string())
                },
                jsonwebtoken::errors::ErrorKind::InvalidSignature => {
                    SecurityError::InvalidToken("Invalid token signature".to_string())
                },
                _ => SecurityError::InvalidToken(format!("Token validation failed: {}", e)),
            })
    }

    /// Refresh token if it will expire within the given threshold
    /// 如果令牌将在给定阈值内过期,则刷新令牌
    ///
    /// If the token's remaining lifetime is less than `threshold_secs` seconds,
    /// a new token is created with the same claims but a fresh expiration.
    /// Otherwise, the original token string is returned unchanged.
    /// 如果令牌的剩余生存期少于`threshold_secs`秒,
    /// 则创建具有相同声明但具有新过期时间的新令牌。
    /// 否则,原令牌字符串不变地返回。
    ///
    /// # Arguments / 参数
    ///
    /// * `token` - The current JWT token / 当前的JWT令牌
    /// * `threshold_secs` - Seconds before expiration to trigger refresh / 触发刷新的过期前秒数
    ///
    /// # Returns / 返回
    ///
    /// A tuple of (token_string, was_refreshed) / 一个元组(令牌字符串,是否已刷新)
    pub fn refresh_if_needed(token: &str, threshold_secs: i64) -> SecurityResult<(String, bool)> {
        let claims = Self::decode_without_validation(token)?;

        let now = Utc::now().timestamp();
        let remaining = claims.exp - now;

        if remaining < threshold_secs {
            // Token is close to expiry or already expired; refresh it
            // 令牌即将过期或已经过期;刷新它
            let authorities: Vec<Authority> = claims
                .authorities
                .iter()
                .filter_map(|s| Authority::from_string(s))
                .collect();
            let new_token = Self::create_token(&claims.sub, &claims.username, &authorities)?;
            Ok((new_token, true))
        } else {
            Ok((token.to_string(), false))
        }
    }
}

/// JWT token provider
/// JWT token 提供者
///
/// Equivalent to Spring's `JwtTokenProvider`.
/// `等价于Spring的JwtTokenProvider`。
///
/// Supports HMAC (HS256/HS384/HS512) and RSA (RS256) algorithms.
/// 支持HMAC(HS256/HS384/HS512)和RSA(RS256)算法。
///
/// # Spring Equivalent / Spring等价物
///
/// ```java
/// public class JwtTokenProvider {
///     public String generateToken(Authentication authentication) { ... }
///     public boolean validateToken(String token) { ... }
///     public Authentication getAuthentication(String token) { ... }
/// }
/// ```
#[derive(Clone)]
pub struct JwtTokenProvider {
    /// Secret key for signing tokens (HMAC) or PEM-encoded RSA private key
    /// 签名令牌的密钥(HMAC)或PEM编码的RSA私钥
    secret: String,

    /// PEM-encoded RSA public key for RS256 verification (optional)
    /// PEM编码的RSA公钥,用于RS256验证(可选)
    rsa_public_key_pem: Option<String>,

    /// Token expiration in hours
    /// Token过期时间(小时)
    expiration_hours: i64,

    /// Signing algorithm
    /// 签名算法
    algorithm: JwtAlgorithm,

    /// Expected issuer for validation
    /// 用于验证的预期签发者
    issuer: Option<String>,

    /// Expected audience for validation
    /// 用于验证的预期受众
    audience: Option<String>,
}

impl JwtTokenProvider {
    /// Create new JWT token provider with default settings
    /// 使用默认设置创建新的JWT令牌提供者
    pub fn new() -> Self {
        Self {
            secret: JwtUtil::get_secret(),
            rsa_public_key_pem: None,
            expiration_hours: JwtUtil::get_default_expiration(),
            algorithm: JwtAlgorithm::default(),
            issuer: Some("hiver-security".to_string()),
            audience: None,
        }
    }

    /// Create with custom secret and expiration
    /// 使用自定义密钥和过期时间创建
    pub fn with_settings(secret: impl Into<String>, expiration_hours: i64) -> Self {
        Self {
            secret: secret.into(),
            rsa_public_key_pem: None,
            expiration_hours,
            algorithm: JwtAlgorithm::default(),
            issuer: Some("hiver-security".to_string()),
            audience: None,
        }
    }

    /// Set the signing algorithm
    /// 设置签名算法
    pub fn with_algorithm(mut self, algorithm: JwtAlgorithm) -> Self {
        self.algorithm = algorithm;
        self
    }

    /// Set the expected issuer for validation
    /// 设置用于验证的预期签发者
    pub fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Set the expected audience for validation
    /// 设置用于验证的预期受众
    pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }

    /// Set RSA public key PEM for RS256 verification
    /// 设置用于RS256验证的RSA公钥PEM
    ///
    /// When using RS256, the private key is used for signing and
    /// the public key is used for verification.
    /// 使用RS256时,私钥用于签名,公钥用于验证。
    pub fn with_rsa_public_key(mut self, pem: impl Into<String>) -> Self {
        self.rsa_public_key_pem = Some(pem.into());
        self
    }

    /// Get the encoding key based on the algorithm
    /// 根据算法获取编码密钥
    fn encoding_key(&self) -> SecurityResult<EncodingKey> {
        match self.algorithm {
            JwtAlgorithm::Rs256 => EncodingKey::from_rsa_pem(self.secret.as_bytes())
                .map_err(|e| SecurityError::Jwt(format!("Invalid RSA private key: {}", e))),
            _ => Ok(EncodingKey::from_secret(self.secret.as_ref())),
        }
    }

    /// Get the decoding key based on the algorithm
    /// 根据算法获取解码密钥
    fn decoding_key(&self) -> SecurityResult<DecodingKey> {
        match self.algorithm {
            JwtAlgorithm::Rs256 => {
                let pem = self.rsa_public_key_pem.as_deref().unwrap_or(&self.secret);
                DecodingKey::from_rsa_pem(pem.as_bytes())
                    .map_err(|e| SecurityError::Jwt(format!("Invalid RSA public key: {}", e)))
            },
            _ => Ok(DecodingKey::from_secret(self.secret.as_ref())),
        }
    }

    /// Build the validation rules
    /// 构建验证规则
    fn validation(&self) -> Validation {
        let mut validation = Validation::new(self.algorithm.to_algorithm());
        if let Some(ref iss) = self.issuer {
            validation.set_issuer(&[iss.as_str()]);
        }
        if let Some(ref aud) = self.audience {
            validation.set_audience(&[aud.as_str()]);
        } else {
            // If no audience is configured, disable audience validation
            // 如果未配置受众,则禁用受众验证
            validation.set_audience::<&str>(&[]);
        }
        validation
    }

    /// Generate token from authentication
    /// 从认证生成token
    pub fn generate_token(
        &self,
        user_id: impl Into<String>,
        username: impl Into<String>,
        authorities: &[Authority],
    ) -> SecurityResult<String> {
        let mut claims = JwtClaims::new(user_id, username, authorities, self.expiration_hours);

        // Apply provider-level issuer and audience to claims
        // 将提供者级别的签发者和受众应用于声明
        if self.issuer.is_some() {
            claims.iss.clone_from(&self.issuer);
        }
        if let Some(ref aud) = self.audience {
            claims.aud = Some(serde_json::Value::String(aud.clone()));
        }

        let encoding_key = self.encoding_key()?;
        let header = Header::new(self.algorithm.to_algorithm());

        encode(&header, &claims, &encoding_key)
            .map_err(|e| SecurityError::TokenError(format!("Failed to encode token: {}", e)))
    }

    /// Validate token, returning true if valid
    /// 验证令牌,有效则返回true
    pub fn validate_token(&self, token: &str) -> SecurityResult<bool> {
        match self.decode_and_validate(token) {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Get authentication from token
    /// 从token获取认证
    pub fn get_authentication(&self, token: &str) -> SecurityResult<JwtClaims> {
        self.decode_and_validate(token)
    }

    /// Refresh token
    /// 刷新token
    pub fn refresh_token(&self, token: &str) -> SecurityResult<String> {
        let claims = self.decode_and_validate(token)?;
        let authorities: Vec<Authority> = claims
            .authorities
            .iter()
            .filter_map(|s| Authority::from_string(s))
            .collect();
        self.generate_token(&claims.sub, &claims.username, &authorities)
    }

    /// Full validation: verify signature, check exp/nbf, optionally check issuer/audience
    /// 完整验证:验证签名,检查exp/nbf,可选检查签发者/受众
    ///
    /// Returns the decoded claims if all validations pass.
    /// 如果所有验证都通过,则返回解码后的声明。
    pub fn decode_and_validate(&self, token: &str) -> SecurityResult<JwtClaims> {
        let decoding_key = self.decoding_key()?;
        let validation = self.validation();

        decode::<JwtClaims>(token, &decoding_key, &validation)
            .map(|data| data.claims)
            .map_err(|e| match e.kind() {
                jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
                    SecurityError::TokenExpired("Token has expired".to_string())
                },
                jsonwebtoken::errors::ErrorKind::InvalidSignature => {
                    SecurityError::InvalidToken("Invalid token signature".to_string())
                },
                _ => SecurityError::InvalidToken(format!("Token validation failed: {}", e)),
            })
    }

    /// Decode token without validation (reads claims without checking signature)
    /// 不验证地解码令牌(读取声明而不检查签名)
    pub fn decode_without_validation(&self, token: &str) -> SecurityResult<JwtClaims> {
        JwtUtil::decode_without_validation(token)
    }

    /// Refresh token if it will expire within the given threshold
    /// 如果令牌将在给定阈值内过期,则刷新令牌
    ///
    /// Returns (token_string, was_refreshed).
    /// 返回(令牌字符串,是否已刷新)。
    pub fn refresh_if_needed(
        &self,
        token: &str,
        threshold_secs: i64,
    ) -> SecurityResult<(String, bool)> {
        let claims = JwtUtil::decode_without_validation(token)?;

        let now = Utc::now().timestamp();
        let remaining = claims.exp - now;

        if remaining < threshold_secs {
            let authorities: Vec<Authority> = claims
                .authorities
                .iter()
                .filter_map(|s| Authority::from_string(s))
                .collect();
            let new_token = self.generate_token(&claims.sub, &claims.username, &authorities)?;
            Ok((new_token, true))
        } else {
            Ok((token.to_string(), false))
        }
    }

    // ── OAuth2 / OIDC helpers ─────────────────────────────────────────────────

    /// Convenience constructor: HMAC-SHA256 with a custom issuer.
    /// 便捷构造函数:使用自定义签发者的 HMAC-SHA256。
    pub fn new_hmac(secret: impl Into<String>, issuer: impl Into<String>) -> Self {
        Self {
            secret: secret.into(),
            rsa_public_key_pem: None,
            expiration_hours: 1,
            algorithm: JwtAlgorithm::Hs256,
            issuer: Some(issuer.into()),
            audience: None,
        }
    }

    /// Generate an OAuth2 access token embedding `scope` and `client_id` custom claims.
    /// 生成包含 `scope` 和 `client_id` 自定义声明的 OAuth2 访问令牌。
    pub fn generate_oauth2_token(
        &self,
        subject: &str,
        client_id: &str,
        scope: &str,
        ttl: std::time::Duration,
    ) -> SecurityResult<String> {
        let now = Utc::now().timestamp();
        let exp = now + ttl.as_secs() as i64;
        let mut custom: HashMap<String, serde_json::Value> = HashMap::new();
        custom.insert("scope".into(), serde_json::Value::String(scope.to_string()));
        custom.insert("client_id".into(), serde_json::Value::String(client_id.to_string()));
        let claims = JwtClaims {
            sub: subject.to_string(),
            username: subject.to_string(),
            authorities: Vec::new(),
            iat: now,
            exp,
            iss: self.issuer.clone(),
            aud: None,
            nbf: None,
            jti: None,
            custom,
        };
        let encoding_key = self.encoding_key()?;
        let header = Header::new(self.algorithm.to_algorithm());
        encode(&header, &claims, &encoding_key)
            .map_err(|e| SecurityError::TokenError(format!("Failed to encode OAuth2 token: {e}")))
    }

    /// Generate a minimal OIDC ID token (subject + audience).
    /// 生成最小化的 OIDC ID 令牌(主体 + 受众)。
    pub fn generate_id_token(&self, subject: &str, client_id: &str) -> SecurityResult<String> {
        let now = Utc::now().timestamp();
        let exp = now + 3600;
        let claims = JwtClaims {
            sub: subject.to_string(),
            username: subject.to_string(),
            authorities: Vec::new(),
            iat: now,
            exp,
            iss: self.issuer.clone(),
            aud: Some(serde_json::Value::String(client_id.to_string())),
            nbf: None,
            jti: None,
            custom: HashMap::new(),
        };
        let encoding_key = self.encoding_key()?;
        let header = Header::new(self.algorithm.to_algorithm());
        encode(&header, &claims, &encoding_key)
            .map_err(|e| SecurityError::TokenError(format!("Failed to encode ID token: {e}")))
    }
}

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

/// JWT authentication result
/// JWT认证结果
#[derive(Debug, Clone)]
pub struct JwtAuthentication {
    /// User ID
    pub user_id: String,

    /// Username
    pub username: String,

    /// Authorities
    pub authorities: Vec<Authority>,
}

impl JwtAuthentication {
    /// Create from claims
    /// 从声明创建
    pub fn from_claims(claims: &JwtClaims) -> Self {
        Self {
            user_id: claims.sub.clone(),
            username: claims.username.clone(),
            authorities: claims.get_authorities(),
        }
    }

    /// Check if has authority
    /// 检查是否有权限
    pub fn has_authority(&self, authority: &Authority) -> bool {
        self.authorities.contains(authority)
    }

    /// Check if has role
    /// 检查是否有角色
    pub fn has_role(&self, role: &Role) -> bool {
        self.authorities.contains(&Authority::Role(role.clone()))
    }
}

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

    #[test]
    fn test_create_and_verify_token() {
        let authorities = vec![
            Authority::Role(Role::User),
            Authority::Permission("user:read".to_string()),
        ];

        let token = JwtUtil::create_token("123", "alice", &authorities).unwrap();
        assert!(!token.is_empty());

        let claims = JwtUtil::verify_token(&token).unwrap();
        assert_eq!(claims.sub, "123");
        assert_eq!(claims.username, "alice");
        assert_eq!(claims.authorities.len(), 2);
        assert!(!claims.is_expired());
    }

    #[test]
    fn test_token_authorities() {
        let authorities = vec![Authority::Role(Role::Admin), Authority::Role(Role::User)];

        let token = JwtUtil::create_token("123", "admin", &authorities).unwrap();
        let claims = JwtUtil::verify_token(&token).unwrap();

        assert!(claims.has_role(&Role::Admin));
        assert!(claims.has_role(&Role::User));
        assert!(!claims.has_role(&Role::Guest));
    }

    #[test]
    fn test_token_provider() {
        let provider = JwtTokenProvider::new();
        let authorities = vec![Authority::Role(Role::User)];

        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        assert!(provider.validate_token(&token).unwrap());

        let auth = provider.get_authentication(&token).unwrap();
        assert_eq!(auth.username, "alice");
    }

    #[test]
    fn test_refresh_token() {
        let authorities = vec![Authority::Role(Role::User)];
        let old_token = JwtUtil::create_token("123", "alice", &authorities).unwrap();

        // Sleep briefly to ensure different timestamp
        std::thread::sleep(std::time::Duration::from_secs(2));

        let new_token = JwtUtil::refresh_token(&old_token).unwrap();
        assert_ne!(old_token, new_token);

        let claims = JwtUtil::verify_token(&new_token).unwrap();
        assert_eq!(claims.sub, "123");
    }

    #[test]
    fn test_jwt_authentication_from_claims() {
        let authorities = vec![Authority::Role(Role::Admin)];
        let token = JwtUtil::create_token("123", "admin", &authorities).unwrap();
        let claims = JwtUtil::verify_token(&token).unwrap();

        let auth = JwtAuthentication::from_claims(&claims);
        assert_eq!(auth.user_id, "123");
        assert_eq!(auth.username, "admin");
        assert!(auth.has_role(&Role::Admin));
    }

    #[test]
    fn test_token_with_custom_expiration() {
        let authorities = vec![Authority::Role(Role::User)];
        let token =
            JwtUtil::create_token_with_expiration("123", "alice", &authorities, 48).unwrap();

        let claims = JwtUtil::verify_token(&token).unwrap();
        // Should expire in ~48 hours
        let time_left = claims.time_until_expiration();
        assert!(time_left.num_hours() > 47);
        assert!(time_left.num_hours() <= 48);
    }

    #[test]
    fn test_invalid_token() {
        let result = JwtUtil::verify_token("invalid.token.here");
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_without_validation() {
        let authorities = vec![Authority::Role(Role::User)];
        let token = JwtUtil::create_token("123", "alice", &authorities).unwrap();

        let claims = JwtUtil::decode_without_validation(&token).unwrap();
        assert_eq!(claims.sub, "123");
        assert_eq!(claims.username, "alice");
    }

    #[test]
    fn test_decode_without_validation_invalid_format() {
        let result = JwtUtil::decode_without_validation("not.a.valid.jwt.token");
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_and_validate() {
        let secret = "test-secret-for-validation";
        let provider = JwtTokenProvider::with_settings(secret, 24);

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        // Should succeed with the same secret
        let claims =
            JwtUtil::decode_and_validate(&token, secret, &JwtAlgorithm::Hs256, None, None).unwrap();
        assert_eq!(claims.sub, "123");
    }

    #[test]
    fn test_decode_and_validate_wrong_secret() {
        let secret = "correct-secret";
        let provider = JwtTokenProvider::with_settings(secret, 24);

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        // Should fail with wrong secret
        let result =
            JwtUtil::decode_and_validate(&token, "wrong-secret", &JwtAlgorithm::Hs256, None, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_decode_and_validate_with_issuer() {
        let secret = "test-secret";
        let provider = JwtTokenProvider::with_settings(secret, 24).with_issuer("my-app");

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        // Should succeed with matching issuer
        let claims = JwtUtil::decode_and_validate(
            &token,
            secret,
            &JwtAlgorithm::Hs256,
            Some("my-app"),
            None,
        )
        .unwrap();
        assert_eq!(claims.iss, Some("my-app".to_string()));
    }

    #[test]
    fn test_decode_and_validate_wrong_issuer() {
        let secret = "test-secret";
        let provider = JwtTokenProvider::with_settings(secret, 24).with_issuer("my-app");

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        // Should fail with wrong issuer
        let result = JwtUtil::decode_and_validate(
            &token,
            secret,
            &JwtAlgorithm::Hs256,
            Some("wrong-issuer"),
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_refresh_if_needed_no_refresh() {
        let authorities = vec![Authority::Role(Role::User)];
        // Token expires in 24 hours by default
        let token = JwtUtil::create_token("123", "alice", &authorities).unwrap();

        // Threshold of 1 hour - token has ~24 hours left, should NOT refresh
        let (returned_token, refreshed) = JwtUtil::refresh_if_needed(&token, 3600).unwrap();
        assert!(!refreshed);
        assert_eq!(returned_token, token);
    }

    #[test]
    fn test_provider_refresh_if_needed_no_refresh() {
        let provider = JwtTokenProvider::new();
        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        // Token has ~24h left, threshold 1h -> no refresh
        let (returned_token, refreshed) = provider.refresh_if_needed(&token, 3600).unwrap();
        assert!(!refreshed);
        assert_eq!(returned_token, token);
    }

    #[test]
    fn test_provider_with_audience() {
        let provider = JwtTokenProvider::with_settings("secret", 24).with_audience("my-api");

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        let claims = provider.decode_and_validate(&token).unwrap();
        assert_eq!(claims.audiences(), vec!["my-api"]);
        assert!(claims.has_audience("my-api"));
        assert!(!claims.has_audience("other-api"));
    }

    #[test]
    fn test_claims_builder() {
        let claims = JwtClaims::builder("123", "alice")
            .authorities(&[Authority::Role(Role::Admin)])
            .expiration_hours(48)
            .issuer("test-app")
            .audience("my-api")
            .jwt_id("unique-id-123")
            .custom_claim("department", serde_json::Value::String("engineering".to_string()))
            .build();

        assert_eq!(claims.sub, "123");
        assert_eq!(claims.username, "alice");
        assert_eq!(claims.iss, Some("test-app".to_string()));
        assert_eq!(claims.audiences(), vec!["my-api"]);
        assert_eq!(claims.jti, Some("unique-id-123".to_string()));
        assert_eq!(
            claims.custom.get("department").unwrap(),
            &serde_json::Value::String("engineering".to_string())
        );
    }

    #[test]
    fn test_claims_with_audiences() {
        let claims = JwtClaims::new("123", "alice", &[], 24)
            .with_audiences(vec!["api-v1".to_string(), "api-v2".to_string()]);

        assert_eq!(claims.audiences(), vec!["api-v1", "api-v2"]);
        assert!(claims.has_audience("api-v1"));
        assert!(claims.has_audience("api-v2"));
        assert!(!claims.has_audience("api-v3"));
    }

    #[test]
    fn test_claims_custom_claims() {
        let claims = JwtClaims::new("123", "alice", &[], 24)
            .with_custom_claim("role", serde_json::Value::String("manager".to_string()))
            .with_custom_claim("level", serde_json::Value::Number(5.into()));

        assert_eq!(
            claims.custom.get("role").unwrap(),
            &serde_json::Value::String("manager".to_string())
        );
        assert_eq!(claims.custom.get("level").unwrap(), &serde_json::Value::Number(5.into()));
    }

    #[test]
    fn test_provider_hs384() {
        let provider =
            JwtTokenProvider::with_settings("secret-key", 24).with_algorithm(JwtAlgorithm::Hs384);

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        assert!(provider.validate_token(&token).unwrap());

        let claims = provider.decode_and_validate(&token).unwrap();
        assert_eq!(claims.sub, "123");
    }

    #[test]
    fn test_provider_hs512() {
        let provider =
            JwtTokenProvider::with_settings("secret-key", 24).with_algorithm(JwtAlgorithm::Hs512);

        let authorities = vec![Authority::Role(Role::User)];
        let token = provider
            .generate_token("123", "alice", &authorities)
            .unwrap();

        assert!(provider.validate_token(&token).unwrap());

        let claims = provider.decode_and_validate(&token).unwrap();
        assert_eq!(claims.sub, "123");
    }

    #[test]
    fn test_algorithm_default() {
        assert_eq!(JwtAlgorithm::default(), JwtAlgorithm::Hs256);
    }

    #[test]
    fn test_expired_token_rejection() {
        // Create a token that expires immediately (0 hours = already past)
        // Note: we can't truly create an expired token with the current API,
        // so we test with a very short expiration and check the logic
        let claims = JwtClaims {
            sub: "123".to_string(),
            username: "alice".to_string(),
            authorities: vec![],
            iat: Utc::now().timestamp() - 7200, // 2 hours ago
            exp: Utc::now().timestamp() - 3600, // 1 hour ago (expired)
            iss: Some("hiver-security".to_string()),
            aud: None,
            nbf: None,
            jti: None,
            custom: HashMap::new(),
        };

        assert!(claims.is_expired());
    }

    #[test]
    fn test_token_round_trip_all_claims() {
        let provider = JwtTokenProvider::with_settings("test-secret", 1)
            .with_issuer("test-issuer")
            .with_audience("test-audience");

        let authorities = vec![Authority::Role(Role::Admin)];
        let token = provider
            .generate_token("user-1", "bob", &authorities)
            .unwrap();

        let claims = provider.decode_and_validate(&token).unwrap();

        assert_eq!(claims.sub, "user-1");
        assert_eq!(claims.username, "bob");
        assert_eq!(claims.iss, Some("test-issuer".to_string()));
        assert!(claims.has_audience("test-audience"));
        assert!(!claims.is_expired());
        assert!(claims.has_role(&Role::Admin));
    }
}