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
//! JSON Web Tokens ([RFC 7519][RFC7519])
//!
//! This module implements the JWS and JWE formats for representing JSON Web Tokens.
//! It is designed to both accept registered headers and claims (see [crate::claims]) as
//! well as custom payloads and entirely custom headers. All registered fields are optional
//! except for the "alg" field in the JOSE header which is required to identify the signing
//! algorithm in use.
//!
//! [RFC7519]: https://tools.ietf.org/html/rfc7519

use std::marker::PhantomData;
use std::{fmt::Write, str::FromStr};

use base64ct::Encoding;
use bytes::Bytes;
use serde::{
    de::{self, DeserializeOwned},
    ser, Deserialize, Serialize,
};

use crate::algorithms::VerifyAlgorithm;
#[cfg(feature = "fmt")]
use crate::fmt;
use crate::{
    algorithms::{AlgorithmIdentifier, SigningAlgorithm},
    base64data::{Base64Data, Base64JSON, DecodeError},
    jose::{HeaderAccess, HeaderAccessMut, HeaderState},
    Header,
};

mod formats;
mod state;

use self::formats::TokenParseError;
pub use self::formats::{Compact, Flat, FlatUnprotected, TokenFormat, TokenFormattingError};
pub use self::state::{HasSignature, MaybeSigned, Signed, Unsigned, Unverified, Verified};

/// A JWT Playload. Most payloads are JSON objects, which are serialized, and then converted
/// to a base64url string. However, some payloads are empty, and are represented as an empty
/// string, and therefore not base64url encoded.
///
/// It is hard to express this empty type naturally in the Rust type system in a way that interacts
/// well with [serde_json].
#[derive(Debug, Clone)]
enum Payload<P> {
    /// A payload which will be serialized as JSON and then base64url encoded.
    Json(Base64JSON<P>),

    /// An empty payload. This is represented as an empty string, and is not base64url encoded.s
    Empty,
}

#[cfg(feature = "fmt")]
impl<P> fmt::JWTFormat for Payload<P>
where
    P: Serialize,
{
    fn fmt<W: fmt::Write>(&self, f: &mut fmt::IndentWriter<'_, W>) -> fmt::Result {
        match self {
            Payload::Json(data) => <Base64JSON<P> as fmt::JWTFormat>::fmt(data, f),
            Payload::Empty => f.write_str("\"\""),
        }
    }
}

impl<P> Payload<P>
where
    P: Serialize,
{
    fn serialized_value(&self) -> Result<String, serde_json::Error> {
        match self {
            Payload::Json(data) => data.serialized_value(),
            Payload::Empty => Ok("".to_owned()),
        }
    }

    fn serialized_bytes(&self) -> Result<Bytes, serde_json::Error> {
        match self {
            Payload::Json(data) => data.serialized_bytes(),
            Payload::Empty => Ok(Bytes::new()),
        }
    }
}

impl<P> Payload<P>
where
    P: DeserializeOwned,
{
    fn parse(value: &str) -> Result<Self, DecodeError> {
        if value.is_empty() {
            return Ok(Payload::Empty);
        }

        let parsed = Base64JSON::<P>::parse(value)?;
        Ok(Payload::Json(parsed.data.into()))
    }
}

impl<P> From<P> for Payload<P> {
    fn from(value: P) -> Self {
        Payload::Json(value.into())
    }
}

impl<P> ser::Serialize for Payload<P>
where
    P: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Payload::Json(data) => data.serialize(serializer),
            Payload::Empty => serializer.serialize_str(""),
        }
    }
}

impl<'de, P> de::Deserialize<'de> for Payload<P>
where
    P: for<'d> Deserialize<'d>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct PayloadVisitor<P>(PhantomData<P>);

        impl<'de, P> de::Visitor<'de> for PayloadVisitor<P>
        where
            P: de::DeserializeOwned,
        {
            type Value = Payload<P>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a base64url encoded json document")
            }

            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if v.is_empty() {
                    return Ok(Payload::Empty);
                }

                let data = base64ct::Base64UrlUnpadded::decode_vec(v).map_err(|_| {
                    E::invalid_value(de::Unexpected::Str(v), &"invalid base64url encoding")
                })?;

                let data = serde_json::from_slice(&data)
                    .map_err(|err| E::custom(format!("invalid JSON: {err}")))?;
                Ok(Payload::Json(data))
            }
        }

        deserializer.deserialize_str(PayloadVisitor(PhantomData))
    }
}

/// A JSON web token, generic over the signing state, format, and payload.
///
/// Tokens can change state using the `sign`, `verify`, and `unverify` methods.
/// The format can generally not be changed after constructing the token.
///
/// JAWS does not support the general JWS format, only the compact format and
/// the flat format.
///
/// # Examples
///
/// ## Creating a compact token
/// ```
/// use jaws::token::Token;
///
/// let token = Token::compact((), ());
/// ```
///
/// This token will have no payload, and no custom headers.
#[cfg_attr(
    feature = "fmt",
    doc = r#"
To view a debug representation of the token, use the [`fmt::JWTFormat`] trait:

```
# use jaws::token::Token;
# let token = Token::compact((), ());

use jaws::fmt::JWTFormat;

println!("{}", token.formatted());
```
"#
)]
///
///
/// ## Transitioning a token between states
///
/// See [`Token::sign`], [`Token::verify`], and [`Token::unverify`].
///
#[derive(Debug, Clone)]
pub struct Token<P, State: MaybeSigned = Unsigned<()>, Fmt: TokenFormat = Compact> {
    payload: Payload<P>,
    state: State,
    fmt: Fmt,
}

impl<P, State: MaybeSigned, Fmt: TokenFormat> Token<P, State, Fmt> {
    /// Access to Token header values.
    ///
    /// All access is read-only, and the header cannot be modified here,
    /// see [`Token::header_mut`] for mutable access.
    ///
    /// Header fields are accessed as methods on [`HeaderAccess`], and
    /// their types will depend on the state of the token. Additionally,
    /// the `alg` field will not be availalbe for unsigned token types.
    ///
    /// # Example: No custom headers, only registered headers.
    ///
    /// ```
    /// use jaws::token::Token;
    ///
    /// let token = Token::compact((), ());
    /// let header = token.header();
    /// assert_eq!(&header.r#type(), &None);
    /// ```
    pub fn header(&self) -> HeaderAccess<'_, State::Header, State::HeaderState> {
        HeaderAccess::new(self.state.header())
    }

    /// Mutable access to Token header values
    pub fn header_mut(&mut self) -> HeaderAccessMut<State::Header, State::HeaderState> {
        HeaderAccessMut::new(self.state.header_mut())
    }
}

impl<P, H, Fmt> Token<P, Unsigned<H>, Fmt>
where
    Fmt: TokenFormat,
{
    /// Create a new token with the given header and payload, in a given format.
    ///
    /// See also [`Token::compact`] and [`Token::flat`] to create a token in a specific format.
    pub fn new(header: H, payload: P, fmt: Fmt) -> Self {
        Token {
            payload: Payload::Json(payload.into()),
            state: Unsigned {
                header: Header::new(header),
            },
            fmt,
        }
    }

    /// Create an empty token with a given header and format.
    pub fn empty(header: H, fmt: Fmt) -> Self {
        Token {
            payload: Payload::Empty,
            state: Unsigned {
                header: Header::new(header),
            },
            fmt,
        }
    }
}

impl<P, H> Token<P, Unsigned<H>, Compact> {
    /// Create a new token with the given header and payload, in the compact format.
    ///
    /// See also [`Token::new`] and [`Token::flat`] to create a token in a specific format.
    ///
    /// The compact format is the format with base64url encoded header and payload, separated
    /// by a dot, and with the signature appended.
    ///
    pub fn compact(header: H, payload: P) -> Token<P, Unsigned<H>, Compact> {
        Token::new(header, payload, Compact::new())
    }
}

impl<P, H> Token<P, Unsigned<H>, Flat> {
    /// Create a new token with the given header and payload, in the flat format.
    ///
    /// See also [`Token::new`] and [`Token::compact`] to create a token in a specific format.
    ///
    /// The flat format is the format with a JSON object containing the header, payload, and
    /// signature, all in the same object. It can also include additional JSON data as "unprotected"\
    /// headers, which are not signed and cannot be verified.
    pub fn flat(header: H, payload: P) -> Token<P, Unsigned<H>, Flat> {
        Token::new(header, payload, Flat)
    }
}

/// Token serialization and message packing.
impl<P, S, Fmt> Token<P, S, Fmt>
where
    S: MaybeSigned,
    Fmt: TokenFormat,
{
    /// Get the payload and header of the token, serialized in the compact format,
    /// suitable as input into a signature algorithm.
    pub fn message(&self) -> Result<String, serde_json::Error>
    where
        P: Serialize,
        <S as MaybeSigned>::Header: Serialize,
        <S as MaybeSigned>::HeaderState: Serialize + HeaderState,
    {
        let mut msg = String::new();
        let header =
            base64ct::Base64UrlUnpadded::encode_string(&serde_json::to_vec(self.state.header())?);
        let payload = self.payload.serialized_value()?;
        write!(msg, "{}.{}", header, payload).unwrap();
        Ok(msg)
    }

    /// Get the payload and header of the token, serialized including signature data.
    ///
    /// This method is only available when the token is in a signed state.
    pub fn rendered(&self) -> Result<String, TokenFormattingError>
    where
        P: Serialize,
        S: HasSignature,
        <S as MaybeSigned>::Header: Serialize,
        <S as MaybeSigned>::HeaderState: HeaderState,
    {
        let mut msg = String::new();
        self.fmt.render(&mut msg, self)?;
        Ok(msg)
    }
}

impl<H, Fmt, P> Token<P, Unsigned<H>, Fmt>
where
    Fmt: TokenFormat,
{
    pub fn payload(&self) -> Option<&P> {
        match &self.payload {
            Payload::Json(data) => Some(data.as_ref()),
            Payload::Empty => None,
        }
    }
}

impl<H, Fmt, P> Token<P, Unsigned<H>, Fmt>
where
    H: Serialize,
    P: Serialize,
    Fmt: TokenFormat,
{
    /// Sign this token using the given algorithm.
    ///
    /// This method consumes the token and returns a new one with the signature attached.
    /// Once the signature is attached, the internal fields are no longer mutable (as that
    /// would invalidate the signature), but they are still recoverable.
    #[allow(clippy::type_complexity)]
    pub fn sign<A>(
        self,
        algorithm: &A,
    ) -> Result<Token<P, Signed<H, A>, Fmt>, TokenSigningError<A::Error>>
    where
        A: crate::algorithms::SigningAlgorithm,
        A::Key: Clone,
        // A::Signature: Serialize,
    {
        let header = self.state.header.into_signed_header::<A>(algorithm.key());
        let headers = Base64JSON(&header).serialized_value()?;
        let payload = self.payload.serialized_value()?;
        let signature = algorithm
            .sign(&headers, &payload)
            .map_err(TokenSigningError::Signing)?;
        Ok(Token {
            payload: self.payload,
            state: Signed { header, signature },
            fmt: self.fmt,
        })
    }
}

impl<H, Fmt, P> Token<P, Unverified<H>, Fmt>
where
    Fmt: TokenFormat,
    H: Serialize,
    P: Serialize,
{
    /// Verify the signature of the token with the given algorithm.
    ///
    /// This method consumes the token and returns a new one with the signature verified.
    ///
    /// The algorithm must be uniquely specified for verification, otherwise the token
    /// could perform a signature downgrade attack.
    #[allow(clippy::type_complexity)]
    pub fn verify<A>(
        self,
        algorithm: &A,
    ) -> Result<Token<P, Verified<H, A>, Fmt>, TokenVerifyingError<A::Error>>
    where
        A: crate::algorithms::VerifyAlgorithm,
        A::Key: Clone,
        P: Serialize,
        H: Serialize,
    {
        if A::IDENTIFIER != *self.state.header.algorithm() {
            return Err(TokenVerifyingError::Algorithm(
                A::IDENTIFIER,
                *self.state.header.algorithm(),
            ));
        }

        let signature = &self.state.signature;
        let signature = algorithm
            .verify(
                &self.state.header.state.raw,
                &self.state.payload,
                signature.as_ref(),
            )
            .map_err(TokenVerifyingError::Verify)?;

        let header = self.state.header.into_signed_header::<A>(algorithm.key());

        Ok(Token {
            payload: self.payload,
            state: Verified { header, signature },
            fmt: self.fmt,
        })
    }
}

impl<P, H, Fmt> FromStr for Token<P, Unverified<H>, Fmt>
where
    P: DeserializeOwned,
    H: DeserializeOwned,
    Fmt: TokenFormat,
{
    type Err = TokenParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Fmt::parse(Bytes::from(s.to_owned()))
    }
}

impl<P, H, Alg, Fmt> Token<P, Signed<H, Alg>, Fmt>
where
    Fmt: TokenFormat,
    Alg: SigningAlgorithm,
    Alg::Key: Clone,
    H: Serialize,
    P: Serialize,
{
    /// Transition the token back into an unverified state.
    ///
    /// This method consumes the token and returns a new one, which still includes the signature
    /// but which is no longer considered verified.
    pub fn unverify(self) -> Token<P, Unverified<H>, Fmt> {
        let payload = self
            .payload
            .serialized_bytes()
            .expect("valid payload bytes");
        Token {
            payload: self.payload,
            state: Unverified {
                payload,
                header: self.state.header.into_rendered_header(),
                signature: Base64Data(self.state.signature.as_ref().to_owned().into()),
            },
            fmt: self.fmt,
        }
    }
}

impl<H, Fmt, P, Alg> Token<P, Signed<H, Alg>, Fmt>
where
    Fmt: TokenFormat,
    Alg: SigningAlgorithm,
{
    pub fn payload(&self) -> Option<&P> {
        match &self.payload {
            Payload::Json(data) => Some(data.as_ref()),
            Payload::Empty => None,
        }
    }
}

impl<P, H, Alg, Fmt> Token<P, Verified<H, Alg>, Fmt>
where
    Fmt: TokenFormat,
    Alg: VerifyAlgorithm,
    Alg::Key: Clone,
    H: Serialize,
    P: Serialize,
{
    /// Transition the token back into an unverified state.
    ///
    /// This method consumes the token and returns a new one, which still includes the signature
    /// but which is no longer considered verified.
    pub fn unverify(self) -> Token<P, Unverified<H>, Fmt> {
        let payload = self
            .payload
            .serialized_bytes()
            .expect("valid payload bytes");
        Token {
            payload: self.payload,
            state: Unverified {
                payload,
                header: self.state.header.into_rendered_header(),
                signature: Base64Data(self.state.signature.as_ref().to_owned().into()),
            },
            fmt: self.fmt,
        }
    }
}

impl<H, Fmt, P, Alg> Token<P, Verified<H, Alg>, Fmt>
where
    Fmt: TokenFormat,
    Alg: VerifyAlgorithm,
{
    pub fn payload(&self) -> Option<&P> {
        match &self.payload {
            Payload::Json(data) => Some(data.as_ref()),
            Payload::Empty => None,
        }
    }
}

#[cfg(feature = "fmt")]
impl<P, S, Fmt> fmt::JWTFormat for Token<P, S, Fmt>
where
    S: HasSignature,
    <S as MaybeSigned>::Header: Serialize,
    <S as MaybeSigned>::HeaderState: HeaderState,
    P: Serialize,
    Fmt: TokenFormat,
{
    fn fmt<W: std::fmt::Write>(&self, f: &mut fmt::IndentWriter<'_, W>) -> std::fmt::Result {
        let header = serde_json::to_value(self.state.header()).unwrap();
        let payload = serde_json::to_value(&self.payload).unwrap();
        let signature = serde_json::to_value(Base64Data(self.state.signature())).unwrap();

        let token = serde_json::json!({
            "header": header,
            "payload": payload,
            "signature": signature,
        });

        let rendered = serde_json::to_string_pretty(&token).unwrap();

        f.write_str(&rendered)
    }
}

#[cfg(feature = "fmt")]
impl<P, H, Fmt> fmt::JWTFormat for Token<P, Unsigned<H>, Fmt>
where
    H: Serialize,
    P: Serialize,
    Fmt: TokenFormat,
{
    fn fmt<W: std::fmt::Write>(&self, f: &mut fmt::IndentWriter<'_, W>) -> std::fmt::Result {
        let header = self
            .state
            .header()
            .value()
            .expect("header should serialize to json:");
        let payload =
            serde_json::to_value(&self.payload).expect("payload should serialize to json:");

        let token = serde_json::json!({
            "header": header,
            "payload": payload,
            "signature": "<signature>",
        });

        let rendered = serde_json::to_string_pretty(&token).unwrap();

        f.write_str(&rendered)
    }
}

/// An error which occured while verifying a token.
#[derive(Debug, thiserror::Error)]
pub enum TokenVerifyingError<E> {
    /// The verification failed during the cryptographic process, meaning
    /// that the signature was invalid, or the algorithm was invalid.
    #[error("verifying: {0}")]
    Verify(E),

    /// An error occured while re-serailizing the header or payload for
    /// signature verification. This indicates that something is probably
    /// wrong with your custom types.
    #[error("serializing: {0}")]
    Serialization(#[from] serde_json::Error),

    /// The algorithm specified in the header does not match the algorithm
    /// of the verifier.
    #[error("algorithm mismatch: expected {0:?}, got {1:?}")]
    Algorithm(AlgorithmIdentifier, AlgorithmIdentifier),
}

/// An error which occured while verifying a token.
#[derive(Debug, thiserror::Error)]
pub enum TokenSigningError<E> {
    /// The verification failed during the cryptographic process, meaning
    /// that the signature was invalid, or the algorithm was invalid.
    #[error("signing: {0}")]
    Signing(E),

    /// An error occured while serailizing the header or payload for
    /// signature computation. This indicates that something is probably
    /// wrong with your custom types.
    #[error("serializing: {0}")]
    Serialization(#[from] serde_json::Error),
}

#[cfg(all(test, feature = "rsa"))]
mod test_rsa {
    use super::*;
    use crate::claims::Claims;

    use base64ct::Encoding;
    use chrono::TimeZone;
    use serde_json::json;
    use sha2::Sha256;

    use signature::Keypair;

    use crate::key::jwk_reader::rsa;

    fn strip_whitespace(s: &str) -> String {
        s.chars().filter(|c| !c.is_whitespace()).collect()
    }

    fn rfc7515_example_a2_key() -> ::rsa::RsaPrivateKey {
        rsa(&json!( {"kty":"RSA",
              "n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx
       HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs
       D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH
       SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV
       MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8
       NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ",
              "e":"AQAB",
              "d":"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I
       jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0
       BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn
       439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT
       CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh
       BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ",
              "p":"4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH_5IB3jw3bcxGn6QLvnEtfdUdi
       YrqBdss1l58BQ3KhooKeQTa9AB0Hw_Py5PJdTJNPY8cQn7ouZ2KKDcmnPG
       BY5t7yLc1QlQ5xHdwW1VhvKn-nXqhJTBgIPgtldC-KDV5z-y2XDwGUc",
              "q":"uQPEfgmVtjL0Uyyx88GZFF1fOunH3-7cepKmtH4pxhtCoHqpWmT8YAmZxa
       ewHgHAjLYsp1ZSe7zFYHj7C6ul7TjeLQeZD_YwD66t62wDmpe_HlB-TnBA
       -njbglfIsRLtXlnDzQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdc",
              "dp":"BwKfV3Akq5_MFZDFZCnW-wzl-CCo83WoZvnLQwCTeDv8uzluRSnm71I3Q
       CLdhrqE2e9YkxvuxdBfpT_PI7Yz-FOKnu1R6HsJeDCjn12Sk3vmAktV2zb
       34MCdy7cpdTh_YVr7tss2u6vneTwrA86rZtu5Mbr1C1XsmvkxHQAdYo0",
              "dq":"h_96-mK1R_7glhsum81dZxjTnYynPbZpHziZjeeHcXYsXaaMwkOlODsWa
       7I9xXDoRwbKgB719rrmI2oKr6N3Do9U0ajaHF-NKJnwgjMd2w9cjz3_-ky
       NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU",
              "qi":"IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o
       y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU
       W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U"
             }
        ))
    }

    #[test]
    fn rfc7515_example_a2() {
        // This test alters the example from RFC 7515, section A.2, since
        // the RFC does not require a specific JSON serialization format,
        // so we use the compact representation without newlines, as opposed
        // to the one presented in the RFC.
        //
        // Link: https://tools.ietf.org/html/rfc7515#appendix-A.2
        //
        // See crate::algorithms::rsa::test::rfc7515_example_A2 for a test
        // which validates the signature against the RFC example.

        let pkey = rfc7515_example_a2_key();

        let custom = json!({
            "http://example.com/is_root": true
        });

        let mut claims = Claims::from(custom);
        claims.registered.issued_at = chrono::Utc.timestamp_opt(1300819380, 0).single();
        claims.registered.issuer = Some("joe".into());

        let token = Token::new((), claims, Compact::new());
        let algorithm: crate::algorithms::rsa::RsaPkcs1v15<Sha256> =
            crate::algorithms::rsa::RsaPkcs1v15::new_with_prefix(pkey);
        let signed = token.sign(&algorithm).unwrap();
        {
            let hdr = base64ct::Base64UrlUnpadded::encode_string(
                &serde_json::to_vec(&signed.state.header()).unwrap(),
            );
            assert_eq!(hdr, "eyJhbGciOiJSUzI1NiJ9")
        }
        {
            let msg = signed.message().unwrap();
            assert_eq!(
                msg,
                strip_whitespace(
                    "eyJhbGciOiJSUzI1NiJ9
            .
            eyJpc3MiOiJqb2UiLCJpYXQiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtc
            GxlLmNvbS9pc19yb290Ijp0cnVlfQ"
                )
            )
        }

        {
            let tkn = signed.rendered().unwrap();
            assert_eq!(
                tkn,
                strip_whitespace(
                    "
            eyJhbGciOiJSUzI1NiJ9
            .
            eyJpc3MiOiJqb2UiLCJpYXQiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtc
            GxlLmNvbS9pc19yb290Ijp0cnVlfQ
            .
            OqzEd_gl5CDmUo9jVwC7yrlKSWUaAQoa2_4JSVzSem5nBjv5mx2PbkEZw
            0qP6karpsUfa0qkNlvtIrdYCWS3GnHff7LBkJkN8tvJgI1zCY2QqIOD0e
            E1yK3AGgxR0yMDHgY9SIFoXi5cK1UHPeiGkU7GlMmZf2zH-YFOQMK7__7
            VdH1y7cap6j3xW4LczctcBjJRFRku7i_gAy9JiR34WsqolbxKOQPIGK8w
            TE3Qo5BhB70IRMJL6O-jqgYVDAl0BrakNKqZtVTLss41ErM5Twyvin740
            UPIE2oHq3cLzCzXcEPEIPqr4_jerU9Wc8vevZ3-wE5czssL6RgtzJjuyw"
                )
            )
        }

        let algorithm = algorithm.verifying_key();

        signed.unverify().verify(&algorithm).unwrap();
    }
}

#[cfg(all(test, feature = "ecdsa", feature = "p256"))]
mod test_ecdsa {
    use super::*;

    use base64ct::Encoding;
    use elliptic_curve::{FieldBytes, SecretKey};
    use serde_json::json;
    use zeroize::Zeroize;

    fn strip_whitespace(s: &str) -> String {
        s.chars().filter(|c| !c.is_whitespace()).collect()
    }

    fn ecdsa(jwk: &serde_json::Value) -> SecretKey<p256::NistP256> {
        let d_b64 = strip_whitespace(jwk["d"].as_str().unwrap());
        let mut d_bytes = FieldBytes::<p256::NistP256>::default();
        base64ct::Base64UrlUnpadded::decode(&d_b64, &mut d_bytes).unwrap();

        let key = SecretKey::from_slice(&d_bytes).unwrap();
        d_bytes.zeroize();
        key
    }

    #[test]
    fn rfc7515_example_a3() {
        let pkey = &json!({
        "kty":"EC",
        "crv":"P-256",
        "x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
        "y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0",
        "d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI"
        });

        let key = ecdsa(pkey);

        let token = Token::compact((), "This is a signed message");

        let signed = token.sign(&key).unwrap();

        let verifying_key: ecdsa::VerifyingKey<_> = key.public_key().into();

        let verified = signed.unverify().verify(&verifying_key).unwrap();

        assert_eq!(verified.payload(), Some(&"This is a signed message"));
    }
}

#[cfg(all(test, feature = "hmac"))]
mod test_hmac {
    use crate::algorithms::hmac::{Hmac, HmacKey};

    use super::*;

    use base64ct::Encoding;
    use serde_json::json;
    use sha2::Sha256;

    fn strip_whitespace(s: &str) -> String {
        s.chars().filter(|c| !c.is_whitespace()).collect()
    }

    #[test]
    fn rfc7515_example_a1() {
        let pkey = &json!({
            "kty":"oct",
            "k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75
                aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
        }
        );

        let key_data = strip_whitespace(pkey["k"].as_str().unwrap());

        let decoded_len = 3 * key_data.len() / 4;

        let mut key = HmacKey::with_capacity(decoded_len);
        key.resize(decoded_len, 0);

        base64ct::Base64UrlUnpadded::decode(&key_data, key.as_mut()).unwrap();

        let algorithm: Hmac<Sha256> = Hmac::new(key);

        let token = Token::compact((), "This is an HMAC'd message");

        let signed = token.sign(&algorithm).unwrap();

        let verified = signed.unverify().verify(&algorithm).unwrap();

        assert_eq!(verified.payload(), Some(&"This is an HMAC'd message"));
    }
}