forked from hashicorp/cap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing_provider.go
1707 lines (1542 loc) · 53.2 KB
/
testing_provider.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 oidc
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"crypto/subtle"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"hash"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/hashicorp/cap/oidc/internal/strutils"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/require"
"gopkg.in/square/go-jose.v2"
)
var (
codeTimeout = 5 * time.Minute
codeCleanupInterval = 1 * time.Minute
)
// TestProvider is a local http server that supports test provider capabilities
// which makes writing tests much easier. Much of this TestProvider
// design/implementation comes from Consul's oauthtest package. A big thanks to
// the original package's contributors.
//
// It's important to remember that the TestProvider is stateful (see any of its
// receiver functions that begin with Set*).
//
// Once you've started a TestProvider http server with StartTestProvider(...),
// the following test endpoints are supported:
//
// * GET /.well-known/openid-configuration OIDC Discovery
//
// * GET or POST /authorize OIDC authorization supporting both
// the authorization code flow (with
// optional PKCE) and the implicit
// flow with form_post.
//
// * POST /token OIDC token
//
// * GET /userinfo OAuth UserInfo
//
// * GET /.well-known/jwks.json JWKs used to verify issued JWT tokens
//
// Making requests to these endpoints are facilitated by
// * TestProvider.HTTPClient which returns an http.Client for making requests.
// * TestProvider.CACert which the pem-encoded CA certificate used by the HTTPS server.
//
// Runtime Configuration:
// * Issuer: Addr() returns the the current base URL for the test provider's
// running webserver, which can be used as an OIDC Issuer for discovery and
// is also used for the iss claim when issuing JWTs.
//
// * Relying Party ClientID/ClientSecret: SetClientCreds(...) updates the
// creds and they are empty by default.
//
// * Now: SetNowFunc(...) updates the provider's "now" function and time.Now
// is the default.
//
// * Subject: SetExpectedSubject(sub string) configures the expected subject for
// any JWTs issued by the provider (the default is "alice@example.com")
//
// * Subject Passwords: SetSubjectInfo(...) configures a subject/password
// dictionary. If configured, then an interactive Login form is presented by
// the /authorize endpoint and the TestProvider becomes an interactive test
// provider using the provided subject/password dictionary.
//
// * Expiry: SetExpectedExpiry(exp time.Duration) updates the expiry and
// now + 5 * time.Second is the default.
//
// * Signing keys: SetSigningKeys(...) updates the keys and a ECDSA P-256 pair
// of priv/pub keys are the default with a signing algorithm of ES256
//
// * Authorization Code: SetExpectedAuthCode(...) updates the auth code
// required by the /authorize endpoint and the code is empty by default.
//
// * Authorization Nonce: SetExpectedAuthNonce(...) updates the nonce required
// by the /authorize endpont and the nonce is empty by default.
//
// * Allowed RedirectURIs: SetAllowedRedirectURIs(...) updates the allowed
// redirect URIs and "https://example.com" is the default.
//
// * Custom Claims: SetCustomClaims(...) updates custom claims added to JWTs issued
// and the custom claims are empty by default.
//
// * Audiences: SetCustomAudience(...) updates the audience claim of JWTs issued
// and the ClientID is the default.
//
// * Authentication Time (auth_time): SetOmitAuthTimeClaim(...) allows you to
// turn off/on the inclusion of an auth_time claim in issued JWTs and the claim
// is included by default.
//
// * Issuing id_tokens: SetOmitIDTokens(...) allows you to turn off/on the issuing of
// id_tokens from the /token endpoint. id_tokens are issued by default.
//
// * Issuing access_tokens: SetOmitAccessTokens(...) allows you to turn off/on
// the issuing of access_tokens from the /token endpoint. access_tokens are issued
// by default.
//
// * Authorization State: SetExpectedState sets the value for the state parameter
// returned from the /authorized endpoint
//
// * Token Responses: SetDisableToken disables the /token endpoint, causing
// it to return a 401 http status.
//
// * Implicit Flow Responses: SetDisableImplicit disables implicit flow responses,
// causing them to return a 401 http status.
//
// * PKCE verifier: SetPKCEVerifier(oidc.CodeVerifier) sets the PKCE code_verifier
// and PKCEVerifier() returns the current verifier.
//
// * UserInfo: SetUserInfoReply sets the UserInfo endpoint response and
// UserInfoReply() returns the current response.
type TestProvider struct {
httpServer *httptest.Server
caCert string
startContext context.Context
startCancel context.CancelFunc
jwks *jose.JSONWebKeySet
allowedRedirectURIs []string
replySubject string
subjectInfo map[string]*TestSubject
codes map[string]*codeState
replyUserinfo map[string]interface{}
replyExpiry time.Duration
mu sync.Mutex
clientID string
clientSecret string
expectedAuthCode string
expectedAuthNonce string
expectedState string
customClaims map[string]interface{}
customAudiences []string
supportedScopes []string
omitAuthTimeClaim bool
omitIDToken bool
omitAccessToken bool
disableUserInfo bool
disableJWKs bool
disableToken bool
disableImplicit bool
invalidJWKs bool
nowFunc func() time.Time
pkceVerifier CodeVerifier
// privKey *ecdsa.PrivateKey
privKey crypto.PrivateKey
pubKey crypto.PublicKey
keyID string
alg Alg
t TestingT
client *http.Client
}
// Stop stops the running TestProvider.
func (p *TestProvider) Stop() {
p.httpServer.Close()
if p.client != nil {
p.client.CloseIdleConnections()
}
p.startCancel()
}
// TestSubject is a struct that contains various values for customizing per-user
// responses via SubjectInfo in TestProvider. See the description of those
// values in TestProvider; these are simply overrides.
type TestSubject struct {
Password string
UserInfo map[string]interface{}
CustomClaims map[string]interface{}
}
// StartTestProvider creates and starts a running TestProvider http server. The
// WithTestDefaults, WithNoTLS and WithPort options are supported. If the
// TestingT parameter supports a CleanupT interface, then TestProvider will be
// shutdown when the test and all it's subtests complete via a registered
// function with t.Cleanup(...).
func StartTestProvider(t TestingT, opt ...Option) *TestProvider {
if v, ok := interface{}(t).(HelperT); ok {
v.Helper()
}
require := require.New(t)
opts := getTestProviderOpts(t, opt...)
p := &TestProvider{
t: t,
clientID: *opts.withDefaults.ClientID,
clientSecret: *opts.withDefaults.ClientSecret,
expectedAuthCode: *opts.withDefaults.ExpectedCode,
expectedState: *opts.withDefaults.ExpectedState,
expectedAuthNonce: *opts.withDefaults.ExpectedNonce,
allowedRedirectURIs: opts.withDefaults.AllowedRedirectURIs,
replyUserinfo: opts.withDefaults.UserInfoReply,
supportedScopes: opts.withDefaults.SupportedScopes,
customAudiences: opts.withDefaults.CustomAudiences,
customClaims: opts.withDefaults.CustomClaims,
privKey: opts.withDefaults.SigningKey.PrivKey,
pubKey: opts.withDefaults.SigningKey.PubKey,
alg: opts.withDefaults.SigningKey.Alg,
replyExpiry: *opts.withDefaults.Expiry,
nowFunc: opts.withDefaults.NowFunc,
pkceVerifier: opts.withDefaults.PKCEVerifier,
replySubject: *opts.withDefaults.ExpectedSubject,
subjectInfo: opts.withDefaults.SubjectInfo, // default is not to use a login form, so no passwords required for subjects
codes: map[string]*codeState{},
invalidJWKs: opts.withDefaults.InvalidJWKS,
omitAuthTimeClaim: opts.withDefaults.OmitAuthTime,
omitIDToken: opts.withDefaults.OmitIDTokens,
omitAccessToken: opts.withDefaults.OmitAccessTokens,
disableToken: opts.withDefaults.DisableTokenEndpoint,
disableImplicit: opts.withDefaults.DisableImplicitFlow,
disableUserInfo: opts.withDefaults.DisableUserInfo,
disableJWKs: opts.withDefaults.DisableJWKs,
keyID: strconv.Itoa(int(time.Now().Unix())),
}
p.jwks = &jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{
{
Key: p.pubKey,
KeyID: p.keyID,
},
},
}
p.httpServer = httptestNewUnstartedServerWithOpts(t, p, opt...)
p.httpServer.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
if opts.withNoTLS {
p.httpServer.Start()
} else {
p.httpServer.StartTLS()
}
if v, ok := interface{}(t).(CleanupT); ok {
v.Cleanup(p.Stop)
}
if !opts.withNoTLS {
cert := p.httpServer.Certificate()
var buf bytes.Buffer
err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
require.NoError(err)
p.caCert = buf.String()
}
p.startContext, p.startCancel = context.WithCancel(context.Background())
p.startCachedCodesCleanupTicking(p.startContext)
return p
}
// testProviderOptions is the set of available options for TestProvider
// functions
type testProviderOptions struct {
withHost string
withPort int
withAtHashOf string
withCHashOf string
withNoTLS bool
withSubject string
withNonce string
withDefaults *TestProviderDefaults
}
// testProviderDefaults is a handy way to get the defaults at runtime and during unit
// tests.
func testProviderDefaults(t TestingT) testProviderOptions {
require := require.New(t)
v, err := NewCodeVerifier()
require.NoError(err)
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(err)
exp := 5 * time.Second
sub := "alice@example.com"
emptyString := ""
return testProviderOptions{
withDefaults: &TestProviderDefaults{
ClientID: &emptyString,
ClientSecret: &emptyString,
ExpectedCode: &emptyString,
ExpectedState: &emptyString,
ExpectedNonce: &emptyString,
SigningKey: &TestSigningKey{
PrivKey: priv,
PubKey: &priv.PublicKey,
Alg: ES256,
},
NowFunc: time.Now,
PKCEVerifier: v,
Expiry: &exp,
AllowedRedirectURIs: []string{
"https://example.com",
},
CustomClaims: map[string]interface{}{
"name": "Alice Doe Smith",
"email": "alice@example.com",
},
ExpectedSubject: &sub,
UserInfoReply: map[string]interface{}{
"sub": "alice@example.com",
"dob": "1978",
"friend": "bob",
"nickname": "A",
"advisor": "Faythe",
"nosy-neighbor": "Eve",
},
SupportedScopes: []string{"openid"}, // required openid is the default
SubjectInfo: map[string]*TestSubject{}, // default is not to use a login form, so no passwords required for subjects
InvalidJWKS: false,
},
}
}
// getTestProviderOpts gets the test provider defaults and applies the opt
// overrides passed in
func getTestProviderOpts(t TestingT, opt ...Option) testProviderOptions {
opts := testProviderDefaults(t)
ApplyOpts(&opts, opt...)
return opts
}
// withTestSubject provides the option to provide a subject
//
func withTestSubject(s string) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withSubject = s
}
}
}
// withTestNonce provides the option to provide a nonce
//
func withTestNonce(n string) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withNonce = n
}
}
}
// TestSigningKey defines a type for specifying a test signing key and algorithm
// when providing TestProviderDefaults
type TestSigningKey struct {
Alg Alg
PrivKey crypto.PrivateKey
PubKey crypto.PublicKey
}
// TestProviderDefaults define a type for composing all the defaults for
// StartTestProvider(...)
type TestProviderDefaults struct {
// ClientID for test relying party which is empty by default
ClientID *string
// ClientSecret for test relying party which is empty by default
ClientSecret *string
// ExpectedSubject configures the expected subject for any JWTs issued by
// the provider (the default is "alice@example.com")
ExpectedSubject *string
// ExpectedCode configures the auth code required by the /authorize endpoint
// and the code is empty by default
ExpectedCode *string
// ExpectedState configures the value for the state parameter returned from
// the /authorize endpoint which is empty by default
ExpectedState *string
// ExpectedAuthNonce configures the nonce value required for /authorize
// endpoint which is empty by default
ExpectedNonce *string
// AllowedRedirectURIs configures the allowed redirect URIs for the OIDC
// workflow which is "https://example.com" by default
AllowedRedirectURIs []string
// UserInfoReply configures the UserInfo endpoint response. There is a
// basic response for sub == "alice@example.com" by default.
UserInfoReply map[string]interface{}
// SupportedScopes configures the supported scopes which is "openid" by
// default
SupportedScopes []string
// CustomAudiences configures what audience value to embed in the JWT issued
// by the OIDC workflow. By default only the ClientId is in the aud claim
// returned.
CustomAudiences []string
// CustomClaims configures the custom claims added to JWTs returned. By
// default there are no additional custom claims
CustomClaims map[string]interface{}
// SigningKey configures the signing key and algorithm for JWTs returned.
// By default an ES256 key is generated and used.
SigningKey *TestSigningKey
// Expiry configures the expiry for JWTs returned and now + 5 * time.Second
// is the default
Expiry *time.Duration
// NowFunc configures how the test provider will determine the current time
// The default is time.Now()
NowFunc func() time.Time
// PKCEVerifier(oidc.CodeVerifier) configures the PKCE code_verifier
PKCEVerifier CodeVerifier
// OmitAuthTime turn on/off the omitting of an auth_time claim from
// id_tokens from the /token endpoint. If set to true, the test provider will
// not include the auth_time claim in issued id_tokens from the /token
// endpoint. The default is false, so auth_time will be included
OmitAuthTime bool
// OmitIDTokens turn on/off the omitting of id_tokens from the /token
// endpoint. If set to true, the test provider will not omit (issue) id_tokens
// from the /token endpoint. The default is false, so ID tokens will be included
OmitIDTokens bool
// OmitAccessTokens turn on/off the omitting of access_tokens from the /token
// endpoint. If set to true, the test provider will not omit (issue)
// access_tokens from the /token endpoint. The default is false, so Access
// tokens will be included
OmitAccessTokens bool
// DisableTokenEndpoint makes the /token endpoint return 401. It is false by
// default, so the endpoint is on
DisableTokenEndpoint bool
// DisableImplicitFlow disables implicit flow responses, causing them to
// return a 401 http status. The implicit flow is allowed by default
DisableImplicitFlow bool
// DisableUserInfo disables userinfo responses, causing it to return a 404
// http status. The userinfo endpoint is enabled by default
DisableUserInfo bool
// DisableJWKs disables the JWKs endpoint, causing it to 404. It is enabled
// by default
DisableJWKs bool
// InvalidJWKS makes the JWKs endpoint return an invalid response. Valid
// JWKs are returned by default.
InvalidJWKS bool
// SubjectInfo configures a subject/password dictionary. If configured,
// then an interactive Login form is presented by the /authorize endpoint
// and the TestProvider becomes an interactive test provider using the
// provided subject/password dictionary.
SubjectInfo map[string]*TestSubject
}
// WithTestDefaults provides an option to provide a set of defaults to
// StartTestProvider(...) which make it much more composable.
//
// Valid for: StartTestProvider(...)
func WithTestDefaults(defaults *TestProviderDefaults) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
if defaults != nil {
if defaults.ClientID != nil {
o.withDefaults.ClientID = defaults.ClientID
}
if defaults.ClientSecret != nil {
o.withDefaults.ClientSecret = defaults.ClientSecret
}
if defaults.ExpectedCode != nil {
o.withDefaults.ExpectedCode = defaults.ExpectedCode
}
if defaults.ExpectedState != nil {
o.withDefaults.ExpectedState = defaults.ExpectedState
}
if defaults.ExpectedNonce != nil {
o.withDefaults.ExpectedNonce = defaults.ExpectedNonce
}
if defaults.AllowedRedirectURIs != nil {
o.withDefaults.AllowedRedirectURIs = defaults.AllowedRedirectURIs
}
if defaults.UserInfoReply != nil {
o.withDefaults.UserInfoReply = defaults.UserInfoReply
}
if defaults.SupportedScopes != nil {
o.withDefaults.SupportedScopes = defaults.SupportedScopes
}
if defaults.CustomAudiences != nil {
o.withDefaults.CustomAudiences = defaults.CustomAudiences
}
if defaults.CustomClaims != nil {
o.withDefaults.CustomClaims = defaults.CustomClaims
}
if defaults.SigningKey != nil {
o.withDefaults.SigningKey = defaults.SigningKey
}
if defaults.Expiry != nil {
o.withDefaults.Expiry = defaults.Expiry
}
if defaults.NowFunc != nil {
o.withDefaults.NowFunc = defaults.NowFunc
}
if defaults.PKCEVerifier != nil {
o.withDefaults.PKCEVerifier = defaults.PKCEVerifier
}
if defaults.ExpectedSubject != nil {
o.withDefaults.ExpectedSubject = defaults.ExpectedSubject
}
if defaults.SubjectInfo != nil {
o.withDefaults.SubjectInfo = defaults.SubjectInfo
}
if defaults.InvalidJWKS {
o.withDefaults.InvalidJWKS = defaults.InvalidJWKS
}
if defaults.OmitAuthTime {
o.withDefaults.OmitAuthTime = defaults.OmitAuthTime
}
if defaults.OmitIDTokens {
o.withDefaults.OmitIDTokens = defaults.OmitIDTokens
}
if defaults.OmitAccessTokens {
o.withDefaults.OmitAccessTokens = defaults.OmitAccessTokens
}
if defaults.DisableTokenEndpoint {
o.withDefaults.DisableTokenEndpoint = defaults.DisableTokenEndpoint
}
if defaults.DisableImplicitFlow {
o.withDefaults.DisableImplicitFlow = defaults.DisableImplicitFlow
}
if defaults.DisableJWKs {
o.withDefaults.DisableJWKs = defaults.DisableJWKs
}
}
}
}
}
// WithNoTLS provides the option to not use TLS for the test provider.
//
// Valid for: StartTestProvider(...)
func WithNoTLS() Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withNoTLS = true
}
}
}
// WithTestHost provides an optional address for the test provider.
//
// Valid for: TestProvider.StartTestProvider
func WithTestHost(host string) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withHost = host
}
}
}
// WithTestPort provides an optional port for the test provider. -1 causes an
// unstarted server with a random port. 0 causes a started server with a random
// port. Any other value returns a started server on that port.
//
// Valid for: TestProvider.StartTestProvider
func WithTestPort(port int) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withPort = port
}
}
}
// withTestAtHash provides an option to request the at_hash claim. Valid for:
// TestProvider.issueSignedJWT
func withTestAtHash(accessToken string) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withAtHashOf = accessToken
}
}
}
// withTestCHash provides an option to request the c_hash claim. Valid for:
// TestProvider.issueSignedJWT
func withTestCHash(authorizationCode string) Option {
return func(o interface{}) {
if o, ok := o.(*testProviderOptions); ok {
o.withCHashOf = authorizationCode
}
}
}
// HTTPClient returns an http.Client for the test provider. The returned client
// uses a pooled transport (so it can reuse connections) that uses the
// test provider's CA certificate. This client's idle connections are closed in
// TestProvider.Done()
func (p *TestProvider) HTTPClient() *http.Client {
p.mu.Lock()
defer p.mu.Unlock()
if p.client != nil {
return p.client
}
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
if p.caCert == "" {
p.client = &http.Client{}
return p.client
}
// use the cleanhttp package to create a "pooled" transport that's better
// configured for requests that re-use the same provider host. Among other
// things, this transport supports better concurrency when making requests
// to the same host. On the downside, this transport can leak file
// descriptors over time, so we'll be sure to call
// client.CloseIdleConnections() in the TestProvider.Done() to stave that off.
tr := cleanhttp.DefaultPooledTransport()
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM([]byte(p.caCert))
require.True(ok)
tr.TLSClientConfig = &tls.Config{
RootCAs: certPool,
}
p.client = &http.Client{
Transport: tr,
}
return p.client
}
// SetSupportedScopes sets the values for the scopes supported for
// authorization. Valid supported scopes are: openid, profile, email,
// address, phone
func (p *TestProvider) SetSupportedScopes(scope ...string) {
p.mu.Lock()
defer p.mu.Unlock()
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
for _, s := range scope {
require.Containsf([]string{"openid", "profile", "email", "address", "phone"}, s, "unsupported scope %q", s)
}
if !strutils.StrListContains(scope, "openid") {
scope = append(scope, "openid")
}
p.supportedScopes = scope
}
// SupportedScopes returns the values for the scopes supported.
func (p *TestProvider) SupportedScopes() []string {
p.mu.Lock()
defer p.mu.Unlock()
return p.supportedScopes
}
// SetExpectedSubject is for configuring the expected subject for
// any JWTs issued by the provider (the default is "alice@example.com")
func (p *TestProvider) SetExpectedSubject(sub string) {
p.mu.Lock()
defer p.mu.Unlock()
p.replySubject = sub
}
// ExpectedSubject returns the subject for any JWTs issued by the
// provider See: SetExpectedSubject(...) to override the default which
// is "alice@example.com"
func (p *TestProvider) ExpectedSubject() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.replySubject
}
// SetSubjectInfo is for configuring subject passwords when you wish to
// have login prompts for interactive testing.
func (p *TestProvider) SetSubjectInfo(subjectInfo map[string]*TestSubject) {
p.mu.Lock()
defer p.mu.Unlock()
p.subjectInfo = subjectInfo
}
// SubjectInfo returns the current subject passwords when you wish to have
// login prompts for interactive testing.
func (p *TestProvider) SubjectInfo() map[string]*TestSubject {
p.mu.Lock()
defer p.mu.Unlock()
clone := map[string]*TestSubject{}
for k, v := range p.subjectInfo {
clone[k] = v
}
return clone
}
// SetExpectedExpiry is for configuring the expected expiry for any JWTs issued
// by the provider (the default is 5 seconds)
func (p *TestProvider) SetExpectedExpiry(exp time.Duration) {
p.mu.Lock()
defer p.mu.Unlock()
p.replyExpiry = exp
}
// SetClientCreds is for configuring the relying party client ID and client
// secret information required for the OIDC workflows.
func (p *TestProvider) SetClientCreds(clientID, clientSecret string) {
p.mu.Lock()
defer p.mu.Unlock()
p.clientID = clientID
p.clientSecret = clientSecret
}
// ClientCreds returns the relying party client information required for the
// OIDC workflows.
func (p *TestProvider) ClientCreds() (clientID, clientSecret string) {
p.mu.Lock()
defer p.mu.Unlock()
return p.clientID, p.clientSecret
}
// SetExpectedAuthCode configures the auth code to return from /auth and the
// allowed auth code for /token.
func (p *TestProvider) SetExpectedAuthCode(code string) {
p.mu.Lock()
defer p.mu.Unlock()
p.expectedAuthCode = code
}
// SetExpectedAuthNonce configures the nonce value required for /auth.
func (p *TestProvider) SetExpectedAuthNonce(nonce string) {
p.mu.Lock()
defer p.mu.Unlock()
p.expectedAuthNonce = nonce
}
// SetAllowedRedirectURIs allows you to configure the allowed redirect URIs for
// the OIDC workflow. If not configured a sample of "https://example.com" is
// used.
func (p *TestProvider) SetAllowedRedirectURIs(uris []string) {
p.mu.Lock()
defer p.mu.Unlock()
p.allowedRedirectURIs = uris
}
// SetCustomClaims lets you set claims to return in the JWT issued by the OIDC
// workflow.
func (p *TestProvider) SetCustomClaims(customClaims map[string]interface{}) {
p.mu.Lock()
defer p.mu.Unlock()
p.customClaims = customClaims
}
// SetCustomAudience configures what audience value to embed in the JWT issued
// by the OIDC workflow.
func (p *TestProvider) SetCustomAudience(customAudiences ...string) {
p.mu.Lock()
defer p.mu.Unlock()
p.customAudiences = customAudiences
}
// SetNowFunc configures how the test provider will determine the current time. The
// default is time.Now()
func (p *TestProvider) SetNowFunc(n func() time.Time) {
p.mu.Lock()
defer p.mu.Unlock()
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
require.NotNilf(n, "TestProvider.SetNowFunc: time func is nil")
p.nowFunc = n
}
// SetOmitAuthTimeClaim turn on/off the omitting of an auth_time claim from
// id_tokens from the /token endpoint. If set to true, the test provider will
// not include the auth_time claim in issued id_tokens from the /token endpoint.
func (p *TestProvider) SetOmitAuthTimeClaim(omitAuthTime bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.omitAuthTimeClaim = omitAuthTime
}
// SetOmitIDTokens turn on/off the omitting of id_tokens from the /token
// endpoint. If set to true, the test provider will not omit (issue) id_tokens
// from the /token endpoint.
func (p *TestProvider) SetOmitIDTokens(omitIDTokens bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.omitIDToken = omitIDTokens
}
// OmitAccessTokens turn on/off the omitting of access_tokens from the /token
// endpoint. If set to true, the test provider will not omit (issue)
// access_tokens from the /token endpoint.
func (p *TestProvider) SetOmitAccessTokens(omitAccessTokens bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.omitAccessToken = omitAccessTokens
}
// SetDisableUserInfo makes the userinfo endpoint return 404 and omits it from the
// discovery config.
func (p *TestProvider) SetDisableUserInfo(disable bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.disableUserInfo = disable
}
// SetDisableJWKs makes the JWKs endpoint return 404
func (p *TestProvider) SetDisableJWKs(disable bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.disableJWKs = disable
}
// SetInvalidJWKS makes the JWKs endpoint return an invalid response
func (p *TestProvider) SetInvalidJWKS(invalid bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.invalidJWKs = invalid
}
// SetExpectedState sets the value for the state parameter returned from
// /authorized
func (p *TestProvider) SetExpectedState(s string) {
p.mu.Lock()
defer p.mu.Unlock()
p.expectedState = s
}
// SetDisableToken makes the /token endpoint return 401
func (p *TestProvider) SetDisableToken(disable bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.disableToken = disable
}
// SetDisableImplicit makes implicit flow responses return 401
func (p *TestProvider) SetDisableImplicit(disable bool) {
p.mu.Lock()
defer p.mu.Unlock()
p.disableImplicit = disable
}
// SetPKCEVerifier sets the PKCE oidc.CodeVerifier
func (p *TestProvider) SetPKCEVerifier(verifier CodeVerifier) {
p.mu.Lock()
defer p.mu.Unlock()
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require.NotNil(p.t, verifier)
p.pkceVerifier = verifier
}
// PKCEVerifier returns the PKCE oidc.CodeVerifier
func (p *TestProvider) PKCEVerifier() CodeVerifier {
p.mu.Lock()
defer p.mu.Unlock()
return p.pkceVerifier
}
// SetUserInfoReply sets the UserInfo endpoint response.
func (p *TestProvider) SetUserInfoReply(resp map[string]interface{}) {
p.mu.Lock()
defer p.mu.Unlock()
p.replyUserinfo = resp
}
// UserInfoReply gets the UserInfo endpoint response.
func (p *TestProvider) UserInfoReply() map[string]interface{} {
p.mu.Lock()
defer p.mu.Unlock()
return p.replyUserinfo
}
// Addr returns the current base URL for the test provider's running webserver,
// which can be used as an OIDC issuer for discovery and is also used for the
// iss claim when issuing JWTs.
func (p *TestProvider) Addr() string { return p.httpServer.URL }
// CACert returns the pem-encoded CA certificate used by the test provider's
// HTTPS server. If the TestProvider was started the WithNoTLS option, then
// this will return an empty string
func (p *TestProvider) CACert() string { return p.caCert }
// SigningKeys returns the test provider's keys used to sign JWTs, its Alg and
// Key ID.
func (p *TestProvider) SigningKeys() (crypto.PrivateKey, crypto.PublicKey, Alg, string) {
p.mu.Lock()
defer p.mu.Unlock()
return p.privKey, p.pubKey, p.alg, p.keyID
}
// SetSigningKeys sets the test provider's keys and alg used to sign JWTs.
func (p *TestProvider) SetSigningKeys(privKey crypto.PrivateKey, pubKey crypto.PublicKey, alg Alg, KeyID string) {
const op = "TestProvider.SetSigningKeys"
p.mu.Lock()
defer p.mu.Unlock()
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
require.NotNilf(privKey, "%s: private key is nil")
require.NotNilf(pubKey, "%s: public key is empty")
require.NotEmptyf(alg, "%s: alg is empty")
require.NotEmptyf(KeyID, "%s: key id is empty")
p.privKey = privKey
p.pubKey = pubKey
p.alg = alg
p.keyID = KeyID
p.jwks = &jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{
{
Key: p.pubKey,
KeyID: p.keyID,
},
},
}
}
func (p *TestProvider) writeJSON(w http.ResponseWriter, out interface{}) error {
const op = "TestProvider.writeJSON"
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
require.NotNilf(w, "%s: http.ResponseWriter is nil")
enc := json.NewEncoder(w)
return enc.Encode(out)
}
// writeImplicitResponse will write the required form data response for an
// implicit flow response to the OIDC authorize endpoint
func (p *TestProvider) writeImplicitResponse(w http.ResponseWriter, state, redirectURL string) error {
if v, ok := interface{}(p.t).(HelperT); ok {
v.Helper()
}
require := require.New(p.t)
require.NotNilf(w, "%s: http.ResponseWriter is nil")
w.Header().Set("Content-Type", "application/x-www-form-urlencoded")
const respForm = `
<!DOCTYPE html>
<html lang="en">
<head><title>Submit This Form</title></head>
<body onload="javascript:document.forms[0].submit()">
<form method="post" action="%s">
<input type="hidden" name="state" id="state" value="%s"/>
%s
</form>
</body>
</html>`
const tokenField = `<input type="hidden" name="%s" id="%s" value="%s"/>
`
accessToken := p.issueSignedJWT()
idToken := p.issueSignedJWT(withTestAtHash(accessToken))
var respTokens strings.Builder
if !p.omitAccessToken {
respTokens.WriteString(fmt.Sprintf(tokenField, "access_token", "access_token", accessToken))
}
if !p.omitIDToken {
respTokens.WriteString(fmt.Sprintf(tokenField, "id_token", "id_token", idToken))
}
if _, err := w.Write([]byte(fmt.Sprintf(respForm, redirectURL, state, respTokens.String()))); err != nil {
return err
}
return nil
}
func (p *TestProvider) issueSignedJWT(opt ...Option) string {