-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathvangoh_test.go
740 lines (605 loc) · 21.2 KB
/
vangoh_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
package vangoh
import (
"bytes"
"crypto"
_ "crypto/sha1"
"errors"
"fmt"
"hash"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func checkAlgorithm(vg *Vangoh, algo func() hash.Hash) bool {
vga := fmt.Sprintf("%T", vg.algorithm())
toCheck := fmt.Sprintf("%T", algo())
return vga == toCheck
}
func assertNilError(t *testing.T, a *AuthenticationError) {
if a != nil {
t.Errorf("Expected no error, instead received HTTP %d: %s", a.StatusCode(), a)
t.FailNow()
}
}
func assertError(t *testing.T, a *AuthenticationError, e *AuthenticationError) {
if a == nil {
t.Errorf("Expected an error with HTTP Status %d, but received no error", e.StatusCode())
t.FailNow()
}
if a != e {
t.Errorf(
"Expected an error with status HTTP %d, message '%s', but received HTTP %d, message '%s'", a.StatusCode(), a, e.StatusCode(), e)
t.FailNow()
}
}
type testProvider struct {
promptErr bool
key []byte
secret []byte
}
func (tp *testProvider) GetSecret(key []byte) ([]byte, error) {
if tp.promptErr {
return nil, errors.New("testing error")
}
if !bytes.Equal(tp.key, key) {
return nil, nil
}
return tp.secret, nil
}
type testCallbackProvider struct {
promptErr bool
key []byte
secret []byte
modifyCallbackPayload bool
T *testing.T
}
type testCallbackData struct{ Value string }
var testCallbackValue = "testcallbackvalue"
func (tcp *testCallbackProvider) GetSecret(key []byte, cbPayload *CallbackPayload) ([]byte, error) {
if tcp.promptErr {
return nil, errors.New("testing error")
}
if !bytes.Equal(tcp.key, key) {
return nil, nil
}
if cbPayload.GetPayload() != nil {
tcp.T.Error("Expected to be passed a nil cbPayload.")
tcp.T.FailNow()
}
if tcp.modifyCallbackPayload {
cbPayload.SetPayload(&testCallbackData{Value: testCallbackValue})
}
return tcp.secret, nil
}
func (tcp *testCallbackProvider) SuccessCallback(r *http.Request, cbPayload *CallbackPayload) {
if tcp.modifyCallbackPayload && cbPayload.GetPayload() == nil {
tcp.T.Error("Expected to be passed a valid cbPayload.")
tcp.T.FailNow()
}
if !tcp.modifyCallbackPayload && cbPayload.GetPayload() != nil {
tcp.T.Error("Expected to be passed a nil cbPayload.")
tcp.T.FailNow()
}
payload := cbPayload.GetPayload()
if payload != nil {
data, ok := payload.(*testCallbackData)
if !ok {
tcp.T.Error("Expected callback payload to cast to testCallbackData")
tcp.T.FailNow()
}
if data.Value != testCallbackValue {
tcp.T.Error("Expected to unpack the test callback value.")
tcp.T.FailNow()
}
}
}
var awsOrg = "AWS"
var awsKey = []byte("AKIAIOSFODNN7EXAMPLE")
var awsSecret = []byte("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
var tp1 = &testProvider{
promptErr: false,
key: []byte("testIDOne"),
secret: []byte("secretOne"),
}
var tp2 = &testProvider{
promptErr: false,
key: []byte("testIDTwo"),
secret: []byte("secretTwo"),
}
var tpErr = &testProvider{
promptErr: true,
key: []byte("testIDErr"),
secret: []byte("secretErr"),
}
var awsExampleProvider = &testProvider{
promptErr: false,
key: awsKey,
secret: awsSecret,
}
func TestNew(t *testing.T) {
vg := New()
if vg.includedHeaders == nil {
t.Error("includeHeaders not properly intialized")
}
if vg.providersByOrg == nil {
t.Error("providersByOrg not properly intialized")
}
if vg.singleProvider != nil {
t.Error("default constructor should not create a single provider instance")
}
if !checkAlgorithm(vg, crypto.SHA256.New) {
t.Error("default constructor should instantiate the algorithm to SHA256")
}
}
func TestIncludeHeader(t *testing.T) {
// Valid regex with ^ and $ should succeed unchanged.
vg := New()
valid := "^example$"
vg.IncludeHeader(valid)
if _, found := vg.includedHeaders[valid]; !found {
t.Error("Valid regex was not left unmodified.")
}
// Valid regex without ^ should be fixed to include it.
missingLeadingAnchor := "example$"
vg = New()
vg.IncludeHeader(missingLeadingAnchor)
if _, found := vg.includedHeaders[missingLeadingAnchor]; found {
t.Error("Regex without anchor prefix was not left unmodified.")
}
if _, found := vg.includedHeaders[valid]; !found {
t.Error("Regex without anchor prefix was not fixed correctly.")
}
// Valid regex without $ should be fixed to include it.
missingTrailingAnchor := "^example"
vg = New()
vg.IncludeHeader(missingTrailingAnchor)
if _, found := vg.includedHeaders[missingTrailingAnchor]; found {
t.Error("Regex without anchor suffix was not left unmodified.")
}
if _, found := vg.includedHeaders[valid]; !found {
t.Error("Regex without anchor suffix was not fixed correctly.")
}
// Invalid regex should return an error after compilation fails.
invalidRegex := "^($"
vg = New()
err := vg.IncludeHeader(invalidRegex)
if err == nil {
t.Error("Invalid regex should return an error when compilation fails.")
}
if len(vg.includedHeaders) != 0 {
t.Error("Invalid regex should not result in any addition to includedHeaders.")
}
// Multiple matching regexes should not result in a header being added to the
// signing string multiple times.
vg = NewSingleProvider(awsExampleProvider)
regexA := "^X-.*$" // Matches X-Test.
err = vg.IncludeHeader(regexA)
if err != nil {
t.Error("Error adding valid header regex " + regexA)
t.FailNow()
}
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
req.Header.Set("X-Test", "foo")
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
// Add a new header regex, so that there are two regexes that match the same
// header, and try authenticating request with the exact same signature hash.
// This should succeed because the signing bodies should be the same.
regexB := "^X-T.*$" // Matches X-Test.
err = vg.IncludeHeader(regexB)
if err != nil {
t.Error("Error adding valid header regex " + regexB)
t.FailNow()
}
authErr = vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestNewSingleProvider(t *testing.T) {
vg := NewSingleProvider(tp1)
if vg.includedHeaders == nil {
t.Error("includeHeaders not properly intialized")
}
if vg.providersByOrg == nil {
t.Error("providersByOrg not properly intialized")
}
if vg.singleProvider == nil {
t.Error("singleProvider constructor should create a single provider instance")
}
}
func TestAddProvider(t *testing.T) {
vg := New()
if len(vg.providersByOrg) != 0 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
err := vg.AddProvider("test", tp1)
if err != nil {
t.Error("Should not have encountered error when adding a new provider")
}
if len(vg.providersByOrg) != 1 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
err = vg.AddProvider("test", tp2)
if err == nil {
t.Error("Should error when trying to add multiple providers for same org tag")
}
if len(vg.providersByOrg) != 1 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
err = vg.AddProvider("notTest", tp2)
if err != nil {
t.Error("Should not error when trying to add multiple providers for different org tags")
}
if len(vg.providersByOrg) != 2 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
spvg := NewSingleProvider(tp1)
if len(spvg.providersByOrg) != 0 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
err = spvg.AddProvider("test", tp2)
if err == nil {
t.Error("Should error when trying to add second provider to single provider instance")
}
if len(spvg.providersByOrg) != 0 {
t.Error("Wrong number of key providers in the Vangoh instance")
}
}
func TestAlgorithm(t *testing.T) {
vg := New()
if !checkAlgorithm(vg, crypto.SHA256.New) {
t.Error("default constructor should instantiate the algorithm to SHA256")
}
vg.SetAlgorithm(crypto.SHA1.New)
if !checkAlgorithm(vg, crypto.SHA1.New) {
t.Error("Algorithm not correctly updated with SetAlgorithm method")
}
}
func TestAuthHeaderMissingFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
// No authorizaiton header is added.
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorAuthHeaderMissing)
}
func TestAuthHeaderMalformedFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
// Add malformed header.
req.Header.Set("Authorization", "wooo ORG KEY:SECRET")
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorAuthHeaderMalformed)
}
func TestProviderWithErrorFails(t *testing.T) {
vg := NewSingleProvider(tpErr)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorInProviderKeyLookup)
}
func TestCallbackProviderWithErrorFails(t *testing.T) {
var tcpErr = &testCallbackProvider{
promptErr: true,
key: awsKey,
secret: awsSecret,
modifyCallbackPayload: true,
T: t,
}
vg := NewSingleProvider(tcpErr)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorInProviderKeyLookup)
}
func TestCallbackProviderMissingSecret(t *testing.T) {
var tcp = &testCallbackProvider{
promptErr: false,
key: []byte("NOTTHERIGHTKEY"),
secret: []byte("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"),
modifyCallbackPayload: true,
T: t,
}
vg := NewSingleProvider(tcp)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorSecretNotFound)
}
func TestCallbackProviderSucceedsWithoutModifyingPtr(t *testing.T) {
var tcp = &testCallbackProvider{
promptErr: false,
key: []byte(awsKey),
secret: []byte("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"),
modifyCallbackPayload: false,
T: t,
}
vg := NewSingleProvider(tcp)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestCallbackProviderSucceeds(t *testing.T) {
var tcp = &testCallbackProvider{
promptErr: false,
key: []byte(awsKey),
secret: []byte("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"),
modifyCallbackPayload: true,
T: t,
}
vg := NewSingleProvider(tcp)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestMissingProviderFails(t *testing.T) {
vg := New()
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorAuthOrgUnknown)
}
func TestNonSingleProviderSucceeds(t *testing.T) {
vg := New()
vg.AddProvider("AWS", awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestGetSucceedsWithCorrectSignature(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestGetFailsWithIncorrectSignature(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
validSignature := vg.ConstructBase64Signature(req, awsExampleProvider.secret)
invalidSignature := "aaaa" + validSignature
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:"+invalidSignature)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorHMACSignatureMismatch)
}
func TestAwsPut(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("PUT", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
req.Header.Set("Content-Type", "image/jpeg")
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestAwsPutFail(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("PUT", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
req.Header.Set("Content-Type", "image/jpeg")
// This signature is invalid.
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:NyyxeRY7whkBe+bq8fHCL/2kKUg=")
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorHMACSignatureMismatch)
}
func TestAwsUpload(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
vg.IncludeHeader("^X-Amz-.*")
req, _ := http.NewRequest("PUT", "/static.johnsmith.net/db-backup.dat.gz", nil)
AddDateHeader(req)
req.Header.Set("Content-MD5", "4gJE4saaMU4BqNR0kLY+lw==")
req.Header.Set("Content-Type", "application/x-download")
// Custom Headers
req.Header.Set("X-Amz-Acl", "public-read")
req.Header.Set("X-Amz-Meta-ReviewedBy", "joe@johnsmith.net")
req.Header.Add("X-Amz-Meta-ReviewedBy", "jane@johnsmith.net")
req.Header.Set("X-Amz-Meta-FileChecksum", "0x02661779")
req.Header.Set("X-Amz-Meta-ChecksumAlgorithm", "crc32")
req.Header.Set("Content-Disposition", "attachment; filename=database.dat")
req.Header.Set("Content-Encoding", "gzip")
req.Header.Set("Content-Length", "5913339")
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestAwsUploadFail(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("PUT", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
req.Header.Set("Content-Type", "image/jpeg")
// This signature is invalid.
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:NyyxeRY7whkBe+bq8fHCL/2kKUg=")
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorHMACSignatureMismatch)
}
func TestDateInBoundsSucceeds(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
timeSkew := time.Minute * 30
vg.SetMaxTimeSkew(timeSkew)
// Mock clock.Now().
present := time.Now()
clock.Now = func() time.Time {
return present
}
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
tooOld := present.Add(-1 * (timeSkew - time.Second))
req.Header.Set("Date", tooOld.UTC().Format(time.RFC1123Z))
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestDateMissingFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
vg.SetMaxTimeSkew(time.Minute * 30)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorDateHeaderMissing)
}
func TestDateTooOldFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
timeSkew := time.Minute * 30
vg.SetMaxTimeSkew(timeSkew)
// Mock clock.Now().
present := time.Now()
clock.Now = func() time.Time {
return present
}
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
tooOld := present.Add(-1 * (time.Second + timeSkew))
req.Header.Set("Date", tooOld.UTC().Format(time.RFC1123Z))
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorDateHeaderTooSkewed)
}
func TestDateTooNewFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
maxTimeSkew := time.Minute * 15
vg.SetMaxTimeSkew(maxTimeSkew)
// Mock clock.Now().
present := time.Now()
clock.Now = func() time.Time {
return present
}
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
skewedDateStr := (present.Add(maxTimeSkew + time.Second)).UTC().Format(time.RFC1123Z)
req.Header.Set("Date", skewedDateStr)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorDateHeaderTooSkewed)
}
func TestDateMalformedFails(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
date, err := time.Parse(time.RFC1123Z, "Tue, 27 Mar 2007 19:36:42 +0000")
if err != nil {
t.Error("Date couldn't be parsed")
}
skew := time.Now().Sub(date) + (time.Second * 10)
vg.SetMaxTimeSkew(skew)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
req.Header.Set("Date", "2007-03-27T19:36:42Z00:00") // RFC 3339 - not supported
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:bWq2s1WEIj+Ydj0vQ697zp+IXMU=")
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorDateHeaderMalformed)
}
func TestCustomDate(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
vg.SetCustomDateHeader("X-AWS-Date")
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddCustomDateHeader(req, "X-AWS-Date")
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestCustomDateFallback(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
vg.SetCustomDateHeader("X-AWS-Date")
vg2 := NewSingleProvider(awsExampleProvider)
vg2.SetAlgorithm(crypto.SHA1.New)
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg2, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertNilError(t, authErr)
}
func TestCustomDateMissingAllDates(t *testing.T) {
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
vg.SetCustomDateHeader("X-AWS-Date")
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
authErr := vg.AuthenticateRequest(req)
assertError(t, authErr, ErrorDateHeaderMissing)
}
func TestHandler(t *testing.T) {
// Check that successfully authenticated requests reach the inner handler.
testHandlerEntered := false
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
testHandlerEntered = true
w.WriteHeader(http.StatusOK)
})
vg := NewSingleProvider(awsExampleProvider)
vg.SetAlgorithm(crypto.SHA1.New)
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
AddAuthorizationHeader(vg, req, awsOrg, awsKey, awsSecret)
vg.Handler(testHandler).ServeHTTP(resp, req)
if !(testHandlerEntered && resp.Code == http.StatusOK) {
t.Error("Request should have succeeded.")
t.FailNow()
}
// Check that badly authenticated requests never reach the inner handler.
brokenHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Error("Handler should never be reached.")
t.FailNow()
})
resp = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
validSignature := vg.ConstructBase64Signature(req, awsExampleProvider.secret)
invalidSignature := "aaaa" + validSignature
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:"+invalidSignature)
vg.Handler(brokenHandler).ServeHTTP(resp, req)
if resp.Code != http.StatusForbidden {
t.Error("Success should have failed.")
t.FailNow()
}
// Check that debug mode sets an error message in the response body.
resp = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/johnsmith/photos/puppy.jpg", nil)
AddDateHeader(req)
validSignature = vg.ConstructBase64Signature(req, awsExampleProvider.secret)
invalidSignature = "aaaa" + validSignature
req.Header.Set("Authorization", "AWS AKIAIOSFODNN7EXAMPLE:"+invalidSignature)
vg.SetDebug(true)
vg.Handler(brokenHandler).ServeHTTP(resp, req)
if resp.Code != http.StatusForbidden {
t.Error("Success should have failed.")
t.FailNow()
}
if _, found := resp.Header()["Content-Type"]; !found {
t.Error("Expected valid content-type header.")
t.FailNow()
}
if len(resp.Body.Bytes()) == 0 {
t.Error("Expected error description in body.")
t.FailNow()
}
}