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 ( f2abf1...e54155 )
by Jackson
09:16
created

credentials.*Config.SetDisableIMDSv1   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
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
	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
// NewCredential return a credential according to the type in config.
202
// if config is nil, the function will use default provider chain to get credentials.
203
// please see README.md for detail.
204
func NewCredential(config *Config) (credential Credential, err error) {
205
	if config == nil {
206
		provider := providers.NewDefaultCredentialsProvider()
207
		credential = fromCredentialsProvider("default", provider)
208
		return
209
	}
210
	switch tea.StringValue(config.Type) {
211
	case "credentials_uri":
212
		credential = newURLCredential(tea.StringValue(config.Url))
213
	case "oidc_role_arn":
214
		provider, err := providers.NewOIDCCredentialsProviderBuilder().
215
			WithRoleArn(tea.StringValue(config.RoleArn)).
216
			WithOIDCTokenFilePath(tea.StringValue(config.OIDCTokenFilePath)).
217
			WithOIDCProviderARN(tea.StringValue(config.OIDCProviderArn)).
218
			WithDurationSeconds(tea.IntValue(config.RoleSessionExpiration)).
219
			WithPolicy(tea.StringValue(config.Policy)).
220
			WithRoleSessionName(tea.StringValue(config.RoleSessionName)).
221
			WithSTSEndpoint(tea.StringValue(config.STSEndpoint)).
222
			WithHttpOptions(&providers.HttpOptions{
223
				Proxy:          tea.StringValue(config.Proxy),
224
				ReadTimeout:    tea.IntValue(config.Timeout),
225
				ConnectTimeout: tea.IntValue(config.ConnectTimeout),
226
			}).
227
			Build()
228
229
		if err != nil {
230
			return nil, err
231
		}
232
		credential = fromCredentialsProvider("oidc_role_arn", provider)
233
	case "access_key":
234
		provider, err := providers.NewStaticAKCredentialsProviderBuilder().
235
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
236
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
237
			Build()
238
		if err != nil {
239
			return nil, err
240
		}
241
242
		credential = fromCredentialsProvider("access_key", provider)
243
	case "sts":
244
		provider, err := providers.NewStaticSTSCredentialsProviderBuilder().
245
			WithAccessKeyId(tea.StringValue(config.AccessKeyId)).
246
			WithAccessKeySecret(tea.StringValue(config.AccessKeySecret)).
247
			WithSecurityToken(tea.StringValue(config.SecurityToken)).
248
			Build()
249
		if err != nil {
250
			return nil, err
251
		}
252
253
		credential = fromCredentialsProvider("sts", provider)
254
	case "ecs_ram_role":
255
		provider, err := providers.NewECSRAMRoleCredentialsProviderBuilder().
256
			WithRoleName(tea.StringValue(config.RoleName)).
257
			WithDisableIMDSv1(tea.BoolValue(config.DisableIMDSv1)).
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 && *config.SecurityToken != "" {
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
	transport := &http.Transport{}
389
	if proxy != nil && runtime.Proxy != "" {
390
		transport.Proxy = http.ProxyURL(proxy)
391
	}
392
	transport.DialContext = utils.Timeout(time.Duration(runtime.ConnectTimeout) * time.Second)
393
	httpClient.Transport = transport
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
// Deprecated: use GetCredential() instead of
423
func (cp *credentialsProviderWrap) GetAccessKeyId() (accessKeyId *string, err error) {
424
	cc, err := cp.provider.GetCredentials()
425
	if err != nil {
426
		return
427
	}
428
	accessKeyId = &cc.AccessKeyId
429
	return
430
}
431
432
// Deprecated: use GetCredential() instead of
433
func (cp *credentialsProviderWrap) GetAccessKeySecret() (accessKeySecret *string, err error) {
434
	cc, err := cp.provider.GetCredentials()
435
	if err != nil {
436
		return
437
	}
438
	accessKeySecret = &cc.AccessKeySecret
439
	return
440
}
441
442
// Deprecated: use GetCredential() instead of
443
func (cp *credentialsProviderWrap) GetSecurityToken() (securityToken *string, err error) {
444
	cc, err := cp.provider.GetCredentials()
445
	if err != nil {
446
		return
447
	}
448
	securityToken = &cc.SecurityToken
449
	return
450
}
451
452
// Deprecated: don't use it
453
func (cp *credentialsProviderWrap) GetBearerToken() (bearerToken *string) {
454
	return tea.String("")
455
}
456
457
// Get credentials
458
func (cp *credentialsProviderWrap) GetCredential() (cm *CredentialModel, err error) {
459
	c, err := cp.provider.GetCredentials()
460
	if err != nil {
461
		return
462
	}
463
464
	cm = &CredentialModel{
465
		AccessKeyId:     &c.AccessKeyId,
466
		AccessKeySecret: &c.AccessKeySecret,
467
		SecurityToken:   &c.SecurityToken,
468
		Type:            &c.ProviderName,
469
	}
470
	return
471
}
472
473
func (cp *credentialsProviderWrap) GetType() *string {
474
	return &cp.typeName
475
}
476
477
func fromCredentialsProvider(typeName string, cp providers.CredentialsProvider) Credential {
478
	return &credentialsProviderWrap{
479
		typeName: typeName,
480
		provider: cp,
481
	}
482
}
483