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 ( 412f4e...f5d62c )
by Jackson
16:33 queued 06:27
created

credentials.checkoutAssumeRamoidc   A

Complexity

Conditions 3

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nop 1
dl 0
loc 10
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
		runtime := &utils.Runtime{
211
			Host:           tea.StringValue(config.Host),
212
			Proxy:          tea.StringValue(config.Proxy),
213
			ReadTimeout:    tea.IntValue(config.Timeout),
214
			ConnectTimeout: tea.IntValue(config.ConnectTimeout),
215
		}
216
217
		provider, err := providers.NewOIDCCredentialsProviderBuilder().
218
			WithRoleArn(tea.StringValue(config.RoleArn)).
219
			WithOIDCTokenFilePath(tea.StringValue(config.OIDCTokenFilePath)).
220
			WithOIDCProviderARN(tea.StringValue(config.OIDCProviderArn)).
221
			WithDurationSeconds(tea.IntValue(config.RoleSessionExpiration)).
222
			WithPolicy(tea.StringValue(config.Policy)).
223
			WithRoleSessionName(tea.StringValue(config.RoleSessionName)).
224
			WithSTSEndpoint(tea.StringValue(config.STSEndpoint)).
225
			WithRuntime(runtime).
226
			Build()
227
228
		if err != nil {
229
			return nil, err
230
		}
231
		credential = fromCredentialsProvider("oidc_role_arn", provider)
232
	case "access_key":
233
		provider, err := providers.NewStaticAKCredentialsProviderBuilder().
234
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
235
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
236
			Build()
237
		if err != nil {
238
			return nil, err
239
		}
240
241
		credential = fromCredentialsProvider("access_key", provider)
242
	case "sts":
243
		provider, err := providers.NewStaticSTSCredentialsProviderBuilder().
244
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
245
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
246
			WithSecurityToken(tea.StringValue(config.SecurityToken)).
247
			Build()
248
		if err != nil {
249
			return nil, err
250
		}
251
252
		credential = fromCredentialsProvider("sts", provider)
253
	case "ecs_ram_role":
254
		provider, err := providers.NewECSRAMRoleCredentialsProviderBuilder().
255
			WithRoleName(tea.StringValue(config.RoleName)).
256
			WithEnableIMDSv2(tea.BoolValue(config.EnableIMDSv2)).
257
			WithMetadataTokenDurationSeconds(tea.IntValue(config.MetadataTokenDuration)).
258
			Build()
259
260
		if err != nil {
261
			return nil, err
262
		}
263
264
		credential = fromCredentialsProvider("ecs_ram_role", provider)
265
	case "ram_role_arn":
266
		var credentialsProvider providers.CredentialsProvider
267
		if config.SecurityToken != nil {
268
			credentialsProvider, err = providers.NewStaticSTSCredentialsProviderBuilder().
269
				WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
270
				WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
271
				WithSecurityToken(tea.StringValue(config.SecurityToken)).
272
				Build()
273
		} else {
274
			credentialsProvider, err = providers.NewStaticAKCredentialsProviderBuilder().
275
				WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
276
				WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
277
				Build()
278
		}
279
280
		if err != nil {
281
			return nil, err
282
		}
283
284
		provider, err := providers.NewRAMRoleARNCredentialsProviderBuilder().
285
			WithCredentialsProvider(credentialsProvider).
286
			WithRoleArn(tea.StringValue(config.RoleArn)).
287
			WithRoleSessionName(tea.StringValue(config.RoleSessionName)).
288
			WithPolicy(tea.StringValue(config.Policy)).
289
			WithDurationSeconds(tea.IntValue(config.RoleSessionExpiration)).
290
			WithExternalId(tea.StringValue(config.ExternalId)).
291
			WithStsEndpoint(tea.StringValue(config.STSEndpoint)).
292
			WithHttpOptions(&providers.HttpOptions{
293
				Proxy:          tea.StringValue(config.Proxy),
294
				ReadTimeout:    tea.IntValue(config.Timeout),
295
				ConnectTimeout: tea.IntValue(config.ConnectTimeout),
296
			}).
297
			Build()
298
		if err != nil {
299
			return nil, err
300
		}
301
302
		credential = fromCredentialsProvider("ram_role_arn", provider)
303
	case "rsa_key_pair":
304
		err = checkRSAKeyPair(config)
305
		if err != nil {
306
			return
307
		}
308
		file, err1 := os.Open(tea.StringValue(config.PrivateKeyFile))
309
		if err1 != nil {
310
			err = fmt.Errorf("InvalidPath: Can not open PrivateKeyFile, err is %s", err1.Error())
311
			return
312
		}
313
		defer file.Close()
314
		var privateKey string
315
		scan := bufio.NewScanner(file)
316
		for scan.Scan() {
317
			if strings.HasPrefix(scan.Text(), "----") {
318
				continue
319
			}
320
			privateKey += scan.Text() + "\n"
321
		}
322
		runtime := &utils.Runtime{
323
			Host:           tea.StringValue(config.Host),
324
			Proxy:          tea.StringValue(config.Proxy),
325
			ReadTimeout:    tea.IntValue(config.Timeout),
326
			ConnectTimeout: tea.IntValue(config.ConnectTimeout),
327
			STSEndpoint:    tea.StringValue(config.STSEndpoint),
328
		}
329
		credential = newRsaKeyPairCredential(
330
			privateKey,
331
			tea.StringValue(config.PublicKeyId),
332
			tea.IntValue(config.SessionExpiration),
333
			runtime)
334
	case "bearer":
335
		if tea.StringValue(config.BearerToken) == "" {
336
			err = errors.New("BearerToken cannot be empty")
337
			return
338
		}
339
		credential = newBearerTokenCredential(tea.StringValue(config.BearerToken))
340
	default:
341
		err = errors.New("invalid type option, support: access_key, sts, ecs_ram_role, ram_role_arn, rsa_key_pair")
342
		return
343
	}
344
	return credential, nil
345
}
346
347
func checkRSAKeyPair(config *Config) (err error) {
348
	if tea.StringValue(config.PrivateKeyFile) == "" {
349
		err = errors.New("PrivateKeyFile cannot be empty")
350
		return
351
	}
352
	if tea.StringValue(config.PublicKeyId) == "" {
353
		err = errors.New("PublicKeyId cannot be empty")
354
		return
355
	}
356
	return
357
}
358
359
func doAction(request *request.CommonRequest, runtime *utils.Runtime) (content []byte, err error) {
360
	var urlEncoded string
361
	if request.BodyParams != nil {
362
		urlEncoded = utils.GetURLFormedMap(request.BodyParams)
363
	}
364
	httpRequest, err := http.NewRequest(request.Method, request.URL, strings.NewReader(urlEncoded))
365
	if err != nil {
366
		return
367
	}
368
	httpRequest.Proto = "HTTP/1.1"
369
	httpRequest.Host = request.Domain
370
	debuglog("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
371
	debuglog("> Host: %s", httpRequest.Host)
372
	for key, value := range request.Headers {
373
		if value != "" {
374
			debuglog("> %s: %s", key, value)
375
			httpRequest.Header[key] = []string{value}
376
		}
377
	}
378
	debuglog(">")
379
	httpClient := &http.Client{}
380
	httpClient.Timeout = time.Duration(runtime.ReadTimeout) * time.Second
381
	proxy := &url.URL{}
382
	if runtime.Proxy != "" {
383
		proxy, err = url.Parse(runtime.Proxy)
384
		if err != nil {
385
			return
386
		}
387
	}
388
	trans := &http.Transport{}
389
	if proxy != nil && runtime.Proxy != "" {
390
		trans.Proxy = http.ProxyURL(proxy)
391
	}
392
	trans.DialContext = utils.Timeout(time.Duration(runtime.ConnectTimeout) * time.Second)
393
	httpClient.Transport = trans
394
	httpResponse, err := hookDo(httpClient.Do)(httpRequest)
395
	if err != nil {
396
		return
397
	}
398
	debuglog("< %s %s", httpResponse.Proto, httpResponse.Status)
399
	for key, value := range httpResponse.Header {
400
		debuglog("< %s: %v", key, strings.Join(value, ""))
401
	}
402
	debuglog("<")
403
404
	resp := &response.CommonResponse{}
405
	err = hookParse(resp.ParseFromHTTPResponse(httpResponse))
406
	if err != nil {
407
		return
408
	}
409
	debuglog("%s", resp.GetHTTPContentString())
410
	if resp.GetHTTPStatus() != http.StatusOK {
411
		err = fmt.Errorf("httpStatus: %d, message = %s", resp.GetHTTPStatus(), resp.GetHTTPContentString())
412
		return
413
	}
414
	return resp.GetHTTPContentBytes(), nil
415
}
416
417
type credentialsProviderWrap struct {
418
	typeName string
419
	provider providers.CredentialsProvider
420
}
421
422
func (cp *credentialsProviderWrap) GetAccessKeyId() (accessKeyId *string, err error) {
423
	cc, err := cp.provider.GetCredentials()
424
	if err != nil {
425
		return
426
	}
427
	accessKeyId = &cc.AccessKeyId
428
	return
429
}
430
431
func (cp *credentialsProviderWrap) GetAccessKeySecret() (accessKeySecret *string, err error) {
432
	cc, err := cp.provider.GetCredentials()
433
	if err != nil {
434
		return
435
	}
436
	accessKeySecret = &cc.AccessKeySecret
437
	return
438
}
439
440
func (cp *credentialsProviderWrap) GetSecurityToken() (securityToken *string, err error) {
441
	cc, err := cp.provider.GetCredentials()
442
	if err != nil {
443
		return
444
	}
445
	securityToken = &cc.SecurityToken
446
	return
447
}
448
449
func (cp *credentialsProviderWrap) GetBearerToken() (bearerToken *string) {
450
	return tea.String("")
451
}
452
453
func (cp *credentialsProviderWrap) GetCredential() (cm *CredentialModel, err error) {
454
	c, err := cp.provider.GetCredentials()
455
	if err != nil {
456
		return
457
	}
458
459
	cm = &CredentialModel{
460
		AccessKeyId:     &c.AccessKeyId,
461
		AccessKeySecret: &c.AccessKeySecret,
462
		SecurityToken:   &c.SecurityToken,
463
		Type:            &c.ProviderName,
464
	}
465
	return
466
}
467
468
func (cp *credentialsProviderWrap) GetType() *string {
469
	return &cp.typeName
470
}
471
472
func fromCredentialsProvider(typeName string, cp providers.CredentialsProvider) Credential {
473
	return &credentialsProviderWrap{
474
		typeName: typeName,
475
		provider: cp,
476
	}
477
}
478