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.
Completed
Push — master ( ecef9a...1c7b65 )
by Jackson
08:09
created

credentials.*RsaKeyPairCredential.updateCredential   D

Complexity

Conditions 13

Size

Total Lines 61
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 50
nop 0
dl 0
loc 61
rs 4.2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like credentials.*RsaKeyPairCredential.updateCredential often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package credentials
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"strconv"
8
	"time"
9
10
	"github.com/aliyun/credentials-go/credentials/request"
11
	"github.com/aliyun/credentials-go/credentials/utils"
12
)
13
14
// RsaKeyPairCredential is a kind of credentials
15
type RsaKeyPairCredential struct {
16
	*credentialUpdater
17
	PrivateKey        string
18
	PublicKeyID       string
19
	SessionExpiration int
20
	sessionCredential *sessionCredential
21
	runtime           *utils.Runtime
22
}
23
24
type rsaKeyPairResponse struct {
25
	SessionAccessKey *sessionAccessKey `json:"SessionAccessKey" xml:"SessionAccessKey"`
26
}
27
28
type sessionAccessKey struct {
29
	SessionAccessKeyID     string `json:"SessionAccessKeyID" xml:"SessionAccessKeyID"`
30
	SessionAccessKeySecret string `json:"SessionAccessKeySecret" xml:"SessionAccessKeySecret"`
31
	Expiration             string `json:"Expiration" xml:"Expiration"`
32
}
33
34
func newRsaKeyPairCredential(privateKey, publicKeyID string, sessionExpiration int, runtime *utils.Runtime) *RsaKeyPairCredential {
35
	return &RsaKeyPairCredential{
36
		PrivateKey:        privateKey,
37
		PublicKeyID:       publicKeyID,
38
		SessionExpiration: sessionExpiration,
39
		credentialUpdater: new(credentialUpdater),
40
		runtime:           runtime,
41
	}
42
}
43
44
// GetAccessKeyID reutrns RsaKeyPairCredential's AccessKeyID
45
// if AccessKeyID is not exist or out of date, the function will update it.
46
func (r *RsaKeyPairCredential) GetAccessKeyId() (string, error) {
47
	if r.sessionCredential == nil || r.needUpdateCredential() {
48
		err := r.updateCredential()
49
		if err != nil {
50
			return "", err
51
		}
52
	}
53
	return r.sessionCredential.AccessKeyID, nil
54
}
55
56
// GetAccessSecret reutrns  RsaKeyPairCredential's AccessKeySecret
57
// if AccessKeySecret is not exist or out of date, the function will update it.
58
func (r *RsaKeyPairCredential) GetAccessKeySecret() (string, error) {
59
	if r.sessionCredential == nil || r.needUpdateCredential() {
60
		err := r.updateCredential()
61
		if err != nil {
62
			return "", err
63
		}
64
	}
65
	return r.sessionCredential.AccessKeySecret, nil
66
}
67
68
// GetSecurityToken is useless  RsaKeyPairCredential
69
func (r *RsaKeyPairCredential) GetSecurityToken() (string, error) {
70
	return "", nil
71
}
72
73
// GetBearerToken is useless for  RsaKeyPairCredential
74
func (r *RsaKeyPairCredential) GetBearerToken() string {
75
	return ""
76
}
77
78
// GetType reutrns  RsaKeyPairCredential's type
79
func (r *RsaKeyPairCredential) GetType() string {
80
	return "rsa_key_pair"
81
}
82
83
func (r *RsaKeyPairCredential) updateCredential() (err error) {
84
	if r.runtime == nil {
85
		r.runtime = new(utils.Runtime)
86
	}
87
	request := request.NewCommonRequest()
88
	request.Domain = "sts.aliyuncs.com"
89
	if r.runtime.Host != "" {
90
		request.Domain = r.runtime.Host
91
	}
92
	request.Scheme = "HTTPS"
93
	request.Method = "GET"
94
	request.QueryParams["AccessKeyId"] = r.PublicKeyID
95
	request.QueryParams["Action"] = "GenerateSessionAccessKey"
96
	request.QueryParams["Format"] = "JSON"
97
	if r.SessionExpiration > 0 {
98
		if r.SessionExpiration >= 900 && r.SessionExpiration <= 3600 {
99
			request.QueryParams["DurationSeconds"] = strconv.Itoa(r.SessionExpiration)
100
		} else {
101
			err = errors.New("[InvalidParam]:Key Pair session duration should be in the range of 15min - 1Hr")
102
			return
103
		}
104
	} else {
105
		request.QueryParams["DurationSeconds"] = strconv.Itoa(defaultDurationSeconds)
106
	}
107
	request.QueryParams["SignatureMethod"] = "SHA256withRSA"
108
	request.QueryParams["SignatureType"] = "PRIVATEKEY"
109
	request.QueryParams["SignatureVersion"] = "1.0"
110
	request.QueryParams["Version"] = "2015-04-01"
111
	request.QueryParams["Timestamp"] = utils.GetTimeInFormatISO8601()
112
	request.QueryParams["SignatureNonce"] = utils.GetUUID()
113
	signature := utils.Sha256WithRsa(request.BuildStringToSign(), r.PrivateKey)
114
	request.QueryParams["Signature"] = signature
115
	request.Headers["Host"] = request.Domain
116
	request.Headers["Accept-Encoding"] = "identity"
117
	request.URL = request.BuildURL()
118
	content, err := doAction(request, r.runtime)
119
	if err != nil {
120
		return fmt.Errorf("refresh KeyPair err: %s", err.Error())
121
	}
122
	var resp *rsaKeyPairResponse
123
	err = json.Unmarshal(content, &resp)
124
	if err != nil {
125
		return fmt.Errorf("refresh KeyPair err: Json Unmarshal fail: %s", err.Error())
126
	}
127
	if resp == nil || resp.SessionAccessKey == nil {
128
		return fmt.Errorf("refresh KeyPair err: SessionAccessKey is empty")
129
	}
130
	sessionAccessKey := resp.SessionAccessKey
131
	if sessionAccessKey.SessionAccessKeyID == "" || sessionAccessKey.SessionAccessKeySecret == "" || sessionAccessKey.Expiration == "" {
132
		return fmt.Errorf("refresh KeyPair err: SessionAccessKeyID: %v, SessionAccessKeySecret: %v, Expiration: %v", sessionAccessKey.SessionAccessKeyID, sessionAccessKey.SessionAccessKeySecret, sessionAccessKey.Expiration)
133
	}
134
135
	expirationTime, err := time.Parse("2006-01-02T15:04:05Z", sessionAccessKey.Expiration)
136
	r.lastUpdateTimestamp = time.Now().Unix()
137
	r.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix())
138
	r.sessionCredential = &sessionCredential{
139
		AccessKeyID:     sessionAccessKey.SessionAccessKeyID,
140
		AccessKeySecret: sessionAccessKey.SessionAccessKeySecret,
141
	}
142
143
	return
144
}
145