rowdy 0.0.9

`rowdy` is a Rocket based JSON Web token based authentication server.
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
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
//! Authentication token structs, and methods
//!
//! This module provides the `Token` struct which encapsulates a JSON Web Token or `JWT`.
//! Clients will pass the encapsulated JWT to services that require it.
//! The JWT should be considered opaque to clients.
//! The `Token` struct contains enough information for the client to act on, including expiry times.
use std::borrow::Borrow;
use std::collections::HashSet;
use std::error;
use std::fmt;
use std::fs::File;
use std::io::{self, Cursor, Read};
use std::ops::Deref;
use std::str::FromStr;
use std::time::Duration;

use crate::cors;
use crate::jwt::{self, jwa, jwk, jws};
use chrono::{self, DateTime, Utc};
use rocket::http::{ContentType, Method, Status};
use rocket::response::{Responder, Response};
use rocket::Request;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json;
use uuid::Uuid;

use crate::{ByteSequence, JsonValue};

/// Token errors
#[derive(Debug)]
pub enum Error {
    /// Raised when attempting to encode an already encoded token
    TokenAlreadyEncoded,
    /// Raised when attempting to decode an already decoded token
    TokenAlreadyDecoded,
    /// Raised when attempting to use a decoded token when an encoded one is expected
    TokenNotEncoded,
    /// Raised when attempting to use an encoded token when an decoded one is expected
    TokenNotDecoded,
    /// Raised when attempting to perform an operation on the refresh token,
    /// but the refresh token is not present
    NoRefreshToken,
    /// Raised when attempting to encrypt and sign an already encrypted and signed refresh token
    RefreshTokenAlreadyEncrypted,
    /// Raised when attempting to decrypt and verify an already decrypted and verified refresh token
    RefreshTokenAlreadyDecrypted,
    /// Raised when attempting to use an encrypted refresh token when a decrypted one is expected
    RefreshTokenNotDecrypted,
    /// Raised when attempting to use an decrypted refresh token when a encrypted one is expected
    RefreshTokenNotEncrypted,
    /// Raised when the service requested is not in the list of intended audiences
    InvalidService,
    /// Raised when the issuer is invalid
    InvalidIssuer,
    /// Raised when the audience is invalid
    InvalidAudience,

    /// Generic Error
    GenericError(String),
    /// IO Error when reading keys from files
    IOError(io::Error),
    /// Errors during token encoding/decoding
    JWTError(Box<jwt::errors::Error>),
    /// Errors during token serialization
    TokenSerializationError(serde_json::Error),
}

impl_from_error!(io::Error, Error::IOError);
impl_from_error!(serde_json::Error, Error::TokenSerializationError);
impl_from_error!(String, Error::GenericError);

impl From<jwt::errors::Error> for Error {
    fn from(jwt: jwt::errors::Error) -> Self {
        Error::JWTError(Box::new(jwt))
    }
}

impl<'a> From<&'a str> for Error {
    fn from(s: &'a str) -> Error {
        Error::GenericError(s.to_string())
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::TokenAlreadyEncoded => "Token is already encoded",
            Error::TokenAlreadyDecoded => "Token is already decoded",
            Error::TokenNotEncoded => "Token is not encoded and cannot be used in this context",
            Error::TokenNotDecoded => "Token is not decoded and cannot be used in this context",
            Error::NoRefreshToken => "Refresh token is not present",
            Error::RefreshTokenAlreadyEncrypted => "Refresh token is already encrypted and signed",
            Error::RefreshTokenAlreadyDecrypted => {
                "Refresh token is already decrypted and verified"
            }
            Error::RefreshTokenNotDecrypted => {
                "Refresh token is not decrypted and cannot be used in this context"
            }
            Error::RefreshTokenNotEncrypted => {
                "Refresh token is not encrypted and cannot be used in this context"
            }
            Error::InvalidService => "Service requested is not in the list of intended audiences",
            Error::InvalidIssuer => "The token has an invalid issuer",
            Error::InvalidAudience => "The token has invalid audience",
            Error::JWTError(ref e) => e.description(),
            Error::IOError(ref e) => e.description(),
            Error::TokenSerializationError(ref e) => e.description(),
            Error::GenericError(ref e) => e,
        }
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        match *self {
            Error::JWTError(ref e) => Some(e),
            Error::IOError(ref e) => Some(e),
            Error::TokenSerializationError(ref e) => Some(e),
            _ => Some(self),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Error::JWTError(ref e) => fmt::Display::fmt(e, f),
            Error::IOError(ref e) => fmt::Display::fmt(e, f),
            Error::TokenSerializationError(ref e) => fmt::Display::fmt(e, f),
            Error::GenericError(ref e) => fmt::Display::fmt(e, f),
            _ => write!(f, "{}", error::Error::description(self)),
        }
    }
}

impl<'r> Responder<'r> for Error {
    fn respond_to(self, _: &Request<'_>) -> Result<Response<'r>, Status> {
        error_!("Token Error: {:?}", self);
        match self {
            Error::InvalidService | Error::InvalidIssuer | Error::InvalidAudience => {
                Err(Status::Forbidden)
            }
            Error::JWTError(ref e) => {
                use crate::jwt::errors::Error::*;

                let status = match **e {
                    ValidationError(_)
                    | JsonError(_)
                    | DecodeBase64(_)
                    | Utf8(_)
                    | UnspecifiedCryptographicError => Status::Unauthorized,
                    _ => Status::InternalServerError,
                };
                Err(status)
            }
            _ => Err(Status::InternalServerError),
        }
    }
}

fn make_uuid() -> Result<Uuid, Error> {
    use crate::jwt::jwa::SecureRandom;
    use std::error::Error;

    let mut bytes = vec![0; 16];
    crate::rng()
        .fill(&mut bytes)
        .map_err(|_| "Unable to generate UUID")?;
    Ok(Uuid::from_bytes(&bytes).map_err(|e| e.description().to_string())?)
}

fn make_header(signature_algorithm: Option<jwa::SignatureAlgorithm>) -> jws::Header<jwt::Empty> {
    let registered = jws::RegisteredHeader {
        algorithm: signature_algorithm.unwrap_or_else(|| jwa::SignatureAlgorithm::None),
        ..Default::default()
    };
    jws::Header::from_registered_header(registered)
}

fn make_registered_claims(
    subject: &str,
    now: DateTime<Utc>,
    expiry_duration: Duration,
    issuer: &jwt::StringOrUri,
    audience: &jwt::SingleOrMultiple<jwt::StringOrUri>,
) -> Result<jwt::RegisteredClaims, crate::Error> {
    let expiry_duration = chrono::Duration::from_std(expiry_duration).map_err(|e| e.to_string())?;

    Ok(jwt::RegisteredClaims {
        issuer: Some(issuer.clone()),
        subject: Some(FromStr::from_str(subject).map_err(|e| Error::JWTError(Box::new(e)))?),
        audience: Some(audience.clone()),
        issued_at: Some(now.into()),
        not_before: Some(now.into()),
        expiry: Some((now + expiry_duration).into()),
        id: Some(make_uuid()?.urn().to_string()),
    })
}

/// Make a new JWS
#[cfg_attr(feature = "clippy_lints", allow(too_many_arguments))] // Internal function
fn make_token<P: Serialize + DeserializeOwned + 'static>(
    subject: &str,
    issuer: &jwt::StringOrUri,
    audience: &jwt::SingleOrMultiple<jwt::StringOrUri>,
    expiry_duration: Duration,
    private_claims: P,
    signature_algorithm: Option<jwa::SignatureAlgorithm>,
    now: DateTime<Utc>,
) -> Result<jwt::JWT<P, jwt::Empty>, crate::Error> {
    let header = make_header(signature_algorithm);
    let registered_claims =
        make_registered_claims(subject, now, expiry_duration, issuer, audience)?;

    Ok(jwt::JWT::new_decoded(
        header,
        jwt::ClaimsSet::<P> {
            private: private_claims,
            registered: registered_claims,
        },
    ))
}

/// Verify that the service requested for is allowed in the configuration
fn verify_service(config: &Configuration, service: &str) -> Result<(), Error> {
    if !config.audience.contains(&FromStr::from_str(service)?) {
        Err(Error::InvalidService)
    } else {
        Ok(())
    }
}

/// Verify that the issuer is expected from the configuration
fn verify_issuer(config: &Configuration, issuer: &jwt::StringOrUri) -> Result<(), Error> {
    if *issuer == config.issuer {
        Ok(())
    } else {
        Err(Error::InvalidIssuer)
    }
}

/// Verify that the requested audience is a strict subset of the audience configured
fn verify_audience(
    config: &Configuration,
    audience: &jwt::SingleOrMultiple<jwt::StringOrUri>,
) -> Result<(), Error> {
    let allowed_audience: HashSet<jwt::StringOrUri> = config.audience.iter().cloned().collect();
    let audience: HashSet<jwt::StringOrUri> = audience.iter().cloned().collect();

    if audience.is_subset(&allowed_audience) {
        Ok(())
    } else {
        Err(Error::InvalidAudience)
    }
}

/// A wrapper around `cors::Options` for options specific to the token retrival route
pub type TokenGetterCorsOptions = cors::Cors;

const TOKEN_GETTER_METHODS: &[Method] = &[Method::Get];
const TOKEN_GETTER_HEADERS: &[&str] = &[
    "Authorization",
    "Accept",
    "Accept-Language",
    "Content-Language",
    "Content-Type",
    "Origin",
];

/// Token configuration. Usually deserialized as part of [`crate::Configuration`] from JSON for use.
///
///
/// # Examples
/// This is a standard JSON serialized example.
///
/// ```json
/// {
///     "issuer": "https://www.acme.com",
///     "allowed_origins": { "Some": ["https://www.example.com", "https://www.foobar.com"] },
///     "audience": ["https://www.example.com", "https://www.foobar.com"],
///     "signature_algorithm": "RS256",
///     "secret": {
///                 "rsa_private": "test/fixtures/rsa_private_key.der",
///                 "rsa_public": "test/fixtures/rsa_public_key.der"
///                },
///     "expiry_duration": 86400
/// }
/// ```
///
/// ```
/// extern crate rowdy;
/// extern crate serde_json;
///
/// use rowdy::token::Configuration;
///
/// # fn main() {
/// let json = r#"{
///     "issuer": "https://www.acme.com",
///     "allowed_origins": { "Some": ["https://www.example.com", "https://www.foobar.com"] },
///     "audience": ["https://www.example.com", "https://www.foobar.com"],
///     "signature_algorithm": "RS256",
///     "secret": {
///                 "rsa_private": "test/fixtures/rsa_private_key.der",
///                 "rsa_public": "test/fixtures/rsa_public_key.der"
///                },
///     "expiry_duration": 86400
/// }"#;
/// let deserialized: Configuration = serde_json::from_str(json).unwrap();
/// # }
/// ```
///
/// Variations for the fields `allowed_origins`, `audience` and `secret` exist.
/// Refer to their type documentation for examples.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Configuration {
    /// The issuer of the token. Usually the URI of the authentication server.
    /// The issuer URI will also be used in the UUID generation of the tokens,
    /// and is also the `realm` for authentication purposes.
    pub issuer: jwt::StringOrUri,
    /// Origins that are allowed to issue CORS request. This is needed for browser
    /// access to the authentication server, but tools like `curl` do not obey nor
    /// enforce the CORS convention.
    pub allowed_origins: cors::AllOrSome<HashSet<cors::headers::Url>>,
    /// The audience intended for your tokens. The `service` request paremeter will be
    /// validated against this
    pub audience: jwt::SingleOrMultiple<jwt::StringOrUri>,
    /// Defaults to `none`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_algorithm: Option<jwa::SignatureAlgorithm>,
    /// Secrets for use in signing a JWT.
    /// This enum (de)serialized as an
    /// [untagged](https://serde.rs/enum-representations.html) enum variant.
    ///
    /// Defaults to `None`.
    ///
    /// See [`Secret`] for serialization examples
    #[serde(default)]
    pub secret: Secret,
    /// Expiry duration of tokens, in seconds.
    ///
    /// Defaults to 24 hours when deserialized and left unfilled
    #[serde(
        with = "crate::serde_custom::duration",
        default = "Configuration::default_expiry_duration"
    )]
    pub expiry_duration: Duration,
    /// Customise refresh token options. Set to `None` to disable refresh tokens
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub refresh_token: Option<RefreshTokenConfiguration>,
}

const DEFAULT_EXPIRY_DURATION: u64 = 86400;
impl Configuration {
    fn default_expiry_duration() -> Duration {
        Duration::from_secs(DEFAULT_EXPIRY_DURATION)
    }

    /// Return a new CORS Option
    pub(crate) fn cors_option(&self) -> TokenGetterCorsOptions {
        cors::Cors {
            allowed_origins: self.allowed_origins.clone(),
            allowed_methods: TOKEN_GETTER_METHODS
                .iter()
                .cloned()
                .map(From::from)
                .collect(),
            allowed_headers: cors::AllOrSome::Some(
                TOKEN_GETTER_HEADERS
                    .iter()
                    .map(|s| s.to_string().into())
                    .collect(),
            ),
            allow_credentials: true,
            ..Default::default()
        }
    }

    /// Returns whether refresh tokens are enabled
    pub fn refresh_token_enabled(&self) -> bool {
        self.refresh_token.is_some()
    }

    /// Convenience function to return a reference to the Refresh Token configuration.
    ///
    /// # Panics
    /// Panics if refresh token is not enabled
    pub fn refresh_token(&self) -> &RefreshTokenConfiguration {
        self.refresh_token.as_ref().unwrap()
    }

    /// Prepare the keys for use with various cryptographic operations
    pub fn keys(&self) -> Result<Keys, Error> {
        let (encryption, decryption) = if self.refresh_token_enabled() {
            let key = &self.refresh_token().key;
            (Some(key.for_encryption()?), Some(key.for_decryption()?))
        } else {
            (None, None)
        };

        Ok(Keys {
            signing: self.secret.for_signing()?,
            signature_verification: self.secret.for_verification()?,
            encryption: encryption,
            decryption: decryption,
        })
    }
}

/// Configuration for Refresh Tokens
///
/// Refresh Tokens are encrypted JWS, signed with the same algorithm as access tokens.
/// There are two algorithms used.
///
/// A content encryption algorithm is used to encrypt the payload of the token,
/// and provided some integrity protection.
/// The algorithm used is symmetric. The list of supported algorithm can be found
/// [here](https://lawliet89.github.io/biscuit/biscuit/jwa/enum.ContentEncryptionAlgorithm.html).
/// The key used to encrypt the content is called the Content Encryption Key (CEK).
///
/// Another algorithm is employed to determine and/or encrypt the CEK.
/// The list of supported algorithms  can be found
/// [here](https://lawliet89.github.io/biscuit/biscuit/jwa/enum.KeyManagementAlgorithm.html).
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RefreshTokenConfiguration {
    /// Algorithm used to determine and/or encrypt the CEK
    pub cek_algorithm: jwa::KeyManagementAlgorithm,

    /// Algorithm used to encrypt the content using the CEK
    pub enc_algorithm: jwa::ContentEncryptionAlgorithm,

    /// Key used in determining the CEK, or
    /// directly encrypt the content depending on the `cek_algorithm`
    pub key: Secret,

    /// Expiry duration of refresh tokens, in seconds.
    ///
    /// Defaults to 24 hours when deserialized and left unfilled
    #[serde(
        with = "crate::serde_custom::duration",
        default = "Configuration::default_expiry_duration"
    )]
    pub expiry_duration: Duration,
}

/// Private claims that will be included in the JWT.
pub type PrivateClaim = JsonValue;

/// Convenient typedef for the type of the Refresh Token Payload.
/// This is a signed JWS which contains a JWT Claims set.
pub type RefreshTokenPayload = jwt::JWT<JsonValue, jwt::Empty>;

/// Convenient typedef for the type of the encrypted JWE wrapping `RefreshTokenPayload`.
/// This is a JWE which contains a JWS that contains a JWT Claims set.
pub type RefreshTokenJWE = jwt::jwe::Compact<RefreshTokenPayload, jwt::Empty>;

/// A Refresh Token containing the payload (called refresh payload) used by an
/// authenticator to issue new access tokens without needing the user to re-authenticate.
///
/// Internally, this is a newtype struct wrapping an encrypted JWE containing the
/// `RefreshTokenPayload`. In other words, this is an encrypted token (JWE) containing a payload.
/// The payload is a signed token (JWS) which contains a set of values (JWT Claims Set).
///
/// Usually, the semantics and inner workings of the refresh token is, and should be, opaque to any
/// user. Thus, some of the methods to manipulate the inner details of the refresh tokens are not
/// public.
///
/// This struct is serialized and deserialized to a string, which is the
/// [Compact serialization of a JWE](https://tools.ietf.org/html/rfc7516#section-3.1).
///
/// Before you can serialize the struct, you will need to call `encrypt` to first sign the embedded
/// JWS, and then encrypt it. If you do not do so, `serde` will refuse to serialize.
///
/// Conversely, only an encrypted token can be deserialized. `serde` will refuse to deserialize a
/// decrypted token similarly. You will need to call `decrypt` to decrypt the deserialized token.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct RefreshToken(RefreshTokenJWE);

impl RefreshToken {
    #[cfg_attr(feature = "clippy_lints", allow(too_many_arguments))] // Internal function
    fn new_decrypted(
        subject: &str,
        issuer: &jwt::StringOrUri,
        audience: &jwt::SingleOrMultiple<jwt::StringOrUri>,
        expiry_duration: Duration,
        payload: &JsonValue,
        signature_algorithm: Option<jwa::SignatureAlgorithm>,
        cek_algorithm: jwa::KeyManagementAlgorithm,
        enc_algorithm: jwa::ContentEncryptionAlgorithm,
        now: DateTime<Utc>,
    ) -> Result<Self, crate::Error> {
        // First, make a token
        let token = make_token(
            subject,
            issuer,
            audience,
            expiry_duration,
            payload.clone(),
            signature_algorithm,
            now,
        )?;
        // Wrap it in a JWE
        let jwe = jwt::JWE::new_decrypted(
            From::from(jwt::jwe::RegisteredHeader {
                cek_algorithm: cek_algorithm,
                enc_algorithm: enc_algorithm,
                media_type: Some("JOSE".to_string()),
                content_type: Some("JOSE".to_string()),
                ..Default::default()
            }),
            token,
        );
        Ok(RefreshToken(jwe))
    }

    /// Create a new decrypted struct based on the Base64 encoded token string
    pub fn new_encrypted(token: &str) -> Self {
        RefreshToken(jwt::JWE::new_encrypted(token))
    }

    /// Unwrap and consumes self, producing the wrapped JWE. You generally should not,
    ///  and do not need to call this.
    pub fn unwrap(self) -> RefreshTokenJWE {
        self.0
    }

    /// Returns whether the refresh token is already encrypted and signed
    pub fn encrypted(&self) -> bool {
        match *self.borrow() {
            jwt::jwe::Compact::Decrypted { .. } => false,
            jwt::jwe::Compact::Encrypted(_) => true,
        }
    }

    /// Returns whether the refresh token is already decrypted and verified
    pub fn decrypted(&self) -> bool {
        !self.encrypted()
    }

    // TODO: Random Nonce! Should we keep a counter?
    fn encryption_option(&self) -> Result<jwa::EncryptionOptions, Error> {
        let headers = &self.0.header()?.registered;

        let need_nonce = if let jwa::KeyManagementAlgorithm::A128GCMKW
        | jwa::KeyManagementAlgorithm::A192GCMKW
        | jwa::KeyManagementAlgorithm::A256GCMKW = headers.cek_algorithm
        {
            true
        } else if let jwa::ContentEncryptionAlgorithm::A128GCM
        | jwa::ContentEncryptionAlgorithm::A192GCM
        | jwa::ContentEncryptionAlgorithm::A256GCM = headers.enc_algorithm
        {
            true
        } else {
            false
        };
        if need_nonce {
            let nonce = crate::auth::util::generate_salt(96 / 8)
                .map_err(|_| Error::GenericError("An unknown error".to_string()))?;
            Ok(jwa::EncryptionOptions::AES_GCM { nonce: nonce })
        } else {
            Ok(jwa::EncryptionOptions::None)
        }
    }

    /// Consumes self, and sign and encrypt the refresh token.
    /// If the Refresh Token is already encrypted, this will return an error
    pub fn encrypt(self, secret: &jws::Secret, key: &jwk::JWK<jwt::Empty>) -> Result<Self, Error> {
        if self.encrypted() {
            Err(Error::RefreshTokenAlreadyEncrypted)?
        }
        let options = self.encryption_option()?;
        let (header, jws) = self.unwrap().unwrap_decrypted();
        let jws = jws.into_encoded(secret)?;

        let jwe = jwt::JWE::new_decrypted(header, jws);
        let jwe = jwe.into_encrypted(key, &options)?;

        Ok(From::from(jwe))
    }

    /// Consumes self, and decrypt and verify the signature of the refresh token
    /// If the refresh token is already decrypted, this will return an error
    pub fn decrypt(
        self,
        secret: &jws::Secret,
        key: &jwk::JWK<jwt::Empty>,
        signing_algorithm: jwa::SignatureAlgorithm,
        cek_algorithm: jwa::KeyManagementAlgorithm,
        enc_algorithm: jwa::ContentEncryptionAlgorithm,
    ) -> Result<Self, Error> {
        if self.decrypted() {
            Err(Error::RefreshTokenAlreadyDecrypted)?
        }

        let jwe = self.unwrap();
        let jwe = jwe.into_decrypted(key, cek_algorithm, enc_algorithm)?;

        let (header, jws) = jwe.unwrap_decrypted();
        let jws = jws.into_decoded(secret, signing_algorithm)?;

        let jwe = jwt::JWE::new_decrypted(header, jws);

        Ok(From::from(jwe))
    }

    /// Retrieve a reference to the decrypted claims set
    fn claims_set(&self) -> Result<&jwt::ClaimsSet<JsonValue>, Error> {
        if !self.decrypted() {
            Err(Error::RefreshTokenNotDecrypted)?;
        }

        Ok(self.0.payload()?.payload()?)
    }

    /// Retrieve a reference to the decrypted payload
    pub fn payload(&self) -> Result<&JsonValue, Error> {
        Ok(&self.claims_set()?.private)
    }

    /// Validate the times and claims of the refresh token
    pub fn validate(
        &self,
        service: &str,
        config: &Configuration,
        options: Option<jwt::ValidationOptions>,
    ) -> Result<(), Error> {
        use std::str::FromStr;

        let options = options.unwrap_or_else(|| jwt::ValidationOptions {
            claim_presence_options: jwt::ClaimPresenceOptions {
                issued_at: jwt::Presence::Required,
                not_before: jwt::Presence::Required,
                expiry: jwt::Presence::Required,
                ..Default::default()
            },
            ..Default::default()
        });

        let claims_set = self.claims_set()?;
        let issuer = claims_set
            .registered
            .issuer
            .as_ref()
            .ok_or_else(|| Error::InvalidIssuer)?;
        let audience = claims_set
            .registered
            .audience
            .as_ref()
            .ok_or_else(|| Error::InvalidAudience)?;

        verify_service(config, service)
            .and_then(|_| {
                if audience.contains(&FromStr::from_str(service)?) {
                    Ok(())
                } else {
                    Err(Error::InvalidAudience)
                }
            })
            .and_then(|_| verify_audience(config, audience))
            .and_then(|_| verify_issuer(config, issuer))
            .and_then(|_| {
                claims_set
                    .registered
                    .validate(options)
                    .map_err(|e| Error::JWTError(Box::new(jwt::errors::Error::ValidationError(e))))
            })
    }

    /// Convenience function to convert a decrypted payload to string
    pub fn to_string(&self) -> Result<String, Error> {
        Ok(self
            .0
            .encrypted()
            .map_err(|_| Error::RefreshTokenNotEncrypted)?
            .to_string())
    }
}

impl Borrow<RefreshTokenJWE> for RefreshToken {
    fn borrow(&self) -> &RefreshTokenJWE {
        &self.0
    }
}

impl From<RefreshTokenJWE> for RefreshToken {
    fn from(value: RefreshTokenJWE) -> Self {
        RefreshToken(value)
    }
}

/// A token that will be serialized into JSON and passed to clients.
/// This encapsulates a JSON Web Token or `JWT`. Clients will pass the encapsulated JWT to services
/// that require it. The JWT should be considered opaque to clients. The `Token` struct contains
/// enough information for the client to act on, including expiry times.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Token<T> {
    /// Tne encapsulated JWT.
    pub token: jwt::JWT<T, jwt::Empty>,
    /// The duration from `issued_at` where the token will expire
    #[serde(with = "crate::serde_custom::duration")]
    pub expires_in: Duration,
    /// Time the token was issued at
    pub issued_at: DateTime<Utc>,
    /// Refresh token, if enabled and requested for
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<RefreshToken>,
}

impl<T> Clone for Token<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    fn clone(&self) -> Self {
        Token {
            token: self.token.clone(),
            expires_in: self.expires_in,
            issued_at: self.issued_at,
            refresh_token: self.refresh_token.clone(),
        }
    }
}

impl<T: Serialize + DeserializeOwned + 'static> Token<T> {
    /// Internal token creation that allows for us to override the time `now`. For testing
    fn with_configuration_and_time(
        config: &Configuration,
        subject: &str,
        service: &str,
        private_claims: T,
        refresh_token_payload: Option<&JsonValue>,
        now: DateTime<Utc>,
    ) -> Result<Self, crate::Error> {
        verify_service(config, service)?;

        let access_token = make_token(
            subject,
            &config.issuer,
            &config.audience,
            config.expiry_duration,
            private_claims,
            config.signature_algorithm,
            now,
        )?;
        let refresh_token = match config.refresh_token {
            None => None,
            Some(ref refresh_token_config) => match refresh_token_payload {
                Some(payload) => Some(RefreshToken::new_decrypted(
                    subject,
                    &config.issuer,
                    &config.audience,
                    refresh_token_config.expiry_duration,
                    payload,
                    config.signature_algorithm,
                    refresh_token_config.cek_algorithm,
                    refresh_token_config.enc_algorithm,
                    now,
                )?),
                None => None,
            },
        };

        // Safe to unwrap
        let issued_at = access_token
            .payload()
            .unwrap()
            .registered
            .issued_at
            .unwrap();

        let token = Token::<T> {
            token: access_token,
            expires_in: config.expiry_duration,
            issued_at: *issued_at.deref(),
            refresh_token: refresh_token,
        };
        Ok(token)
    }

    /// Based on the configuration, make a token for the subject, along with some private claims.
    pub fn with_configuration(
        config: &Configuration,
        subject: &str,
        service: &str,
        private_claims: T,
        refresh_token_payload: Option<&JsonValue>,
    ) -> Result<Self, crate::Error> {
        Self::with_configuration_and_time(
            config,
            subject,
            service,
            private_claims,
            refresh_token_payload,
            Utc::now(),
        )
    }

    /// Consumes self and encode the embedded JWT with signature.
    /// If the JWT is already encoded, this returns an error
    pub fn encode(mut self, secret: &jws::Secret) -> Result<Self, Error> {
        match self.token {
            jwt::jws::Compact::Encoded(_) => Err(Error::TokenAlreadyEncoded),
            jwt @ jwt::jws::Compact::Decoded { .. } => {
                self.token = jwt.into_encoded(secret)?;
                Ok(self)
            }
        }
    }

    /// Consumes self and decode the embedded JWT with signature verification
    /// If the JWT is already decoded, this returns an error
    pub fn decode(
        mut self,
        secret: &jws::Secret,
        algorithm: jwa::SignatureAlgorithm,
    ) -> Result<Self, Error> {
        match self.token {
            jwt @ jwt::jws::Compact::Encoded(_) => {
                self.token = jwt.into_decoded(secret, algorithm)?;
                Ok(self)
            }
            jwt::jws::Compact::Decoded { .. } => Err(Error::TokenAlreadyDecoded),
        }
    }

    fn serialize(self) -> Result<String, Error> {
        if self.is_decoded() {
            Err(Error::TokenNotEncoded)?
        }
        let serialized = serde_json::to_string(&self)?;
        Ok(serialized)
    }

    fn respond<'r>(self) -> Result<Response<'r>, Error> {
        let serialized = self.serialize()?;
        Response::build()
            .header(ContentType::JSON)
            .sized_body(Cursor::new(serialized))
            .ok()
    }

    /// Returns whether the wrapped token is decoded and verified
    pub fn is_decoded(&self) -> bool {
        match self.token {
            jwt::jws::Compact::Encoded(_) => false,
            jwt::jws::Compact::Decoded { .. } => true,
        }
    }

    /// Returns whether the wrapped token is encoded and signed
    pub fn is_encoded(&self) -> bool {
        !self.is_decoded()
    }

    /// Convenience function to extract the registered claims from a decoded token
    pub fn registered_claims(&self) -> Result<&jwt::RegisteredClaims, crate::Error> {
        match self.token {
            jwt::jws::Compact::Encoded(_) => Err(Error::TokenNotDecoded)?,
            ref jwt @ jwt::jws::Compact::Decoded { .. } => Ok(match_extract!(*jwt,
                                 jwt::jws::Compact::Decoded {
                                     payload: jwt::ClaimsSet { ref registered, .. },
                                     ..
                                 },
                                 registered)?),
        }
    }

    /// Conveneince function to extract the private claims from a decoded token
    pub fn private_claims(&self) -> Result<&T, crate::Error> {
        match self.token {
            jwt::jws::Compact::Encoded(_) => Err(Error::TokenNotDecoded)?,
            ref jwt @ jwt::jws::Compact::Decoded { .. } => Ok(match_extract!(*jwt,
                                 jwt::jws::Compact::Decoded {
                                     payload: jwt::ClaimsSet { ref private, .. },
                                     ..
                                 },
                                 private)?),
        }
    }

    /// Convenience function to extract the headers from a decoded token
    pub fn header(&self) -> Result<&jwt::jws::Header<jwt::Empty>, crate::Error> {
        match self.token {
            jwt::jws::Compact::Encoded(_) => Err(Error::TokenNotDecoded)?,
            ref jwt @ jwt::jws::Compact::Decoded { .. } => Ok(match_extract!(*jwt,
                                 jwt::jws::Compact::Decoded {
                                     ref header,
                                     ..
                                 },
                                 header)?),
        }
    }

    /// Convenience method to extract the encoded token
    pub fn encoded_token(&self) -> Result<String, crate::Error> {
        Ok(self
            .token
            .encoded()
            .map_err(|e| Error::JWTError(Box::new(e)))?
            .to_string())
    }

    /// Convenience method to obtain a reference to the refresh token
    pub fn refresh_token(&self) -> Option<&RefreshToken> {
        self.refresh_token.as_ref()
    }

    /// Consumes self, and encrypt and sign the embedded refresh token
    pub fn encrypt_refresh_token(
        mut self,
        secret: &jws::Secret,
        key: &jwk::JWK<jwt::Empty>,
    ) -> Result<Self, Error> {
        let refresh_token = self.refresh_token.ok_or_else(|| Error::NoRefreshToken)?;
        let refresh_token = refresh_token.encrypt(secret, key)?;
        self.refresh_token = Some(refresh_token);
        Ok(self)
    }

    /// Consumes self, and decrypt and verify the signature of the embedded refresh token
    pub fn decrypt_refresh_token(
        mut self,
        secret: &jws::Secret,
        key: &jwk::JWK<jwt::Empty>,
        signing_algorithm: jwa::SignatureAlgorithm,
        cek_algorithm: jwa::KeyManagementAlgorithm,
        enc_algorithm: jwa::ContentEncryptionAlgorithm,
    ) -> Result<Self, Error> {
        let refresh_token = self.refresh_token.ok_or_else(|| Error::NoRefreshToken)?;
        let refresh_token =
            refresh_token.decrypt(secret, key, signing_algorithm, cek_algorithm, enc_algorithm)?;
        self.refresh_token = Some(refresh_token);
        Ok(self)
    }

    /// Returns whether there is a refresh token
    pub fn has_refresh_token(&self) -> bool {
        self.refresh_token.is_some()
    }
}

impl<'r, T: Serialize + DeserializeOwned + 'static> Responder<'r> for Token<T> {
    fn respond_to(self, request: &Request<'_>) -> Result<Response<'r>, Status> {
        match self.respond() {
            Ok(r) => Ok(r),
            Err(e) => Err::<String, Error>(e).respond_to(request),
        }
    }
}

/// Secrets for use in signing and encrypting a JWT.
/// This enum (de)serialized as an [untagged](https://serde.rs/enum-representations.html) enum
/// variant.
///
/// Defaults to `None`.
///
/// # Serialization Examples
/// ## No secret
/// ```json
/// {
///     "secret": null
/// }
/// ```
/// ```
/// extern crate rowdy;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate serde_json;
///
/// use rowdy::token;
///
/// # fn main() {
/// #[derive(Serialize, Deserialize)]
/// struct Test {
///     secret: token::Secret
/// }
///
/// let json = r#"{ "secret": null }"#;
/// let deserialized: Test = serde_json::from_str(json).unwrap();
/// # }
/// ```
/// ## HMAC secret string
/// ```json
/// {
///     "secret": "some_secret_string"
/// }
/// ```
/// ```
/// extern crate rowdy;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate serde_json;
///
/// use rowdy::token;
///
/// # fn main() {
/// #[derive(Serialize, Deserialize)]
/// struct Test {
///     secret: token::Secret
/// }
///
/// let json = r#"{ "secret": "some_secret_string" }"#;
/// let deserialized: Test = serde_json::from_str(json).unwrap();
/// # }
/// ```
/// ## RSA Key pair
/// ```json
/// {
///     "secret": { "rsa_private": "private.der", "rsa_public": "public.der" }
/// }
/// ```
/// ```
/// extern crate rowdy;
/// #[macro_use]
/// extern crate serde_derive;
/// extern crate serde_json;
///
/// use rowdy::token;
///
/// # fn main() {
/// #[derive(Serialize, Deserialize)]
/// struct Test {
///     secret: token::Secret
/// }
///
/// let json = r#"{ "secret": { "rsa_private": "private.der", "rsa_public": "public.der" } }"#;
/// let deserialized: Test = serde_json::from_str(json).unwrap();
/// # }
/// ```
// Note: A "smoke test"-ish of (de)serialization is tested in the documentation code above.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Secret {
    /// No secret -- used when no signature or encryption is required.
    None,
    /// Secret for HMAC signing
    ByteSequence(ByteSequence),
    /// Path to a file containing the byte sequence for HMAC signing or encryption key
    Bytes {
        /// Path to the file containing the byte sequence for a HMAC signing or encryption key
        path: String,
    },
    /// DER RSA Key pair.
    /// See [`jwt::jws::Secret`] for more details.
    RSAKeyPair {
        /// Path to DER encoded private key
        rsa_private: String,
        /// Path to DER encoded public key
        rsa_public: String,
    },
}

impl Default for Secret {
    fn default() -> Self {
        Secret::None
    }
}

impl Secret {
    /// Create a [`jws::Secret`] for the purpose of signing
    pub(super) fn for_signing(&self) -> Result<jws::Secret, Error> {
        match *self {
            Secret::None => Ok(jws::Secret::None),
            Secret::ByteSequence(ref bytes) => Ok(jws::Secret::Bytes(bytes.as_bytes())),
            Secret::Bytes { ref path } => Ok(jws::Secret::Bytes(Self::read_file_to_bytes(path)?)),
            Secret::RSAKeyPair {
                ref rsa_private, ..
            } => Ok(jws::Secret::rsa_keypair_from_file(rsa_private)?),
        }
    }

    /// Create a [`jws::Secret`] for the purpose of verifying signatures
    pub(super) fn for_verification(&self) -> Result<jws::Secret, Error> {
        match *self {
            Secret::None => Ok(jws::Secret::None),
            Secret::ByteSequence(ref bytes) => Ok(jws::Secret::Bytes(bytes.as_bytes())),
            Secret::Bytes { ref path } => Ok(jws::Secret::Bytes(Self::read_file_to_bytes(path)?)),
            Secret::RSAKeyPair { ref rsa_public, .. } => {
                Ok(jws::Secret::public_key_from_file(rsa_public)?)
            }
        }
    }

    /// Create a JWK for the purpose of encryption
    pub(super) fn for_encryption(&self) -> Result<jwk::JWK<jwt::Empty>, Error> {
        match *self {
            Secret::None => Err(Error::GenericError(
                "A key is required for encryption".to_string(),
            )),
            Secret::ByteSequence(ref bytes) => Ok(jwk::JWK::new_octect_key(
                &bytes.as_bytes(),
                Default::default(),
            )),
            Secret::Bytes { ref path } => Ok(jwk::JWK::new_octect_key(
                &Self::read_file_to_bytes(path)?,
                Default::default(),
            )),
            Secret::RSAKeyPair { .. } => Err(Error::GenericError("Not supported yet".to_string())),
        }
    }

    /// Create a JWK for the purpose of decryption
    pub(super) fn for_decryption(&self) -> Result<jwk::JWK<jwt::Empty>, Error> {
        // For now
        self.for_encryption()
    }

    fn read_file_to_bytes(path: &str) -> Result<Vec<u8>, Error> {
        let mut file = File::open(path)?;
        let mut bytes = Vec::<u8>::new();
        let _ = file.read_to_end(&mut bytes)?;
        Ok(bytes)
    }
}

/// Keys prepared in a form directly usable for cryptographic operations.
/// This prevents us from having to repeatedly read keys from the file system.
///  Users should prepare the keys from `Configuration` using
/// `Configuration::keys()` and then use this struct to retrieve keys from instead of the
/// functions from `Secret`.
pub struct Keys {
    /// Key used to signed tokens
    pub signing: jws::Secret,
    /// Key used to verify token signatures
    pub signature_verification: jws::Secret,
    /// Key used to encrypt tokens. Used if Refresh tokens are enabled.
    pub encryption: Option<jwk::JWK<jwt::Empty>>,
    /// Key used to decrypt tokens. Used if Refresh tokens are enabled.
    pub decryption: Option<jwk::JWK<jwt::Empty>>,
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;
    use std::time::Duration;

    use chrono::{DateTime, NaiveDateTime, Utc};
    use serde_json;

    use super::*;
    use crate::jwt;
    use crate::{JsonMap, JsonValue};

    #[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
    struct TestClaims {
        company: String,
        department: String,
    }

    impl Default for TestClaims {
        fn default() -> Self {
            TestClaims {
                company: "ACME".to_string(),
                department: "Toilet Cleaning".to_string(),
            }
        }
    }

    fn make_config(refresh_token: bool) -> Configuration {
        let refresh_token = if refresh_token {
            Some(RefreshTokenConfiguration {
                cek_algorithm: jwt::jwa::KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: jwt::jwa::ContentEncryptionAlgorithm::A256GCM,
                key: Secret::ByteSequence(ByteSequence::Bytes(vec![0; 256 / 8])),
                expiry_duration: Duration::from_secs(86400),
            })
        } else {
            None
        };

        let allowed_origins = ["https://www.example.com"];
        let (allowed_origins, _) = crate::cors::AllowedOrigins::some(&allowed_origins);

        Configuration {
            issuer: FromStr::from_str("https://www.acme.com").unwrap(),
            allowed_origins: allowed_origins,
            audience: jwt::SingleOrMultiple::Single(
                FromStr::from_str("https://www.example.com/").unwrap(),
            ),
            signature_algorithm: Some(jwt::jwa::SignatureAlgorithm::HS512),
            secret: Secret::ByteSequence(ByteSequence::String("secret".to_string())),
            expiry_duration: Duration::from_secs(120),
            refresh_token: refresh_token,
        }
    }

    fn refresh_token_payload() -> JsonValue {
        let mut map = JsonMap::with_capacity(1);
        let _ = map.insert("test".to_string(), From::from("foobar"));
        JsonValue::Object(map)
    }

    fn make_refresh_token() -> RefreshToken {
        RefreshToken::new_decrypted(
            "foobar",
            &FromStr::from_str("https://www.acme.com").unwrap(),
            &jwt::SingleOrMultiple::Single(FromStr::from_str("https://www.example.com").unwrap()),
            Duration::from_secs(120),
            &refresh_token_payload(),
            Some(Default::default()),
            jwt::jwa::KeyManagementAlgorithm::A256GCMKW,
            jwt::jwa::ContentEncryptionAlgorithm::A256GCM,
            Utc::now(),
        )
        .unwrap()
    }

    fn make_token(refresh_token: bool) -> Token<TestClaims> {
        let refresh_token = if refresh_token {
            Some(make_refresh_token())
        } else {
            None
        };

        Token {
            token: jwt::JWT::new_decoded(
                jwt::jws::Header::default(),
                jwt::ClaimsSet {
                    private: Default::default(),
                    registered: Default::default(),
                },
            ),
            expires_in: Duration::from_secs(120),
            issued_at: Utc::now(),
            refresh_token: refresh_token,
        }
    }

    #[test]
    fn refresh_token_encryption_round_trip() {
        let key = jwt::jwk::JWK::new_octect_key(&[0; 256 / 8], Default::default());
        let signing_secret = jwt::jws::Secret::bytes_from_str("secret");

        let refresh_token = make_refresh_token();
        assert!(refresh_token.decrypted());

        let encrypted_refresh_token =
            not_err!(refresh_token.clone().encrypt(&signing_secret, &key));
        assert!(encrypted_refresh_token.encrypted());

        let decrypted_refresh_token = not_err!(encrypted_refresh_token.decrypt(
            &signing_secret,
            &key,
            Default::default(),
            jwt::jwa::KeyManagementAlgorithm::A256GCMKW,
            jwt::jwa::ContentEncryptionAlgorithm::A256GCM
        ));
        assert!(decrypted_refresh_token.decrypted());

        let actual_refresh_token_payload: &JsonValue = decrypted_refresh_token.payload().unwrap();
        let map = actual_refresh_token_payload.as_object().unwrap();
        assert_eq!(map.get("test").unwrap().as_str().unwrap(), "foobar");
    }

    #[test]
    fn serializing_and_deserializing_round_trip() {
        let key = jwt::jwk::JWK::new_octect_key(&[0; 256 / 8], Default::default());
        let signing_secret = jwt::jws::Secret::bytes_from_str("secret");
        let token = make_token(true);

        let token = not_err!(token.encode(&signing_secret));
        assert!(token.is_encoded());
        let token = not_err!(token.encrypt_refresh_token(&signing_secret, &key));
        assert!(token.refresh_token().unwrap().encrypted());

        let serialized = not_err!(serde_json::to_string_pretty(&token));
        let deserialized: Token<TestClaims> = not_err!(serde_json::from_str(&serialized));
        assert_eq!(deserialized, token);

        let token = not_err!(token.decode(&signing_secret, Default::default()));
        let token = not_err!(token.decrypt_refresh_token(
            &signing_secret,
            &key,
            Default::default(),
            jwt::jwa::KeyManagementAlgorithm::A256GCMKW,
            jwt::jwa::ContentEncryptionAlgorithm::A256GCM
        ));

        let private = not_err!(token.private_claims());
        assert_eq!(*private, Default::default());

        let refresh_token = token.refresh_token().unwrap();
        let actual_refresh_token_payload: &JsonValue = refresh_token.payload().unwrap();
        let map = actual_refresh_token_payload.as_object().unwrap();
        assert_eq!(map.get("test").unwrap().as_str().unwrap(), "foobar");
    }

    #[test]
    #[should_panic(expected = "TokenAlreadyEncoded")]
    fn panics_when_encoding_encoded() {
        let token = make_token(false);
        let token = not_err!(token.encode(&jwt::jws::Secret::bytes_from_str("secret")));
        let _ = token
            .encode(&jwt::jws::Secret::bytes_from_str("secret"))
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "TokenAlreadyDecoded")]
    fn panics_when_decoding_decoded() {
        let token = make_token(false);
        let _ = token
            .decode(
                &jwt::jws::Secret::bytes_from_str("secret"),
                Default::default(),
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "RefreshTokenAlreadyEncrypted")]
    fn panics_when_encrypting_encrypted() {
        let key = jwt::jwk::JWK::new_octect_key(&[0; 256 / 8], Default::default());
        let signing_secret = jwt::jws::Secret::bytes_from_str("secret");

        let token = make_token(true);
        let token = not_err!(token.encrypt_refresh_token(&signing_secret, &key));
        let _ = token.encrypt_refresh_token(&signing_secret, &key).unwrap();
    }

    #[test]
    #[should_panic(expected = "RefreshTokenAlreadyDecrypted")]
    fn panics_when_decrypting_decrypted() {
        let key = jwt::jwk::JWK::new_octect_key(&[0; 256 / 8], Default::default());
        let signing_secret = jwt::jws::Secret::bytes_from_str("secret");

        let token = make_token(true);
        let _ = token
            .decrypt_refresh_token(
                &signing_secret,
                &key,
                Default::default(),
                jwt::jwa::KeyManagementAlgorithm::A256GCMKW,
                jwt::jwa::ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    #[test]
    fn token_serialization_smoke_test() {
        let expected_token = make_token(false);
        let token = not_err!(expected_token
            .clone()
            .encode(&jwt::jws::Secret::bytes_from_str("secret")));
        let serialized = not_err!(token.serialize());

        let deserialized: Token<TestClaims> = not_err!(serde_json::from_str(&serialized));
        let actual_token = not_err!(deserialized.decode(
            &jwt::jws::Secret::bytes_from_str("secret"),
            Default::default()
        ));
        assert_eq!(expected_token, actual_token);
    }

    #[test]
    fn token_response_smoke_test() {
        let expected_token = make_token(false);
        let token = not_err!(expected_token
            .clone()
            .encode(&jwt::jws::Secret::bytes_from_str("secret")));
        let mut response = not_err!(token.respond());

        assert_eq!(response.status(), Status::Ok);
        let body_str = not_none!(response.body().and_then(|body| body.into_string()));
        let deserialized: Token<TestClaims> = not_err!(serde_json::from_str(&body_str));
        let actual_token = not_err!(deserialized.decode(
            &jwt::jws::Secret::bytes_from_str("secret"),
            Default::default()
        ));
        assert_eq!(expected_token, actual_token);
    }

    #[test]
    fn secrets_are_transformed_for_signing_correctly() {
        let none = Secret::None;
        assert_matches_non_debug!(not_err!(none.for_signing()), jwt::jws::Secret::None);

        let string = Secret::ByteSequence(ByteSequence::String("secret".to_string()));
        assert_matches_non_debug!(not_err!(string.for_signing()), jwt::jws::Secret::Bytes(_));

        let rsa = Secret::RSAKeyPair {
            rsa_private: "test/fixtures/rsa_private_key.der".to_string(),
            rsa_public: "test/fixtures/rsa_public_key.der".to_string(),
        };
        assert_matches_non_debug!(not_err!(rsa.for_signing()), jwt::jws::Secret::RSAKeyPair(_));
    }

    #[test]
    fn secrets_are_transformed_for_verification_correctly() {
        let none = Secret::None;
        assert_matches_non_debug!(not_err!(none.for_verification()), jwt::jws::Secret::None);

        let string = Secret::ByteSequence(ByteSequence::String("secret".to_string()));
        assert_matches_non_debug!(
            not_err!(string.for_verification()),
            jwt::jws::Secret::Bytes(_)
        );

        let rsa = Secret::RSAKeyPair {
            rsa_private: "test/fixtures/rsa_private_key.der".to_string(),
            rsa_public: "test/fixtures/rsa_public_key.der".to_string(),
        };
        assert_matches_non_debug!(
            not_err!(rsa.for_verification()),
            jwt::jws::Secret::PublicKey(_)
        );
    }

    #[test]
    fn token_created_with_refresh_token_disabled() {
        let configuration = make_config(false);

        let mut map = JsonMap::with_capacity(1);
        let _ = map.insert("test".to_string(), From::from("foobar"));
        let refresh_token_payload = JsonValue::Object(map);

        let now = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(0, 0), Utc);
        let expected_expiry = now + chrono::Duration::from_std(Duration::from_secs(120)).unwrap();
        let token = not_err!(Token::<TestClaims>::with_configuration_and_time(
            &configuration,
            "Donald Trump",
            "https://www.example.com/",
            Default::default(),
            Some(&refresh_token_payload),
            now
        ));

        // Assert registered claims
        let registered = not_err!(token.registered_claims());

        assert_eq!(
            registered.issuer,
            Some(FromStr::from_str("https://www.acme.com").unwrap())
        );
        assert_eq!(
            registered.subject,
            Some(FromStr::from_str("Donald Trump").unwrap())
        );
        assert_eq!(
            registered.audience,
            Some(jwt::SingleOrMultiple::Single(
                FromStr::from_str("https://www.example.com").unwrap()
            ))
        );
        assert_eq!(registered.issued_at, Some(now.into()));
        assert_eq!(registered.not_before, Some(now.into()));
        assert_eq!(registered.expiry, Some(expected_expiry.into()));

        // Assert private claims
        let private = not_err!(token.private_claims());
        assert_eq!(*private, Default::default());

        // Assert header
        let header = not_err!(token.header());
        assert_eq!(
            header.registered.algorithm,
            jwt::jwa::SignatureAlgorithm::HS512
        );

        // Assert refresh token
        assert!(token.refresh_token().is_none());
    }

    #[test]
    fn token_created_with_no_refresh_token_payload() {
        let configuration = make_config(true);

        let now = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(0, 0), Utc);
        let expected_expiry = now + chrono::Duration::from_std(Duration::from_secs(120)).unwrap();
        let token = not_err!(Token::<TestClaims>::with_configuration_and_time(
            &configuration,
            "Donald Trump",
            "https://www.example.com/",
            Default::default(),
            None,
            now
        ));

        // Assert registered claims
        let registered = not_err!(token.registered_claims());

        assert_eq!(
            registered.issuer,
            Some(FromStr::from_str("https://www.acme.com").unwrap())
        );
        assert_eq!(
            registered.subject,
            Some(FromStr::from_str("Donald Trump").unwrap())
        );
        assert_eq!(
            registered.audience,
            Some(jwt::SingleOrMultiple::Single(
                FromStr::from_str("https://www.example.com").unwrap()
            ))
        );
        assert_eq!(registered.issued_at, Some(now.into()));
        assert_eq!(registered.not_before, Some(now.into()));
        assert_eq!(registered.expiry, Some(expected_expiry.into()));

        // Assert private claims
        let private = not_err!(token.private_claims());
        assert_eq!(*private, Default::default());

        // Assert header
        let header = not_err!(token.header());
        assert_eq!(
            header.registered.algorithm,
            jwt::jwa::SignatureAlgorithm::HS512
        );

        // Assert refresh token
        assert!(token.refresh_token().is_none());
    }

    #[test]
    fn token_created_with_refresh_token() {
        let configuration = make_config(true);

        let mut map = JsonMap::with_capacity(1);
        let _ = map.insert("test".to_string(), From::from("foobar"));
        let refresh_token_payload = JsonValue::Object(map);

        let now = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(0, 0), Utc);
        let expected_expiry = now + chrono::Duration::from_std(Duration::from_secs(120)).unwrap();
        let token = not_err!(Token::<TestClaims>::with_configuration_and_time(
            &configuration,
            "Donald Trump",
            "https://www.example.com/",
            Default::default(),
            Some(&refresh_token_payload),
            now
        ));

        // Assert registered claims
        let registered = not_err!(token.registered_claims());

        assert_eq!(
            registered.issuer,
            Some(FromStr::from_str("https://www.acme.com").unwrap())
        );
        assert_eq!(
            registered.subject,
            Some(FromStr::from_str("Donald Trump").unwrap())
        );
        assert_eq!(
            registered.audience,
            Some(jwt::SingleOrMultiple::Single(
                FromStr::from_str("https://www.example.com").unwrap()
            ))
        );
        assert_eq!(registered.issued_at, Some(now.into()));
        assert_eq!(registered.not_before, Some(now.into()));
        assert_eq!(registered.expiry, Some(expected_expiry.into()));

        // Assert private claims
        let private = not_err!(token.private_claims());
        assert_eq!(*private, Default::default());

        // Assert header
        let header = not_err!(token.header());
        assert_eq!(
            header.registered.algorithm,
            jwt::jwa::SignatureAlgorithm::HS512
        );

        // Assert refresh token
        let refresh_token = token.refresh_token().unwrap();
        let actual_refresh_token_payload: &JsonValue = refresh_token.payload().unwrap();
        assert_eq!(*actual_refresh_token_payload, refresh_token_payload);
    }

    #[test]
    #[should_panic(expected = "InvalidService")]
    fn validates_service_correctly() {
        let configuration = make_config(true);

        let now = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(0, 0), Utc);
        let _ = Token::<TestClaims>::with_configuration_and_time(
            &configuration,
            "Donald Trump",
            "invalid",
            Default::default(),
            None,
            now,
        )
        .unwrap();
    }

    #[test]
    fn refresh_token_validates_correctly() {
        let configuration = make_config(true);
        let refresh_token = make_refresh_token();
        not_err!(refresh_token.validate("https://www.example.com/", &configuration, None));
    }

    /// Token does not have an issuer field
    #[test]
    #[should_panic(expected = "InvalidIssuer")]
    fn refresh_token_validates_missing_issuer() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.issuer = None;
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// Token does not have an audience field
    #[test]
    #[should_panic(expected = "InvalidAudience")]
    fn refresh_token_validates_missing_audience() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.audience = None;
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// An invalid service was requested for
    #[test]
    #[should_panic(expected = "InvalidService")]
    fn refresh_token_validates_invalid_service() {
        let configuration = make_config(true);
        let refresh_token = make_refresh_token();
        refresh_token
            .validate("https://www.invalid.com/", &configuration, None)
            .unwrap();
    }

    /// Configuration has the right audience request configured,
    /// but the token does not indicate that it is for the audience requested
    #[test]
    #[should_panic(expected = "InvalidAudience")]
    fn refresh_token_validates_mismatch_service_and_audience() {
        let mut configuration = make_config(true);
        configuration.audience =
            jwt::SingleOrMultiple::Single(FromStr::from_str("https://www.invalid.com/").unwrap());
        let refresh_token = make_refresh_token();
        refresh_token
            .validate("https://www.invalid.com/", &configuration, None)
            .unwrap();
    }

    /// Token's audience is not a subset of the connfigured audience
    #[test]
    #[should_panic(expected = "InvalidAudience")]
    fn refresh_token_validates_invalid_audience() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.audience = Some(jwt::SingleOrMultiple::Multiple(vec![
                FromStr::from_str("https://www.invalid.com/").unwrap(),
                FromStr::from_str("https://www.example.com/").unwrap(),
            ]));
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// Token's issuer is not expected
    #[test]
    #[should_panic(expected = "InvalidIssuer")]
    fn refresh_token_validates_invalid_issuer() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.issuer =
                Some(FromStr::from_str("https://www.invalid.com/").unwrap());
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// Issued at time is required
    #[test]
    #[should_panic(expected = "MissingRequiredClaims([\"iat\"])")]
    fn refresh_token_validates_missing_issued_at() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.issued_at = None;
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// Not before time is required
    #[test]
    #[should_panic(expected = "MissingRequiredClaims([\"nbf\"])")]
    fn refresh_token_validates_missing_not_before() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.not_before = None;
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }

    /// Expiry time is required
    #[test]
    #[should_panic(expected = "MissingRequiredClaims([\"exp\"])")]
    fn refresh_token_validates_missing_expiry() {
        let configuration = make_config(true);

        let refresh_token = make_refresh_token();
        let mut jwe = refresh_token.unwrap();
        {
            let jws = jwe.payload_mut().unwrap();
            let claims_set = jws.payload_mut().unwrap();
            claims_set.registered.expiry = None;
        }
        let refresh_token = RefreshToken(jwe);

        refresh_token
            .validate("https://www.example.com/", &configuration, None)
            .unwrap();
    }
}