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 ( b588b4...b187c4 )
by
unknown
10:06
created

er_getCredentials   C

Complexity

Conditions 8

Size

Total Lines 92
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 65
nop 1
dl 0
loc 92
rs 6.2787
c 0
b 0
f 0

How to fix   Long Method   

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:

1
package providers
2
3
import (
4
	"errors"
5
	"strings"
6
	"testing"
7
	"time"
8
9
	httputil "github.com/aliyun/credentials-go/credentials/internal/http"
10
	"github.com/stretchr/testify/assert"
11
)
12
13
// contains is a helper function to check if a string contains a substring
14
func contains(s, substr string) bool {
15
	return strings.Contains(s, substr)
16
}
17
18
func TestNewCloudSSOCredentialsProvider(t *testing.T) {
19
20
	_, err := NewCloudSSOCredentialsProviderBuilder().Build()
21
	assert.NotNil(t, err)
22
	assert.Equal(t, "CloudSSO access token is empty or expired, please re-login with cli", err.Error())
23
24
	_, err = NewCloudSSOCredentialsProviderBuilder().WithAccessToken("token").Build()
25
	assert.NotNil(t, err)
26
	assert.Equal(t, "CloudSSO access token is empty or expired, please re-login with cli", err.Error())
27
28
	_, err = NewCloudSSOCredentialsProviderBuilder().
29
		WithAccessToken("token").
30
		WithAccessTokenExpire(time.Now().Unix() + 1000).
31
		Build()
32
	assert.NotNil(t, err)
33
	assert.Equal(t, "CloudSSO sign in url or account id or access config is empty", err.Error())
34
35
	_, err = NewCloudSSOCredentialsProviderBuilder().
36
		WithAccessToken("token").
37
		WithAccessTokenExpire(time.Now().Unix() + 1000).
38
		WithSignInUrl("https://signin.aliyun.com").
39
		Build()
40
	assert.NotNil(t, err)
41
	assert.Equal(t, "CloudSSO sign in url or account id or access config is empty", err.Error())
42
43
	_, err = NewCloudSSOCredentialsProviderBuilder().
44
		WithAccessToken("token").
45
		WithAccessTokenExpire(time.Now().Unix() + 1000).
46
		WithSignInUrl("https://signin.aliyun.com").
47
		WithAccountId("123456").
48
		Build()
49
	assert.NotNil(t, err)
50
	assert.Equal(t, "CloudSSO sign in url or account id or access config is empty", err.Error())
51
52
	p, err := NewCloudSSOCredentialsProviderBuilder().
53
		WithAccessToken("token").
54
		WithAccessTokenExpire(time.Now().Unix() + 1000).
55
		WithSignInUrl("https://signin.aliyun.com").
56
		WithAccountId("123456").
57
		WithAccessConfig("config").
58
		Build()
59
	assert.Nil(t, err)
60
61
	assert.Equal(t, "https://signin.aliyun.com", p.signInUrl)
62
63
}
64
65
func TestCloudSSOCredentialsProvider_getCredentials(t *testing.T) {
66
	originHttpDo := httpDo
67
	defer func() { httpDo = originHttpDo }()
68
69
	p, err := NewCloudSSOCredentialsProviderBuilder().
70
		WithSignInUrl("https://signin-cn-shanghai.alibabacloudsso.com/a/login").
71
		WithAccountId("uid").
72
		WithAccessConfig("config").
73
		WithAccessToken("token").
74
		WithAccessTokenExpire(time.Now().Unix() + 1000).
75
		Build()
76
	assert.Nil(t, err)
77
78
	// case 1: mock new http request failed
79
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
80
		err = errors.New("mock server error")
81
		return
82
	}
83
	_, err = p.getCredentials()
84
	assert.NotNil(t, err)
85
	assert.Equal(t, "mock server error", err.Error())
86
87
	// case 2: 4xx error
88
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
89
		res = &httputil.Response{
90
			StatusCode: 400,
91
			Body:       []byte("4xx error"),
92
		}
93
		return
94
	}
95
	_, err = p.getCredentials()
96
	assert.NotNil(t, err)
97
	assert.Equal(t, "get session token from sso failed: 4xx error", err.Error())
98
99
	// case 3: invalid json
100
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
101
		res = &httputil.Response{
102
			StatusCode: 200,
103
			Body:       []byte("invalid json"),
104
		}
105
		return
106
	}
107
	_, err = p.getCredentials()
108
	assert.NotNil(t, err)
109
	assert.Equal(t, "get session token from sso failed, json.Unmarshal fail: invalid character 'i' looking for beginning of value", err.Error())
110
111
	// case 4: empty response json
112
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
113
		res = &httputil.Response{
114
			StatusCode: 200,
115
			Body:       []byte("null"),
116
		}
117
		return
118
	}
119
	_, err = p.getCredentials()
120
	assert.NotNil(t, err)
121
	assert.Equal(t, "get session token from sso failed, fail to get credentials", err.Error())
122
123
	// case 5: empty session ak response json
124
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
125
		res = &httputil.Response{
126
			StatusCode: 200,
127
			Body:       []byte(`{"Credentials": {}}`),
128
		}
129
		return
130
	}
131
	_, err = p.getCredentials()
132
	assert.NotNil(t, err)
133
	assert.Equal(t, "get session token from sso failed, fail to get credentials", err.Error())
134
135
	// case 6: mock ok value
136
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
137
		res = &httputil.Response{
138
			StatusCode: 200,
139
			Body:       []byte(`{"RequestId": "123", "CloudCredential": {"AccessKeyId":"ak","AccessKeySecret":"sk","Expiration":"2021-10-20T04:27:09Z","SecurityToken":"token"}}`),
140
		}
141
		return
142
	}
143
	creds, err := p.getCredentials()
144
	assert.Nil(t, err)
145
	assert.Equal(t, "ak", creds.AccessKeyId)
146
	assert.Equal(t, "sk", creds.AccessKeySecret)
147
	assert.Equal(t, "token", creds.SecurityToken)
148
	assert.Equal(t, "2021-10-20T04:27:09Z", creds.Expiration)
149
150
	// needUpdateCredential
151
	assert.True(t, p.needUpdateCredential())
152
	p.expirationTimestamp = time.Now().Unix()
153
	assert.True(t, p.needUpdateCredential())
154
155
	p.expirationTimestamp = time.Now().Unix() + 300
156
	assert.False(t, p.needUpdateCredential())
157
}
158
159
func TestCloudSSOCredentialsProviderGetCredentials(t *testing.T) {
160
161
	p, err := NewCloudSSOCredentialsProviderBuilder().
162
		WithSignInUrl("https://signin-cn-shanghai.alibabacloudsso.com/a/login").
163
		WithAccountId("uid").
164
		WithAccessConfig("config").
165
		WithAccessToken("token").
166
		WithAccessTokenExpire(time.Now().Unix() + 1000).
167
		WithHttpOptions(&HttpOptions{
168
			ConnectTimeout: 10000,
169
		}).
170
		Build()
171
172
	assert.Nil(t, err)
173
	assert.Equal(t, 10000, p.httpOptions.ConnectTimeout)
174
	_, err = p.GetCredentials()
175
	assert.NotNil(t, err)
176
	// Network-dependent test: accept expected error or any network-related error
177
	errMsg := err.Error()
178
	validError := contains(errMsg, "InvalidParameter.AccountId.InvalidChars") ||
179
		contains(errMsg, "timeout") ||
180
		contains(errMsg, "TLS handshake") ||
181
		contains(errMsg, "dial tcp") ||
182
		contains(errMsg, "lookup") ||
183
		contains(errMsg, "connection refused") ||
184
		contains(errMsg, "no such host")
185
	assert.True(t, validError, "Expected error about invalid account ID or network error, got: %s", errMsg)
186
187
	originHttpDo := httpDo
188
	defer func() { httpDo = originHttpDo }()
189
190
	// case 1: mock new http request failed
191
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
192
		err = errors.New("mock server error")
193
		return
194
	}
195
	_, err = p.GetCredentials()
196
	assert.NotNil(t, err)
197
	assert.Equal(t, "mock server error", err.Error())
198
199
	// case 2: get invalid expiration
200
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
201
		res = &httputil.Response{
202
			StatusCode: 200,
203
			Body:       []byte(`{"CloudCredential": {"AccessKeyId":"akid","AccessKeySecret":"aksecret","Expiration":"invalidexpiration","SecurityToken":"ststoken"}}`),
204
		}
205
		return
206
	}
207
	_, err = p.GetCredentials()
208
	assert.NotNil(t, err)
209
	assert.Equal(t, "parsing time \"invalidexpiration\" as \"2006-01-02T15:04:05Z\": cannot parse \"invalidexpiration\" as \"2006\"", err.Error())
210
211
	// case 3: happy result
212
	httpDo = func(req *httputil.Request) (res *httputil.Response, err error) {
213
		res = &httputil.Response{
214
			StatusCode: 200,
215
			Body:       []byte(`{"CloudCredential": {"AccessKeyId":"akid","AccessKeySecret":"aksecret","Expiration":"2021-10-20T04:27:09Z","SecurityToken":"ststoken"}}`),
216
		}
217
		return
218
	}
219
	cc, err := p.GetCredentials()
220
	assert.Nil(t, err)
221
	assert.Equal(t, "akid", cc.AccessKeyId)
222
	assert.Equal(t, "aksecret", cc.AccessKeySecret)
223
	assert.Equal(t, "ststoken", cc.SecurityToken)
224
	assert.Equal(t, "cloud_sso", cc.ProviderName)
225
	assert.True(t, p.needUpdateCredential())
226
}
227
228
func TestCloudSSOCredentialsProviderGetCredentialsWithHttpOptions(t *testing.T) {
229
	p, err := NewCloudSSOCredentialsProviderBuilder().
230
		WithSignInUrl("https://signin-cn-shanghai.alibabacloudsso.com/a/login").
231
		WithAccountId("uid").
232
		WithAccessConfig("config").
233
		WithAccessToken("token").
234
		WithAccessTokenExpire(time.Now().Unix() + 1000).
235
		WithHttpOptions(&HttpOptions{
236
			ConnectTimeout: 1000,
237
			ReadTimeout:    1000,
238
			Proxy:          "localhost:3999",
239
		}).
240
		Build()
241
242
	assert.Nil(t, err)
243
	_, err = p.GetCredentials()
244
	assert.NotNil(t, err)
245
	assert.Contains(t, err.Error(), "proxyconnect tcp:")
246
}
247