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 ( 1d5d24...5a1e97 )
by Jackson
08:58
created

credentials/credential.go   F

Size/Duplication

Total Lines 485
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 80
eloc 341
dl 0
loc 485
rs 2
c 0
b 0
f 0

37 Methods

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