forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 6
/
e2e_test.go
340 lines (313 loc) · 9.97 KB
/
e2e_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
335
336
337
338
339
340
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/http2"
)
func makeTestCACertPool() *x509.CertPool {
crt, err := os.ReadFile(caCert)
if err != nil {
msg := fmt.Sprintf("cannot read test CA cert file: %v", err)
panic(msg)
}
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(crt)
if !ok {
panic("cannot add cert to CA pool")
}
return caCertPool
}
// controlledRedirect is a client RoundTripper to capture all cookies exchanged during the redirection process
// (assuming HttpOnly is not set for testing purpose)
type controlledRedirect struct {
Transport http.RoundTripper
CollectedCookies map[string]*http.Cookie
}
// checkListenOrBail waits on a endpoint listener to respond.
// This avoids race conditions with test listeners as go routines
func checkListenOrBail(endpoint string) bool {
const (
maxWaitCycles = 10
waitTime = 100 * time.Millisecond
)
transport := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: makeTestCACertPool(),
NextProtos: []string{"h2", "http/1.1"},
},
}
err := http2.ConfigureTransport(transport)
if err != nil {
log.Fatalf("cannot configure test transport: %v", err)
}
checkListen := http.Client{
Transport: transport,
}
//nolint: noctx
resp, err := checkListen.Get(endpoint)
if err == nil {
defer func() {
_ = resp.Body.Close()
}()
}
limit := 0
for err != nil && limit < maxWaitCycles {
time.Sleep(waitTime)
//nolint: noctx
resp, err = checkListen.Get(endpoint)
if err == nil {
defer func() {
_ = resp.Body.Close()
}()
}
limit++
}
return limit < maxWaitCycles
}
func runTestGatekeeper(t *testing.T, config *Config) error {
proxy, err := newProxy(config)
if err != nil {
return err
}
_ = proxy.Run()
var scheme string
if config.TLSCertificate != "" {
scheme = "https"
} else {
scheme = "http"
}
u := fmt.Sprintf("%s://%s/oauth/login", scheme, config.Listen)
if !assert.True(t, checkListenOrBail(u)) {
err = fmt.Errorf("cannot connect to test %s listener on: %s", scheme, u)
t.Logf("%v", err)
t.FailNow()
return err
}
t.Logf("test proxy gatekeeper: %s", config.Listen)
return nil
}
func runTestUpstream(t *testing.T, listener, route string, markers ...string) error {
go func() {
upstreamHandler := func(w http.ResponseWriter, req *http.Request) {
_, _ = io.WriteString(w, `{"listener": "`+listener+`", "route": "`+route+`", "message": "test"`)
for _, m := range markers {
_, _ = io.WriteString(w, `,"marker": "`+m+`"`)
}
_, _ = io.WriteString(w, `}`)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Upstream-Response-Header", "test")
}
http.HandleFunc(route, upstreamHandler)
_ = http.ListenAndServe(listener, nil)
}()
if !assert.True(t, checkListenOrBail("http://"+path.Join(listener, route))) {
err := fmt.Errorf("cannot connect to test http listener on: %s", "http://"+path.Join(listener, route))
t.Logf("%v", err)
t.FailNow()
return err
}
t.Logf("test upstream server: %s%s", listener, route)
return nil
}
func runTestApp(t *testing.T, listener, route string) error {
go func() {
mux := http.NewServeMux()
appHandler := func(w http.ResponseWriter, req *http.Request) {
_, _ = io.WriteString(w, `{"message": "ok"}`)
w.Header().Set("Content-Type", "application/json")
}
mux.HandleFunc(route, appHandler)
_ = http.ListenAndServe(listener, mux)
}()
if !assert.True(t, checkListenOrBail("http://"+path.Join(listener, route))) {
err := fmt.Errorf("cannot connect to test http listener on: %s", "http://"+path.Join(listener, route))
t.Logf("%v", err)
t.FailNow()
return err
}
t.Logf("test app server: %s%s", listener, route)
return nil
}
func testDiscoveryPath(realm string) string {
return path.Join("/auth", "realms", realm, ".well-known", "openid-configuration")
}
func testDiscoveryURL(listener, realm string) string {
return "http://" + listener + testDiscoveryPath(realm)
}
func runTestAuth(t *testing.T, listener, realm string) error {
// a stub OIDC provider
fake := newFakeAuthServer()
fake.location, _ = url.Parse("http://" + listener)
issuer := "http://" + listener + path.Join("/auth", "realms", realm)
discoveryURL := testDiscoveryPath(realm)
authorizeURL := path.Join("/auth", "realms", realm, "protocol", "openid-connect", "auth")
// #nosec
tokenURL := path.Join("/auth", "realms", realm, "protocol", "openid-connect", "token")
jwksURL := path.Join("/auth", "realms", realm, "protocol", "openid-connect", "certs")
go func() {
mux := http.NewServeMux()
configurationHandler := func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{
"issuer": "`+issuer+`",
"subject_types_supported":["public","pairwise"],
"id_token_signing_alg_values_supported":["ES384","RS384","HS256","HS512","ES256","RS256","HS384","ES512","RS512"],
"userinfo_signing_alg_values_supported":["ES384","RS384","HS256","HS512","ES256","RS256","HS384","ES512","RS512","none"],
"authorization_endpoint":"http://`+listener+authorizeURL+`",
"token_endpoint":"http://`+listener+tokenURL+`",
"jwks_uri":"http://`+listener+jwksURL+`"
}`)
}
authorizeHandler := func(w http.ResponseWriter, req *http.Request) {
redirect := req.FormValue("redirect_uri")
state := req.FormValue("state")
code := "xyz"
location, _ := url.PathUnescape(redirect)
u, _ := url.Parse(location)
v := u.Query()
v.Set("code", code)
v.Set("state", state)
u.RawQuery = v.Encode()
http.Redirect(w, req, u.String(), http.StatusFound)
}
tokenHandler := func(w http.ResponseWriter, req *http.Request) {
fake.tokenHandler(w, req)
}
keysHandler := func(w http.ResponseWriter, req *http.Request) {
fake.keysHandler(w, req)
}
mux.HandleFunc(discoveryURL, configurationHandler)
mux.HandleFunc(authorizeURL, authorizeHandler)
mux.HandleFunc(tokenURL, tokenHandler)
mux.HandleFunc(jwksURL, keysHandler)
_ = http.ListenAndServe(listener, mux)
}()
if !assert.True(t, checkListenOrBail("http://"+path.Join(listener, jwksURL))) {
err := fmt.Errorf("cannot connect to test http listener on: %s", "http://"+path.Join(listener, jwksURL))
t.Logf("%v", err)
t.FailNow()
return err
}
t.Logf("test auth server: %s [%s]", listener, realm)
return nil
}
// runTestConnect exercises a connect scenario in which the client gets redirected to
// an OIDC authorize endpoint, then to the gatekeeper caller, and
// eventually to a custom endpoint specified in an initial cookie.
//
// NOTE: in this scenario, the "state" possibly passed by the initial query
// is no more carried on til the end of the endshake
//
// This scenario mimics a typical browser app running the authentication handshake
// in an iframe, the calling a custom URL to close the iframe after successful authentication.
//
// NOTE: for testing purposes, we use http transport and have to force our test client to
// forward the expected "request_uri" cookie set by the client.
func runTestConnect(t *testing.T, config *Config, listener, route string) (string, []*http.Cookie, error) {
client := http.Client{
Transport: controlledRedirect{
CollectedCookies: make(map[string]*http.Cookie, 10),
},
CheckRedirect: onRedirect,
}
u, _ := url.Parse("http://" + config.Listen + "/oauth/authorize")
v := u.Query()
v.Set("state", "my_client_nonce") // NOTE: this state provided by the client is not currently carried on to the end (lost)
u.RawQuery = v.Encode()
req := &http.Request{
Method: http.MethodGet,
URL: u,
Header: make(http.Header),
}
// add request_uri to specify last stop redirection (inner workings since PR #440)
encoded := base64.StdEncoding.EncodeToString([]byte("http://" + listener + route))
ck := &http.Cookie{
Name: "request_uri",
Value: encoded,
Path: "/",
// real life cookie gets Secure, SameSite
}
req.AddCookie(ck)
// attempts to login
resp, err := client.Do(req)
if !assert.NoError(t, err) {
return "", nil, err
}
defer func() {
_ = resp.Body.Close()
}()
// check that we get the final redirection to app correctly
assert.Equal(t, http.StatusOK, resp.StatusCode)
buf, erb := io.ReadAll(resp.Body)
assert.NoError(t, erb)
assert.JSONEq(t, `{"message": "ok"}`, string(buf))
// returns all collected cookies during the handshake
collector, ok := client.Transport.(controlledRedirect)
require.True(t, ok)
collected := make([]*http.Cookie, 0, 10)
for _, ck := range collector.CollectedCookies {
collected = append(collected, ck)
}
// assert kc-access cookie
var (
found bool
accessToken string
)
for _, ck := range collected {
if ck.Name == config.CookieAccessName {
accessToken = ck.Value
found = true
break
}
}
assert.True(t, found)
if t.Failed() {
return "", nil, errors.New("failed to connect")
}
return accessToken, collected, nil
}
func getCookie(resp *http.Response, name string) (cookie *http.Cookie) {
for _, ck := range resp.Cookies() {
if ck.Name == name {
cookie = ck
break
}
}
return
}
func copyCookies(req *http.Request, cookies []*http.Cookie) {
ckMap := make(map[string]*http.Cookie, len(cookies))
for _, ck := range cookies {
if ck != nil {
ckMap[ck.Name] = ck // dedupe
// forward cookies obtained during authentication stage (mimicks browser)
req.AddCookie(ckMap[ck.Name])
}
}
}