-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtokenizer_test.go
More file actions
705 lines (605 loc) · 23.8 KB
/
tokenizer_test.go
File metadata and controls
705 lines (605 loc) · 23.8 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
package tokenizer
import (
"bufio"
"bytes"
"crypto/ed25519"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"sync"
"testing"
"time"
"github.com/alecthomas/assert/v2"
"github.com/sirupsen/logrus"
"github.com/superfly/flysrc-go"
"github.com/superfly/macaroon"
tkmac "github.com/superfly/tokenizer/macaroon"
"golang.org/x/crypto/nacl/box"
)
func TestTokenizer(t *testing.T) {
appServer := httptest.NewTLSServer(echo)
defer appServer.Close()
u, err := url.Parse(appServer.URL)
assert.NoError(t, err)
u.Scheme = "http"
appURL := u.String()
appHost := u.Host
appPort := u.Port()
var (
pub, priv, _ = box.GenerateKey(rand.Reader)
sealKey = hex.EncodeToString(pub[:])
openKey = hex.EncodeToString(priv[:])
)
flysrcParser, err := flysrc.New(
flysrc.WithPubkey(flySrcVerifyKey(t)),
flysrc.WithFlyProxyNet(&net.IPNet{
IP: net.ParseIP("127.0.0.1"),
Mask: net.CIDRMask(16, 32),
}),
)
assert.NoError(t, err)
// we can build a server without a fly src parser
tkz := NewTokenizer(openKey)
assert.True(t, tkz != nil)
tkz = NewTokenizer(openKey, WithFlysrcParser(flysrcParser))
tkz.ProxyHttpServer.Verbose = true
tkzServer := httptest.NewServer(tkz)
defer tkzServer.Close()
req, err := http.NewRequest(http.MethodPost, appURL+"/foo", nil)
assert.NoError(t, err)
auth := "trustno1"
token := "supersecret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// TLS error (proxy doesn't trust upstream)
client, err := Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err := client.Get(appURL)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadGateway, resp.StatusCode)
// make proxy trust upstream
UpstreamTrust.AddCert(appServer.Certificate())
// error if no secrets
client, err = Client(tkzServer.URL, WithAuth(auth))
assert.NoError(t, err)
resp, err = client.Get(appURL)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
t.Run("inject processor", func(t *testing.T) {
auth := "trustno1"
token := "supersecret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// no auth
client, err = Client(tkzServer.URL, WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// bad auth
client, err = Client(tkzServer.URL, WithSecret(secret, nil), WithAuth("bogus"))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// happy path
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// Inject dst param
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamDst: "Foo"}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Foo": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// Inject fmt param
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamFmt: "Other %s"}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Other %s", token)}},
Body: "",
}, doEcho(t, client, req))
// CONNECT proxy
conn, err := net.Dial("tcp", tkzServer.Listener.Addr().String())
connreader := bufio.NewReader(conn)
assert.NoError(t, err)
creq, err := http.NewRequest(http.MethodConnect, appURL, nil)
assert.NoError(t, err)
opts := clientOptions{}
WithAuth(auth)(&opts)
WithSecret(secret, nil)(&opts)
mergeHeader(creq.Header, opts.headers)
assert.NoError(t, creq.Write(conn))
resp, err = http.ReadResponse(connreader, creq)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
// request via CONNECT proxy
client = &http.Client{Transport: &http.Transport{Dial: func(network, addr string) (net.Conn, error) { return conn, nil }}}
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// good auth + bad auth
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil), WithAuth("bogus"))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// one good auth, one missing auth
otherSecret, err := (&Secret{AuthConfig: NewBearerAuthConfig("other"), ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil), WithSecret(otherSecret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
})
t.Run("inject hmac processor", func(t *testing.T) {
auth := "secreter"
key := []byte("trustno2")
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectHMACProcessorConfig{Key: key, Hash: "sha256"}}).Seal(sealKey)
assert.NoError(t, err)
// InjectHMAC - sign request body
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
req.Body = io.NopCloser(bytes.NewReader([]byte("foo")))
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %x", hmacSHA256(t, key, "foo"))}},
Body: "foo",
}, doEcho(t, client, req))
// InjectHMAC - sign param
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamPayload: "my payload"}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %x", hmacSHA256(t, key, "my payload"))}},
Body: "",
}, doEcho(t, client, req))
// InjectHMAC - dst param
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamDst: "Foo"}))
assert.NoError(t, err)
req.Body = io.NopCloser(bytes.NewReader([]byte("foo")))
assert.Equal(t, &echoResponse{
Headers: http.Header{"Foo": {fmt.Sprintf("Bearer %x", hmacSHA256(t, key, "foo"))}},
Body: "foo",
}, doEcho(t, client, req))
// InjectHMAC - fmt param
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamFmt: "%X"}))
assert.NoError(t, err)
req.Body = io.NopCloser(bytes.NewReader([]byte("foo")))
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("%X", hmacSHA256(t, key, "foo"))}},
Body: "foo",
}, doEcho(t, client, req))
})
t.Run("oauth processor", func(t *testing.T) {
auth := "secret-oauth-auth"
token := &OAuthToken{AccessToken: "access-token", RefreshToken: "refresh-token"}
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &OAuthProcessorConfig{token}}).Seal(sealKey)
assert.NoError(t, err)
// OAuth - access token (implicit)
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token.AccessToken)}},
Body: "",
}, doEcho(t, client, req))
// OAuth - access token (explicit)
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamSubtoken: SubtokenAccess}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token.AccessToken)}},
Body: "",
}, doEcho(t, client, req))
// OAuth - refresh token (explicit)
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamSubtoken: SubtokenRefresh}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token.RefreshToken)}},
Body: "",
}, doEcho(t, client, req))
})
t.Run("allow-hosts validator", func(t *testing.T) {
auth := "allow-host auth"
token := "allow-host secret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}, RequestValidators: []RequestValidator{AllowHosts(appHost)}}).Seal(sealKey)
assert.NoError(t, err)
// allowed hosts - good
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// allowed hosts - bad
badHostReq, err := http.NewRequest(http.MethodPost, "http://127.0.0.1.nip.io:"+appPort, nil)
assert.NoError(t, err)
badHostReq.URL.Host = "127.0.0.1.nip.io:" + badHostReq.URL.Port()
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(badHostReq)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
t.Run("allow-host-pattern validator", func(t *testing.T) {
auth := "allow-host-pattern auth"
token := "allow-host-pattern secret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}, RequestValidators: []RequestValidator{AllowHostPattern(regexp.MustCompile("^" + appHost + "$"))}}).Seal(sealKey)
assert.NoError(t, err)
// allowed host pattern - good
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// allowed host pattern - bad
badHostReq, err := http.NewRequest(http.MethodPost, "http://127.0.0.1.nip.io:"+appPort, nil)
assert.NoError(t, err)
badHostReq.URL.Host = "127.0.0.1.nip.io:" + badHostReq.URL.Port()
badHostReq, err = http.NewRequest(http.MethodPost, "http://127.0.0.1.nip.io:"+appPort, nil)
assert.NoError(t, err)
badHostReq.URL.Host = "127.0.0.1.nip.io:" + badHostReq.URL.Port()
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(badHostReq)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
t.Run("dst processor", func(t *testing.T) {
auth := "trustno1"
token := "supersecret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token, DstProcessor: DstProcessor{AllowedDst: []string{"asdf", "qwer"}}}}).Seal(sealKey)
assert.NoError(t, err)
// default dst pulled from allow-list
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Asdf": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// can specify non-normalized allowed value
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamDst: "qWeR"}))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Qwer": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// disallowed dst
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, map[string]string{ParamDst: "zxcv"}))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
t.Run("macaroon auth", func(t *testing.T) {
key := macaroon.NewSigningKey()
auth := NewMacaroonAuthConfig(key)
token := "supersecret"
secret, err := (&Secret{AuthConfig: auth, ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// empty macaroon - good
m, err := auth.Macaroon()
assert.NoError(t, err)
client, err := Client(tkzServer.URL, WithAuth(m), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// request matches caveats - good
m, err = auth.Macaroon(
tkmac.ConstrainRequestMethod(http.MethodPost),
tkmac.ConstrainRequestHost(appHost),
tkmac.ConstrainRequestPath("/foo"),
)
assert.NoError(t, err)
client, err = Client(tkzServer.URL, WithAuth(m), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
// method mismatch - bad
m, err = auth.Macaroon(tkmac.ConstrainRequestMethod(http.MethodGet))
assert.NoError(t, err)
client, err = Client(tkzServer.URL, WithAuth(m), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// host mismatch - bad
m, err = auth.Macaroon(tkmac.ConstrainRequestHost("fly.io"))
assert.NoError(t, err)
client, err = Client(tkzServer.URL, WithAuth(m), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// paht mismatch - bad
m, err = auth.Macaroon(tkmac.ConstrainRequestPath("/bar"))
assert.NoError(t, err)
client, err = Client(tkzServer.URL, WithAuth(m), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
})
t.Run("fly-src auth", func(t *testing.T) {
const (
headerFlySrc = "Fly-Src"
headerFlySrcSignature = "Fly-Src-Signature"
)
priv := flySrcSignKey(t)
auth := NewFlySrcAuthConfig(AllowlistFlySrcOrgs("foo"))
secret, err := (&Secret{AuthConfig: auth, ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// Good
fs := &flysrc.FlySrc{Org: "foo", App: "bar", Instance: "baz", Timestamp: time.Now().Truncate(time.Second)}
hdrSrc := fs.String()
hdrSig := fs.Sign(priv)
assert.NoError(t, err)
client, err := Client(tkzServer.URL, withHeaders(http.Header{
headerFlySrc: []string{hdrSrc},
headerFlySrcSignature: []string{hdrSig},
}), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{
"Authorization": {fmt.Sprintf("Bearer %s", token)},
headerFlySrc: []string{hdrSrc},
headerFlySrcSignature: []string{hdrSig},
},
Body: "",
}, doEcho(t, client, req))
// Bad, the same request fails, without panic, if flysrc parser is nil
parser := tkz.flysrcParser
tkz.flysrcParser = nil
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
tkz.flysrcParser = parser
// Bad org
fs = &flysrc.FlySrc{Org: "WRONG!", App: "bar", Instance: "baz", Timestamp: time.Now().Truncate(time.Second)}
hdrSrc = fs.String()
hdrSig = fs.Sign(priv)
assert.NoError(t, err)
client, err = Client(tkzServer.URL, withHeaders(http.Header{
headerFlySrc: []string{hdrSrc},
headerFlySrcSignature: []string{hdrSig},
}), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// Missing signature
fs = &flysrc.FlySrc{Org: "foo", App: "bar", Instance: "baz", Timestamp: time.Now().Truncate(time.Second)}
hdrSrc = fs.String()
assert.NoError(t, err)
client, err = Client(tkzServer.URL, withHeaders(http.Header{headerFlySrc: []string{hdrSrc}}), WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
})
t.Run("MultiProcessor", func(t *testing.T) {
auth := "trustno1"
token1 := "supersecret"
token2 := "extrasecret"
pc := &MultiProcessorConfig{
&InjectProcessorConfig{Token: token1, DstProcessor: DstProcessor{Dst: "A"}},
&InjectProcessorConfig{Token: token2, DstProcessor: DstProcessor{Dst: "B"}},
}
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: pc}).Seal(sealKey)
assert.NoError(t, err)
// no auth
client, err = Client(tkzServer.URL, WithSecret(secret, nil))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// bad auth
client, err = Client(tkzServer.URL, WithSecret(secret, nil), WithAuth("bogus"))
assert.NoError(t, err)
resp, err = client.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusProxyAuthRequired, resp.StatusCode)
// happy path
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{
"A": {fmt.Sprintf("Bearer %s", token1)},
"B": {fmt.Sprintf("Bearer %s", token2)},
},
Body: "",
}, doEcho(t, client, req))
})
}
func withHeaders(h http.Header) ClientOption {
return func(co *clientOptions) {
if co.headers == nil {
co.headers = make(http.Header)
}
for k, v := range h {
co.headers[k] = v
}
}
}
type echoResponse struct {
Headers http.Header
Body string
}
var echo http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "failed read", 500)
return
}
r.Header.Del("User-Agent")
r.Header.Del("Accept-Encoding")
r.Header.Del("Content-Length")
r.Header.Del("Connection")
if err := json.NewEncoder(w).Encode(&echoResponse{Headers: r.Header, Body: string(body)}); err != nil {
logrus.WithError(err).Panicf("failed writing response")
}
})
func doEcho(t testing.TB, c *http.Client, r *http.Request) *echoResponse {
t.Helper()
resp, err := c.Do(r)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
j := echoResponse{Headers: make(http.Header)}
assert.NoError(t, json.NewDecoder(resp.Body).Decode(&j))
return &j
}
func hmacSHA256(t testing.TB, key []byte, msg string) []byte {
hm := hmac.New(sha256.New, key)
_, err := hm.Write([]byte(msg))
assert.NoError(t, err)
return hm.Sum(nil)
}
var (
_setupFlySrcSignKey sync.Once
_flySrcSignKey ed25519.PrivateKey
_flySrcVerifyKey ed25519.PublicKey
)
func flySrcSignKey(t *testing.T) ed25519.PrivateKey {
t.Helper()
var err error
_setupFlySrcSignKey.Do(func() {
_flySrcVerifyKey, _flySrcSignKey, err = ed25519.GenerateKey(nil)
})
assert.NoError(t, err)
assert.NotZero(t, _flySrcSignKey)
return _flySrcSignKey
}
func flySrcVerifyKey(t *testing.T) ed25519.PublicKey {
t.Helper()
_ = flySrcSignKey(t)
return _flySrcVerifyKey
}
func TestTokenizerHeaders(t *testing.T) {
appServer := httptest.NewTLSServer(echo)
defer appServer.Close()
u, err := url.Parse(appServer.URL)
assert.NoError(t, err)
u.Scheme = "http"
appURL := u.String()
var (
pub, priv, _ = box.GenerateKey(rand.Reader)
sealKey = hex.EncodeToString(pub[:])
openKey = hex.EncodeToString(priv[:])
)
UpstreamTrust.AddCert(appServer.Certificate())
t.Run("default header Proxy-Tokenizer", func(t *testing.T) {
origHeaders := TokenizerHeaders
defer func() { TokenizerHeaders = origHeaders }()
// Set default to only Proxy-Tokenizer
TokenizerHeaders = []string{"Proxy-Tokenizer"}
tkz := NewTokenizer(openKey)
tkzServer := httptest.NewServer(tkz)
defer tkzServer.Close()
auth := "trustno1"
token := "supersecret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// Request with Proxy-Tokenizer header should work
client, err := Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
req, err := http.NewRequest(http.MethodGet, appURL, nil)
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
})
t.Run("custom headers with priority", func(t *testing.T) {
origHeaders := TokenizerHeaders
defer func() { TokenizerHeaders = origHeaders }()
// Configure multiple headers in priority order
TokenizerHeaders = []string{"X-Custom-Auth", "X-Api-Key", "Proxy-Tokenizer"}
tkz := NewTokenizer(openKey)
tkzServer := httptest.NewServer(tkz)
defer tkzServer.Close()
auth := "trustno1"
token := "supersecret"
secret, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth), ProcessorConfig: &InjectProcessorConfig{Token: token}}).Seal(sealKey)
assert.NoError(t, err)
// Request with X-Custom-Auth header (highest priority) should work
client, err := Client(tkzServer.URL, WithAuth(auth), withHeaders(http.Header{
"X-Custom-Auth": {secret},
}))
assert.NoError(t, err)
req, err := http.NewRequest(http.MethodGet, appURL, nil)
assert.NoError(t, err)
resp := doEcho(t, client, req)
// Should inject the token as Authorization header
assert.Equal(t, fmt.Sprintf("Bearer %s", token), resp.Headers.Get("Authorization"))
// X-Custom-Auth is not filtered by default, so it passes through
assert.True(t, len(resp.Headers.Get("X-Custom-Auth")) > 0)
// Request with X-Api-Key header (second priority) should work
client, err = Client(tkzServer.URL, WithAuth(auth), withHeaders(http.Header{
"X-Api-Key": {secret},
}))
assert.NoError(t, err)
req, err = http.NewRequest(http.MethodGet, appURL, nil)
assert.NoError(t, err)
resp = doEcho(t, client, req)
assert.Equal(t, fmt.Sprintf("Bearer %s", token), resp.Headers.Get("Authorization"))
assert.True(t, len(resp.Headers.Get("X-Api-Key")) > 0)
// Request with Proxy-Tokenizer header (lowest priority) should work
client, err = Client(tkzServer.URL, WithAuth(auth), WithSecret(secret, nil))
assert.NoError(t, err)
req, err = http.NewRequest(http.MethodGet, appURL, nil)
assert.NoError(t, err)
assert.Equal(t, &echoResponse{
Headers: http.Header{"Authorization": {fmt.Sprintf("Bearer %s", token)}},
Body: "",
}, doEcho(t, client, req))
})
t.Run("first matching header takes precedence", func(t *testing.T) {
origHeaders := TokenizerHeaders
defer func() { TokenizerHeaders = origHeaders }()
// Configure multiple headers
TokenizerHeaders = []string{"X-Custom-Auth", "X-Api-Key"}
tkz := NewTokenizer(openKey)
tkzServer := httptest.NewServer(tkz)
defer tkzServer.Close()
auth1 := "auth1"
token1 := "token1"
secret1, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth1), ProcessorConfig: &InjectProcessorConfig{Token: token1}}).Seal(sealKey)
assert.NoError(t, err)
auth2 := "auth2"
token2 := "token2"
secret2, err := (&Secret{AuthConfig: NewBearerAuthConfig(auth2), ProcessorConfig: &InjectProcessorConfig{Token: token2}}).Seal(sealKey)
assert.NoError(t, err)
// When both headers are present, X-Custom-Auth takes precedence
client, err := Client(tkzServer.URL, WithAuth(auth1), withHeaders(http.Header{
"X-Custom-Auth": {secret1},
"X-Api-Key": {secret2},
}))
assert.NoError(t, err)
req, err := http.NewRequest(http.MethodGet, appURL, nil)
assert.NoError(t, err)
// Should use token1 from X-Custom-Auth, not token2 from X-Api-Key
resp := doEcho(t, client, req)
assert.Equal(t, fmt.Sprintf("Bearer %s", token1), resp.Headers.Get("Authorization"))
// Both headers pass through (not filtered by default)
assert.True(t, len(resp.Headers.Get("X-Custom-Auth")) > 0)
assert.True(t, len(resp.Headers.Get("X-Api-Key")) > 0)
})
}