-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathauthentication.go
More file actions
1237 lines (1041 loc) · 39 KB
/
authentication.go
File metadata and controls
1237 lines (1041 loc) · 39 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
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 oas
import (
"encoding/json"
"errors"
"fmt"
"iter"
"reflect"
"sort"
"time"
"github.com/TykTechnologies/tyk/apidef"
"github.com/getkin/kin-openapi/openapi3"
clone "github.com/huandu/go-clone/generic"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v3"
)
// SecurityProcessingMode constants define how multiple security requirements are processed
const (
// SecurityProcessingModeLegacy processes only the first security requirement and uses BaseIdentityProvider
SecurityProcessingModeLegacy = "legacy"
// SecurityProcessingModeCompliant processes all security requirements with OR logic and uses dynamic identity provider
SecurityProcessingModeCompliant = "compliant"
)
// ValidateSecurityProcessingMode validates the security processing mode value.
func ValidateSecurityProcessingMode(mode string) bool {
return mode == "" || mode == SecurityProcessingModeLegacy || mode == SecurityProcessingModeCompliant
}
// GetDefaultSecurityProcessingMode returns the default security processing mode.
func GetDefaultSecurityProcessingMode() string {
return SecurityProcessingModeLegacy
}
// Authentication contains configuration about the authentication methods and security policies applied to requests.
type Authentication struct {
// Enabled makes the API protected when one of the authentication modes is enabled.
//
// Tyk classic API definition: `!use_keyless`.
Enabled bool `bson:"enabled" json:"enabled"` // required
// StripAuthorizationData ensures that any security tokens used for accessing APIs are stripped and not passed to the upstream.
//
// Tyk classic API definition: `strip_auth_data`.
StripAuthorizationData bool `bson:"stripAuthorizationData,omitempty" json:"stripAuthorizationData,omitempty"`
// BaseIdentityProvider enables the use of multiple authentication mechanisms.
// It provides the session object that determines access control, rate limits and usage quotas.
//
// It should be set to one of the following:
//
// - `auth_token`
// - `hmac_key`
// - `basic_auth_user`
// - `jwt_claim`
// - `oidc_user`
// - `oauth_key`
// - `custom_auth`
//
// Tyk classic API definition: `base_identity_provided_by`.
BaseIdentityProvider apidef.AuthTypeEnum `bson:"baseIdentityProvider,omitempty" json:"baseIdentityProvider,omitempty"`
// HMAC contains the configurations related to HMAC authentication mode.
//
// Tyk classic API definition: `auth_configs["hmac"]`
HMAC *HMAC `bson:"hmac,omitempty" json:"hmac,omitempty"`
// OIDC contains the configurations related to OIDC authentication mode.
//
// Tyk classic API definition: `auth_configs["oidc"]`
OIDC *OIDC `bson:"oidc,omitempty" json:"oidc,omitempty"`
// Custom contains the configurations related to Custom authentication mode.
//
// Tyk classic API definition: `auth_configs["coprocess"]`
Custom *CustomPluginAuthentication `bson:"custom,omitempty" json:"custom,omitempty"`
// SecuritySchemes contains security schemes definitions.
SecuritySchemes SecuritySchemes `bson:"securitySchemes,omitempty" json:"securitySchemes,omitempty"`
// CustomKeyLifetime contains configuration for the maximum retention period for access tokens.
CustomKeyLifetime *CustomKeyLifetime `bson:"customKeyLifetime,omitempty" json:"customKeyLifetime,omitempty"`
// SecurityProcessingMode controls how Tyk will process the OpenAPI `security` field if multiple security requirement objects are declared.
// - "legacy" (default): Only the first security requirement object will be processed; uses BaseIdentityProvider to create the session object.
// - "compliant": All security requirement objects will be processed, request will be authorized if any of these are validated; the origin for the session object will be determined dynamically based on the validated security requirement.
SecurityProcessingMode string `bson:"securityProcessingMode,omitempty" json:"securityProcessingMode,omitempty"`
// Security is an extension to the OpenAPI security field and is used when securityProcessingMode is set to "compliant".
// This can be used to combine any declared securitySchemes including Tyk proprietary auth methods.
Security [][]string `bson:"security,omitempty" json:"security,omitempty"`
}
// CustomKeyLifetime contains configuration for custom key retention.
type CustomKeyLifetime struct {
// Enabled enables custom maximum retention for keys for the API.
Enabled bool `bson:"enabled,omitempty" json:"enabled,omitempty"`
// Value configures the expiry interval for a Key.
// The value is a string that specifies the interval in a compact form,
// where hours, minutes and seconds are denoted by 'h', 'm' and 's' respectively.
// Multiple units can be combined to represent the duration.
//
// Examples of valid shorthand notations:
// - "1h" : one hour
// - "20m" : twenty minutes
// - "30s" : thirty seconds
// - "1m29s": one minute and twenty-nine seconds
// - "1h30m" : one hour and thirty minutes
//
// An empty value is interpreted as "0s"
//
// Tyk classic API definition: `session_lifetime`.
Value ReadableDuration `bson:"value" json:"value"`
// RespectValidity ensures that Tyk respects the expiry configured in the key when the API level configuration grants a shorter lifetime.
// That is, Redis waits until the key has expired before deleting it.
//
// Tyk classic API definition: `session_lifetime_respects_key_expiration`.
RespectValidity bool `bson:"respectValidity,omitempty" json:"respectValidity,omitempty"`
}
// Fill fills *CustomKeyLifetime from apidef.APIDefinition.
func (k *CustomKeyLifetime) Fill(api apidef.APIDefinition) {
k.RespectValidity = api.SessionLifetimeRespectsKeyExpiration
if api.SessionLifetime == 0 {
k.Enabled = false
} else {
k.Enabled = true
k.Value = ReadableDuration(time.Duration(api.SessionLifetime) * time.Second)
}
}
// ExtractTo extracts *Authentication into *apidef.APIDefinition.
func (k *CustomKeyLifetime) ExtractTo(api *apidef.APIDefinition) {
api.SessionLifetimeRespectsKeyExpiration = k.RespectValidity
if k.Enabled {
api.SessionLifetime = int64(k.Value.Seconds())
} else {
api.SessionLifetime = 0
}
}
// Fill fills *Authentication from apidef.APIDefinition.
func (a *Authentication) Fill(api apidef.APIDefinition) {
a.Enabled = !api.UseKeylessAccess
a.StripAuthorizationData = api.StripAuthData
a.BaseIdentityProvider = api.BaseIdentityProvidedBy
if a.Custom == nil {
a.Custom = &CustomPluginAuthentication{}
}
a.Custom.Fill(api)
if ShouldOmit(a.Custom) {
a.Custom = nil
}
if a.CustomKeyLifetime == nil {
a.CustomKeyLifetime = &CustomKeyLifetime{}
}
a.CustomKeyLifetime.Fill(api)
if ShouldOmit(a.CustomKeyLifetime) {
a.CustomKeyLifetime = nil
}
if api.AuthConfigs == nil || len(api.AuthConfigs) == 0 {
return
}
if _, ok := api.AuthConfigs[apidef.HMACType]; ok {
if a.HMAC == nil {
a.HMAC = &HMAC{}
}
a.HMAC.Fill(api)
}
if ShouldOmit(a.HMAC) {
a.HMAC = nil
}
if _, ok := api.AuthConfigs[apidef.OIDCType]; ok {
if a.OIDC == nil {
a.OIDC = &OIDC{}
}
a.OIDC.Fill(api)
}
if ShouldOmit(a.OIDC) {
a.OIDC = nil
}
}
// ExtractTo extracts *Authentication into *apidef.APIDefinition.
func (a *Authentication) ExtractTo(api *apidef.APIDefinition) {
api.UseKeylessAccess = !a.Enabled
api.StripAuthData = a.StripAuthorizationData
api.BaseIdentityProvidedBy = a.BaseIdentityProvider
if a.HMAC != nil {
a.HMAC.ExtractTo(api)
}
if a.OIDC != nil {
a.OIDC.ExtractTo(api)
}
if a.Custom == nil {
a.Custom = &CustomPluginAuthentication{}
defer func() {
a.Custom = nil
}()
}
a.Custom.ExtractTo(api)
if a.CustomKeyLifetime == nil {
a.CustomKeyLifetime = &CustomKeyLifetime{}
defer func() {
a.CustomKeyLifetime = nil
}()
}
a.CustomKeyLifetime.ExtractTo(api)
}
// SecuritySchemes zero value is usable. Methods lazily initialize internal state.
// Recommendation: prefer NewSecuritySchemes for clarity and explicit initialization.
type SecuritySchemes struct {
container map[string]SecuritySchemeMarker
}
func (ss SecuritySchemes) Set(key string, value SecuritySchemeMarker) SecuritySchemes {
if reflect.TypeOf(value).Kind() != reflect.Pointer {
panic("value must be a pointer")
}
var res SecuritySchemes
res.container = clone.Clone(ss.container)
if res.container == nil {
res.container = map[string]SecuritySchemeMarker{}
}
res.container[key] = value
return res
}
// Get retrieves a security scheme by name.
// It returns the stored value and true when present, otherwise (nil, false).
func (ss SecuritySchemes) Get(key string) (SecuritySchemeMarker, bool) {
if ss.container == nil {
return nil, false
}
value, ok := ss.container[key]
return value, ok
}
// GetVal retrieves a security scheme by name.
// It returns the stored value and true when present, otherwise nil.
func (ss SecuritySchemes) GetVal(key string) interface{} {
val, _ := ss.Get(key)
return val
}
// Delete removes a scheme from the receiver by name.
// It silently returns when the receiver or its container map is nil.
func (ss SecuritySchemes) delete(key string) SecuritySchemes {
var res SecuritySchemes
res.container = clone.Clone(ss.container)
delete(res.container, key)
return res
}
// Len reports the number of registered security schemes.
// A nil receiver reports zero.
func (ss SecuritySchemes) Len() int {
return len(ss.container)
}
// Iter returns a snapshot under a short read lock to avoid holding locks during iteration.
// This allocates per call. Given the typical small number of schemes, the trade-off is acceptable.
func (ss SecuritySchemes) Iter() iter.Seq2[string, interface{}] {
return func(yield func(string, interface{}) bool) {
for k, v := range ss.container {
if !yield(k, v) {
return
}
}
}
}
// MarshalJSON implements json.Marshaler.
func (ss *SecuritySchemes) MarshalJSON() ([]byte, error) {
if ss.container == nil {
return []byte(`{}`), nil
}
return json.Marshal(ss.container)
}
// UnmarshalJSON implements json.Unmarshaler.
func (ss *SecuritySchemes) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
ss.container = nil
return nil
}
tmp := make(map[string]interface{})
if err := json.Unmarshal(b, &tmp); err != nil {
return err
}
container := make(map[string]SecuritySchemeMarker)
for k, v := range tmp {
if decoded, err := decodeScheme(v); err != nil {
return err
} else {
container[k] = decoded
}
}
ss.container = container
return nil
}
// MarshalYAML makes SecuritySchemes YAML-friendly by exposing its container map.
func (ss *SecuritySchemes) MarshalYAML() (interface{}, error) {
if ss.container == nil {
return map[string]interface{}{}, nil
}
return clone.Clone(ss.container), nil
}
// UnmarshalYAML populates SecuritySchemes.container from YAML.
func (ss *SecuritySchemes) UnmarshalYAML(n *yaml.Node) error {
//todo remap keys in the existing map
if n.Tag == "!!null" {
ss.container = make(map[string]SecuritySchemeMarker)
return nil
}
var tmp map[string]interface{}
if err := n.Decode(&tmp); err != nil {
return err
}
if container, err := decodeSchemes(tmp); err != nil {
return err
} else {
ss.container = container
}
return nil
}
var _ yaml.Unmarshaler = (*SecuritySchemes)(nil)
var _ yaml.Marshaler = (*SecuritySchemes)(nil)
var _ json.Marshaler = (*SecuritySchemes)(nil)
var _ json.Unmarshaler = (*SecuritySchemes)(nil)
// SecurityScheme defines an Importer interface for security schemes.
type SecurityScheme interface {
Import(nativeSS *openapi3.SecurityScheme, enable bool)
}
// loadForImport returns an existing *T if present,
// or builds a new *T hydrated from a map (if possible),
// or otherwise returns a zero-value *T.
func loadForImport[T SecuritySchemeMarker](ss *SecuritySchemes, name string) T {
var zero T
if ss == nil {
return zero
}
scheme, exists := ss.Get(name)
if !exists {
return zero
}
if typed, ok := scheme.(T); ok {
return typed
}
var v T
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{TagName: "json", Result: v})
if err != nil {
log.Debug("Initialization of the new decoder couldn't succeed")
return zero
}
err = decoder.Decode(scheme)
if err != nil {
log.Debug("Unmarshalling to struct couldn't succeed")
return zero
}
return v
}
func decodeSchemes(in map[string]interface{}) (map[string]SecuritySchemeMarker, error) {
out := make(map[string]SecuritySchemeMarker, len(in))
for k, v := range in {
if decoded, err := decodeScheme(v); err != nil {
return nil, err
} else {
out[k] = decoded
}
}
return out, nil
}
func decodeScheme(raw interface{}) (SecuritySchemeMarker, error) {
return nil, errors.New("not implemented")
}
func (ss SecuritySchemes) importNative(name string, nativeSS *openapi3.SecurityScheme, enable bool) (SecuritySchemes, error) {
self := ss
switch {
case nativeSS.Type == typeAPIKey:
token := loadForImport[*Token](&ss, name)
token.Enabled = &enable
self = self.Set(name, token)
case nativeSS.Type == typeHTTP &&
nativeSS.Scheme == schemeBearer &&
nativeSS.BearerFormat == bearerFormatJWT:
jwt := loadForImport[*JWT](&ss, name)
jwt.Import(enable)
self = self.Set(name, jwt)
case nativeSS.Type == typeHTTP &&
nativeSS.Scheme == schemeBasic:
basic := loadForImport[*Basic](&ss, name)
basic.Import(enable)
self = self.Set(name, basic)
case nativeSS.Type == typeOAuth2:
oauth := loadForImport[*OAuth](&ss, name)
oauth.Import(enable)
self = self.Set(name, oauth)
default:
return SecuritySchemes{}, fmt.Errorf(unsupportedSecuritySchemeFmt, name)
}
return self, nil
}
func baseIdentityProviderPrecedence(authType apidef.AuthTypeEnum) int {
switch authType {
case apidef.AuthToken:
return 1
case apidef.JWTClaim:
return 2
case apidef.OAuthKey:
return 3
case apidef.BasicAuthUser:
return 4
default:
return 5
}
}
// GetBaseIdentityProvider returns the identity provider by precedence from SecuritySchemes.
func (ss SecuritySchemes) GetBaseIdentityProvider() (res apidef.AuthTypeEnum) {
if ss.Len() < 2 {
return
}
resBaseIdentityProvider := baseIdentityProviderPrecedence(apidef.AuthTypeNone)
res = apidef.OAuthKey
for _, scheme := range ss.Iter() {
if _, ok := scheme.(*Token); ok {
return apidef.AuthToken
}
if _, ok := scheme.(*JWT); ok {
if baseIdentityProviderPrecedence(apidef.JWTClaim) < resBaseIdentityProvider {
resBaseIdentityProvider = baseIdentityProviderPrecedence(apidef.JWTClaim)
res = apidef.JWTClaim
}
}
}
return
}
// AuthSources defines authentication source configuration: headers, cookies and query parameters.
//
// Tyk classic API definition: `auth_configs{}`.
type AuthSources struct {
// Header contains configurations for the header value auth source, it is enabled by default.
//
// Tyk classic API definition: `auth_configs[x].header`
Header *AuthSource `bson:"header,omitempty" json:"header,omitempty"`
// Cookie contains configurations for the cookie value auth source.
//
// Tyk classic API definition: `auth_configs[x].cookie`
Cookie *AuthSource `bson:"cookie,omitempty" json:"cookie,omitempty"`
// Query contains configurations for the query parameters auth source.
//
// Tyk classic API definition: `auth_configs[x].query`
Query *AuthSource `bson:"query,omitempty" json:"query,omitempty"`
}
// Fill fills *AuthSources from apidef.AuthConfig.
func (as *AuthSources) Fill(authConfig apidef.AuthConfig) {
// Allocate auth sources being filled.
if as.Header == nil {
as.Header = &AuthSource{}
}
if as.Cookie == nil {
as.Cookie = &AuthSource{}
}
if as.Query == nil {
as.Query = &AuthSource{}
}
// Fill the auth source structures.
as.Header.Fill(!authConfig.DisableHeader, authConfig.AuthHeaderName)
as.Query.Fill(authConfig.UseParam, authConfig.ParamName)
as.Cookie.Fill(authConfig.UseCookie, authConfig.CookieName)
// Check if auth sources should be omitted as they may be undefined.
if ShouldOmit(as.Cookie) {
as.Cookie = nil
}
if ShouldOmit(as.Header) {
as.Header = nil
}
if ShouldOmit(as.Query) {
as.Query = nil
}
}
// ExtractTo extracts *AuthSources to *apidef.AuthConfig.
func (as *AuthSources) ExtractTo(authConfig *apidef.AuthConfig) {
// Extract Header auth source.
if as.Header != nil {
var enabled bool
as.Header.ExtractTo(&enabled, &authConfig.AuthHeaderName)
authConfig.DisableHeader = !enabled
} else {
authConfig.DisableHeader = true
}
// Extract Query auth source.
if as.Query != nil {
as.Query.ExtractTo(&authConfig.UseParam, &authConfig.ParamName)
}
// Extract Cookie auth source.
if as.Cookie != nil {
as.Cookie.ExtractTo(&authConfig.UseCookie, &authConfig.CookieName)
}
}
// AuthSource defines an authentication source.
type AuthSource struct {
// Enabled activates the auth source.
//
// Tyk classic API definition: `auth_configs[X].use_param/use_cookie`.
Enabled bool `bson:"enabled" json:"enabled"` // required
// Name is the name of the auth source.
//
// Tyk classic API definition: `auth_configs[X].param_name/cookie_name`.
Name string `bson:"name,omitempty" json:"name,omitempty"`
}
// Fill fills *AuthSource with values from the parameters.
func (as *AuthSource) Fill(enabled bool, name string) {
as.Enabled = enabled
as.Name = name
}
// ExtractTo extracts *AuthSource into the function parameters.
func (as *AuthSource) ExtractTo(enabled *bool, name *string) {
*enabled = as.Enabled
*name = as.Name
}
// Signature holds the configuration for signature validation.
type Signature struct {
// Enabled activates signature validation.
//
// Tyk classic API definition: `auth_configs[X].validate_signature`.
Enabled bool `bson:"enabled" json:"enabled"` // required
// Algorithm is the signature method to use.
//
// Tyk classic API definition: `auth_configs[X].signature.algorithm`.
Algorithm string `bson:"algorithm,omitempty" json:"algorithm,omitempty"`
// Header is the name of the header to consume.
//
// Tyk classic API definition: `auth_configs[X].signature.header`.
Header string `bson:"header,omitempty" json:"header,omitempty"`
// Query is the name of the query parameter to consume.
//
// Tyk classic API definition: `auth_configs[X].signature.use_param/param_name`.
Query AuthSource `bson:"query,omitempty" json:"query,omitempty"`
// Secret is the signing secret used for signature validation.
//
// Tyk classic API definition: `auth_configs[X].signature.secret`.
Secret string `bson:"secret,omitempty" json:"secret,omitempty"`
// AllowedClockSkew configures a grace period in seconds during which an expired token is still valid.
//
// Tyk classic API definition: `auth_configs[X].signature.allowed_clock_skew`.
AllowedClockSkew int64 `bson:"allowedClockSkew,omitempty" json:"allowedClockSkew,omitempty"`
// ErrorCode configures the HTTP response code for a validation failure.
// If unconfigured, a HTTP 401 Unauthorized status code will be emitted.
//
// Tyk classic API definition: `auth_configs[X].signature.error_code`.
ErrorCode int `bson:"errorCode,omitempty" json:"errorCode,omitempty"`
// ErrorMessage configures the error message that is emitted on validation failure.
// A default error message is emitted if unset.
//
// Tyk classic API definition: `auth_configs[X].signature.error_message`.
ErrorMessage string `bson:"errorMessage,omitempty" json:"errorMessage,omitempty"`
}
// Fill fills *Signature from apidef.AuthConfig.
func (s *Signature) Fill(authConfig apidef.AuthConfig) {
signature := authConfig.Signature
s.Enabled = authConfig.ValidateSignature
s.Algorithm = signature.Algorithm
s.Header = signature.Header
s.Query.Fill(signature.UseParam, signature.ParamName)
s.Secret = signature.Secret
s.AllowedClockSkew = signature.AllowedClockSkew
s.ErrorCode = signature.ErrorCode
s.ErrorMessage = signature.ErrorMessage
}
// ExtractTo extracts *Signature to *apidef.AuthConfig.
func (s *Signature) ExtractTo(authConfig *apidef.AuthConfig) {
authConfig.ValidateSignature = s.Enabled
authConfig.Signature.Algorithm = s.Algorithm
authConfig.Signature.Header = s.Header
s.Query.ExtractTo(&authConfig.Signature.UseParam, &authConfig.Signature.ParamName)
authConfig.Signature.Secret = s.Secret
authConfig.Signature.AllowedClockSkew = s.AllowedClockSkew
authConfig.Signature.ErrorCode = s.ErrorCode
authConfig.Signature.ErrorMessage = s.ErrorMessage
}
// Scopes holds the scope to policy mappings for a claim name.
// This struct is used for both JWT and OIDC authentication.
type Scopes struct {
// ClaimName contains the claim name.
//
// Tyk classic API definition:
// - For OIDC: `scopes.oidc.scope_claim_name`
// - For JWT: `scopes.jwt.scope_claim_name`
ClaimName string `bson:"claimName,omitempty" json:"claimName,omitempty"`
// Claims specifies a list of claims that can be used to provide the scope-to-policy mapping.
// The first match from the list found in the token will be interrogated to retrieve the scopes that are then checked against the scopeToPolicyMapping.
Claims []string `bson:"claims,omitempty" json:"claims,omitempty"`
// ScopeToPolicyMapping contains the mappings of scopes to policy IDs.
//
// Tyk classic API definition:
// - For OIDC: `scopes.oidc.scope_to_policy`
// - For JWT: `scopes.jwt.scope_to_policy`
ScopeToPolicyMapping []ScopeToPolicy `bson:"scopeToPolicyMapping,omitempty" json:"scopeToPolicyMapping,omitempty"`
}
// Fill fills *Scopes from *apidef.ScopeClaim.
func (s *Scopes) Fill(scopeClaim *apidef.ScopeClaim) {
s.ClaimName = scopeClaim.ScopeClaimName
if s.ClaimName != "" && len(s.Claims) < 1 {
s.Claims = []string{scopeClaim.ScopeClaimName}
}
s.ScopeToPolicyMapping = []ScopeToPolicy{}
for scope, policyID := range scopeClaim.ScopeToPolicy {
s.ScopeToPolicyMapping = append(s.ScopeToPolicyMapping, ScopeToPolicy{Scope: scope, PolicyID: policyID})
}
sort.Slice(s.ScopeToPolicyMapping, func(i, j int) bool {
return s.ScopeToPolicyMapping[i].Scope < s.ScopeToPolicyMapping[j].Scope
})
if len(s.ScopeToPolicyMapping) == 0 {
s.ScopeToPolicyMapping = nil
}
}
// ExtractTo extracts *Scopes to *apidef.ScopeClaim.
func (s *Scopes) ExtractTo(scopeClaim *apidef.ScopeClaim) {
scopeClaim.ScopeClaimName = s.ClaimName
scopeClaim.ScopeToPolicy = map[string]string{}
for _, v := range s.ScopeToPolicyMapping {
scopeClaim.ScopeToPolicy[v.Scope] = v.PolicyID
}
}
// ScopeToPolicy contains a single scope to policy ID mapping.
// This struct is used for both JWT and OIDC authentication.
type ScopeToPolicy struct {
// Scope contains the scope name.
//
// Tyk classic API definition:
// - For OIDC: Key in `scopes.oidc.scope_to_policy` map
// - For JWT: Key in `scopes.jwt.scope_to_policy` map.
Scope string `bson:"scope,omitempty" json:"scope,omitempty"`
// PolicyID contains the Policy ID.
//
// Tyk classic API definition:
// - For OIDC: Value in `scopes.oidc.scope_to_policy` map
// - For JWT: Value in `scopes.jwt.scope_to_policy` map.
PolicyID string `bson:"policyId,omitempty" json:"policyId,omitempty"`
}
// HMAC holds the configuration for the HMAC authentication mode.
type HMAC struct {
SecuritySchemeMarkerImpl
// Enabled activates the HMAC authentication mode.
//
// Tyk classic API definition: `enable_signature_checking`.
Enabled bool `bson:"enabled" json:"enabled"` // required
// AuthSources contains authentication token source configuration (header, cookie, query).
AuthSources `bson:",inline" json:",inline"`
// AllowedAlgorithms is the array of HMAC algorithms which are allowed.
//
// Tyk supports the following HMAC algorithms:
//
// - `hmac-sha1`
// - `hmac-sha256`
// - `hmac-sha384`
// - `hmac-sha512`
//
// and reads the value from the algorithm header.
//
// Tyk classic API definition: `hmac_allowed_algorithms`.
AllowedAlgorithms []string `bson:"allowedAlgorithms,omitempty" json:"allowedAlgorithms,omitempty"`
// AllowedClockSkew is the amount of milliseconds that will be tolerated for clock skew. It is used against replay attacks.
// The default value is `0`, which deactivates clock skew checks.
//
// Tyk classic API definition: `hmac_allowed_clock_skew`.
AllowedClockSkew float64 `bson:"allowedClockSkew,omitempty" json:"allowedClockSkew,omitempty"`
}
// Fill fills *HMAC from apidef.APIDefinition.
func (h *HMAC) Fill(api apidef.APIDefinition) {
h.Enabled = api.EnableSignatureChecking
h.AuthSources.Fill(api.AuthConfigs["hmac"])
h.AllowedAlgorithms = api.HmacAllowedAlgorithms
h.AllowedClockSkew = api.HmacAllowedClockSkew
}
// ExtractTo extracts *HMAC to *apidef.APIDefinition.
func (h *HMAC) ExtractTo(api *apidef.APIDefinition) {
api.EnableSignatureChecking = h.Enabled
authConfig := apidef.AuthConfig{}
h.AuthSources.ExtractTo(&authConfig)
if api.AuthConfigs == nil {
api.AuthConfigs = make(map[string]apidef.AuthConfig)
}
api.AuthConfigs["hmac"] = authConfig
api.HmacAllowedAlgorithms = h.AllowedAlgorithms
api.HmacAllowedClockSkew = h.AllowedClockSkew
}
// OIDC contains configuration for the OIDC authentication mode.
// OIDC support will be deprecated starting from 5.7.0.
// To avoid any disruptions, we recommend that you use JSON Web Token (JWT) instead,
// as explained in https://tyk.io/docs/basic-config-and-security/security/authentication-authorization/openid-connect/.
type OIDC struct {
// Enabled activates the OIDC authentication mode.
//
// Tyk classic API definition: `use_openid`
Enabled bool `bson:"enabled" json:"enabled"` // required
// AuthSources contains authentication token source configuration (header, cookie, query).
AuthSources `bson:",inline" json:",inline"`
// SegregateByClientId is a boolean flag. If set to `true, the policies will be applied to a combination of Client ID and User ID.
//
// Tyk classic API definition: `openid_options.segregate_by_client`.
SegregateByClientId bool `bson:"segregateByClientId,omitempty" json:"segregateByClientId,omitempty"`
// Providers contains a list of authorized providers, their Client IDs and matched policies.
//
// Tyk classic API definition: `openid_options.providers`.
Providers []Provider `bson:"providers,omitempty" json:"providers,omitempty"`
// Scopes contains the defined scope claims.
Scopes *Scopes `bson:"scopes,omitempty" json:"scopes,omitempty"`
}
// Fill fills *OIDC from apidef.APIDefinition.
func (o *OIDC) Fill(api apidef.APIDefinition) {
o.Enabled = api.UseOpenID
o.AuthSources.Fill(api.AuthConfigs["oidc"])
o.SegregateByClientId = api.OpenIDOptions.SegregateByClient
o.Providers = []Provider{}
for _, v := range api.OpenIDOptions.Providers {
var mapping []ClientToPolicy
for clientID, polID := range v.ClientIDs {
mapping = append(mapping, ClientToPolicy{ClientID: clientID, PolicyID: polID})
}
if len(mapping) == 0 {
mapping = nil
}
sort.Slice(mapping, func(i, j int) bool {
return mapping[i].ClientID < mapping[j].ClientID
})
o.Providers = append(o.Providers, Provider{Issuer: v.Issuer, ClientToPolicyMapping: mapping})
}
if len(o.Providers) == 0 {
o.Providers = nil
}
if o.Scopes == nil {
o.Scopes = &Scopes{}
}
o.Scopes.Fill(&api.Scopes.OIDC)
if ShouldOmit(o.Scopes) {
o.Scopes = nil
}
}
// ExtractTo extracts *OIDC to *apidef.APIDefinition.
func (o *OIDC) ExtractTo(api *apidef.APIDefinition) {
api.UseOpenID = o.Enabled
authConfig := apidef.AuthConfig{}
o.AuthSources.ExtractTo(&authConfig)
if api.AuthConfigs == nil {
api.AuthConfigs = make(map[string]apidef.AuthConfig)
}
api.AuthConfigs["oidc"] = authConfig
api.OpenIDOptions.SegregateByClient = o.SegregateByClientId
api.OpenIDOptions.Providers = []apidef.OIDProviderConfig{}
for _, p := range o.Providers {
clientIDs := make(map[string]string)
for _, mapping := range p.ClientToPolicyMapping {
clientIDs[mapping.ClientID] = mapping.PolicyID
}
api.OpenIDOptions.Providers = append(api.OpenIDOptions.Providers, apidef.OIDProviderConfig{Issuer: p.Issuer, ClientIDs: clientIDs})
}
if o.Scopes != nil {
o.Scopes.ExtractTo(&api.Scopes.OIDC)
}
}
// Provider defines an issuer to validate and the Client ID to Policy ID mappings.
type Provider struct {
// Issuer contains a validation value for the issuer claim, usually a domain name e.g. `accounts.google.com` or similar.
//
// Tyk classic API definition: `openid_options.providers[].issuer`.
Issuer string `bson:"issuer,omitempty" json:"issuer,omitempty"`
// ClientToPolicyMapping contains mappings of Client IDs to Policy IDs.
//
// Tyk classic API definition: `openid_options.providers[].client_ids`.
ClientToPolicyMapping []ClientToPolicy `bson:"clientToPolicyMapping,omitempty" json:"clientToPolicyMapping,omitempty"`
}
// ClientToPolicy contains a 1-1 mapping between Client ID and Policy ID.
type ClientToPolicy struct {
// ClientID contains a Client ID.
//
// Tyk classic API definition: Key in `openid_options.providers[].client_ids` map.
ClientID string `bson:"clientId,omitempty" json:"clientId,omitempty"`
// PolicyID contains a Policy ID.
//
// Tyk classic API definition: Value in `openid_options.providers[].client_ids` map.
PolicyID string `bson:"policyId,omitempty" json:"policyId,omitempty"`
}
// CustomPluginAuthentication holds configuration for custom plugins.
type CustomPluginAuthentication struct {
SecuritySchemeMarkerImpl
// Enabled activates the CustomPluginAuthentication authentication mode.
//
// Tyk classic API definition: `enable_coprocess_auth`/`use_go_plugin_auth`.
Enabled bool `bson:"enabled" json:"enabled"` // required
// Config contains configuration related to custom authentication plugin.
//
// Tyk classic API definition: `custom_middleware.auth_check`.
Config *AuthenticationPlugin `bson:"config,omitempty" json:"config,omitempty"`
// AuthSources contains authentication token sources (header, cookie, query).
// Valid only when driver is coprocess.
//
// Tyk classic API definition: `auth_configs["coprocess"]`.
AuthSources `bson:",inline" json:",inline"`
}
// Fill fills *CustomPluginAuthentication from apidef.AuthConfig.
func (c *CustomPluginAuthentication) Fill(api apidef.APIDefinition) {
c.Enabled = api.CustomPluginAuthEnabled
if c.Config == nil {
c.Config = &AuthenticationPlugin{}
}
c.Config.Fill(api)
if ShouldOmit(c.Config) {
c.Config = nil
}
if ShouldOmit(api.AuthConfigs[apidef.CoprocessType]) {
return
}
c.AuthSources.Fill(api.AuthConfigs[apidef.CoprocessType])
}
// ExtractTo extracts *CustomPluginAuthentication to *apidef.APIDefinition.
func (c *CustomPluginAuthentication) ExtractTo(api *apidef.APIDefinition) {
api.CustomPluginAuthEnabled = c.Enabled
if c.Config == nil {
c.Config = &AuthenticationPlugin{}
defer func() {
c.Config = nil
}()
}
c.Config.ExtractTo(api)
authConfig := apidef.AuthConfig{}
c.AuthSources.ExtractTo(&authConfig)
if reflect.DeepEqual(authConfig, apidef.AuthConfig{DisableHeader: true}) {
return
}
if api.AuthConfigs == nil {
api.AuthConfigs = make(map[string]apidef.AuthConfig)
}
api.AuthConfigs[apidef.CoprocessType] = authConfig
}
// AuthenticationPlugin holds the configuration for custom authentication plugin.
type AuthenticationPlugin struct {
// Enabled activates custom authentication plugin.
//
// Tyk classic API definition: `custom_middleware.auth_check.disabled` (negated).
Enabled bool `bson:"enabled" json:"enabled"` // required.
// FunctionName is the name of authentication method.
//
// Tyk classic API definition: `custom_middleware.auth_check.name`.
FunctionName string `bson:"functionName" json:"functionName"` // required.
// Path is the path to shared object file in case of goplugin mode or path to JS code in case of otto auth plugin.
//
// Tyk classic API definition: `custom_middleware.auth_check.path`.
Path string `bson:"path" json:"path"`