-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathoauth_authenticator_test.go
334 lines (289 loc) · 11.2 KB
/
oauth_authenticator_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"math"
"math/big"
"net/http"
"net/http/httptest"
"net/url"
"runtime"
"strings"
"testing"
"github.com/UiPath/uipathcli/cache"
"github.com/UiPath/uipathcli/utils/process"
)
func TestOAuthAuthenticatorNotEnabled(t *testing.T) {
config := map[string]interface{}{
"clientId": "my-client-id",
"scopes": "OR.Users",
}
request := NewAuthenticatorRequest("http:/localhost", map[string]string{})
context := NewAuthenticatorContext("login", config, createIdentityUrl(""), false, false, *request)
authenticator := NewOAuthAuthenticator(cache.NewFileCache(), *NewBrowserLauncher())
result := authenticator.Auth(*context)
if result.Error != "" {
t.Errorf("Expected no error when oauth flow is skipped, but got: %v", result.Error)
}
if len(result.RequestHeader) != 0 {
t.Errorf("Expected request header to be empty, but got: %v", result.RequestHeader)
}
}
func TestOAuthAuthenticatorPreservesExistingHeaders(t *testing.T) {
config := map[string]interface{}{
"redirectUri": "http://localhost:0",
"scopes": "OR.Users",
}
headers := map[string]string{
"my-header": "my-value",
}
request := NewAuthenticatorRequest("http:/localhost", headers)
context := NewAuthenticatorContext("login", config, createIdentityUrl(""), false, false, *request)
authenticator := NewOAuthAuthenticator(cache.NewFileCache(), *NewBrowserLauncher())
result := authenticator.Auth(*context)
if result.Error != "" {
t.Errorf("Expected no error when oauth flow is skipped, but got: %v", result.Error)
}
if result.RequestHeader["my-header"] != "my-value" {
t.Errorf("Request header should not be changed, but got: %v", result.RequestHeader)
}
}
func TestOAuthAuthenticatorInvalidConfig(t *testing.T) {
config := map[string]interface{}{
"clientId": 1,
"redirectUri": "http://localhost:0",
"scopes": "OR.Users",
}
request := NewAuthenticatorRequest("http:/localhost", map[string]string{})
context := NewAuthenticatorContext("login", config, createIdentityUrl(""), false, false, *request)
authenticator := NewOAuthAuthenticator(cache.NewFileCache(), *NewBrowserLauncher())
result := authenticator.Auth(*context)
if result.Error != "Invalid oauth authenticator configuration: Invalid value for clientId: '1'" {
t.Errorf("Expected error with invalid config, but got: %v", result.Error)
}
}
func TestOAuthFlowIdentityFails(t *testing.T) {
identityServerFake := identityServerFake{
ResponseStatus: 400,
ResponseBody: "Invalid token request",
}
identityBaseUrl := identityServerFake.Start(t)
context := createAuthContext(identityBaseUrl)
loginUrl, resultChannel := callAuthenticator(context)
performLogin(loginUrl, t)
result := <-resultChannel
if result.Error != "Error retrieving access token: Token service returned status code '400' and body 'Invalid token request'" {
t.Errorf("Expected error when identity call fails, but got: %v", result.Error)
}
}
func TestOAuthFlowSuccessful(t *testing.T) {
identityServerFake := identityServerFake{
ResponseStatus: 200,
ResponseBody: `{"access_token": "my-access-token", "expires_in": 3600, "token_type": "Bearer", "scope": "OR.Users"}`,
}
identityBaseUrl := identityServerFake.Start(t)
context := createAuthContext(identityBaseUrl)
loginUrl, resultChannel := callAuthenticator(context)
performLogin(loginUrl, t)
result := <-resultChannel
if result.Error != "" {
t.Errorf("Expected no error when performing oauth flow, but got: %v", result.Error)
}
authorizationHeader := result.RequestHeader["Authorization"]
if authorizationHeader != "Bearer my-access-token" {
t.Errorf("Expected JWT bearer token in authorization header, but got: %v", authorizationHeader)
}
}
func TestOAuthFlowIsCached(t *testing.T) {
identityServerFake := identityServerFake{
ResponseStatus: 200,
ResponseBody: `{"access_token": "my-access-token", "expires_in": 3600, "token_type": "Bearer", "scope": "OR.Users"}`,
}
identityBaseUrl := identityServerFake.Start(t)
context := createAuthContext(identityBaseUrl)
loginUrl, resultChannel := callAuthenticator(context)
performLogin(loginUrl, t)
<-resultChannel
authenticator := NewOAuthAuthenticator(cache.NewFileCache(), *NewBrowserLauncher())
result := authenticator.Auth(context)
if result.Error != "" {
t.Errorf("Expected no error when performing oauth flow, but got: %v", result.Error)
}
authorizationHeader := result.RequestHeader["Authorization"]
if authorizationHeader != "Bearer my-access-token" {
t.Errorf("Expected JWT bearer token in authorization header, but got: %v", authorizationHeader)
}
}
func TestProvidesCorrectPkceCodes(t *testing.T) {
identityFake := identityServerFake{
ResponseStatus: 200,
ResponseBody: `{"access_token": "my-access-token", "expires_in": 3600, "token_type": "Bearer", "scope": "OR.Users"}`,
}
identityUrl := identityFake.Start(t)
context := createAuthContext(identityUrl)
loginUrl, resultChannel := callAuthenticator(context)
identityFake.VerifyCodeChallenge(loginUrl.Query().Get("code_challenge"))
performLogin(loginUrl, t)
result := <-resultChannel
if result.Error != "" {
t.Errorf("Expected no error when performing oauth flow, but got: %v", result.Error)
}
}
func TestShowsSuccessfullyLoggedInPage(t *testing.T) {
identityServerFake := identityServerFake{
ResponseStatus: 200,
ResponseBody: `{"access_token": "my-access-token", "expires_in": 3600, "token_type": "Bearer", "scope": "OR.Users"}`,
}
identityBaseUrl := identityServerFake.Start(t)
context := createAuthContext(identityBaseUrl)
loginUrl, _ := callAuthenticator(context)
responseBody := performLogin(loginUrl, t)
if !strings.Contains(responseBody, "Successfully logged in") {
t.Errorf("Expected successfully logged in page, but got: %v", responseBody)
}
}
func TestInvalidStateShowsErrorMessage(t *testing.T) {
identityUrl, _ := url.Parse("http://localhost")
context := createAuthContext(*identityUrl)
loginUrl, _ := callAuthenticator(context)
queryString := loginUrl.Query()
queryString.Set("state", "invalid")
loginUrl.RawQuery = queryString.Encode()
responseBody := performLogin(loginUrl, t)
if responseBody != "The query string 'state' in the redirect_url did not match" {
t.Errorf("Expected error message that state does not match, but got: %v", responseBody)
}
}
func TestMissingCodeShowsErrorMessage(t *testing.T) {
identityUrl, _ := url.Parse("http://localhost")
context := createAuthContext(*identityUrl)
loginUrl, _ := callAuthenticator(context)
redirectUri := loginUrl.Query().Get("redirect_uri")
state := loginUrl.Query().Get("state")
response, err := http.Get(redirectUri + "?code=&state=" + state)
if err != nil {
t.Fatalf("Unexpected error calling login url: %v", err)
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("Login url response body cannot be read: %v", err)
}
if string(responseBody) != "Could not find query string 'code' in redirect_url" {
t.Errorf("Expected error message that state does not match, but got: %v", string(responseBody))
}
}
func callAuthenticator(context AuthenticatorContext) (url.URL, chan AuthenticatorResult) {
loginChan := make(chan string)
authenticator := NewOAuthAuthenticator(cache.NewFileCache(), BrowserLauncher{
Exec: process.NewExecCustomProcess(0, "", "", func(name string, args []string) {
switch runtime.GOOS {
case "windows":
loginChan <- args[1]
default:
loginChan <- args[0]
}
}),
})
resultChannel := make(chan AuthenticatorResult)
go func(context AuthenticatorContext) {
result := authenticator.Auth(context)
resultChannel <- result
}(context)
loginUrl := <-loginChan
url, _ := url.Parse(loginUrl)
return *url, resultChannel
}
func createAuthContext(baseUrl url.URL) AuthenticatorContext {
config := map[string]interface{}{
"clientId": newClientId(),
"redirectUri": "http://localhost:0",
"scopes": "OR.Users",
}
identityUrl := createIdentityUrl(baseUrl.Host)
request := NewAuthenticatorRequest(fmt.Sprintf("%s://%s", baseUrl.Scheme, baseUrl.Host), map[string]string{})
context := NewAuthenticatorContext("login", config, identityUrl, false, false, *request)
return *context
}
func createIdentityUrl(hostName string) url.URL {
if hostName == "" {
hostName = "localhost"
}
identityUrl, _ := url.Parse(fmt.Sprintf("http://%s/identity_", hostName))
return *identityUrl
}
func performLogin(loginUrl url.URL, t *testing.T) string {
redirectUri := loginUrl.Query().Get("redirect_uri")
state := loginUrl.Query().Get("state")
response, err := http.Get(redirectUri + "?code=testcode&state=" + state)
if err != nil {
t.Fatalf("Unexpected error calling login url: %v", err)
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("Login url response body cannot be read: %v", err)
}
return string(data)
}
func newClientId() string {
value, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic(fmt.Errorf("Unexpected error generating new client id: %w", err))
}
return value.String()
}
type identityServerFake struct {
ResponseStatus int
ResponseBody string
codeChallenge *string
}
func (i *identityServerFake) Start(t *testing.T) url.URL {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == "/identity_/connect/token" {
i.handleIdentityTokenRequest(r, w)
return
}
}))
t.Cleanup(func() { srv.Close() })
uri, _ := url.Parse(srv.URL)
return *uri
}
func (i *identityServerFake) VerifyCodeChallenge(codeChallenge string) {
i.codeChallenge = &codeChallenge
}
func (i *identityServerFake) handleIdentityTokenRequest(request *http.Request, response http.ResponseWriter) {
body, _ := io.ReadAll(request.Body)
requestBody := string(body)
data, _ := url.ParseQuery(requestBody)
if len(data["client_id"]) != 1 || data["client_id"][0] == "" {
i.writeValidationErrorResponse(response, "client_id is missing")
} else if len(data["code"]) != 1 || data["code"][0] == "" {
i.writeValidationErrorResponse(response, "code is missing")
} else if len(data["code_verifier"]) != 1 || data["code_verifier"][0] == "" {
i.writeValidationErrorResponse(response, "code_verifier is missing")
} else if len(data["redirect_uri"]) != 1 || data["redirect_uri"][0] == "" {
i.writeValidationErrorResponse(response, "redirect_uri is missing")
} else if len(data["grant_type"]) != 1 || data["grant_type"][0] != "authorization_code" {
i.writeValidationErrorResponse(response, "Invalid grant_type")
} else if i.codeChallenge != nil && !i.validPkce(data["code_verifier"][0], *i.codeChallenge) {
i.writeValidationErrorResponse(response, "Invalid pkce")
} else {
response.WriteHeader(i.ResponseStatus)
_, _ = response.Write([]byte(i.ResponseBody))
}
}
func (i identityServerFake) validPkce(codeVerifier string, expectedCodeChallenge string) bool {
hash := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.StdEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:])
codeChallenge = strings.ReplaceAll(codeChallenge, "+", "-")
codeChallenge = strings.ReplaceAll(codeChallenge, "/", "_")
return codeChallenge == expectedCodeChallenge
}
func (i identityServerFake) writeValidationErrorResponse(response http.ResponseWriter, message string) {
response.WriteHeader(400)
_, _ = response.Write([]byte(message))
}