-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathauthentication_helpers.go
235 lines (208 loc) · 6.07 KB
/
authentication_helpers.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
package authentication
import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
libs "github.com/dysnix/predictkube-libs/external/configs"
"github.com/dysnix/predictkube-libs/external/http_transport"
pConfig "github.com/prometheus/common/config"
kedautil "github.com/kedacore/keda/v2/pkg/util"
)
const (
AuthModesKey = "authModes"
)
func GetAuthConfigs(triggerMetadata, authParams map[string]string) (out *AuthMeta, err error) {
out = &AuthMeta{}
authModes, ok := triggerMetadata[AuthModesKey]
// no authMode specified
if !ok {
return nil, nil
}
authTypes := strings.Split(authModes, ",")
for _, t := range authTypes {
authType := Type(strings.TrimSpace(t))
switch authType {
case BearerAuthType:
if len(authParams["bearerToken"]) == 0 {
return nil, errors.New("no bearer token provided")
}
if out.EnableBasicAuth {
return nil, errors.New("both bearer and basic authentication can not be set")
}
if out.EnableOAuth {
return nil, errors.New("both bearer and OAuth can not be set")
}
out.BearerToken = strings.TrimSuffix(authParams["bearerToken"], "\n")
out.EnableBearerAuth = true
case BasicAuthType:
if len(authParams["username"]) == 0 {
return nil, errors.New("no username given")
}
if out.EnableBearerAuth {
return nil, errors.New("both bearer and basic authentication can not be set")
}
if out.EnableOAuth {
return nil, errors.New("both bearer and OAuth can not be set")
}
out.Username = authParams["username"]
// password is optional. For convenience, many application implement basic auth with
// username as apikey and password as empty
out.Password = authParams["password"]
out.EnableBasicAuth = true
case TLSAuthType:
if len(authParams["cert"]) == 0 {
return nil, errors.New("no cert given")
}
out.Cert = authParams["cert"]
if len(authParams["key"]) == 0 {
return nil, errors.New("no key given")
}
out.Key = authParams["key"]
out.EnableTLS = true
case CustomAuthType:
if len(authParams["customAuthHeader"]) == 0 {
return nil, errors.New("no custom auth header given")
}
out.CustomAuthHeader = strings.TrimSuffix(authParams["customAuthHeader"], "\n")
if len(authParams["customAuthValue"]) == 0 {
return nil, errors.New("no custom auth value given")
}
out.CustomAuthValue = strings.TrimSuffix(authParams["customAuthValue"], "\n")
out.EnableCustomAuth = true
case OAuthType:
if out.EnableBasicAuth {
return nil, errors.New("both oauth and basic authentication can not be set")
}
if out.EnableBearerAuth {
return nil, errors.New("both oauth and bearer authentication can not be set")
}
out.EnableOAuth = true
out.OauthTokenURI = authParams["oauthTokenURI"]
out.Scopes = ParseScope(authParams["scope"])
out.ClientID = authParams["clientID"]
out.ClientSecret = authParams["clientSecret"]
v, err := ParseEndpointParams(authParams["endpointParams"])
if err != nil {
return nil, fmt.Errorf("incorrect value for endpointParams is given: %s", authParams["endpointParams"])
}
out.EndpointParams = v
default:
return nil, fmt.Errorf("incorrect value for authMode is given: %s", t)
}
}
if len(authParams["ca"]) > 0 {
out.CA = authParams["ca"]
}
return out, err
}
// ParseScope parse OAuth scopes from a comma separated string
// whitespace is trimmed
func ParseScope(inputStr string) []string {
scope := strings.TrimSpace(inputStr)
if scope != "" {
scopes := make([]string, 0)
list := strings.Split(scope, ",")
for _, sc := range list {
sc := strings.TrimSpace(sc)
if sc != "" {
scopes = append(scopes, sc)
}
}
if len(scopes) == 0 {
return nil
}
return scopes
}
return nil
}
// ParseEndpointParams parse OAuth endpoint params from URL-encoded query string.
func ParseEndpointParams(inputStr string) (url.Values, error) {
v, err := url.ParseQuery(inputStr)
if err != nil {
return nil, err
}
if len(v) == 0 {
return nil, nil
}
return v, nil
}
func GetBearerToken(auth *AuthMeta) string {
return fmt.Sprintf("Bearer %s", auth.BearerToken)
}
func NewTLSConfig(auth *AuthMeta, unsafeSsl bool) (*tls.Config, error) {
return kedautil.NewTLSConfig(
auth.Cert,
auth.Key,
auth.CA,
unsafeSsl,
)
}
func CreateHTTPRoundTripper(roundTripperType TransportType, auth *AuthMeta, conf ...*HTTPTransport) (rt http.RoundTripper, err error) {
unsafeSsl := false
tlsConfig := kedautil.CreateTLSClientConfig(unsafeSsl)
if auth != nil && (auth.CA != "" || auth.EnableTLS) {
tlsConfig, err = NewTLSConfig(auth, unsafeSsl)
if err != nil || tlsConfig == nil {
return nil, fmt.Errorf("error creating the TLS config: %w", err)
}
}
switch roundTripperType {
case NetHTTP:
// from official github.com/prometheus/client_golang/api package
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: tlsConfig,
}, nil
case FastHTTP:
// default configs
httpConf := &libs.HTTPTransport{
MaxIdleConnDuration: 10,
ReadTimeout: time.Second * 15,
WriteTimeout: time.Second * 15,
}
if len(conf) > 0 {
httpConf = &libs.HTTPTransport{
MaxIdleConnDuration: conf[0].MaxIdleConnDuration,
ReadTimeout: conf[0].ReadTimeout,
WriteTimeout: conf[0].WriteTimeout,
}
}
var roundTripper http.RoundTripper
if roundTripper, err = http_transport.NewHttpTransport(
libs.SetTransportConfigs(httpConf),
libs.SetTLS(tlsConfig),
); err != nil {
return nil, fmt.Errorf("error creating fast http round tripper: %w", err)
}
if auth != nil {
if auth.EnableBasicAuth {
rt = pConfig.NewBasicAuthRoundTripper(
auth.Username,
pConfig.Secret(auth.Password),
"", roundTripper,
)
}
if auth.EnableBearerAuth {
rt = pConfig.NewAuthorizationCredentialsRoundTripper(
"Bearer",
pConfig.Secret(auth.BearerToken),
roundTripper,
)
}
} else {
rt = roundTripper
}
return rt, nil
}
return rt, nil
}