GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 09e2c6...a4f7a0 )
by
unknown
05:49
created

credentials.Config.GoString   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
package credentials
2
3
import (
4
	"bufio"
5
	"errors"
6
	"fmt"
7
	"net/http"
8
	"net/url"
9
	"os"
10
	"strings"
11
	"time"
12
13
	"github.com/alibabacloud-go/debug/debug"
14
	"github.com/alibabacloud-go/tea/tea"
15
	"github.com/aliyun/credentials-go/credentials/internal/providers"
16
	"github.com/aliyun/credentials-go/credentials/internal/utils"
17
	"github.com/aliyun/credentials-go/credentials/request"
18
	"github.com/aliyun/credentials-go/credentials/response"
19
)
20
21
var debuglog = debug.Init("credential")
22
23
var hookParse = func(err error) error {
24
	return err
25
}
26
27
// Credential is an interface for getting actual credential
28
type Credential interface {
29
	// Deprecated: GetAccessKeyId is deprecated, use GetCredential instead of.
30
	GetAccessKeyId() (*string, error)
31
	// Deprecated: GetAccessKeySecret is deprecated, use GetCredential instead of.
32
	GetAccessKeySecret() (*string, error)
33
	// Deprecated: GetSecurityToken is deprecated, use GetCredential instead of.
34
	GetSecurityToken() (*string, error)
35
	GetBearerToken() *string
36
	GetType() *string
37
	GetCredential() (*CredentialModel, error)
38
}
39
40
// Config is important when call NewCredential
41
type Config struct {
42
	Type                  *string  `json:"type"`
43
	AccessKeyId           *string  `json:"access_key_id"`
44
	AccessKeySecret       *string  `json:"access_key_secret"`
45
	OIDCProviderArn       *string  `json:"oidc_provider_arn"`
46
	OIDCTokenFilePath     *string  `json:"oidc_token"`
47
	RoleArn               *string  `json:"role_arn"`
48
	RoleSessionName       *string  `json:"role_session_name"`
49
	PublicKeyId           *string  `json:"public_key_id"`
50
	RoleName              *string  `json:"role_name"`
51
	EnableIMDSv2          *bool    `json:"enable_imds_v2"`
52
	MetadataTokenDuration *int     `json:"metadata_token_duration"`
53
	SessionExpiration     *int     `json:"session_expiration"`
54
	PrivateKeyFile        *string  `json:"private_key_file"`
55
	BearerToken           *string  `json:"bearer_token"`
56
	SecurityToken         *string  `json:"security_token"`
57
	RoleSessionExpiration *int     `json:"role_session_expiratioon"`
58
	Policy                *string  `json:"policy"`
59
	Host                  *string  `json:"host"`
60
	Timeout               *int     `json:"timeout"`
61
	ConnectTimeout        *int     `json:"connect_timeout"`
62
	Proxy                 *string  `json:"proxy"`
63
	InAdvanceScale        *float64 `json:"inAdvanceScale"`
64
	Url                   *string  `json:"url"`
65
	STSEndpoint           *string  `json:"sts_endpoint"`
66
	ExternalId            *string  `json:"external_id"`
67
}
68
69
func (s Config) String() string {
70
	return tea.Prettify(s)
71
}
72
73
func (s Config) GoString() string {
74
	return s.String()
75
}
76
77
func (s *Config) SetAccessKeyId(v string) *Config {
78
	s.AccessKeyId = &v
79
	return s
80
}
81
82
func (s *Config) SetAccessKeySecret(v string) *Config {
83
	s.AccessKeySecret = &v
84
	return s
85
}
86
87
func (s *Config) SetSecurityToken(v string) *Config {
88
	s.SecurityToken = &v
89
	return s
90
}
91
92
func (s *Config) SetRoleArn(v string) *Config {
93
	s.RoleArn = &v
94
	return s
95
}
96
97
func (s *Config) SetRoleSessionName(v string) *Config {
98
	s.RoleSessionName = &v
99
	return s
100
}
101
102
func (s *Config) SetPublicKeyId(v string) *Config {
103
	s.PublicKeyId = &v
104
	return s
105
}
106
107
func (s *Config) SetRoleName(v string) *Config {
108
	s.RoleName = &v
109
	return s
110
}
111
112
func (s *Config) SetEnableIMDSv2(v bool) *Config {
113
	s.EnableIMDSv2 = &v
114
	return s
115
}
116
117
func (s *Config) SetMetadataTokenDuration(v int) *Config {
118
	s.MetadataTokenDuration = &v
119
	return s
120
}
121
122
func (s *Config) SetSessionExpiration(v int) *Config {
123
	s.SessionExpiration = &v
124
	return s
125
}
126
127
func (s *Config) SetPrivateKeyFile(v string) *Config {
128
	s.PrivateKeyFile = &v
129
	return s
130
}
131
132
func (s *Config) SetBearerToken(v string) *Config {
133
	s.BearerToken = &v
134
	return s
135
}
136
137
func (s *Config) SetRoleSessionExpiration(v int) *Config {
138
	s.RoleSessionExpiration = &v
139
	return s
140
}
141
142
func (s *Config) SetPolicy(v string) *Config {
143
	s.Policy = &v
144
	return s
145
}
146
147
func (s *Config) SetHost(v string) *Config {
148
	s.Host = &v
149
	return s
150
}
151
152
func (s *Config) SetTimeout(v int) *Config {
153
	s.Timeout = &v
154
	return s
155
}
156
157
func (s *Config) SetConnectTimeout(v int) *Config {
158
	s.ConnectTimeout = &v
159
	return s
160
}
161
162
func (s *Config) SetProxy(v string) *Config {
163
	s.Proxy = &v
164
	return s
165
}
166
167
func (s *Config) SetType(v string) *Config {
168
	s.Type = &v
169
	return s
170
}
171
172
func (s *Config) SetOIDCTokenFilePath(v string) *Config {
173
	s.OIDCTokenFilePath = &v
174
	return s
175
}
176
177
func (s *Config) SetOIDCProviderArn(v string) *Config {
178
	s.OIDCProviderArn = &v
179
	return s
180
}
181
182
func (s *Config) SetURLCredential(v string) *Config {
183
	if v == "" {
184
		v = os.Getenv("ALIBABA_CLOUD_CREDENTIALS_URI")
185
	}
186
	s.Url = &v
187
	return s
188
}
189
190
func (s *Config) SetSTSEndpoint(v string) *Config {
191
	s.STSEndpoint = &v
192
	return s
193
}
194
195
// NewCredential return a credential according to the type in config.
196
// if config is nil, the function will use default provider chain to get credential.
197
// please see README.md for detail.
198
func NewCredential(config *Config) (credential Credential, err error) {
199
	if config == nil {
200
		config, err = defaultChain.resolve()
201
		if err != nil {
202
			return
203
		}
204
		return NewCredential(config)
205
	}
206
	switch tea.StringValue(config.Type) {
207
	case "credentials_uri":
208
		credential = newURLCredential(tea.StringValue(config.Url))
209
	case "oidc_role_arn":
210
		err = checkoutAssumeRamoidc(config)
211
		if err != nil {
212
			return
213
		}
214
		runtime := &utils.Runtime{
215
			Host:           tea.StringValue(config.Host),
216
			Proxy:          tea.StringValue(config.Proxy),
217
			ReadTimeout:    tea.IntValue(config.Timeout),
218
			ConnectTimeout: tea.IntValue(config.ConnectTimeout),
219
			STSEndpoint:    tea.StringValue(config.STSEndpoint),
220
		}
221
		credential, err = newOIDCRoleArnCredential(
222
			tea.StringValue(config.AccessKeyId),
223
			tea.StringValue(config.AccessKeySecret),
224
			tea.StringValue(config.RoleArn),
225
			tea.StringValue(config.OIDCProviderArn),
226
			tea.StringValue(config.OIDCTokenFilePath),
227
			tea.StringValue(config.RoleSessionName),
228
			tea.StringValue(config.Policy),
229
			tea.IntValue(config.RoleSessionExpiration),
230
			runtime)
231
		if err != nil {
232
			return
233
		}
234
	case "access_key":
235
		provider, err := providers.NewStaticAKCredentialsProviderBuilder().
236
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
237
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
238
			Build()
239
		if err != nil {
240
			return nil, err
241
		}
242
243
		credential = fromCredentialsProvider("access_key", provider)
244
	case "sts":
245
		provider, err := providers.NewStaticSTSCredentialsProviderBuilder().
246
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
247
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
248
			WithSecurityToken(tea.StringValue(config.SecurityToken)).
249
			Build()
250
		if err != nil {
251
			return nil, err
252
		}
253
254
		credential = fromCredentialsProvider("sts", provider)
255
	case "ecs_ram_role":
256
		runtime := &utils.Runtime{
257
			Host:           tea.StringValue(config.Host),
258
			ReadTimeout:    tea.IntValue(config.Timeout),
259
			ConnectTimeout: tea.IntValue(config.ConnectTimeout),
260
		}
261
		credential = newEcsRAMRoleCredentialWithEnableIMDSv2(
262
			tea.StringValue(config.RoleName),
263
			tea.BoolValue(config.EnableIMDSv2),
264
			tea.IntValue(config.MetadataTokenDuration),
265
			tea.Float64Value(config.InAdvanceScale),
266
			runtime)
267
	case "ram_role_arn":
268
		var credentialsProvider providers.CredentialsProvider
269
		if config.SecurityToken != nil {
270
			credentialsProvider, err = providers.NewStaticSTSCredentialsProviderBuilder().
271
				WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
272
				WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
273
				WithSecurityToken(tea.StringValue(config.SecurityToken)).
274
				Build()
275
		} else {
276
			credentialsProvider, err = providers.NewStaticAKCredentialsProviderBuilder().
277
				WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
278
				WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
279
				Build()
280
		}
281
282
		if err != nil {
283
			return nil, err
284
		}
285
286
		provider, err := providers.NewRAMRoleARNCredentialsProviderBuilder().
287
			WithCredentialsProvider(credentialsProvider).
288
			WithRoleArn(tea.StringValue(config.RoleArn)).
289
			WithRoleSessionName(tea.StringValue(config.RoleSessionName)).
290
			WithPolicy(tea.StringValue(config.Policy)).
291
			WithDurationSeconds(tea.IntValue(config.RoleSessionExpiration)).
292
			WithExternalId(tea.StringValue(config.ExternalId)).
293
			WithStsEndpoint(tea.StringValue(config.STSEndpoint)).
294
			WithHttpOptions(&providers.HttpOptions{
295
				Proxy:          tea.StringValue(config.Proxy),
296
				ReadTimeout:    tea.IntValue(config.Timeout),
297
				ConnectTimeout: tea.IntValue(config.ConnectTimeout),
298
			}).
299
			Build()
300
		if err != nil {
301
			return nil, err
302
		}
303
304
		credential = fromCredentialsProvider("ram_role_arn", provider)
305
	case "rsa_key_pair":
306
		err = checkRSAKeyPair(config)
307
		if err != nil {
308
			return
309
		}
310
		file, err1 := os.Open(tea.StringValue(config.PrivateKeyFile))
311
		if err1 != nil {
312
			err = fmt.Errorf("InvalidPath: Can not open PrivateKeyFile, err is %s", err1.Error())
313
			return
314
		}
315
		defer file.Close()
316
		var privateKey string
317
		scan := bufio.NewScanner(file)
318
		for scan.Scan() {
319
			if strings.HasPrefix(scan.Text(), "----") {
320
				continue
321
			}
322
			privateKey += scan.Text() + "\n"
323
		}
324
		runtime := &utils.Runtime{
325
			Host:           tea.StringValue(config.Host),
326
			Proxy:          tea.StringValue(config.Proxy),
327
			ReadTimeout:    tea.IntValue(config.Timeout),
328
			ConnectTimeout: tea.IntValue(config.ConnectTimeout),
329
			STSEndpoint:    tea.StringValue(config.STSEndpoint),
330
		}
331
		credential = newRsaKeyPairCredential(
332
			privateKey,
333
			tea.StringValue(config.PublicKeyId),
334
			tea.IntValue(config.SessionExpiration),
335
			runtime)
336
	case "bearer":
337
		if tea.StringValue(config.BearerToken) == "" {
338
			err = errors.New("BearerToken cannot be empty")
339
			return
340
		}
341
		credential = newBearerTokenCredential(tea.StringValue(config.BearerToken))
342
	default:
343
		err = errors.New("invalid type option, support: access_key, sts, ecs_ram_role, ram_role_arn, rsa_key_pair")
344
		return
345
	}
346
	return credential, nil
347
}
348
349
func checkRSAKeyPair(config *Config) (err error) {
350
	if tea.StringValue(config.PrivateKeyFile) == "" {
351
		err = errors.New("PrivateKeyFile cannot be empty")
352
		return
353
	}
354
	if tea.StringValue(config.PublicKeyId) == "" {
355
		err = errors.New("PublicKeyId cannot be empty")
356
		return
357
	}
358
	return
359
}
360
361
func checkoutAssumeRamoidc(config *Config) (err error) {
362
	if tea.StringValue(config.RoleArn) == "" {
363
		err = errors.New("RoleArn cannot be empty")
364
		return
365
	}
366
	if tea.StringValue(config.OIDCProviderArn) == "" {
367
		err = errors.New("OIDCProviderArn cannot be empty")
368
		return
369
	}
370
	return
371
}
372
373
func doAction(request *request.CommonRequest, runtime *utils.Runtime) (content []byte, err error) {
374
	var urlEncoded string
375
	if request.BodyParams != nil {
376
		urlEncoded = utils.GetURLFormedMap(request.BodyParams)
377
	}
378
	httpRequest, err := http.NewRequest(request.Method, request.URL, strings.NewReader(urlEncoded))
379
	if err != nil {
380
		return
381
	}
382
	httpRequest.Proto = "HTTP/1.1"
383
	httpRequest.Host = request.Domain
384
	debuglog("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
385
	debuglog("> Host: %s", httpRequest.Host)
386
	for key, value := range request.Headers {
387
		if value != "" {
388
			debuglog("> %s: %s", key, value)
389
			httpRequest.Header[key] = []string{value}
390
		}
391
	}
392
	debuglog(">")
393
	httpClient := &http.Client{}
394
	httpClient.Timeout = time.Duration(runtime.ReadTimeout) * time.Second
395
	proxy := &url.URL{}
396
	if runtime.Proxy != "" {
397
		proxy, err = url.Parse(runtime.Proxy)
398
		if err != nil {
399
			return
400
		}
401
	}
402
	trans := &http.Transport{}
403
	if proxy != nil && runtime.Proxy != "" {
404
		trans.Proxy = http.ProxyURL(proxy)
405
	}
406
	trans.DialContext = utils.Timeout(time.Duration(runtime.ConnectTimeout) * time.Second)
407
	httpClient.Transport = trans
408
	httpResponse, err := hookDo(httpClient.Do)(httpRequest)
409
	if err != nil {
410
		return
411
	}
412
	debuglog("< %s %s", httpResponse.Proto, httpResponse.Status)
413
	for key, value := range httpResponse.Header {
414
		debuglog("< %s: %v", key, strings.Join(value, ""))
415
	}
416
	debuglog("<")
417
418
	resp := &response.CommonResponse{}
419
	err = hookParse(resp.ParseFromHTTPResponse(httpResponse))
420
	if err != nil {
421
		return
422
	}
423
	debuglog("%s", resp.GetHTTPContentString())
424
	if resp.GetHTTPStatus() != http.StatusOK {
425
		err = fmt.Errorf("httpStatus: %d, message = %s", resp.GetHTTPStatus(), resp.GetHTTPContentString())
426
		return
427
	}
428
	return resp.GetHTTPContentBytes(), nil
429
}
430
431
type credentialsProviderWrap struct {
432
	typeName string
433
	provider providers.CredentialsProvider
434
}
435
436
func (cp *credentialsProviderWrap) GetAccessKeyId() (accessKeyId *string, err error) {
437
	cc, err := cp.provider.GetCredentials()
438
	if err != nil {
439
		return
440
	}
441
	accessKeyId = &cc.AccessKeyId
442
	return
443
}
444
445
func (cp *credentialsProviderWrap) GetAccessKeySecret() (accessKeySecret *string, err error) {
446
	cc, err := cp.provider.GetCredentials()
447
	if err != nil {
448
		return
449
	}
450
	accessKeySecret = &cc.AccessKeySecret
451
	return
452
}
453
454
func (cp *credentialsProviderWrap) GetSecurityToken() (securityToken *string, err error) {
455
	cc, err := cp.provider.GetCredentials()
456
	if err != nil {
457
		return
458
	}
459
	securityToken = &cc.SecurityToken
460
	return
461
}
462
463
func (cp *credentialsProviderWrap) GetBearerToken() (bearerToken *string) {
464
	return tea.String("")
465
}
466
467
func (cp *credentialsProviderWrap) GetCredential() (cm *CredentialModel, err error) {
468
	c, err := cp.provider.GetCredentials()
469
	if err != nil {
470
		return
471
	}
472
473
	cm = &CredentialModel{
474
		AccessKeyId:     &c.AccessKeyId,
475
		AccessKeySecret: &c.AccessKeySecret,
476
		SecurityToken:   &c.SecurityToken,
477
		Type:            &c.ProviderName,
478
	}
479
	return
480
}
481
482
func (cp *credentialsProviderWrap) GetType() *string {
483
	return &cp.typeName
484
}
485
486
func fromCredentialsProvider(typeName string, cp providers.CredentialsProvider) Credential {
487
	return &credentialsProviderWrap{
488
		typeName: typeName,
489
		provider: cp,
490
	}
491
}
492