-
Notifications
You must be signed in to change notification settings - Fork 0
/
integration_test.go
321 lines (261 loc) · 7.22 KB
/
integration_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
package oauth2_test
import (
"context"
"crypto/ecdsa"
"fmt"
"log"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"testing"
"time"
oauth2 "github.com/oxisto/oauth2go"
"github.com/oxisto/oauth2go/login"
"github.com/oxisto/oauth2go/storage"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/net/html"
"golang.org/x/oauth2/clientcredentials"
)
func TestIntegration(t *testing.T) {
srv := oauth2.NewServer(
":0",
oauth2.WithClient("client", "secret", ""),
oauth2.WithSigningKeysFunc(func() map[int]*ecdsa.PrivateKey {
return storage.LoadSigningKeys("storage/testdata/ecdsa.pem", "changeme", false)
}),
)
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
t.Errorf("Error while listening key: %v", err)
}
port := ln.Addr().(*net.TCPAddr).Port
go srv.Serve(ln)
defer srv.Close()
config := clientcredentials.Config{
ClientID: "client",
ClientSecret: "secret",
TokenURL: fmt.Sprintf("http://localhost:%d/token", port),
}
token, err := config.Token(context.Background())
if err != nil {
t.Errorf("Error while retrieving a token: %v", err)
}
log.Printf("Token: %s", token.AccessToken)
jwtoken, err := jwt.ParseWithClaims(token.AccessToken, &jwt.RegisteredClaims{}, func(t *jwt.Token) (interface{}, error) {
kid, _ := strconv.ParseInt(t.Header["kid"].(string), 10, 64)
return srv.PublicKeys()[int(kid)], nil
})
if err != nil {
t.Errorf("Error while retrieving a token: %v", err)
}
log.Printf("JWT: %+v", jwtoken)
}
func TestThreeLeggedFlowPublicClient(t *testing.T) {
var (
res *http.Response
req *http.Request
client *http.Client
form url.Values
session *http.Cookie
token *oauth2.Token
newToken *oauth2.Token
source oauth2.TokenSource
code string
challenge string
verifier string
)
srv := oauth2.NewServer(":0",
oauth2.WithClient("public", "", "/test"),
login.WithLoginPage(login.WithUser("admin", "admin")),
)
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
t.Errorf("Error while listening key: %v", err)
}
port := ln.Addr().(*net.TCPAddr).Port
go srv.Serve(ln)
defer srv.Close()
config := oauth2.Config{
ClientID: "public",
ClientSecret: "",
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("http://localhost:%d/authorize", port),
TokenURL: fmt.Sprintf("http://localhost:%d/token", port),
},
RedirectURL: "/test",
}
// create a challenge and verifier
verifier = "012345678901234567890123456789012345678901234567890123456789"
challenge = oauth2.GenerateCodeChallenge(verifier)
// Let's pretend to be a browser
res, err = http.Get(config.AuthCodeURL("some-state",
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
))
if err != nil {
t.Errorf("Error while POST /authorize: %v", err)
}
// We are interested in two things
// - The session ID (or the cookie)
// - The CSRF token
for _, c := range res.Cookies() {
if c.Name == "id" {
session = c
break
}
}
if session == nil {
t.Errorf("Error session is nil")
}
// Parse the HTML body to look for the csrf_token
root, _ := html.Parse(res.Body)
form = url.Values{}
walker := func(node *html.Node) {
if node.Type == html.ElementNode &&
node.Data == "input" &&
len(node.Attr) == 3 {
form.Add(node.Attr[1].Val, node.Attr[2].Val)
}
}
traverse(root, walker)
form.Add("username", "admin")
form.Add("password", "admin")
req, _ = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/login", port), strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(session)
// Let's POST our login
client = &http.Client{}
res, err = client.Do(req)
if err != nil {
t.Errorf("Error while POST /login: %v", err)
}
// Extract the code from the response
code = res.Request.URL.Query().Get("code")
token, err = config.Exchange(context.Background(),
code,
oauth2.SetAuthURLParam("code_verifier", verifier),
)
if err != nil {
t.Errorf("Error while Exchange: %v", err)
}
if token.AccessToken == "" {
t.Error("Access token is empty")
}
if token.RefreshToken == "" {
t.Error("Access token is empty")
}
// For some extra fun, let's use our refresh token by declaring our token expired
token.Expiry = time.Now().Add(-5 * time.Minute)
source = config.TokenSource(context.Background(), token)
newToken, err = source.Token()
if err != nil {
t.Errorf("Error while fetching from token source: %v", err)
}
if newToken.AccessToken == "" {
t.Error("Access token is empty")
}
// Access tokens should be different
if newToken.AccessToken == token.AccessToken {
t.Error("New token is not different")
}
// Refresh tokens should be the same
if newToken.RefreshToken != token.RefreshToken {
t.Error("Refresh token is different")
}
}
func TestThreeLeggedFlowConfidentialClient(t *testing.T) {
var (
res *http.Response
req *http.Request
client *http.Client
form url.Values
session *http.Cookie
token *oauth2.Token
code string
)
srv := oauth2.NewServer(":0",
oauth2.WithClient("client", "secret", "/test"),
login.WithLoginPage(login.WithUser("admin", "admin")),
)
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
t.Errorf("Error while listening key: %v", err)
}
port := ln.Addr().(*net.TCPAddr).Port
go srv.Serve(ln)
defer srv.Close()
config := oauth2.Config{
ClientID: "client",
ClientSecret: "secret",
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("http://localhost:%d/authorize", port),
TokenURL: fmt.Sprintf("http://localhost:%d/token", port),
},
RedirectURL: "/test",
}
// Let's pretend to be a browser
res, err = http.Get(config.AuthCodeURL("some-state"))
if err != nil {
t.Errorf("Error while POST /authorize: %v", err)
}
// We are interested in two things
// - The session ID (or the cookie)
// - The CSRF token
for _, c := range res.Cookies() {
if c.Name == "id" {
session = c
break
}
}
if session == nil {
t.Errorf("Error session is nil")
}
// Parse the HTML body to look for the csrf_token
root, _ := html.Parse(res.Body)
form = url.Values{}
walker := func(node *html.Node) {
if node.Type == html.ElementNode &&
node.Data == "input" &&
len(node.Attr) == 3 {
form.Add(node.Attr[1].Val, node.Attr[2].Val)
}
}
traverse(root, walker)
form.Add("username", "admin")
form.Add("password", "admin")
req, _ = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/login", port), strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(session)
// Let's POST our login
client = &http.Client{}
res, err = client.Do(req)
if err != nil {
t.Errorf("Error while POST /login: %v", err)
}
// Extract the code from the response
code = res.Request.URL.Query().Get("code")
token, err = config.Exchange(context.Background(),
code,
)
if err != nil {
t.Errorf("Error while Exchange: %v", err)
}
if token.AccessToken == "" {
t.Error("Access token is empty", err)
}
if token.RefreshToken == "" {
t.Error("Access token is empty", err)
}
}
func traverse(root *html.Node, walker func(node *html.Node)) {
var f func(*html.Node)
f = func(n *html.Node) {
walker(n)
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(root)
}