-
Notifications
You must be signed in to change notification settings - Fork 2
/
signatures_test.go
2178 lines (1990 loc) · 89.7 KB
/
signatures_test.go
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
package httpsign
import (
"bufio"
"bytes"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"fmt"
"github.com/stretchr/testify/assert"
"net/http"
"strings"
"testing"
"time"
)
var httpreq1 = `POST /foo?param=value&pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Cache-Control: max-age=60
Cache-Control: must-revalidate
Content-Length: 18
{"hello": "world"}
`
var httpres1 = `HTTP/1.1 200 OK
Date: Tue, 20 Apr 2021 02:07:56 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Content-Length: 18
{"hello": "world"}
`
var httpreq1pssMinimal = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Content-Digest: sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:
Content-Length: 18
Signature-Input: sig-b21=();created=1618884473;keyid="test-key-rsa-pss";nonce="b3k2pp5k7z-50gnwp.yemd"
Signature: sig-b21=:d2pmTvmbncD3xQm8E9ZV2828BjQWGgiwAaw5bAkgibUopemLJcWDy/lkbbHAve4cRAtx31Iq786U7it++wgGxbtRxf8Udx7zFZsckzXaJMkA7ChG52eSkFxykJeNqsrWH5S+oxNFlD4dzVuwe8DhTSja8xxbR/Z2cOGdCbzR72rgFWhzx2VjBqJzsPLMIQKhO4DGezXehhWwE56YCE+O6c0mKZsfxVrogUvA4HELjVKWmAvtl6UnCh8jYzuVG5WSb/QEVPnP5TmcAnLH1g+s++v6d4s8m0gCw1fV5/SITLq9mhho8K3+7EPYTU8IU1bLhdxO5Nyt8C8ssinQ98Xw9Q==:
{"hello": "world"}
`
var httpreq1pssSelective = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Content-Digest: sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:
Content-Length: 18
Signature-Input: sig-b22=("@authority" "content-digest" "@query-param";name="Pet");created=1618884473;keyid="test-key-rsa-pss";tag="header-example"
Signature: sig-b22=:LjbtqUbfmvjj5C5kr1Ugj4PmLYvx9wVjZvD9GsTT4F7GrcQEdJzgI9qHxICagShLRiLMlAJjtq6N4CDfKtjvuJyE5qH7KT8UCMkSowOB4+ECxCmT8rtAmj/0PIXxi0A0nxKyB09RNrCQibbUjsLS/2YyFYXEu4TRJQzRw1rLEuEfY17SARYhpTlaqwZVtR8NV7+4UKkjqpcAoFqWFQh62s7Cl+H2fjBSpqfZUJcsIk4N6wiKYd4je2U/lankenQ99PZfB4jY3I5rSV2DSBVkSFsURIjYErOs0tFTQosMTAoxk//0RoKUqiYY8Bh0aaUEb0rQl3/XaVe4bXTugEjHSw==:
{"hello": "world"}
`
var httpreq1pssSelectiveBad = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Cache-Control: max-age=60
Cache-Control: must-revalidate
Content-Length: 18
Signature-Input: sig1=("@authority" "content-type");created=1618884475;keyid="test-key-rsa-pss"
Signature: sig1=:badbadik+OtGmM/kFqENDf9Plm8AmPtqtC7C9a+zYSaxr58b/E6h81ghJS3PcH+m1asiMp8yvccnO/RfaexnqanVB3C72WRNZN7skPTJmUVmoIeqZncdP2mlfxlLP6UbkrgYsk91NS6nwkKC6RRgLhBFqzP42oq8D2336OiQPDAo/04SxZt4Wx9nDGuy2SfZJUhsJqZyEWRk4204x7YEB3VxDAAlVgGt8ewilWbIKKTOKp3ymUeQIwptqYwv0l8mN404PPzRBTpB7+HpClyK4CNp+SVv46+6sHMfJU4taz10s/NoYRmYCGXyadzYYDj0BYnFdERB6NblI/AOWFGl5Axhhmjg==:
{"hello": "world"}
`
var httpreq1pssFull = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Content-Digest: sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:
Content-Length: 18
Signature-Input: sig-b23=("date" "@method" "@path" "@query" "@authority" "content-type" "content-digest" "content-length");created=1618884473;keyid="test-key-rsa-pss"
Signature: sig-b23=:bbN8oArOxYoyylQQUU6QYwrTuaxLwjAC9fbY2F6SVWvh0yBiMIRGOnMYwZ/5MR6fb0Kh1rIRASVxFkeGt683+qRpRRU5p2voTp768ZrCUb38K0fUxN0O0iC59DzYx8DFll5GmydPxSmme9v6ULbMFkl+V5B1TP/yPViV7KsLNmvKiLJH1pFkh/aYA2HXXZzNBXmIkoQoLd7YfW91kE9o/CCoC1xMy7JA1ipwvKvfrs65ldmlu9bpG6A9BmzhuzF8Eim5f8ui9eH8LZH896+QIF61ka39VBrohr9iyMUJpvRX2Zbhl5ZJzSRxpJyoEZAFL2FUo5fTIztsDZKEgM4cUA==:
{"hello": "world"}
`
var httpreq1ed25519 = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Content-Digest: sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:
Content-Length: 18
Signature-Input: sig-b26=("date" "@method" "@path" "@authority" "content-type" "content-length");created=1618884473;keyid="test-key-ed25519"
Signature: sig-b26=:wqcAqbmYJ2ji2glfAMaRy4gruYYnx2nEFN2HN6jrnDnQCK1u02Gb04v9EDgwUPiu4A0w6vuQv5lIp5WPpBKRCw==:
{"hello": "world"}
`
var httpreq1p256 = `POST /foo?param=value&pet=dog HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Cache-Control: max-age=60
Cache-Control: must-revalidate
Content-Length: 18
Signature-Input: sig1=("content-type" "digest" "content-length");created=1618884475;keyid="test-key-ecc-p256"
Signature: sig1=:n8RKXkj0iseWDmC6PNSQ1GX2R9650v+lhbb6rTGoSrSSx18zmn6fPOtBx48/WffYLO0n1RHHf9scvNGAgGq52Q==:
{"hello": "world"}
`
var httpreq2 = `POST /foo?param=value&pet=dog&pet=snake&bar=baz HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Cache-Control: max-age=60
Cache-Control: must-revalidate
Content-Length: 18
{"hello": "world"}
`
var httpres2 = `HTTP/1.1 200 OK
Date: Tue, 20 Apr 2021 02:07:56 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Content-Length: 18
{"hello": "world"}
`
var httpreq3 = `POST /foo?param=value&pet=dog&pet=snake&bar=baz HTTP/1.1
Host: example.com
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
@Method: GET
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Cache-Control: max-age=60
Cache-Control: must-revalidate
Content-Length: 18
{"hello": "world"}
`
var httpres3 = `HTTP/1.1 200 OK
Date: Tue, 20 Apr 2021 02:07:56 GMT
Content-Type: application/json
Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=
Signature: sig7=:n8RKXkj0iseWDmC6PNSQ1GX2R9650v+lhbb6rTGoSrSSx18zmn6fPOtBx48/WffYLO0n1RHHf9scvNGAgGq52Q==:
Signature-Input: sig7=("content-type" "digest" "content-length");keyid="my-key"
Content-Length: 18
{"hello": "world"}
`
var httpres4 = `HTTP/1.1 200 OK
Date: Tue, 20 Apr 2021 02:07:56 GMT
Content-Type: application/json
Content-Digest: sha-512=:mEWXIS7MaLRuGgxOBdODa3xqM1XdEvxoYhvlCFJ41QJgJc4GTsPp29l5oGX69wWdXymyU0rjJuahq4l5aGgfLQ==:
Content-Length: 23
Signature-Input: sig-b24=("@status" "content-type" "content-digest" "content-length");created=1618884473;keyid="test-key-ecc-p256"
Signature: sig-b24=:wNmSUAhwb5LxtOtOpNa6W5xj067m5hFrj0XQ4fvpaCLx0NKocgPquLgyahnzDnDAUy5eCdlYUEkLIj+32oiasw==:
{"message": "good dog"}
`
var httpreqtlsproxy = `POST /foo?param=Value&Pet=dog HTTP/1.1
Host: service.internal.example
Date: Tue, 20 Apr 2021 02:07:55 GMT
Content-Type: application/json
Content-Length: 18
Client-Cert: :MIIBqDCCAU6gAwIBAgIBBzAKBggqhkjOPQQDAjA6MRswGQYDVQQKDBJMZXQncyBBdXRoZW50aWNhdGUxGzAZBgNVBAMMEkxBIEludGVybWVkaWF0ZSBDQTAeFw0yMDAxMTQyMjU1MzNaFw0yMTAxMjMyMjU1MzNaMA0xCzAJBgNVBAMMAkJDMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8YnXXfaUgmnMtOXU/IncWalRhebrXmckC8vdgJ1p5Be5F/3YC8OthxM4+k1M6aEAEFcGzkJiNy6J84y7uzo9M6NyMHAwCQYDVR0TBAIwADAfBgNVHSMEGDAWgBRm3WjLa38lbEYCuiCPct0ZaSED2DAOBgNVHQ8BAf8EBAMCBsAwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0RAQH/BBMwEYEPYmRjQGV4YW1wbGUuY29tMAoGCCqGSM49BAMCA0gAMEUCIBHda/r1vaL6G3VliL4/Di6YK0Q6bMjeSkC3dFCOOB8TAiEAx/kHSB4urmiZ0NX5r5XarmPk0wmuydBVoU4hBVZ1yhk=:
Signature-Input: ttrp=("@path" "@query" "@method" "@authority" "client-cert");created=1618884473;keyid="test-key-ecc-p256"
Signature: ttrp=:xVMHVpawaAC/0SbHrKRs9i8I3eOs5RtTMGCWXm/9nvZzoHsIg6Mce9315T6xoklyy0yzhD9ah4JHRwMLOgmizw==:
{"hello": "world"}`
var rsaPubKey = `
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAhAKYdtoeoy8zcAcR874L8cnZxKzAGwd7v36APp7Pv6Q2jdsPBRrw
WEBnez6d0UDKDwGbc6nxfEXAy5mbhgajzrw3MOEt8uA5txSKobBpKDeBLOsdJKFq
MGmXCQvEG7YemcxDTRPxAleIAgYYRjTSd/QBwVW9OwNFhekro3RtlinV0a75jfZg
kne/YiktSvLG34lw2zqXBDTC5NHROUqGTlML4PlNZS5Ri2U4aCNx2rUPRcKIlE0P
uKxI4T+HIaFpv8+rdV6eUgOrB2xeI1dSFFn/nnv5OoZJEIB+VmuKn3DCUcCZSFlQ
PSXSfBDiUGhwOw76WuSSsf1D4b/vLoJ10wIDAQAB
-----END RSA PUBLIC KEY-----
`
/*
var rsaPrvKey = `
-----BEGIN RSA PRIVATE KEY-----
MIIEqAIBAAKCAQEAhAKYdtoeoy8zcAcR874L8cnZxKzAGwd7v36APp7Pv6Q2jdsP
BRrwWEBnez6d0UDKDwGbc6nxfEXAy5mbhgajzrw3MOEt8uA5txSKobBpKDeBLOsd
JKFqMGmXCQvEG7YemcxDTRPxAleIAgYYRjTSd/QBwVW9OwNFhekro3RtlinV0a75
jfZgkne/YiktSvLG34lw2zqXBDTC5NHROUqGTlML4PlNZS5Ri2U4aCN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l3vJFwDmPuJM/PfxoPsJXhqczWOagmk
vXpY/uJsF3nGVtfuBUhXpISKfZAp4XPR1pQ4WgzPjY01C7c7X+clZRy616tL4J66
RC5qUJ35joz/0cqEmXtibz9wmJYXRuFq7uDtt6ygvQKBgQCMopIJCcH5+DmbXmyw
J8fxjxp8YpkEoFMtloaJ7lWHkiCUSWYCbGlvG1Nb1CoVqOuMffGXAZKAU9cw7YA2
cJQuDUjlA0haDD4W3IibLGbANw414qqpqRmo5kM6aMpnShGsvxpp/0+XKrfcwgiC
Ufa6y08wtZ/O7ZCBBbJTY90uqA==
-----END PRIVATE KEY-----
`
var rsaPSSPubKey = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr4tmm3r20Wd/PbqvP1s2
+QEtvpuRaV8Yq40gjUR8y2Rjxa6dpG2GXHbPfvMs8ct+Lh1GH45x28Rw3Ry53mm+
oAXjyQ86OnDkZ5N8lYbggD4O3w6M6pAvLkhk95AndTrifbIFPNU8PPMO7OyrFAHq
gDsznjPFmTOtCEcN2Z1FpWgchwuYLPL+Wokqltd11nqqzi+bJ9cvSKADYdUAAN5W
Utzdpiy6LbTgSxP7ociU4Tn0g5I6aDZJ7A8Lzo0KSyZYoA485mqcO0GVAdVw9lq4
aOT9v6d+nb4bnNkQVklLQ3fVAvJm+xdDOp9LCNCN48V2pnDOkFV6+U9nV5oyc6XI
2wIDAQAB
-----END PUBLIC KEY-----
`
// To generate the private key: openssl genpkey -algorithm RSA-PSS -outform PEM -out priv-op.key
var rsaPSSPrvKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADALBgkqhkiG9w0BAQoEggSqMIIEpgIBAAKCAQEAr4tmm3r20Wd/Pbqv
P1s2+QEtvpuRaV8Yq40gjUR8y2Rjxa6dpG2GXHbPfvMs8ct+Lh1GH45x28Rw3Ry5
3mm+oAXjyQ86OnDkZ5N8lYbggD4O3w6M6pAvLkhk95AndTrifbIFPN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SY8glSSHJwRAMog+hFGW1AYdt7w80XBAoGBAImR
NUugqapgaEA8TrFxkJmngXYaAqpA0iYRA7kv3S4QavPBUGtFJHBNULzitydkNtVZ
3w6hgce0h9YThTo/nKc+OZDZbgfN9s7cQ75x0PQCAO4fx2P91Q+mDzDUVTeG30mE
t2m3S0dGe47JiJxifV9P3wNBNrZGSIF3mrORBVNDAoGBAI0QKn2Iv7Sgo4T/XjND
dl2kZTXqGAk8dOhpUiw/HdM3OGWbhHj2NdCzBliOmPyQtAr770GITWvbAI+IRYyF
S7Fnk6ZVVVHsxjtaHy1uJGFlaZzKR4AGNaUTOJMs6NadzCmGPAxNQQOCqoUjn4XR
rOjr9w349JooGXhOxbu8nOxX
-----END RSA PRIVATE KEY-----
`
// Note: the private key from the draft is never used
var p256PubKey2 = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqIVYZVLCrPZHGHjP17CTW0/+D9Lf
w0EkjqF7xB4FivAxzic30tMM4GF+hR6Dxh71Z50VGGdldkkDXZCnTNnoXQ==
-----END PUBLIC KEY-----
`
var ed25519PrvKey = `-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIJ+DYvh6SEqVTm50DFtMDoQikTmiCqirVv9mWG9qfSnF
-----END PRIVATE KEY-----`
// Workaround, from https://go.dev/play/p/fIz218Lj2L0. Credit: Ryan Castner.
var oidRsaPss = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
var oidEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
func loadRSAPSSPrivateKey(pemEncodedPK string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemEncodedPK))
if block == nil {
return nil, fmt.Errorf("empty block")
}
// taken from crypto/x509/pkcs8.go
type pkcs8 struct {
Version int
Algo pkix.AlgorithmIdentifier
PrivateKey []byte
// optional attributes omitted.
}
var privKey pkcs8
if _, err := asn1.Unmarshal(block.Bytes, &privKey); err != nil {
return nil, err
}
if privKey.Algo.Algorithm.Equal(oidRsaPss) {
rsaPrivKey, err := x509.ParsePKCS1PrivateKey(privKey.PrivateKey)
if err == nil {
return rsaPrivKey, nil
}
}
return nil, fmt.Errorf("unknown algorithm")
}
// This will work for PSS when crypto/x509 implements PKCS8 RSA-PSS keys
func parseRsaPrivateKeyFromPemStr(pemString string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemString))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM")
}
k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return k.(*rsa.PrivateKey), nil
}
func parseRsaPublicKeyFromPemStr(pemString string) (*rsa.PublicKey, error) {
block, _ := pem.Decode([]byte(pemString))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM")
}
k, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
return k.(*rsa.PublicKey), nil
}
func parseRsaPublicKey(pkey string) (*rsa.PublicKey, error) {
block, _ := pem.Decode([]byte(pkey))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM")
}
k, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, err
}
return k, nil
}
func parseECPublicKeyFromPemStr(pemString string) (*ecdsa.PublicKey, error) {
block, _ := pem.Decode([]byte(pemString))
if block == nil {
return nil, fmt.Errorf("cannot decode PEM")
}
k, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
return k.(*ecdsa.PublicKey), nil
}
func parseEdDSAPrivateKeyFromPemStr(pemEncodedPK string) (ed25519.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemEncodedPK))
if block == nil {
return nil, fmt.Errorf("empty block")
}
// taken from crypto/x509/pkcs8.go
type pkcs8 struct {
Version int
Algo pkix.AlgorithmIdentifier
SeedStructWrapper []byte
// optional attributes omitted.
}
type seedInner []byte // This appears to be an openssl bug: the seed octet string is wrapped
// inside another octet string
var privKey pkcs8
if _, err := asn1.Unmarshal(block.Bytes, &privKey); err != nil {
return nil, err
}
if !privKey.Algo.Algorithm.Equal(oidEd25519) {
return nil, fmt.Errorf("unknown algorithm")
}
var seed seedInner
_, err := asn1.Unmarshal(privKey.SeedStructWrapper, &seed) // double trouble
if err != nil {
return nil, fmt.Errorf("could not unmarshal inner asn.1 octet string")
}
if len(seed) != ed25519.SeedSize {
return nil, fmt.Errorf("seed is malformed")
}
prv := ed25519.NewKeyFromSeed(seed)
return prv, nil
}
func TestSignRequest(t *testing.T) {
type args struct {
signatureName string
signer Signer
req *http.Request
}
tests := []struct {
name string
args args
want string
want1 string
wantErr bool
}{
{
name: "test case B.2.5",
args: args{
signatureName: "sig-b25",
signer: (func() Signer {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884473).SetKeyID("test-shared-secret")
fields := Headers("date", "@authority", "content-type")
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
return *signer
})(),
req: readRequest(httpreq1),
},
want: "sig-b25=(\"date\" \"@authority\" \"content-type\");created=1618884473;keyid=\"test-shared-secret\"",
want1: "sig-b25=:pxcQw6G3AjtMBQjwo8XzkZf/bws5LelbaMk5rGIGtE8=:",
wantErr: false,
},
{
name: "missing derived field",
args: args{
signatureName: "sig1",
signer: (func() Signer {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-shared-secret")
fields := Headers("@authorityxx", "date", "content-type")
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
return *signer
})(),
req: readRequest(httpreq1),
},
want: "",
want1: "",
wantErr: true,
},
{
name: "missing header",
args: args{
signatureName: "sig1",
signer: (func() Signer {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-shared-secret")
fields := Headers("@authority", "date-not-really", "content-type")
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
return *signer
})(),
req: readRequest(httpreq1),
},
want: "",
want1: "",
wantErr: true,
},
{
name: "sign request: nil request",
args: args{
signatureName: "sig1",
signer: (func() Signer {
prvKey, err := loadRSAPSSPrivateKey(rsaPSSPrvKey)
if err != nil {
t.Errorf("cannot parse private key: %v", err)
}
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-key-rsa-pss")
fields := *NewFields()
signer, _ := NewRSAPSSSigner(*prvKey, config, fields)
return *signer
})(),
req: nil,
},
want: "",
want1: "",
wantErr: true,
},
{
name: "sign request: malicious request",
args: args{
signatureName: "sig1",
signer: makeRSAPSSSigner(t, *NewSignConfig().SignAlg(false).setFakeCreated(1618884475), *NewFields()),
req: readRequest(httpreq3),
},
want: "",
want1: "",
wantErr: true,
},
{
name: "sign request: empty sig name",
args: args{
signatureName: "",
signer: makeRSAPSSSigner(t, *NewSignConfig().SignAlg(false).setFakeCreated(1618884475), *NewFields()),
req: readRequest(httpreq1),
},
want: "",
want1: "",
wantErr: true,
},
{
name: "sign request: missing required field",
args: args{
signatureName: "sig1",
signer: makeRSAPSSSigner(t, *NewSignConfig().SignAlg(false).setFakeCreated(1618884475), *NewFields().AddHeader("Missing")),
req: readRequest(httpreq1),
},
want: "",
want1: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1, err := SignRequest(tt.args.signatureName, tt.args.signer, tt.args.req)
if (err != nil) != tt.wantErr {
t.Errorf("SignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("SignRequest() got = %v, want %v", got, tt.want)
}
if got1 != tt.want1 {
t.Errorf("SignRequest() got1 = %v, want %v", got1, tt.want1)
}
})
}
}
func makeRSAPSSSigner(t *testing.T, config SignConfig, fields Fields) Signer {
prvKey, err := loadRSAPSSPrivateKey(rsaPSSPrvKey)
assert.NoError(t, err, "cannot parse private key")
config.SetKeyID("test-key-rsa-pss")
signer, _ := NewRSAPSSSigner(*prvKey, &config, fields)
return *signer
}
func makeHMACSigner(config SignConfig, fields Fields) Signer {
config.SetKeyID("test-key-hmac")
signer, _ := NewHMACSHA256Signer(bytes.Repeat([]byte{0x33}, 64), &config, fields)
return *signer
}
// Do not test for a particular signature: for non-deterministic methods
func TestSignRequestDiscardSig(t *testing.T) {
type args struct {
signatureName string
signer Signer
req *http.Request
}
tests := []struct {
name string
args args
want string
want1 string
wantErr bool
}{
{
name: "test case B.2.1 (partial)", // note: sig params are not in the same order as in the spec
args: args{
signatureName: "sig-b21",
signer: (func() Signer {
config := NewSignConfig().SignAlg(false).
setFakeCreated(1618884473).SetNonce("b3k2pp5k7z-50gnwp.yemd").SetKeyID("test-key-rsa-pss")
fields := *NewFields()
prvKey, err := loadRSAPSSPrivateKey(rsaPSSPrvKey)
if err != nil {
t.Errorf("cannot parse private key: %v", err)
}
signer, _ := NewRSAPSSSigner(*prvKey, config, fields)
return *signer
})(),
req: readRequest(httpreq1),
},
want: "sig-b21=();created=1618884473;nonce=\"b3k2pp5k7z-50gnwp.yemd\";keyid=\"test-key-rsa-pss\"",
want1: "",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1, err := SignRequest(tt.args.signatureName, tt.args.signer, tt.args.req)
if (err != nil) != tt.wantErr {
t.Errorf("SignRequest() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("SignRequest() got = %v, want %v", got, tt.want)
}
if got1 != tt.want1 && tt.want1 != "" { // some signatures are non-deterministic
t.Errorf("SignRequest() got1 = %v, want %v", got1, tt.want1)
}
})
}
}
func readRequest(s string) *http.Request {
in := strings.NewReader(s)
req, err := http.ReadRequest(bufio.NewReader(in))
_ = err
return req
}
func readRequestChunked(s string) *http.Request {
// Go replaces \n by CRLF automatically, but not for chunked encodings, so we do it manually
// We can't do this simple substitution by default because it would change message bodies
// For more details, see https://github.com/golang/go/issues/56835
in := strings.NewReader(strings.ReplaceAll(s, "\n", "\r\n"))
req, err := http.ReadRequest(bufio.NewReader(in))
_ = err
return req
}
func readResponse(s string) *http.Response {
in := strings.NewReader(strings.ReplaceAll(s, "\n", "\r\n"))
res, err := http.ReadResponse(bufio.NewReader(in), nil)
_ = err
return res
}
func TestSignAndVerifyHMAC(t *testing.T) {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-shared-secret")
fields := Headers("@authority", "date", "content-type")
signatureName := "sig1"
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
req := readRequest(httpreq1)
sigInput, sig, _ := SignRequest(signatureName, *signer, req)
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
verifier, err := NewHMACSHA256Verifier(key, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-shared-secret"), fields)
assert.NoError(t, err, "could not generate Verifier")
err = VerifyRequest(signatureName, *verifier, req)
assert.NoError(t, err, "verification error")
}
func TestSignAndVerifyHMACNoHeader(t *testing.T) {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-shared-secret")
fields := Headers("@authority", "content-type")
signatureName := "sig1"
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
req := readRequest(longReq1)
_, sig, err := SignRequest(signatureName, *signer, req)
assert.NoError(t, err, "failed to sign")
req.Header.Add("Signature", sig)
verifier, err := NewHMACSHA256Verifier(key, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-shared-secret"), fields)
assert.NoError(t, err, "could not generate Verifier")
err = VerifyRequest(signatureName, *verifier, req)
assert.Error(t, err, "verification should fail, header not found")
req = readRequest(longReq1)
sigInput, _, err := SignRequest(signatureName, *signer, req)
assert.NoError(t, err, "failed to sign")
req.Header.Add("Signature-Input", sigInput)
verifier, err = NewHMACSHA256Verifier(key, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-shared-secret"), fields)
assert.NoError(t, err, "could not generate Verifier")
err = VerifyRequest(signatureName, *verifier, req)
assert.Error(t, err, "verification should fail, header not found")
}
func TestSignAndVerifyHMACBad(t *testing.T) {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-shared-secret")
fields := Headers("@authority", "date", "content-type")
signatureName := "sig1"
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, config, fields)
req := readRequest(httpreq1)
sigInput, sig, _ := SignRequest(signatureName, *signer, req)
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
badkey := append(key, byte(0x77))
verifier, err := NewHMACSHA256Verifier(badkey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-shared-secret"), fields)
assert.NoError(t, err, "could not generate Verifier")
err = VerifyRequest(signatureName, *verifier, req)
assert.Error(t, err, "verification should have failed")
}
func TestCreated(t *testing.T) {
testOnceWithConfig := func(t *testing.T, createdTime int64, verifyConfig *VerifyConfig, wantSuccess bool) {
fields := Headers("@status", "date", "content-type")
signatureName := "sigres"
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signConfig := NewSignConfig().SignCreated(true).setFakeCreated(createdTime).SetKeyID("test-shared-secret")
signer, _ := NewHMACSHA256Signer(key, signConfig, fields)
res := readResponse(httpres2)
nowStr := time.Now().UTC().Format(http.TimeFormat)
res.Header.Set("Date", nowStr)
sigInput, sig, _ := SignResponse(signatureName, *signer, res, nil)
res2 := readResponse(httpres2)
res2.Header.Set("Date", nowStr)
res2.Header.Add("Signature", sig)
res2.Header.Add("Signature-Input", sigInput)
verifier, err := NewHMACSHA256Verifier(key, verifyConfig, fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyResponse(signatureName, *verifier, res2, nil)
if wantSuccess && err != nil {
t.Errorf("verification error: %s", err)
}
if !wantSuccess && err == nil {
t.Errorf("expected verification to fail")
}
}
testOnce := func(t *testing.T, createdTime int64, wantSuccess bool) {
testOnceWithConfig(t, createdTime, nil, wantSuccess)
}
now := time.Now().Unix() // the window is in ms, but "created" granularity is in sec!
testInWindow := func(t *testing.T) { testOnce(t, now, true) }
testOlder := func(t *testing.T) { testOnce(t, now-20_000, false) }
testNewer := func(t *testing.T) { testOnce(t, now+3_000, false) }
testOldWindow1 := func(t *testing.T) {
testOnceWithConfig(t, now-20_000, NewVerifyConfig().SetNotOlderThan(19_000*time.Second), false)
}
testOldWindow2 := func(t *testing.T) {
testOnceWithConfig(t, now-20_000, NewVerifyConfig().SetNotOlderThan(21_000*time.Second), true)
}
testNewWindow1 := func(t *testing.T) {
testOnceWithConfig(t, now+15_000, NewVerifyConfig().SetNotNewerThan(16_000*time.Second), true)
}
testNewWindow2 := func(t *testing.T) {
testOnceWithConfig(t, now+15_000, NewVerifyConfig().SetNotNewerThan(14_000*time.Second), false)
}
testDate := func(t *testing.T) {
testOnceWithConfig(t, now, NewVerifyConfig().SetVerifyDateWithin(100*time.Millisecond), true)
}
testDateFail := func(t *testing.T) {
testOnceWithConfig(t, now, NewVerifyConfig().SetVerifyCreated(false).SetVerifyDateWithin(100*time.Millisecond), false)
}
t.Run("in window", testInWindow)
t.Run("older", testOlder)
t.Run("newer", testNewer)
t.Run("older, smaller than window", testOldWindow1)
t.Run("older, larger than window", testOldWindow2)
t.Run("newer, smaller than window", testNewWindow1)
t.Run("newer, larger than window", testNewWindow2)
t.Run("verify Date header within window", testDate)
t.Run("verify logic requires to verify Created", testDateFail)
}
func TestSignAndVerifyResponseHMAC(t *testing.T) {
fields := Headers("@status", "date", "content-type")
signatureName := "sigres"
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
config := NewSignConfig().SetExpires(999).SetKeyID("test-shared-secret") // should have expired long ago (but will be ignored by verifier)
signer, _ := NewHMACSHA256Signer(key, config, fields) // default config
res := readResponse(httpres2)
sigInput, sig, _ := SignResponse(signatureName, *signer, res, nil)
res2 := readResponse(httpres2)
res2.Header.Add("Signature", sig)
res2.Header.Add("Signature-Input", sigInput)
verifier, err := NewHMACSHA256Verifier(key, NewVerifyConfig().SetRejectExpired(false).SetKeyID("test-shared-secret"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyResponse(signatureName, *verifier, res2, nil)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignAndVerifyRSAPSS(t *testing.T) {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-key-rsa-pss")
fields := Headers("@authority", "date", "content-type")
signatureName := "sig1"
prvKey, err := loadRSAPSSPrivateKey(rsaPSSPrvKey)
if err != nil {
t.Errorf("cannot read private key")
}
signer, _ := NewRSAPSSSigner(*prvKey, config, fields)
req := readRequest(httpreq1)
sigInput, sig, _ := SignRequest(signatureName, *signer, req)
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
pubKey, err := parseRsaPublicKeyFromPemStr(rsaPSSPubKey)
if err != nil {
t.Errorf("cannot read public key: %v", err)
}
verifier, err := NewRSAPSSVerifier(*pubKey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-key-rsa-pss"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyRequest(signatureName, *verifier, req)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignAndVerifyRSA(t *testing.T) {
config := NewSignConfig().SignAlg(false).setFakeCreated(1618884475).SetKeyID("test-key-rsa")
fields := Headers("@authority", "date", "content-type")
signatureName := "sig1"
prvKey, err := parseRsaPrivateKeyFromPemStr(rsaPrvKey2)
if err != nil {
t.Errorf("cannot read private key")
}
signer, _ := NewRSASigner(*prvKey, config, fields)
req := readRequest(httpreq1)
sigInput, sig, _ := SignRequest(signatureName, *signer, req)
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
pubKey, err := parseRsaPublicKeyFromPemStr(rsaPubKey2)
if err != nil {
t.Errorf("cannot read public key: %v", err)
}
verifier, err := NewRSAVerifier(*pubKey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-key-rsa"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyRequest(signatureName, *verifier, req)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignAndVerifyP256(t *testing.T) {
config := NewSignConfig().setFakeCreated(1618884475).SetKeyID("test-key-p256")
signatureName := "sig1"
prvKey, pubKey, err := genP256KeyPair()
if err != nil {
t.Errorf("cannot generate P-256 keypair")
}
fields := *NewFields().AddHeader("@method").AddHeader("Date").AddHeader("Content-Type").AddQueryParam("pet")
signer, _ := NewP256Signer(*prvKey, config, fields)
req := readRequest(httpreq2)
sigInput, sig, err := SignRequest(signatureName, *signer, req)
if err != nil {
t.Errorf("signature failed: %v", err)
}
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
verifier, err := NewP256Verifier(*pubKey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-key-p256"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyRequest(signatureName, *verifier, req)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignAndVerifyP384(t *testing.T) {
config := NewSignConfig().setFakeCreated(1618884475).SetKeyID("test-key-p384")
signatureName := "sig1"
prvKey, pubKey, err := genP384KeyPair()
if err != nil {
t.Errorf("cannot generate P-384 keypair")
}
fields := *NewFields().AddHeader("@method").AddHeader("Date").AddHeader("Content-Type").AddQueryParam("pet")
signer, _ := NewP384Signer(*prvKey, config, fields)
req := readRequest(httpreq2)
sigInput, sig, err := SignRequest(signatureName, *signer, req)
if err != nil {
t.Errorf("signature failed: %v", err)
}
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
verifier, err := NewP384Verifier(*pubKey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-key-p384"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyRequest(signatureName, *verifier, req)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignAndVerifyEdDSA(t *testing.T) {
pubKey1, prvKey1, err := ed25519.GenerateKey(nil) // Need some tweaking for RFC 8032 keys, see package doc
if err != nil {
t.Errorf("cannot generate keypair: %s", err)
}
config := NewSignConfig().setFakeCreated(1618884475).SetKeyID("test-key-ed25519")
fields := *NewFields().AddHeader("@method").AddHeader("Date").AddHeader("Content-Type").AddQueryParam("pet")
signer1, _ := NewEd25519Signer(prvKey1, config, fields)
signAndVerifyEdDSA(t, signer1, pubKey1, fields)
seed2 := make([]byte, ed25519.SeedSize)
_, err = rand.Read(seed2)
if err != nil {
t.Errorf("rand failed?")
}
config.SetKeyID("test-key-ed25519")
prvKey2 := ed25519.NewKeyFromSeed(seed2)
pubKey2 := prvKey2.Public().(ed25519.PublicKey)
signer2, _ := NewEd25519SignerFromSeed(seed2, config, fields)
signAndVerifyEdDSA(t, signer2, pubKey2, fields)
}
func signAndVerifyEdDSA(t *testing.T, signer *Signer, pubKey ed25519.PublicKey, fields Fields) {
signatureName := "sig1"
req := readRequest(httpreq2)
sigInput, sig, err := SignRequest(signatureName, *signer, req)
if err != nil {
t.Errorf("signature failed: %v", err)
}
req.Header.Add("Signature", sig)
req.Header.Add("Signature-Input", sigInput)
verifier, err := NewEd25519Verifier(pubKey, NewVerifyConfig().SetVerifyCreated(false).SetKeyID("test-key-ed25519"), fields)
if err != nil {
t.Errorf("could not generate Verifier: %s", err)
}
err = VerifyRequest(signatureName, *verifier, req)
if err != nil {
t.Errorf("verification error: %s", err)
}
}
func TestSignResponse(t *testing.T) {
type args struct {
signatureName string
signer Signer
res *http.Response
}
tests := []struct {
name string
args args
want string
want1 string
wantErr bool
}{
{
name: "test response with HMAC",
args: args{
signatureName: "sig1",
signer: (func() Signer {
key, _ := base64.StdEncoding.DecodeString("uzvJfB4u3N0Jy4T7NZ75MDVcr8zSTInedJtkgcu46YW4XByzNJjxBdtjUkdJPBtbmHhIDi6pcl8jsasjlTMtDQ==")
signer, _ := NewHMACSHA256Signer(key, NewSignConfig().setFakeCreated(1618889999).
SetKeyID("test-shared-secret"), Headers("@status", "date", "content-type"))
return *signer
})(),
res: readResponse(httpres1),
},
want: "sig1=(\"@status\" \"date\" \"content-type\");created=1618889999;alg=\"hmac-sha256\";keyid=\"test-shared-secret\"",
want1: "sig1=:5s7SCXZBsy7g/xqoFjVy+WWvWi4bb3G7bQoE+blEyz4=:",
wantErr: false,
},
{
name: "test response with HMAC: nil response",
args: args{
signatureName: "sig1",
signer: (func() Signer {