forked from okta/okta-sdk-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configuration.go
541 lines (463 loc) · 15.3 KB
/
configuration.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
/*
Okta Admin Management
Allows customers to easily access the Okta Management APIs
Copyright 2018 - Present Okta, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API version: 5.1.0
Contact: devex-public@okta.com
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package okta
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/user"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/go-jose/go-jose/v3"
"github.com/kelseyhightower/envconfig"
"gopkg.in/yaml.v3"
)
// contextKeys are used to identify the type of value in the context.
// Since these are string, it is possible to get a short description of the
// context key for logging and debugging using key.String().
type contextKey string
func (c contextKey) String() string {
return "auth " + string(c)
}
var (
// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request.
ContextHttpSignatureAuth = contextKey("httpsignature")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
type BasicAuth struct {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
}
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey
type APIKey struct {
Key string
Prefix string
}
// ServerVariable stores the information about a server variable
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}
// ServerConfiguration stores the information about a server
type ServerConfiguration struct {
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Servers ServerConfigurations
OperationServers map[string]ServerConfigurations
HTTPClient *http.Client
UserAgentExtra string
Context context.Context
Okta struct {
Client struct {
Cache struct {
Enabled bool `yaml:"enabled" envconfig:"OKTA_CLIENT_CACHE_ENABLED"`
DefaultTtl int32 `yaml:"defaultTtl" envconfig:"OKTA_CLIENT_CACHE_DEFAULT_TTL"`
DefaultTti int32 `yaml:"defaultTti" envconfig:"OKTA_CLIENT_CACHE_DEFAULT_TTI"`
} `yaml:"cache"`
Proxy struct {
Port int32 `yaml:"port" envconfig:"OKTA_CLIENT_PROXY_PORT"`
Host string `yaml:"host" envconfig:"OKTA_CLIENT_PROXY_HOST"`
Username string `yaml:"username" envconfig:"OKTA_CLIENT_PROXY_USERNAME"`
Password string `yaml:"password" envconfig:"OKTA_CLIENT_PROXY_PASSWORD"`
} `yaml:"proxy"`
ConnectionTimeout int64 `yaml:"connectionTimeout" envconfig:"OKTA_CLIENT_CONNECTION_TIMEOUT"`
RequestTimeout int64 `yaml:"requestTimeout" envconfig:"OKTA_CLIENT_REQUEST_TIMEOUT"`
RateLimit struct {
MaxRetries int32 `yaml:"maxRetries" envconfig:"OKTA_CLIENT_RATE_LIMIT_MAX_RETRIES"`
MaxBackoff int64 `yaml:"maxBackoff" envconfig:"OKTA_CLIENT_RATE_LIMIT_MAX_BACKOFF"`
} `yaml:"rateLimit"`
OrgUrl string `yaml:"orgUrl" envconfig:"OKTA_CLIENT_ORGURL"`
Token string `yaml:"token" envconfig:"OKTA_CLIENT_TOKEN"`
AuthorizationMode string `yaml:"authorizationMode" envconfig:"OKTA_CLIENT_AUTHORIZATIONMODE"`
ClientId string `yaml:"clientId" envconfig:"OKTA_CLIENT_CLIENTID"`
ClientAssertion string `yaml:"clientAssertion" envconfig:"OKTA_CLIENT_CLIENTASSERTION"`
Scopes []string `yaml:"scopes" envconfig:"OKTA_CLIENT_SCOPES"`
PrivateKey string `yaml:"privateKey" envconfig:"OKTA_CLIENT_PRIVATEKEY"`
PrivateKeyId string `yaml:"privateKeyId" envconfig:"OKTA_CLIENT_PRIVATEKEYID"`
} `yaml:"client"`
Testing struct {
DisableHttpsCheck bool `yaml:"disableHttpsCheck" envconfig:"OKTA_TESTING_DISABLE_HTTPS_CHECK"`
} `yaml:"testing"`
} `yaml:"okta"`
PrivateKeySigner jose.Signer
CacheManager Cache
}
// NewConfiguration returns a new Configuration object
func NewConfiguration(conf ...ConfigSetter) (*Configuration, error) {
cfg := &Configuration{
DefaultHeader: make(map[string]string),
UserAgent: fmt.Sprintf("okta-sdk-golang/%s golang/%s %s/%s", "4.0.0", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Debug: false,
Servers: ServerConfigurations{
{
URL: "https://{yourOktaDomain}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"yourOktaDomain": {
Description: "The domain of your organization. This can be a provided subdomain of an official okta domain (okta.com, oktapreview.com, etc) or one of your configured custom domains.",
DefaultValue: "subdomain.okta.com",
},
},
},
},
OperationServers: map[string]ServerConfigurations{},
}
cfg.Okta.Testing.DisableHttpsCheck = false
cfg.Okta.Client.AuthorizationMode = "SSWS"
cfg = readConfigFromSystem(*cfg)
cfg = readConfigFromApplication(*cfg)
cfg = readConfigFromEnvironment(*cfg)
for _, confSetter := range conf {
confSetter(cfg)
}
purl, err := url.Parse(cfg.Okta.Client.OrgUrl)
if err != nil {
return nil, err
}
cfg.Host = purl.Hostname()
cfg.Scheme = purl.Scheme
if cfg.UserAgentExtra != "" {
cfg.UserAgent = fmt.Sprintf("%s %s", cfg.UserAgent, cfg.UserAgentExtra)
}
ctx := context.WithValue(
context.Background(),
ContextAPIKeys,
map[string]APIKey{
"API_Token": {
Key: cfg.Okta.Client.Token,
Prefix: cfg.Okta.Client.AuthorizationMode,
},
},
)
cfg.Context = ctx
return cfg, nil
}
func readConfigFromFile(location string, c Configuration) (*Configuration, error) {
yamlConfig, err := ioutil.ReadFile(location)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(yamlConfig, &c)
if err != nil {
return nil, err
}
return &c, err
}
func readConfigFromSystem(c Configuration) *Configuration {
currUser, err := user.Current()
if err != nil {
return &c
}
if currUser.HomeDir == "" {
return &c
}
conf, err := readConfigFromFile(currUser.HomeDir+"/.okta/okta.yaml", c)
if err != nil {
return &c
}
return conf
}
// read config from the project's root directory
func readConfigFromApplication(c Configuration) *Configuration {
_, b, _, _ := runtime.Caller(0)
conf, err := readConfigFromFile(filepath.Join(filepath.Dir(path.Join(path.Dir(b))), ".okta.yaml"), c)
if err != nil {
return &c
}
return conf
}
func readConfigFromEnvironment(c Configuration) *Configuration {
err := envconfig.Process("okta", &c)
if err != nil {
fmt.Println("error parsing")
return &c
}
return &c
}
// AddDefaultHeader adds a new HTTP header to the default header in the request
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// URL formats template on a index using given variables
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1)
}
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}
// ServerURL returns URL based on server settings
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, reportError("Invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
if operationIndices, ok := osi.(map[string]int); !ok {
return 0, reportError("Invalid type %T should be map[string]int", osi)
} else {
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
if operationVariables, ok := osv.(map[string]map[string]string); !ok {
return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
} else {
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}
type ConfigSetter func(*Configuration)
func WithCache(cache bool) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Cache.Enabled = cache
}
}
func WithCacheManager(cacheManager Cache) ConfigSetter {
return func(c *Configuration) {
c.CacheManager = cacheManager
}
}
func WithCacheTtl(i int32) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Cache.DefaultTtl = i
}
}
func WithCacheTti(i int32) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Cache.DefaultTti = i
}
}
func WithHttpClientPtr(httpClient *http.Client) ConfigSetter {
return func(c *Configuration) {
c.HTTPClient = httpClient
}
}
func WithConnectionTimeout(i int64) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.ConnectionTimeout = i
}
}
func WithProxyPort(i int32) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Proxy.Port = i
}
}
func WithProxyHost(host string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Proxy.Host = host
}
}
func WithProxyUsername(username string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Proxy.Username = username
}
}
func WithProxyPassword(pass string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Proxy.Password = pass
}
}
func WithOrgUrl(rawUrl string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.OrgUrl = rawUrl
}
}
func WithToken(token string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Token = token
}
}
func WithUserAgentExtra(userAgent string) ConfigSetter {
return func(c *Configuration) {
c.UserAgentExtra = userAgent
}
}
func WithTestingDisableHttpsCheck(httpsCheck bool) ConfigSetter {
return func(c *Configuration) {
c.Okta.Testing.DisableHttpsCheck = httpsCheck
}
}
func WithRequestTimeout(requestTimeout int64) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.RequestTimeout = requestTimeout
}
}
func WithRateLimitMaxRetries(maxRetries int32) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.RateLimit.MaxRetries = maxRetries
}
}
func WithRateLimitMaxBackOff(maxBackoff int64) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.RateLimit.MaxBackoff = maxBackoff
}
}
func WithAuthorizationMode(authzMode string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.AuthorizationMode = authzMode
}
}
func WithClientId(clientId string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.ClientId = clientId
}
}
func WithScopes(scopes []string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.Scopes = scopes
}
}
// WithPrivateKey sets private key key. Can be either a path to a private key or private key itself.
func WithPrivateKey(privateKey string) ConfigSetter {
return func(c *Configuration) {
if fileExists(privateKey) {
content, err := ioutil.ReadFile(privateKey)
if err != nil {
fmt.Printf("failed to read from provided private key file path: %v", err)
}
c.Okta.Client.PrivateKey = string(content)
} else {
c.Okta.Client.PrivateKey = privateKey
}
}
}
func WithPrivateKeyId(privateKeyId string) ConfigSetter {
return func(c *Configuration) {
c.Okta.Client.PrivateKeyId = privateKeyId
}
}
func WithPrivateKeySigner(signer jose.Signer) ConfigSetter {
return func(c *Configuration) {
c.PrivateKeySigner = signer
}
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) || errors.Is(err, syscall.ENAMETOOLONG) {
return false
}
fmt.Println("can not get information about the file containing private key, using provided value as the key itself")
return false
}
return !info.IsDir()
}