forked from cloudfoundry/log-cache-release
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuaa_client_test.go
More file actions
739 lines (587 loc) · 21.1 KB
/
Copy pathuaa_client_test.go
File metadata and controls
739 lines (587 loc) · 21.1 KB
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
package auth_test
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"strings"
"sync"
"time"
"code.cloudfoundry.org/go-metric-registry/testhelpers"
"code.cloudfoundry.org/log-cache/internal/auth"
"bytes"
"encoding/json"
"encoding/pem"
"net/http"
jose "github.com/dvsekhvalnov/jose2go"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("UAAClient", func() {
Context("HS256", func() {
It("accepts tokens that are signed with HS256", func() {
tc := uaaSetup(false)
tc.PrimePublicKeyCache(false)
payload := tc.BuildValidPayload("doppler.firehose")
token := tc.CreateHS256SignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(c.IsAdmin).To(BeTrue())
})
})
Context("Read()", func() {
var tc *UAATestContext
BeforeEach(func() {
tc = uaaSetup(true)
tc.PrimePublicKeyCache(true)
})
It("only accepts tokens that are signed with RS256", func() {
payload := tc.BuildValidPayload("doppler.firehose")
token := tc.CreateUnsignedToken(payload)
_, err := tc.uaaClient.Read(withBearer(token))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("failed to decode token: unsupported algorithm: none"))
})
It("rejects HS256 JWTs when UAA only published an RSA key for that kid (algorithm confusion)", func() {
kid := tc.privateKeys[0].keyId
header := fmt.Sprintf(`{"alg":"HS256","kid":%q}`, kid)
payload := `{"scope":["logs.admin"],"exp":9999999999}`
enc := base64.RawURLEncoding.EncodeToString
forged := enc([]byte(header)) + "." + enc([]byte(payload)) + "."
_, err := tc.uaaClient.Read(withBearer(forged))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to decode token"))
Expect(err.Error()).To(ContainSubstring("incompatible with UAA key material"))
})
It("returns IsAdmin == true when scopes include doppler.firehose", func() {
payload := tc.BuildValidPayload("doppler.firehose")
token := tc.CreateSignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(c.IsAdmin).To(BeTrue())
})
It("returns IsAdmin == true when scopes include logs.admin", func() {
payload := tc.BuildValidPayload("logs.admin")
token := tc.CreateSignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(c.IsAdmin).To(BeTrue())
})
It("returns IsAdmin == false when scopes include neither logs.admin nor doppler.firehose", func() {
payload := tc.BuildValidPayload("foo.bar")
token := tc.CreateSignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(c.IsAdmin).To(BeFalse())
})
It("returns context with correct ExpiresAt", func() {
t := time.Now().Add(time.Hour).Truncate(time.Second)
payload := fmt.Sprintf(`{"scope":["logs.admin"], "exp":%d}`, t.Unix())
token := tc.CreateSignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(c.ExpiresAt).To(Equal(t))
})
It("does offline token validation", func() {
initialRequestCount := len(tc.httpClient.requests)
payload := tc.BuildValidPayload("logs.admin")
token := tc.CreateSignedToken(payload)
_, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
_, err = tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount))
})
It("does not allow use of an expired token", func() {
tc.GenerateSingleTokenKeyResponse(true)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
expiredPayload := tc.BuildExpiredPayload("logs.Admin")
expiredToken := tc.CreateSignedToken(expiredPayload)
_, err = tc.uaaClient.Read(withBearer(expiredToken))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("token is expired"))
})
It("returns an error when token is blank", func() {
_, err := tc.uaaClient.Read("")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("missing token"))
})
Context("when a token is signed with a private key that is unknown", func() {
It("validates the token successfully when the matching public key can be retrieved from UAA", func() {
initialRequestCount := len(tc.httpClient.requests)
newPrivateKey := generateLegitTokenKey("testKey2")
tc.AddPrivateKeyToUAATokenKeyResponse(newPrivateKey)
payload := tc.BuildValidPayload("logs.admin")
token := tc.CreateSignedTokenUsingPrivateKey(payload, newPrivateKey)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
})
It("returns an error when the matching public key cannot be retrieved from UAA", func() {
initialRequestCount := len(tc.httpClient.requests)
newPrivateKey := generateLegitTokenKey("testKey2")
payload := tc.BuildValidPayload("logs.admin")
token := tc.CreateSignedTokenUsingPrivateKey(payload, newPrivateKey)
_, err := tc.uaaClient.Read(withBearer(token))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to decode token: using unknown token key"))
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
})
It("returns an error when given a token signed by an public key that was purged from UAA", func() {
initialRequestCount := len(tc.httpClient.requests)
payload := tc.BuildValidPayload("logs.admin")
tokenSignedWithExpiredPrivateKey := tc.CreateSignedToken(payload)
newAndOnlyPrivateKey := generateLegitTokenKey("testKey2")
tc.MockUAATokenKeyResponseUsingPrivateKey(newAndOnlyPrivateKey)
payload = tc.BuildValidPayload("logs.admin")
tokenSignedWithNewPrivateKey := tc.CreateSignedTokenUsingPrivateKey(payload, newAndOnlyPrivateKey)
_, err := tc.uaaClient.Read(withBearer(tokenSignedWithNewPrivateKey))
Expect(err).ToNot(HaveOccurred())
_, err = tc.uaaClient.Read(withBearer(tokenSignedWithExpiredPrivateKey))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to decode token: using unknown token key"))
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 2))
})
It("continues to accept previously signed tokens when retrieving public keys from UAA fails", func() {
initialRequestCount := len(tc.httpClient.requests)
payload := tc.BuildValidPayload("logs.admin")
toBeExpiredToken := tc.CreateSignedToken(payload)
_, err := tc.uaaClient.Read(withBearer(toBeExpiredToken))
Expect(err).ToNot(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount))
newTokenKey := generateLegitTokenKey("testKey2")
refreshedToken := tc.CreateSignedTokenUsingPrivateKey(payload, newTokenKey)
newTokenKey.publicKey = "corrupted public key"
tc.MockUAATokenKeyResponseUsingPrivateKey(newTokenKey)
_, err = tc.uaaClient.Read(withBearer(refreshedToken))
Expect(err).To(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
_, err = tc.uaaClient.Read(withBearer(toBeExpiredToken))
Expect(err).ToNot(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
})
})
It("returns an error when given a token signed by an unknown but valid key", func() {
initialRequestCount := len(tc.httpClient.requests)
unknownPrivateKey := generateLegitTokenKey("testKey99")
payload := tc.BuildValidPayload("logs.admin")
tokenSignedWithUnknownPrivateKey := tc.CreateSignedTokenUsingPrivateKey(payload, unknownPrivateKey)
_, err := tc.uaaClient.Read(withBearer(tokenSignedWithUnknownPrivateKey))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to decode token: using unknown token key"))
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
})
It("returns an error when the provided token cannot be decoded", func() {
_, err := tc.uaaClient.Read("any-old-token")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("failed to decode token"))
})
DescribeTable("handling the Bearer prefix in the Authorization header",
func(prefix string) {
payload := tc.BuildValidPayload("foo.bar")
token := tc.CreateSignedToken(payload)
c, err := tc.uaaClient.Read(withBearer(token))
Expect(err).ToNot(HaveOccurred())
Expect(c.Token).To(Equal(withBearer(token)))
},
Entry("Standard 'Bearer' prefix", "Bearer "),
Entry("Non-Standard 'bearer' prefix", "bearer "),
Entry("No prefix", ""),
)
})
Context("RefreshTokenKeys()", func() {
It("handles concurrent refreshes", func() {
tc := uaaSetup(true)
tc.GenerateSingleTokenKeyResponse(true)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
payload := tc.BuildValidPayload("logs.admin")
token := tc.CreateSignedToken(payload)
numRequests := len(tc.httpClient.requests)
var wg sync.WaitGroup
for n := 0; n < 4; n++ {
wg.Add(1)
//nolint:errcheck
go func(wg *sync.WaitGroup) {
tc.uaaClient.Read(withBearer(token))
tc.uaaClient.RefreshTokenKeys()
tc.uaaClient.Read(withBearer(token))
wg.Done()
}(&wg)
}
wg.Wait()
Expect(tc.httpClient.requests).To(HaveLen(numRequests + 4))
})
It("calls UAA correctly", func() {
tc := uaaSetup(true)
tc.GenerateSingleTokenKeyResponse(true)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
r := tc.httpClient.requests[0]
Expect(r.Method).To(Equal(http.MethodGet))
Expect(r.Header.Get("Content-Type")).To(Equal("application/json"))
Expect(r.URL.Path).To(Equal("/token_keys"))
// confirm that we're not using any authentication
_, _, ok := r.BasicAuth()
Expect(ok).To(BeFalse())
Expect(r.Body).To(BeNil())
})
It("calls UAA with basic auth", func() {
tc := uaaSetup(true, auth.WithBasicAuth("User", "Password"))
tc.GenerateSingleTokenKeyResponse(true)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
r := tc.httpClient.requests[0]
Expect(r.Method).To(Equal(http.MethodGet))
Expect(r.Header.Get("Content-Type")).To(Equal("application/json"))
Expect(r.URL.Path).To(Equal("/token_keys"))
// confirm that we're not using any authentication
user, password, ok := r.BasicAuth()
Expect(ok).To(BeTrue())
Expect(user).To(Equal("User"))
Expect(password).To(Equal("Password"))
})
It("returns an error when UAA cannot be reached", func() {
tc := uaaSetup(true)
tc.httpClient.resps = []response{{
err: errors.New("error!"),
}}
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
})
It("returns an error when UAA returns a non-200 response", func() {
tc := uaaSetup(true)
tc.httpClient.resps = []response{{
body: []byte{},
status: http.StatusUnauthorized,
}}
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
})
It("returns an error when the response from the UAA is malformed", func() {
tc := uaaSetup(true)
tc.httpClient.resps = []response{{
body: []byte("garbage"),
status: http.StatusOK,
}}
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
})
It("returns an error when the response from the UAA has an empty key", func() {
tc := uaaSetup(true)
tc.GenerateEmptyTokenKeyResponse()
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
})
It("returns an error when the response from the UAA has an unparsable PEM format", func() {
tc := uaaSetup(true)
tc.GenerateTokenKeyResponseWithInvalidPEM()
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("failed to parse PEM block containing the public key"))
})
It("returns an error when the response from the UAA has an invalid key format", func() {
tc := uaaSetup(true)
tc.GenerateTokenKeyResponseWithInvalidKey()
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("error parsing public key"))
})
It("overwrites a pre-existing keyId with the new key", func() {
tc := uaaSetup(true)
tc.PrimePublicKeyCache(true)
payload := tc.BuildValidPayload("doppler.firehose")
token := tc.CreateSignedToken(payload)
_, err := tc.uaaClient.Read(withBearer(token))
Expect(err).NotTo(HaveOccurred())
tokenKey := generateLegitTokenKey("testKey1")
tc.GenerateTokenKeyResponse(true, []mockTokenKey{tokenKey})
err = tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
_, err = tc.uaaClient.Read(withBearer(token))
Expect(err).To(HaveOccurred())
newToken := tc.CreateSignedTokenUsingPrivateKey(payload, tokenKey)
_, err = tc.uaaClient.Read(withBearer(newToken))
Expect(err).NotTo(HaveOccurred())
})
It("overwrites a pre-existing keyId with the new key", func() {
tc := uaaSetup(true)
tc.PrimePublicKeyCache(true)
payload := tc.BuildValidPayload("doppler.firehose")
token := tc.CreateSignedToken(payload)
_, err := tc.uaaClient.Read(withBearer(token))
Expect(err).NotTo(HaveOccurred())
tokenKey := generateLegitTokenKey("testKey1")
tc.GenerateTokenKeyResponse(true, []mockTokenKey{tokenKey})
newToken := tc.CreateSignedTokenUsingPrivateKey(payload, tokenKey)
Eventually(func() bool {
_, err = tc.uaaClient.Read(withBearer(newToken))
return err == nil
}).Should(BeTrue())
_, err = tc.uaaClient.Read(withBearer(token))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("crypto/rsa: verification error"))
})
It("rate limits UAA TokenKey refreshes", func() {
tc := uaaSetup(true, auth.WithMinimumRefreshInterval(200*time.Millisecond))
tc.GenerateSingleTokenKeyResponse(true)
initialRequestCount := len(tc.httpClient.requests)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
time.Sleep(100 * time.Millisecond)
err = tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 1))
time.Sleep(101 * time.Millisecond)
err = tc.uaaClient.RefreshTokenKeys()
Expect(err).To(HaveOccurred())
Expect(tc.httpClient.requests).To(HaveLen(initialRequestCount + 2))
})
})
})
type mockTokenKey struct {
privateKey string
publicKey string
keyId string
}
func generateLegitTokenKey(keyId string) mockTokenKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
publicKeyString, privateKeyString := keyPEMToString(privateKey)
return mockTokenKey{
privateKey: privateKeyString,
publicKey: publicKeyString,
keyId: keyId,
}
}
// func generateHSTokenKey(keyId string) mockTokenKey {
// privateKey := keyId
// return mockTokenKey{
// privateKey: privateKey,
// publicKey: privateKey,
// keyId: keyId,
// }
// }
func uaaSetup(rsa bool, opts ...auth.UAAOption) *UAATestContext {
httpClient := newSpyHTTPClient()
metrics := testhelpers.NewMetricsRegistry()
var tokenKey mockTokenKey
if rsa {
tokenKey = generateLegitTokenKey("testKey1")
} else {
tokenKey = mockTokenKey{
privateKey: "key",
publicKey: "key",
keyId: "key",
}
}
// default the minimumRefreshInterval in tests to 0, but make sure we
// apply user-provided options afterwards
opts = append([]auth.UAAOption{auth.WithMinimumRefreshInterval(0)}, opts...)
uaaClient := auth.NewUAAClient(
"https://uaa.com",
httpClient,
metrics,
log.New(io.Discard, "", 0),
opts...,
)
return &UAATestContext{
uaaClient: uaaClient,
httpClient: httpClient,
metrics: metrics,
privateKeys: []mockTokenKey{tokenKey},
}
}
type UAATestContext struct {
uaaClient *auth.UAAClient
httpClient *spyHTTPClient
metrics *testhelpers.SpyMetricsRegistry
privateKeys []mockTokenKey
}
func (tc *UAATestContext) PrimePublicKeyCache(rsa bool) {
tc.GenerateSingleTokenKeyResponse(rsa)
err := tc.uaaClient.RefreshTokenKeys()
Expect(err).ToNot(HaveOccurred())
}
func (tc *UAATestContext) BuildValidPayload(scope string) string {
t := time.Now().Add(time.Hour).Truncate(time.Second)
payload := fmt.Sprintf(`{"scope":["%s"], "exp":%d}`, scope, t.Unix())
return payload
}
func (tc *UAATestContext) BuildExpiredPayload(scope string) string {
t := time.Now().Add(-time.Minute)
payload := fmt.Sprintf(`{"scope":["%s"], "exp":%d}`, scope, t.Unix())
return payload
}
func (tc *UAATestContext) GenerateTokenKeyResponse(rsa bool, mockTokenKeys []mockTokenKey) {
var tokenKeys []map[string]string
var kty, alg string
if rsa {
kty = "RSA"
alg = "RSA256"
} else {
kty = "MAC"
alg = "HS256"
}
for _, mockPrivateKey := range mockTokenKeys {
tokenKey := map[string]string{
"kty": kty,
"use": "sig",
"kid": mockPrivateKey.keyId,
"alg": alg,
"value": mockPrivateKey.publicKey,
}
tokenKeys = append(tokenKeys, tokenKey)
}
data, err := json.Marshal(map[string][]map[string]string{
"keys": tokenKeys,
})
Expect(err).ToNot(HaveOccurred())
tc.httpClient.resps = []response{{
body: data,
status: http.StatusOK,
}}
}
func (tc *UAATestContext) GenerateSingleTokenKeyResponse(rsa bool) {
tc.GenerateTokenKeyResponse(
rsa,
[]mockTokenKey{
tc.privateKeys[0],
},
)
}
func (tc *UAATestContext) MockUAATokenKeyResponseUsingPrivateKey(tokenKey mockTokenKey) {
tc.GenerateTokenKeyResponse(
true,
[]mockTokenKey{
tokenKey,
},
)
}
func (tc *UAATestContext) AddPrivateKeyToUAATokenKeyResponse(tokenKey mockTokenKey) {
tc.GenerateTokenKeyResponse(
true,
[]mockTokenKey{
tokenKey,
tc.privateKeys[0],
},
)
}
func (tc *UAATestContext) GenerateEmptyTokenKeyResponse() {
tc.GenerateTokenKeyResponse(
true,
[]mockTokenKey{
{publicKey: "", keyId: ""},
},
)
}
func (tc *UAATestContext) GenerateTokenKeyResponseWithInvalidPEM() {
tc.GenerateTokenKeyResponse(
true,
[]mockTokenKey{
{publicKey: "-- BEGIN SOMETHING --\nNOTVALIDPEM\n-- END SOMETHING --\n", keyId: ""},
},
)
}
func (tc *UAATestContext) GenerateTokenKeyResponseWithInvalidKey() {
tc.GenerateTokenKeyResponse(
true,
[]mockTokenKey{
{publicKey: strings.Replace(tc.privateKeys[0].publicKey, "MIIB", "XXXX", 1), keyId: ""},
},
)
}
func (tc *UAATestContext) CreateSignedToken(payload string) string {
tokenKey := tc.privateKeys[0]
decode, _ := pem.Decode([]byte(tokenKey.privateKey))
privateKey, err := x509.ParsePKCS1PrivateKey(decode.Bytes)
Expect(err).ToNot(HaveOccurred())
token, err := jose.Sign(payload, jose.RS256, privateKey, jose.Header("kid", tokenKey.keyId))
Expect(err).ToNot(HaveOccurred())
return token
}
func (tc *UAATestContext) CreateHS256SignedToken(payload string) string {
tokenKey := tc.privateKeys[0]
token, err := jose.Sign(payload, jose.HS256, []byte(tokenKey.privateKey), jose.Header("kid", tokenKey.keyId))
Expect(err).ToNot(HaveOccurred())
return token
}
func (tc *UAATestContext) CreateSignedTokenUsingPrivateKey(payload string, tokenKey mockTokenKey) string {
decode, _ := pem.Decode([]byte(tokenKey.privateKey))
privateKey, err := x509.ParsePKCS1PrivateKey(decode.Bytes)
Expect(err).ToNot(HaveOccurred())
token, err := jose.Sign(payload, jose.RS256, privateKey, jose.Header("kid", tokenKey.keyId))
Expect(err).ToNot(HaveOccurred())
return token
}
func (tc *UAATestContext) CreateUnsignedToken(payload string) string {
token, err := jose.Sign(payload, jose.NONE, nil)
Expect(err).ToNot(HaveOccurred())
return token
}
type spyHTTPClient struct {
mu sync.Mutex
requests []*http.Request
resps []response
tokens []string
}
type response struct {
status int
err error
body []byte
}
func newSpyHTTPClient() *spyHTTPClient {
return &spyHTTPClient{}
}
func (s *spyHTTPClient) Do(r *http.Request) (*http.Response, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.requests = append(s.requests, r)
s.tokens = append(s.tokens, r.Header.Get("Authorization"))
if len(s.resps) == 0 {
return &http.Response{
StatusCode: http.StatusNotFound,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
}
result := s.resps[0]
s.resps = s.resps[1:]
resp := http.Response{
StatusCode: result.status,
Body: io.NopCloser(bytes.NewReader(result.body)),
}
if result.err != nil {
return nil, result.err
}
return &resp, nil
}
func keyPEMToString(privateKey *rsa.PrivateKey) (string, string) {
encodedKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
Expect(err).ToNot(HaveOccurred())
var pemKey = &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: encodedKey,
}
publicKey := string(pem.EncodeToMemory(pemKey))
encodedKey = x509.MarshalPKCS1PrivateKey(privateKey)
pemKey = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: encodedKey,
}
privateKeyString := string(pem.EncodeToMemory(pemKey))
return publicKey, privateKeyString
}
func withBearer(token string) string {
return fmt.Sprintf("Bearer %s", token)
}