httpsig-hyper 0.0.24

Hyper extension for http message signatures (RFC9421)
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
use crate::error::{HyperSigError, HyperSigResult};
use http::{HeaderMap, Request, Response};
use http_body::Body;
use httpsig::prelude::{
  message_component::{
    DerivedComponentName, HttpMessageComponent, HttpMessageComponentId, HttpMessageComponentName, HttpMessageComponentParam,
  },
  AlgorithmName, HttpSignatureBase, HttpSignatureHeaders, HttpSignatureHeadersMap, HttpSignatureParams, SigningKey, VerifyingKey,
};
use indexmap::{IndexMap, IndexSet};
use std::{future::Future, str::FromStr};

/// A type alias for the signature name
type SignatureName = String;
/// A type alias for the key id in base 64
type KeyId = String;

/* --------------------------------------- */
/// A trait about the http message signature common to both request and response
pub trait MessageSignature {
  type Error;

  /// Check if the request has signature and signature-input headers
  fn has_message_signature(&self) -> bool;

  /// Extract all key ids for signature bases contained in the request headers
  fn get_alg_key_ids(&self) -> Result<IndexMap<SignatureName, (Option<AlgorithmName>, Option<KeyId>)>, Self::Error>;

  /// Extract all signature params used to generate signature bases contained in the request headers
  fn get_signature_params(&self) -> Result<IndexMap<SignatureName, HttpSignatureParams>, Self::Error>;
}

/// A trait about http message signature for request
pub trait MessageSignatureReq {
  type Error;
  /// Set the http message signature from given http signature params and signing key
  fn set_message_signature<T>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send
  where
    Self: Sized,
    T: SigningKey + Sync;

  /// Set the http message signatures from given tuples of (http signature params, signing key, name)
  fn set_message_signatures<T>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
  ) -> impl Future<Output = Result<(), Self::Error>> + Send
  where
    Self: Sized,
    T: SigningKey + Sync;

  /// Verify the http message signature with given verifying key if the request has signature and signature-input headers
  fn verify_message_signature<T>(
    &self,
    verifying_key: &T,
    key_id: Option<&str>,
  ) -> impl Future<Output = Result<SignatureName, Self::Error>> + Send
  where
    Self: Sized,
    T: VerifyingKey + Sync;

  /// Verify multiple signatures at once
  fn verify_message_signatures<T>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
  ) -> impl Future<Output = Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>> + Send
  where
    Self: Sized,
    T: VerifyingKey + Sync;

  /// Extract all signature bases contained in the request headers
  fn extract_signatures(&self) -> Result<IndexMap<SignatureName, (HttpSignatureBase, HttpSignatureHeaders)>, Self::Error>;
}

/// A trait about http message signature for response
pub trait MessageSignatureRes {
  type Error;
  /// Set the http message signature from given http signature params and signing key
  fn set_message_signature<T, B>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync;

  /// Set the http message signatures from given tuples of (http signature params, signing key, name)
  fn set_message_signatures<T, B>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync;

  /// Verify the http message signature with given verifying key if the request has signature and signature-input headers
  fn verify_message_signature<T, B>(
    &self,
    verifying_key: &T,
    key_id: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> impl Future<Output = Result<SignatureName, Self::Error>> + Send
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync;

  /// Verify multiple signatures at once
  fn verify_message_signatures<T, B>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> impl Future<Output = Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>> + Send
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync;

  /// Extract all signature bases contained in the request headers
  fn extract_signatures<B>(
    &self,
    req_for_param: Option<&Request<B>>,
  ) -> Result<IndexMap<SignatureName, (HttpSignatureBase, HttpSignatureHeaders)>, Self::Error>;
}

/* --------------------------------------- */
#[cfg(feature = "blocking")]
/// Synchronous counterpart of [`MessageSignatureReq`].
///
/// Every method delegates to the corresponding async method via `futures::executor::block_on`.
///
/// # Panics
///
/// All methods will panic if called from within an async runtime (e.g. a `tokio` task).
/// Use the async [`MessageSignatureReq`] methods instead when you are already in an async context.
pub trait MessageSignatureReqSync: MessageSignatureReq {
  fn set_message_signature_sync<T>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync;

  fn set_message_signatures_sync<T>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync;

  fn verify_message_signature_sync<T>(&self, verifying_key: &T, key_id: Option<&str>) -> Result<SignatureName, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync;

  fn verify_message_signatures_sync<T>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync;
}

#[cfg(feature = "blocking")]
/// Synchronous counterpart of [`MessageSignatureRes`].
///
/// Every method delegates to the corresponding async method via `futures::executor::block_on`.
///
/// # Panics
///
/// All methods will panic if called from within an async runtime (e.g. a `tokio` task).
/// Use the async [`MessageSignatureRes`] methods instead when you are already in an async context.
pub trait MessageSignatureResSync: MessageSignatureRes {
  fn set_message_signature_sync<T, B>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync;

  fn set_message_signatures_sync<T, B>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync;

  fn verify_message_signature_sync<T, B>(
    &self,
    verifying_key: &T,
    key_id: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<SignatureName, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync;

  fn verify_message_signatures_sync<T, B>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync;
}

/* --------------------------------------- */
impl<D> MessageSignature for Request<D>
where
  D: Send + Body + Sync,
{
  type Error = HyperSigError;

  /// Check if the request has signature and signature-input headers
  fn has_message_signature(&self) -> bool {
    has_message_signature_inner(self.headers())
  }

  /// Extract all signature bases contained in the request headers
  fn get_alg_key_ids(&self) -> HyperSigResult<IndexMap<SignatureName, (Option<AlgorithmName>, Option<KeyId>)>> {
    let req_or_res = RequestOrResponse::Request(self);
    get_alg_key_ids_inner(&req_or_res)
  }

  /// Extract all signature params used to generate signature bases contained in the request headers
  fn get_signature_params(&self) -> Result<IndexMap<SignatureName, HttpSignatureParams>, Self::Error> {
    let req_or_res = RequestOrResponse::Request(self);
    get_signature_params_inner(&req_or_res)
  }
}

impl<D> MessageSignatureReq for Request<D>
where
  D: Send + Body + Sync,
{
  type Error = HyperSigError;

  /// Set the http message signature from given http signature params and signing key
  async fn set_message_signature<T>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
  ) -> HyperSigResult<()>
  where
    Self: Sized,
    T: SigningKey + Sync,
  {
    self
      .set_message_signatures(&[(signature_params, signing_key, signature_name)])
      .await
  }

  async fn set_message_signatures<T>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
  {
    let req_or_res = RequestOrResponse::Request(self);
    let vec_signature_bases = params_key_name
      .iter()
      .map(|(params, key, name)| {
        build_signature_base(&req_or_res, params, None as Option<&Request<()>>).map(|base| (base, *key, *name))
      })
      .collect::<Result<Vec<_>, _>>()?;
    let vec_signature_headers = futures::future::join_all(
      vec_signature_bases
        .into_iter()
        .map(|(base, key, name)| async move { base.build_signature_headers(key, name) }),
    )
    .await
    .into_iter()
    .collect::<Result<Vec<_>, _>>()?;
    vec_signature_headers.iter().try_for_each(|headers| {
      self
        .headers_mut()
        .append("signature-input", headers.signature_input_header_value().parse()?);
      self
        .headers_mut()
        .append("signature", headers.signature_header_value().parse()?);
      Ok(()) as Result<(), HyperSigError>
    })
  }

  /// Verify the http message signature with given verifying key if the request has signature and signature-input headers
  /// Return Ok(()) if the signature is valid.
  /// If invalid for the given key or error occurs (like the case where the request does not have signature and/or signature-input headers), return Err.
  /// If key_id is given, it is used to match the key id in signature params
  async fn verify_message_signature<T>(&self, verifying_key: &T, key_id: Option<&str>) -> HyperSigResult<SignatureName>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
  {
    self
      .verify_message_signatures(&[(verifying_key, key_id)])
      .await?
      .pop()
      .unwrap()
  }

  async fn verify_message_signatures<T>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
  {
    if !self.has_message_signature() {
      return Err(HyperSigError::NoSignatureHeaders(
        "The request does not have signature and signature-input headers".to_string(),
      ));
    }
    let map_signature_with_base = self.extract_signatures()?;
    verify_message_signatures_inner(&map_signature_with_base, key_and_id).await
  }

  /// Extract all signature bases contained in the request headers
  fn extract_signatures(&self) -> Result<IndexMap<SignatureName, (HttpSignatureBase, HttpSignatureHeaders)>, Self::Error> {
    let req_or_res = RequestOrResponse::Request(self);
    extract_signatures_inner(&req_or_res, None as Option<&Request<()>>)
  }
}

/* --------------------------------------- */
impl<D> MessageSignature for Response<D>
where
  D: Send + Body + Sync,
{
  type Error = HyperSigError;

  /// Check if the response has signature and signature-input headers
  fn has_message_signature(&self) -> bool {
    has_message_signature_inner(self.headers())
  }

  /// Extract all key ids for signature bases contained in the response headers
  fn get_alg_key_ids(&self) -> Result<IndexMap<SignatureName, (Option<AlgorithmName>, Option<KeyId>)>, Self::Error> {
    let req_or_res = RequestOrResponse::Response(self);
    get_alg_key_ids_inner(&req_or_res)
  }

  /// Extract all signature params used to generate signature bases contained in the response headers
  fn get_signature_params(&self) -> Result<IndexMap<SignatureName, HttpSignatureParams>, Self::Error> {
    let req_or_res = RequestOrResponse::Response(self);
    get_signature_params_inner(&req_or_res)
  }
}

impl<D> MessageSignatureRes for Response<D>
where
  D: Send + Body + Sync,
{
  type Error = HyperSigError;

  /// Set the http message signature from given http signature params and signing key
  async fn set_message_signature<T, B>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync,
  {
    self
      .set_message_signatures(&[(signature_params, signing_key, signature_name)], req_for_param)
      .await
  }

  async fn set_message_signatures<T, B>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
  {
    let req_or_res = RequestOrResponse::Response(self);

    let vec_signature_bases = params_key_name
      .iter()
      .map(|(params, key, name)| build_signature_base(&req_or_res, params, req_for_param).map(|base| (base, *key, *name)))
      .collect::<Result<Vec<_>, _>>()?;
    let vec_signature_headers = futures::future::join_all(
      vec_signature_bases
        .into_iter()
        .map(|(base, key, name)| async move { base.build_signature_headers(key, name) }),
    )
    .await
    .into_iter()
    .collect::<Result<Vec<_>, _>>()?;

    vec_signature_headers.iter().try_for_each(|headers| {
      self
        .headers_mut()
        .append("signature-input", headers.signature_input_header_value().parse()?);
      self
        .headers_mut()
        .append("signature", headers.signature_header_value().parse()?);
      Ok(()) as Result<(), HyperSigError>
    })
  }

  /// Verify the http message signature with given verifying key if the response has signature and signature-input headers
  /// Return Ok(()) if the signature is valid.
  /// If invalid for the given key or error occurs (like the case where the request does not have signature and/or signature-input headers), return Err.
  /// If key_id is given, it is used to match the key id in signature params
  async fn verify_message_signature<T, B>(
    &self,
    verifying_key: &T,
    key_id: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<SignatureName, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync,
  {
    self
      .verify_message_signatures(&[(verifying_key, key_id)], req_for_param)
      .await?
      .pop()
      .unwrap()
  }

  async fn verify_message_signatures<T, B>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
  {
    if !self.has_message_signature() {
      return Err(HyperSigError::NoSignatureHeaders(
        "The response does not have signature and signature-input headers".to_string(),
      ));
    }
    let map_signature_with_base = self.extract_signatures(req_for_param)?;
    verify_message_signatures_inner(&map_signature_with_base, key_and_id).await
  }

  /// Extract all signature bases contained in the response headers
  fn extract_signatures<B>(
    &self,
    req_for_param: Option<&Request<B>>,
  ) -> Result<IndexMap<SignatureName, (HttpSignatureBase, HttpSignatureHeaders)>, Self::Error> {
    let req_or_res = RequestOrResponse::Response(self);
    extract_signatures_inner(&req_or_res, req_for_param)
  }
}

/* --------------------------------------- */
#[cfg(feature = "blocking")]
impl<D> MessageSignatureReqSync for Request<D>
where
  D: Send + Body + Sync,
{
  fn set_message_signature_sync<T>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
  {
    futures::executor::block_on(self.set_message_signature(signature_params, signing_key, signature_name))
  }

  fn set_message_signatures_sync<T>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
  {
    futures::executor::block_on(self.set_message_signatures(params_key_name))
  }

  fn verify_message_signature_sync<T>(&self, verifying_key: &T, key_id: Option<&str>) -> Result<SignatureName, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
  {
    futures::executor::block_on(self.verify_message_signature(verifying_key, key_id))
  }

  fn verify_message_signatures_sync<T>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
  {
    futures::executor::block_on(self.verify_message_signatures(key_and_id))
  }
}

#[cfg(feature = "blocking")]
impl<D> MessageSignatureResSync for Response<D>
where
  D: Send + Body + Sync,
{
  fn set_message_signature_sync<T, B>(
    &mut self,
    signature_params: &HttpSignatureParams,
    signing_key: &T,
    signature_name: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync,
  {
    futures::executor::block_on(self.set_message_signature(signature_params, signing_key, signature_name, req_for_param))
  }

  fn set_message_signatures_sync<T, B>(
    &mut self,
    params_key_name: &[(&HttpSignatureParams, &T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<(), Self::Error>
  where
    Self: Sized,
    T: SigningKey + Sync,
    B: Sync,
  {
    futures::executor::block_on(self.set_message_signatures(params_key_name, req_for_param))
  }

  fn verify_message_signature_sync<T, B>(
    &self,
    verifying_key: &T,
    key_id: Option<&str>,
    req_for_param: Option<&Request<B>>,
  ) -> Result<SignatureName, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync,
  {
    futures::executor::block_on(self.verify_message_signature(verifying_key, key_id, req_for_param))
  }

  fn verify_message_signatures_sync<T, B>(
    &self,
    key_and_id: &[(&T, Option<&str>)],
    req_for_param: Option<&Request<B>>,
  ) -> Result<Vec<Result<SignatureName, Self::Error>>, Self::Error>
  where
    Self: Sized,
    T: VerifyingKey + Sync,
    B: Sync,
  {
    futures::executor::block_on(self.verify_message_signatures(key_and_id, req_for_param))
  }
}

/* --------------------------------------- */
// inner functions
/// has message signature inner function
fn has_message_signature_inner(headers: &HeaderMap) -> bool {
  headers.contains_key("signature") && headers.contains_key("signature-input")
}

/// get key ids inner function
fn get_alg_key_ids_inner<B>(
  req_or_res: &RequestOrResponse<B>,
) -> HyperSigResult<IndexMap<SignatureName, (Option<AlgorithmName>, Option<KeyId>)>> {
  let signature_headers_map = extract_signature_headers_with_name(req_or_res)?;
  let res = signature_headers_map
    .iter()
    .map(|(name, headers)| {
      // Unknown or unsupported algorithm strings are mapped to None
      let alg = headers
        .signature_params()
        .alg
        .clone()
        .map(|a| AlgorithmName::from_str(&a))
        .transpose()
        .ok()
        .flatten();
      let key_id = headers.signature_params().keyid.clone();
      (name.clone(), (alg, key_id))
    })
    .collect();
  Ok(res)
}

/// get signature params inner function
fn get_signature_params_inner<B>(
  req_or_res: &RequestOrResponse<B>,
) -> HyperSigResult<IndexMap<SignatureName, HttpSignatureParams>> {
  let signature_headers_map = extract_signature_headers_with_name(req_or_res)?;
  let res = signature_headers_map
    .iter()
    .map(|(name, headers)| (name.clone(), headers.signature_params().clone()))
    .collect();
  Ok(res)
}

/// extract signatures inner function
fn extract_signatures_inner<B1, B2>(
  req_or_res: &RequestOrResponse<B1>,
  req_for_param: Option<&Request<B2>>,
) -> HyperSigResult<IndexMap<SignatureName, (HttpSignatureBase, HttpSignatureHeaders)>> {
  let signature_headers_map = extract_signature_headers_with_name(req_or_res)?;
  let extracted = signature_headers_map
    .iter()
    .filter_map(|(name, headers)| {
      build_signature_base(req_or_res, headers.signature_params(), req_for_param)
        .ok()
        .map(|base| (name.clone(), (base, headers.clone())))
    })
    .collect();
  Ok(extracted)
}

/// Verify multiple signatures inner function
async fn verify_message_signatures_inner<T>(
  map_signature_with_base: &IndexMap<String, (HttpSignatureBase, HttpSignatureHeaders)>,
  key_and_id: &[(&T, Option<&str>)],
) -> HyperSigResult<Vec<HyperSigResult<SignatureName>>>
where
  T: VerifyingKey + Sync,
{
  // verify for each key_and_id tuple
  let res_fut = key_and_id.iter().map(|(key, key_id)| {
    let filtered = if let Some(key_id) = key_id {
      map_signature_with_base
        .iter()
        .filter(|(_, (base, _))| base.keyid() == Some(key_id))
        .collect::<IndexMap<_, _>>()
    } else {
      map_signature_with_base.iter().collect()
    };

    // check if any one of the signature headers is valid in async manner
    async move {
      if filtered.is_empty() {
        return Err(HyperSigError::NoSignatureHeaders(
          "No signature as appropriate target for verification".to_string(),
        ));
      }
      // check if any one of the signature headers is valid
      let successful_sig_names = filtered
        .iter()
        .filter_map(|(&name, (base, headers))| base.verify_signature_headers(*key, headers).ok().map(|_| name.clone()))
        .collect::<IndexSet<_>>();
      if !successful_sig_names.is_empty() {
        Ok(successful_sig_names.first().unwrap().clone())
      } else {
        Err(HyperSigError::InvalidSignature(
          "Invalid signature for the verifying key".to_string(),
        ))
      }
    }
  });
  let res = futures::future::join_all(res_fut).await;
  Ok(res)
}

/* --------------------------------------- */

/// A type to represent either http request or response
enum RequestOrResponse<'a, B> {
  Request(&'a Request<B>),
  Response(&'a Response<B>),
}

impl<B> RequestOrResponse<'_, B> {
  fn method(&self) -> HyperSigResult<&http::Method> {
    match self {
      RequestOrResponse::Request(req) => Ok(req.method()),
      _ => Err(HyperSigError::InvalidComponentName(
        "`method` is only for request".to_string(),
      )),
    }
  }

  fn uri(&self) -> HyperSigResult<&http::Uri> {
    match self {
      RequestOrResponse::Request(req) => Ok(req.uri()),
      _ => Err(HyperSigError::InvalidComponentName("`uri` is only for request".to_string())),
    }
  }

  fn headers(&self) -> &HeaderMap {
    match self {
      RequestOrResponse::Request(req) => req.headers(),
      RequestOrResponse::Response(res) => res.headers(),
    }
  }

  fn status(&self) -> HyperSigResult<http::StatusCode> {
    match self {
      RequestOrResponse::Response(res) => Ok(res.status()),
      _ => Err(HyperSigError::InvalidComponentName(
        "`status` is only for response".to_string(),
      )),
    }
  }
}

/// Extract signature and signature-input with signature-name indication from http request and response
fn extract_signature_headers_with_name<B>(req_or_res: &RequestOrResponse<B>) -> HyperSigResult<HttpSignatureHeadersMap> {
  let headers = req_or_res.headers();
  if !(headers.contains_key("signature-input") && headers.contains_key("signature")) {
    return Err(HyperSigError::NoSignatureHeaders(
      "The request does not have signature and signature-input headers".to_string(),
    ));
  };

  let signature_input_strings = headers
    .get_all("signature-input")
    .iter()
    .map(|v| v.to_str())
    .collect::<Result<Vec<_>, _>>()?
    .join(", ");
  let signature_strings = headers
    .get_all("signature")
    .iter()
    .map(|v| v.to_str())
    .collect::<Result<Vec<_>, _>>()?
    .join(", ");

  let signature_headers = HttpSignatureHeaders::try_parse(&signature_strings, &signature_input_strings)?;
  Ok(signature_headers)
}

/// Build signature base from hyper http request/response and signature params
/// - req_or_res: the hyper http request or response
/// - signature_params: the http signature params
/// - req_for_param: corresponding request to be considered in the signature base in response
fn build_signature_base<B1, B2>(
  req_or_res: &RequestOrResponse<B1>,
  signature_params: &HttpSignatureParams,
  req_for_param: Option<&Request<B2>>,
) -> HyperSigResult<HttpSignatureBase> {
  let component_lines = signature_params
    .covered_components
    .iter()
    .map(|component_id| {
      if component_id.params.0.contains(&HttpMessageComponentParam::Req) {
        if matches!(req_or_res, RequestOrResponse::Request(_)) {
          return Err(HyperSigError::InvalidComponentParam(
            "`req` is not allowed in request".to_string(),
          ));
        }
        if req_for_param.is_none() {
          return Err(HyperSigError::InvalidComponentParam(
            "`req` is required for the param".to_string(),
          ));
        }
        let req = RequestOrResponse::Request(req_for_param.unwrap());
        extract_http_message_component(&req, component_id)
      } else {
        extract_http_message_component(req_or_res, component_id)
      }
    })
    .collect::<Result<Vec<_>, _>>()?;

  HttpSignatureBase::try_new(&component_lines, signature_params).map_err(|e| e.into())
}

/// Extract http field from hyper http request/response
fn extract_http_field<B>(req_or_res: &RequestOrResponse<B>, id: &HttpMessageComponentId) -> HyperSigResult<HttpMessageComponent> {
  let HttpMessageComponentName::HttpField(header_name) = &id.name else {
    return Err(HyperSigError::InvalidComponentName(
      "invalid http message component name as http field".to_string(),
    ));
  };
  let headers = match req_or_res {
    RequestOrResponse::Request(req) => req.headers(),
    RequestOrResponse::Response(res) => res.headers(),
  };

  let field_values = headers
    .get_all(header_name)
    .iter()
    .map(|v| v.to_str().map(|s| s.to_owned()))
    .collect::<Result<Vec<_>, _>>()?;

  HttpMessageComponent::try_from((id, field_values.as_slice())).map_err(|e| e.into())
}

/// Extract derived component from hyper http request/response
fn extract_derived_component<B>(
  req_or_res: &RequestOrResponse<B>,
  id: &HttpMessageComponentId,
) -> HyperSigResult<HttpMessageComponent> {
  let HttpMessageComponentName::Derived(derived_id) = &id.name else {
    return Err(HyperSigError::InvalidComponentName(
      "invalid http message component name as derived component".to_string(),
    ));
  };
  // Validate parameters allowed on derived components (RFC 9421).
  // - `name`: only valid on `@query-param`
  // - `req`: only valid on response messages (to reference request-derived components, §2.4)
  // - `sf`, `key`, `bs`, `tr`: only valid on HTTP field components, not derived components
  id.params.0.iter().try_for_each(|param| match param {
    HttpMessageComponentParam::Name(_) if matches!(derived_id, DerivedComponentName::QueryParam) => Ok(()),
    HttpMessageComponentParam::Name(_) => Err(HyperSigError::InvalidComponentParam(
      "`name` parameter is only allowed for `@query-param`".to_string(),
    )),
    // `req` is only meaningful in response signatures (RFC 9421 §2.4).
    // `build_signature_base` already validates this and re-dispatches extraction against the
    // original request, so `req_or_res` here should always be `Request`.
    // Guard against misuse by callers that bypass `build_signature_base`.
    HttpMessageComponentParam::Req if matches!(req_or_res, RequestOrResponse::Request(_)) => Ok(()),
    HttpMessageComponentParam::Req => Err(HyperSigError::InvalidComponentParam(
      "`req`-tagged component must be extracted from the source request".to_string(),
    )),
    _ => Err(HyperSigError::InvalidComponentParam(format!(
      "parameter `{}` is not allowed on derived components",
      String::from(param.clone())
    ))),
  })?;

  match req_or_res {
    RequestOrResponse::Request(_) => {
      if matches!(derived_id, DerivedComponentName::Status) {
        return Err(HyperSigError::InvalidComponentName(
          "`status` is only for response".to_string(),
        ));
      }
    }
    RequestOrResponse::Response(_) => {
      let has_req = id.params.0.contains(&HttpMessageComponentParam::Req);
      // Response messages can use `@status` and `@signature-params` directly,
      // or any request-derived component with the `req` parameter (RFC 9421 §2.4).
      if !matches!(derived_id, DerivedComponentName::Status)
        && !matches!(derived_id, DerivedComponentName::SignatureParams)
        && !has_req
      {
        return Err(HyperSigError::InvalidComponentName(
          "derived components other than `@status` and `@signature-params` require `req` parameter for response".to_string(),
        ));
      }
      // `@status` must not have `req` parameter
      if matches!(derived_id, DerivedComponentName::Status) && has_req {
        return Err(HyperSigError::InvalidComponentParam(
          "`@status` does not accept `req` parameter".to_string(),
        ));
      }
    }
  }

  let field_values: Vec<String> = match derived_id {
    DerivedComponentName::Method => vec![req_or_res.method()?.as_str().to_string()],
    DerivedComponentName::TargetUri => vec![req_or_res.uri()?.to_string()],
    DerivedComponentName::Authority => vec![req_or_res.uri()?.authority().map(|s| s.to_string()).unwrap_or("".to_string())],
    DerivedComponentName::Scheme => vec![req_or_res.uri()?.scheme_str().unwrap_or("").to_string()],
    DerivedComponentName::RequestTarget => match *req_or_res.method()? {
      http::Method::CONNECT => vec![req_or_res.uri()?.authority().map(|s| s.to_string()).unwrap_or("".to_string())],
      http::Method::OPTIONS => vec!["*".to_string()],
      _ => vec![req_or_res
        .uri()?
        .path_and_query()
        .map(|s| s.to_string())
        .unwrap_or("".to_string())],
    },
    DerivedComponentName::Path => vec![{
      let p = req_or_res.uri()?.path();
      if p.is_empty() {
        "/".to_string()
      } else {
        p.to_string()
      }
    }],
    DerivedComponentName::Query => vec![req_or_res.uri()?.query().map(|v| format!("?{v}")).unwrap_or("?".to_string())],
    DerivedComponentName::QueryParam => {
      let query = req_or_res.uri()?.query().unwrap_or("");
      query
        .split('&')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect::<Vec<_>>()
    }
    DerivedComponentName::Status => vec![req_or_res.status()?.as_str().to_string()],
    DerivedComponentName::SignatureParams => req_or_res
      .headers()
      .get_all("signature-input")
      .iter()
      .map(|v| v.to_str().unwrap_or("").to_string())
      .collect::<Vec<_>>(),
  };

  HttpMessageComponent::try_from((id, field_values.as_slice())).map_err(|e| e.into())
}

/* --------------------------------------- */
/// Extract http message component from hyper http request
fn extract_http_message_component<B>(
  req_or_res: &RequestOrResponse<B>,
  target_component_id: &HttpMessageComponentId,
) -> HyperSigResult<HttpMessageComponent> {
  match &target_component_id.name {
    HttpMessageComponentName::HttpField(_) => extract_http_field(req_or_res, target_component_id),
    HttpMessageComponentName::Derived(_) => extract_derived_component(req_or_res, target_component_id),
  }
}

/* --------------------------------------- */
#[cfg(test)]
#[path = "hyper_http_tests.rs"]
mod tests;