rama-crypto 0.4.0

All crypto logic used by rama
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
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
use base64::{Engine as _, prelude::BASE64_URL_SAFE_NO_PAD};
use rama_core::error::BoxErrorExt as _;
use rama_core::error::{BoxError, ErrorContext as _};
use rama_utils::{fmt::format_with_capacity, macros::generate_set_and_with};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

fn dotted_pair(first: &str, second: &str) -> String {
    format_with_capacity(
        first.len() + second.len() + 1,
        format_args!("{first}.{second}"),
    )
}

fn dotted_triple(first: &str, second: &str, third: &str) -> String {
    format_with_capacity(
        first.len() + second.len() + third.len() + 2,
        format_args!("{first}.{second}.{third}"),
    )
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
/// When used with serde this will serialize to an empty JSON object (`{}`)
///
/// Some remarks about this struct:
/// - We use Empty {} and not Empty, because they serialize differently `{}` vs explicit `null`
/// - We don't make this `non_exhaustive` since we will never add fields to it, and using `Empty {}`
///   makes a a bit more clear that we are making an empty struct (object)
/// - In most cases you don't want to use this struct directly but instead you want to use [`NO_PAYLOAD`] or [`EMPTY_PAYLOAD`]
pub struct Empty {}

/// Serializes to a JSON null value
pub const NO_PAYLOAD: Option<&'static Empty> = None;
/// Serializes to a JSON empty object `{}`
pub const EMPTY_PAYLOAD: Option<&'static Empty> = Some(&Empty {});

#[derive(Default, Debug, Clone, PartialEq, Eq)]
/// [`JWSBuilder`] should be used when manually creating a [`JWS`], [`JWSCompact`] or [`JWSFlattened`]
pub struct JWSBuilder {
    protected_headers: Headers,
    unprotected_headers: Headers,
    payload: String,
}

#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
/// [`Headers`] store protected or unprotected headers and already
/// serializes them to correct JSON values.
pub struct Headers(Option<Map<String, Value>>);

impl Headers {
    generate_set_and_with! {
        /// Set provided header in the header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use `.header_map()` or `.header_map_raw()`
        /// to get access to the underlying header map
        pub fn header(
            mut self,
            name: String,
            value: impl Serialize,
        ) -> Result<Self, BoxError> {
            let headers = self.0.get_or_insert_default();
            let value = serde_json::to_value(value).context("convert to value")?;
            headers.insert(name, value);
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Set provided headers in the header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use `.header_map()` or `.header_map_raw()`
        /// to get access to the underlying header map
        pub fn headers(mut self, headers: impl Serialize) -> Result<Self, BoxError> {
            let headers =
                serde_json::to_value(headers).context("convert headers to serde json value")?;

            let mut headers = match headers {
                Value::Object(map) => map,
                _ => Err(BoxError::from_static_str(
                    "Can only set multiple headers if input is key value object",
                ))?,
            };

            match &mut self.0 {
                Some(existing_headers) => existing_headers.append(&mut headers),
                None => self.0 = Some(headers),
            };

            Ok(self)
        }
    }

    /// Encode headers to a base64 url safe representation
    fn as_encoded_string(&self) -> Result<String, BoxError> {
        let encoded = match &self.0 {
            Some(headers) => {
                let headers = serde_json::to_vec(headers).context("convert to bytes")?;
                BASE64_URL_SAFE_NO_PAD.encode(headers)
            }
            None => String::new(),
        };
        Ok(encoded)
    }

    fn is_none(&self) -> bool {
        self.0.is_none()
    }

    fn is_some(&self) -> bool {
        self.0.is_some()
    }

    /// Try decode headers to the provided `T`
    pub fn decode<'de, 'a: 'de, T>(&'a self) -> Result<T, BoxError>
    where
        T: Deserialize<'de>,
    {
        match &self.0 {
            Some(headers) => Ok(T::deserialize(headers).context("deserialize headers into T")?),
            None => Err(BoxError::from_static_str(
                "headers are None, deserialize not supported",
            )),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// [`ChainedJWSBuilder`] will be used to create a [`JWS`] with multiple signatures
pub struct ChainedJWSBuilder {
    signatures: Vec<Signature>,
    payload: String,
    protected_headers: Headers,
    unprotected_headers: Headers,
}

impl JWSBuilder {
    /// Create a new builder
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    generate_set_and_with! {
        /// Add the provided payload to this [`JWSBuilder`]
        pub fn payload(mut self, payload: impl AsRef<[u8]>) -> Self {
            let payload = BASE64_URL_SAFE_NO_PAD.encode(payload);
            self.payload = payload;
            self
        }
    }

    generate_set_and_with! {
        /// Set provided header in the protected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use [`Self::protected_headers_mut`] to get access
        /// to the underlying header store
        pub fn protected_header(
            mut self,
            name: String,
            value: impl Serialize,
        ) -> Result<Self, BoxError> {
            self.protected_headers.try_set_header(name, value)?;
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Set provided headers in the protected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use[`Self::protected_headers_mut]` to get access
        /// to the underlying header store
        pub fn protected_headers(mut self, headers: impl Serialize) -> Result<Self, BoxError> {
            self.protected_headers.try_set_headers(headers)?;
            Ok(self)
        }
    }

    /// Get mutable reference to the underlying protected header store
    ///
    /// This can be used in cases where more granual control is needed
    pub fn protected_headers_mut(&mut self) -> &mut Headers {
        &mut self.protected_headers
    }

    generate_set_and_with! {
        /// Set provided header in the unprotected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use [`Self::unprotected_headers_mut`] to get access
        /// to the underlying header store
        pub fn unprotected_header(
            mut self,
            name: String,
            value: impl Serialize,
        ) -> Result<Self, BoxError> {
            self.unprotected_headers.try_set_header(name, value)?;
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Set provided headers in the unprotected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is needed, use [`Self::unprotected_headers_mut`] to get access
        /// to the underlying header store
        pub fn unprotected_headers(mut self, headers: impl Serialize) -> Result<Self, BoxError> {
            self.unprotected_headers.try_set_headers(headers)?;
            Ok(self)
        }
    }

    /// Get mutable reference to the underlying unprotected header store
    ///
    /// This can be used in cases where more granual control is needed
    pub fn unprotected_headers_mut(&mut self) -> &mut Headers {
        &mut self.unprotected_headers
    }

    /// Generate compact serialization of this `JWS`
    ///
    /// This only available if there is no unprotected header set
    pub fn build_compact(mut self, signer: &impl Signer) -> Result<JWSCompact, BoxError> {
        if self.unprotected_headers.is_some() {
            return Err(BoxError::from_static_str(
                "Compact jws does not support unprotected headers",
            ));
        }

        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;
        let protected = self.protected_headers.as_encoded_string()?;
        let mut signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        signing_input.reserve(1 + signature.len());
        signing_input.push('.');
        signing_input.push_str(&signature);
        Ok(JWSCompact(signing_input))
    }

    /// Build a [`JWSFlattened`]
    pub fn build_flattened(mut self, signer: &impl Signer) -> Result<JWSFlattened, BoxError> {
        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;

        let protected = self.protected_headers.as_encoded_string()?;
        let signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        Ok(JWSFlattened {
            signature: Signature {
                protected,
                unprotected: self.unprotected_headers,
                signature,
            },

            payload: self.payload,
        })
    }

    /// Build a [`JWS`]
    pub fn build_jws(mut self, signer: &impl Signer) -> Result<JWS, BoxError> {
        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;

        let protected = self.protected_headers.as_encoded_string()?;
        let signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        let signature = Signature {
            protected,
            signature,
            unprotected: self.unprotected_headers,
        };

        Ok(JWS {
            signatures: vec![signature],
            payload: self.payload,
        })
    }

    /// Create a [`ChainedJWSBuilder`] with the same payload but that can add a new set of headers
    /// and which will be signed again. This is needed to create a [`JWS`] with multiple signatures.
    pub fn add_signature(mut self, signer: &impl Signer) -> Result<ChainedJWSBuilder, BoxError> {
        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;

        let protected = self.protected_headers.as_encoded_string()?;
        let signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        let signature = Signature {
            protected,
            signature,
            unprotected: self.unprotected_headers,
        };

        Ok(ChainedJWSBuilder {
            signatures: vec![signature],
            protected_headers: Default::default(),
            unprotected_headers: Default::default(),
            payload: self.payload,
        })
    }
}

impl ChainedJWSBuilder {
    generate_set_and_with! {
        /// Set provided header in the protected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is use `.protected_headers_mut()` to get access
        /// to the underlying header store
        pub fn protected_header(
            mut self,
            name: String,
            value: impl Serialize,
        ) -> Result<Self, BoxError> {
            self.protected_headers.try_set_header(name, value)?;
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Set provided headers in the protected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is use `.protected_headers_mut()` to get access
        /// to the underlying header store
        pub fn protected_headers(mut self, headers: impl Serialize) -> Result<Self, BoxError> {
            self.protected_headers.try_set_headers(headers)?;
            Ok(self)
        }
    }

    /// Get mutable reference to the underlying protected header store
    ///
    /// This can be used in cases where more granual control is needed
    pub fn protected_headers_mut(&mut self) -> &mut Headers {
        &mut self.protected_headers
    }

    generate_set_and_with! {
        /// Set provided header in the unprotected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is use `.unprotected_headers_mut()` to get access
        /// to the underlying header store
        pub fn unprotected_header(
            mut self,
            name: String,
            value: impl Serialize,
        ) -> Result<Self, BoxError> {
            self.unprotected_headers.try_set_header(name, value)?;
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Set provided headers in the unprotected header map
        ///
        /// Warning: this function will replace already existing headers
        /// If more control is use `.unprotected_headers_mut()` to get access
        /// to the underlying header store
        pub fn with_unprotected_headers(
            mut self,
            headers: impl Serialize,
        ) -> Result<Self, BoxError> {
            self.unprotected_headers.try_set_headers(headers)?;
            Ok(self)
        }
    }

    /// Get mutable reference to the underlying unprotected header store
    ///
    /// This can be used in cases where more granual control is needed
    pub fn unprotected_headers_mut(&mut self) -> &mut Headers {
        &mut self.unprotected_headers
    }

    /// Create a new [`ChainedJWSBuilder`] so we can add another signature
    pub fn add_signature(mut self, signer: &impl Signer) -> Result<Self, BoxError> {
        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;
        let protected = self.protected_headers.as_encoded_string()?;
        let signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        let signature = Signature {
            protected,
            signature,
            unprotected: self.unprotected_headers,
        };

        self.signatures.push(signature);

        Ok(Self {
            signatures: self.signatures,
            protected_headers: Default::default(),
            unprotected_headers: Default::default(),
            payload: self.payload,
        })
    }

    /// Build the final [`JWS] containing all provided signatures
    pub fn build(mut self, signer: &impl Signer) -> Result<JWS, BoxError> {
        signer
            .set_headers(&mut self.protected_headers, &mut self.unprotected_headers)
            .context("signer set headers")?;
        let protected = self.protected_headers.as_encoded_string()?;
        let signing_input = dotted_pair(&protected, &self.payload);

        let signature = signer
            .sign(&signing_input)
            .context("signer sign protected data")?;
        let signature = BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref());

        let signature = Signature {
            protected,
            signature,
            unprotected: self.unprotected_headers,
        };

        self.signatures.push(signature);

        Ok(JWS {
            payload: self.payload,
            signatures: self.signatures,
        })
    }
}

/// [`Signer`] implements all methods which are needed to sign our JWS requests,
/// and add the needed info to our JOSE headers (JOSE headers = protected + unprotected headers)
pub trait Signer {
    type Signature: AsRef<[u8]>;
    type Error: Into<BoxError>;

    /// Set headers which are needed to verify the final `Signature`
    ///
    /// Example headers are: `alg`, `curve`
    fn set_headers(
        &self,
        protected_headers: &mut Headers,
        unprotected_headers: &mut Headers,
    ) -> Result<(), Self::Error>;

    /// Sign the str encoded payload
    fn sign(&self, data: &str) -> Result<Self::Signature, Self::Error>;
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
/// [`JWSCompact`] is a compact `JWS` representation as defined in [`rfc7515, section 7.1`]
///
/// [`rfc7515, section 7.1`]: https://datatracker.ietf.org/doc/html/rfc7515#section-7.1
pub struct JWSCompact(String);

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
/// [`JWSFlattened`] is a `JWS` which is optimized for a single signature, as defined in [`rfc7515, section 7.2.2`]
///
/// It does this by setting protected, header and signature at the root,
/// vs setting it in the signatures array
///
/// [`rfc7515, section 7.2.2`]: https://datatracker.ietf.org/doc/html/rfc7515#section-7.2.2
pub struct JWSFlattened {
    #[serde(default = "Default::default")]
    payload: String,
    #[serde(flatten)]
    signature: Signature,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// [`JWS`] is the general serialization format as defined in [`rfc7515, section 7.2.1`]
///
/// [`rfc7515, section 7.2.1`]: https://datatracker.ietf.org/doc/html/rfc7515#section-7.2.1
pub struct JWS {
    payload: String,
    signatures: Vec<Signature>,
}

impl JWSCompact {
    /// Create a builder which can be used to create a [`JWSCompact`]
    #[must_use]
    pub fn builder() -> JWSBuilder {
        JWSBuilder::new()
    }
}

impl JWS {
    /// Create a builder which can be used to create a [`JWS`]
    #[must_use]
    pub fn builder() -> JWSBuilder {
        JWSBuilder::new()
    }

    /// Decode this [`JWS`] to a [`DecodedJWS`] by decoding all values and checking with [`Verifier`]
    /// if all signatures are correct
    pub fn decode<V: Verifier>(self, verifier: &V) -> Result<(DecodedJWS, V::Output), BoxError> {
        let mut signatures = Vec::with_capacity(self.signatures.len());

        for signature in self.signatures.into_iter() {
            let protected = BASE64_URL_SAFE_NO_PAD
                .decode(&signature.protected)
                .context("decode protected header")?;

            let protected = serde_json::from_slice::<Headers>(&protected)
                .context("deserialize protected headers")?;

            let decoded_signature = BASE64_URL_SAFE_NO_PAD
                .decode(signature.signature)
                .context("decode signature")?;

            let decoded_signature = DecodedSignature {
                protected,
                signature: decoded_signature,
                unprotected: signature.unprotected,
            };

            let to_verify = ToVerifySignature {
                decoded_signature,
                signed_data: dotted_pair(&signature.protected, &self.payload),
            };
            signatures.push(to_verify);
        }

        let payload = BASE64_URL_SAFE_NO_PAD
            .decode(&self.payload)
            .context("decode payload")?;

        let verifier_output = verifier
            .verify(&payload, &signatures)
            .context("signer verify signatures")?;

        let signatures = signatures
            .into_iter()
            .map(|sig| sig.decoded_signature)
            .collect();

        Ok((
            DecodedJWS {
                signatures,
                payload,
            },
            verifier_output,
        ))
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
struct Signature {
    #[serde(skip_serializing_if = "String::is_empty")]
    #[serde(default = "Default::default")]
    protected: String,
    #[serde(skip_serializing_if = "Headers::is_none")]
    #[serde(rename = "headers", default = "Default::default")]
    unprotected: Headers,
    #[serde(skip_serializing_if = "String::is_empty")]
    #[serde(default = "Default::default")]
    signature: String,
}

impl JWSFlattened {
    /// Create a builder which can be used to create a [`JWSFlattened`]
    #[must_use]
    pub fn builder() -> JWSBuilder {
        JWSBuilder::new()
    }

    /// Create a [`JWSCompact`] from this [`JWSFlattened`]
    pub fn as_compact(&self) -> Result<String, BoxError> {
        if self.signature.unprotected.is_some() {
            return Err(BoxError::from_static_str(
                "JWSCompact does not support unprotected headers",
            ));
        };

        Ok(dotted_triple(
            &self.signature.protected,
            &self.payload,
            &self.signature.signature,
        ))
    }

    /// Decode this [`JWS`] to a [`DecodedJWS`] by decoding all values and checking with [`Verifier`]
    /// if the provided signature is correct
    pub fn decode<V: Verifier>(
        self,
        verifier: &V,
    ) -> Result<(DecodedJWSFlattened, V::Output), BoxError> {
        let protected = BASE64_URL_SAFE_NO_PAD
            .decode(&self.signature.protected)
            .context("decode protected header")?;

        let protected = serde_json::from_slice::<Headers>(&protected)
            .context("deserialize protected headers")?;

        let decoded_signature = BASE64_URL_SAFE_NO_PAD
            .decode(self.signature.signature)
            .context("decode signature")?;

        let decoded_signature = DecodedSignature {
            protected,
            signature: decoded_signature,
            unprotected: self.signature.unprotected,
        };

        let to_verify = ToVerifySignature {
            decoded_signature,
            signed_data: dotted_pair(&self.signature.protected, &self.payload),
        };

        let payload = BASE64_URL_SAFE_NO_PAD
            .decode(&self.payload)
            .context("decode payload")?;

        let verify_output = verifier
            .verify(&payload, std::slice::from_ref(&to_verify))
            .context("signer verify signature")?;

        let signature = to_verify.decoded_signature;

        Ok((DecodedJWSFlattened { signature, payload }, verify_output))
    }
}

#[derive(Debug)]
/// Decoded version of a [`JWSFlattened`]
///
/// Data here has already been verified, so everything
/// here is ready for usage
pub struct DecodedJWSFlattened {
    payload: Vec<u8>,
    signature: DecodedSignature,
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// Decode version of a [`JWS`]
///
/// Data here has already been verified, so everything
/// here is ready for usage
pub struct DecodedJWS {
    payload: Vec<u8>,
    signatures: Vec<DecodedSignature>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// Decode version of a `Signature`.
///
/// Data here has already been verified, so everything
/// here is ready for usage
pub struct DecodedSignature {
    protected: Headers,
    unprotected: Headers,
    signature: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// A `Signature` which still needs to be checked
///
/// It included a String representation of the signed data
/// so this doesn't need to be re-encoded
pub struct ToVerifySignature {
    signed_data: String,
    decoded_signature: DecodedSignature,
}

impl ToVerifySignature {
    /// Encoded String representation of protected + payload before it was decoded
    /// again. This should be used instead of re-encoding everything for efficiency
    #[must_use]
    pub fn signed_data(&self) -> &str {
        &self.signed_data
    }

    /// Reference to the [`DecodedSignature`]
    #[must_use]
    pub fn decoded_signature(&self) -> &DecodedSignature {
        &self.decoded_signature
    }
}

impl DecodedSignature {
    /// Reference to the protected [`Headers`]
    #[must_use]
    pub fn protected_headers(&self) -> &Headers {
        &self.protected
    }

    /// Trying decoding the protected headers to the provided `T`
    pub fn decode_protected_headers<'de, 'a: 'de, T: Deserialize<'de>>(
        &'a self,
    ) -> Result<T, BoxError> {
        self.protected.decode()
    }

    /// Reference to the unprotected [`Headers`]
    #[must_use]
    pub fn unprotected_headers(&self) -> &Headers {
        &self.unprotected
    }

    /// Trying decoding the unprotected headers to the provided `T`
    pub fn decode_unprotected_headers<'de, 'a: 'de, T: Deserialize<'de>>(
        &'a self,
    ) -> Result<T, BoxError> {
        self.unprotected.decode()
    }

    /// Signature which was provided for the encoded signature in decoded format
    #[must_use]
    pub fn signature(&self) -> &[u8] {
        self.signature.as_slice()
    }
}

impl DecodedJWS {
    /// Get refence to the [`DecodedSignature`]s
    #[must_use]
    pub fn signatures(&self) -> &[DecodedSignature] {
        self.signatures.as_slice()
    }

    /// Get refence to the payload
    #[must_use]
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }
}

impl DecodedJWSFlattened {
    /// Reference to the protected [`Headers`]
    #[must_use]
    pub fn protected_headers(&self) -> &Headers {
        self.signature.protected_headers()
    }

    /// Trying decoding the protected headers to the provided `T`
    pub fn decode_protected_headers<'de, 'a: 'de, T: Deserialize<'de>>(
        &'a self,
    ) -> Result<T, BoxError> {
        self.signature.decode_protected_headers()
    }

    /// Reference to the unprotected [`Headers`]
    #[must_use]
    pub fn unprotected_headers(&self) -> &Headers {
        self.signature.unprotected_headers()
    }

    /// Trying decoding the unprotected headers to the provided `T`
    pub fn decode_unprotected_headers<'de, 'a: 'de, T: Deserialize<'de>>(
        &'a self,
    ) -> Result<T, BoxError> {
        self.signature.decode_unprotected_headers()
    }

    /// Signature which was provided for the encoded signature in decoded format
    #[must_use]
    pub fn signature(&self) -> &[u8] {
        self.signature.signature()
    }

    /// Get refence to the payload
    #[must_use]
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }
}

/// [`Verifier`] will be called to confirm if the received data is valid
///
/// For some algorithms all signatures need to be valid, but there are also
/// cases when only one or some need to be valid.
///
/// Warning: in some cases order of signatures is not always pre-determined,
/// so in those cases make sure that [`Verifier`] can handle this.
pub trait Verifier {
    type Error: Into<BoxError>;
    type Output;

    /// Verify if data is valid
    fn verify(
        &self,
        payload: &[u8],
        signatures: &[ToVerifySignature],
    ) -> Result<Self::Output, Self::Error>;
}

#[cfg(test)]
mod tests {

    use tokio_test::assert_err;

    use super::*;

    #[test]
    fn dotted_helpers_reserve_exact_capacity() {
        let pair = dotted_pair("protect", "pay");
        assert_eq!(pair, "protect.pay");
        assert_eq!(pair.capacity(), pair.len());

        let triple = dotted_triple("protect", "pay", "xyz");
        assert_eq!(triple, "protect.pay.xyz");
        assert_eq!(triple.capacity(), triple.len());
    }

    #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct AcmeProtected<'a> {
        alg: Option<&'a str>,
        nonce: &'a str,
    }

    #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
    struct Random<'a> {
        data: &'a str,
    }

    struct DummyKey;

    impl Signer for DummyKey {
        type Signature = Vec<u8>;
        type Error = BoxError;

        fn sign(&self, data: &str) -> Result<Self::Signature, BoxError> {
            let mut out = data.as_bytes().to_vec();
            out.push(33);
            Ok(out)
        }

        fn set_headers(
            &self,
            protected_headers: &mut Headers,
            _unprotected_headers: &mut Headers,
        ) -> Result<(), BoxError> {
            protected_headers.try_set_header("alg".to_owned(), "test_algo".to_owned())?;
            Ok(())
        }
    }

    impl Verifier for DummyKey {
        type Error = BoxError;
        type Output = ();

        fn verify(
            &self,
            _payload: &[u8],
            to_verify_sigs: &[ToVerifySignature],
        ) -> Result<(), BoxError> {
            let to_verify = &to_verify_sigs[0];
            let original = to_verify.signed_data.as_bytes();

            let signature = to_verify.decoded_signature.signature();

            if original.len() + 1 != signature.len() {
                Err(BoxError::from_static_str(
                    "signature should add single u8 to original slice",
                ))
            } else if original[..] != signature[..original.len()] {
                Err(BoxError::from_static_str("original data should be equal"))
            } else if signature[signature.len() - 1] != 33 {
                Err(BoxError::from_static_str(
                    "last element in signature should be 33",
                ))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn can_serialize_and_deserialize() {
        let nonce = "random".to_owned();
        let protected = AcmeProtected {
            nonce: &nonce,
            alg: None,
        };

        let something = "something_random".to_owned();
        let header = Random { data: &something };

        let payload = "something".to_owned();

        let signer_and_verifier = DummyKey;

        let jws = JWSBuilder::new()
            .with_payload(payload.clone())
            .try_with_protected_headers(protected.clone())
            .unwrap()
            .try_with_unprotected_headers(header.clone())
            .unwrap()
            .build_flattened(&signer_and_verifier)
            .unwrap();

        let serialized = serde_json::to_string(&jws).unwrap();
        let jws_received = serde_json::from_str::<JWSFlattened>(&serialized).unwrap();

        // This will be set by our signer
        let mut expected_protected = protected.clone();
        expected_protected.alg = Some("test_algo");

        assert_eq!(jws.signature.protected, jws_received.signature.protected);
        assert_eq!(
            jws.signature.unprotected,
            jws_received.signature.unprotected
        );
        assert_eq!(jws.payload, jws_received.payload);

        let (decoded_jws, _) = jws_received.decode(&signer_and_verifier).unwrap();

        let received_payload = String::from_utf8(decoded_jws.payload().to_vec()).unwrap();
        let received_protected = decoded_jws
            .decode_protected_headers::<AcmeProtected>()
            .unwrap();
        let received_header = decoded_jws.decode_unprotected_headers::<Random>().unwrap();

        assert_eq!(payload, received_payload);
        assert_eq!(expected_protected, received_protected);
        assert_eq!(header, received_header);
    }

    #[test]
    fn empty_vs_none() {
        let signer = DummyKey;

        let protected = AcmeProtected {
            nonce: "somthing",
            alg: None,
        };

        let jws = JWSFlattened::builder()
            .try_with_protected_headers(protected.clone())
            .unwrap()
            .build_flattened(&signer)
            .unwrap();

        assert_eq!(jws.payload, "".to_owned());

        let jws = JWSFlattened::builder()
            .with_payload(serde_json::to_vec(&EMPTY_PAYLOAD).unwrap())
            .try_with_protected_headers(protected.clone())
            .unwrap()
            .build_flattened(&signer)
            .unwrap();

        assert_eq!(jws.payload, "e30".to_owned());
    }

    #[test]
    fn tampering_should_be_detected() {
        // This is a very basic signer without and real logic behind it,
        // this test is just here to make sure we detected changes
        let nonce = "random".to_owned();
        let protected = AcmeProtected {
            nonce: &nonce,
            alg: None,
        };

        let payload = "something".to_owned();

        let signer_and_verifier = DummyKey;

        let jws = JWSFlattened::builder()
            .with_payload(payload)
            .try_with_protected_headers(protected.clone())
            .unwrap()
            .build_flattened(&signer_and_verifier)
            .unwrap();

        let serialized = serde_json::to_string(&jws).unwrap();

        // Something should fail in this part
        let server = move |serialized: String| {
            let received =
                serde_json::from_str::<JWSFlattened>(&serialized).context("decode jws")?;
            let _decoded = received.decode(&signer_and_verifier)?;
            Ok::<_, BoxError>(())
        };

        for i in 0..serialized.len() - 1 {
            let mut serialized: String = serialized.clone();
            serialized.insert(i, 't');
            assert_err!(server(serialized), "failed at {i}");
        }
    }

    #[test]
    fn can_create_jws() {
        let nonce = "random".to_owned();

        let something = "something_random".to_owned();
        let header = Random { data: &something };

        let payload = "something".to_owned();

        let signer_and_verifier = DummyKey;

        let jws = JWSBuilder::new()
            .with_payload(payload.clone())
            .try_with_protected_header("nonce".to_owned(), &nonce)
            .unwrap()
            .try_with_unprotected_headers(header.clone())
            .unwrap()
            .build_jws(&signer_and_verifier)
            .unwrap();

        let serialized = serde_json::to_string(&jws).unwrap();
        let received = serde_json::from_str::<JWS>(&serialized).unwrap();
        let (decoded, _) = received.decode(&signer_and_verifier).unwrap();
        let decoded_payload = String::from_utf8(decoded.payload().to_vec()).unwrap();

        assert_eq!(payload, decoded_payload);
    }

    #[test]
    fn can_create_multi_signature_jws() {
        let nonce = "random".to_owned();
        let protected = AcmeProtected {
            nonce: &nonce,
            alg: None,
        };

        let something = "something_random".to_owned();
        let header = Random { data: &something };

        let payload = "something".to_owned();
        let signer_and_verifier = DummyKey;

        let builder = JWSBuilder::new()
            .with_payload(payload.clone())
            .try_with_protected_headers(protected.clone())
            .unwrap()
            .try_with_unprotected_headers(header.clone())
            .unwrap();

        struct SecondSigner;

        impl Signer for SecondSigner {
            type Signature = Vec<u8>;
            type Error = BoxError;

            fn sign(&self, data: &str) -> Result<Self::Signature, BoxError> {
                Ok(data.as_bytes().to_owned())
            }

            fn set_headers(
                &self,
                protected_headers: &mut Headers,
                _unprotected_headers: &mut Headers,
            ) -> Result<(), BoxError> {
                protected_headers.try_set_header("data".to_owned(), "very protected")?;
                Ok(())
            }
        }

        let second_signer = SecondSigner;

        let jws = builder
            .add_signature(&signer_and_verifier)
            .unwrap()
            .try_with_unprotected_header("second".to_owned(), "something second")
            .unwrap()
            .try_with_protected_header("app specific".to_owned(), "will not be used by verifier")
            .unwrap()
            .build(&second_signer)
            .unwrap();

        let serialized = serde_json::to_string(&jws).unwrap();

        #[derive(Debug, Deserialize)]
        struct SecondProtectedHeader {
            data: String,
        }

        struct MultiVerifier {
            dummy_verifier: DummyKey,
        }

        impl Verifier for MultiVerifier {
            type Error = BoxError;
            type Output = ();
            fn verify(
                &self,
                payload: &[u8],
                to_verify_sigs: &[ToVerifySignature],
            ) -> Result<(), BoxError> {
                self.dummy_verifier.verify(payload, to_verify_sigs)?;
                let second = &to_verify_sigs[1];
                let protected_header = second
                    .decoded_signature
                    .decode_protected_headers::<SecondProtectedHeader>()?;

                if protected_header.data.as_str() == "very protected" {
                    Ok(())
                } else {
                    Err(BoxError::from_static_str(
                        "received unexpected second protected header",
                    ))
                }
            }
        }

        let multi_verifier = MultiVerifier {
            dummy_verifier: signer_and_verifier,
        };

        let received = serde_json::from_str::<JWS>(&serialized).unwrap();
        let (decoded, _) = received.decode(&multi_verifier).unwrap();
        let decoded_payload = String::from_utf8(decoded.payload().to_vec()).unwrap();
        assert_eq!(payload, decoded_payload);
    }
}