This repository was archived by the owner on Mar 27, 2026. It is now read-only.
forked from unmojang/drasl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_suite_test.go
More file actions
344 lines (294 loc) · 12.4 KB
/
test_suite_test.go
File metadata and controls
344 lines (294 loc) · 12.4 KB
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
341
342
343
344
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"io"
"log"
"lukechampine.com/blake3"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
)
var _ = os.Setenv("DRASL_TEST", "1")
const TEST_USERNAME = "Username"
const TEST_USERNAME_UPPERCASE = "USERNAME"
const TEST_PLAYER_NAME = "Username"
const TEST_PLAYER_NAME_UPPERCASE = "USERNAME"
const TEST_OTHER_USERNAME = "OtherUsername"
const TEST_OTHER_PLAYER_NAME = "OtherUsername"
const TEST_PASSWORD = "password"
const RED_SKIN_BASE64_STRING = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAE+SURBVHhe7ZtBDoMwDAST/z+6pdcgMXUXCXAn4mY74PV6E0VkDhivMbbn9zHH2J77Dvw4AZABtoAakEiYIugqcPNlMF3mkvb4xF7dIlMAwnVeBoQI2AIXrxJqgCL47yK4ahgxgkQrjSdNPXv+3XlA+oI0XgDCEypi6Dq9DCDKEiVXxGm+qj+9n+zEiHgfUE2o6k8Jkl0AYKcpA6hnqxSj+WyBhZIEGBWA7GqAGnB8JqkIpj1YFbWqP/U42dUANQA0gCjU3Y7/BwhAcwRkQPMCY3oyACFq7iADmhcY05MBCFFzBxnQvMCYngxAiJo7yICzC0xHbHRElcZX8zmdAWkCabwAFBGQAUXAdu5E2XR+iidN+SKeXI7tAvDw3+xiDZABMiC7VZYpUH7hwhZIK6AGqAFqQHSzNG1Bd4LhlZs3vSioQQnlCKsAAAAASUVORK5CYII="
var RED_SKIN []byte = Unwrap(base64.StdEncoding.DecodeString(RED_SKIN_BASE64_STRING))
var redSkinHashBytes = blake3.Sum256(RED_SKIN)
var RED_SKIN_HASH = hex.EncodeToString(redSkinHashBytes[:])
const BLUE_SKIN_BASE64_STRING = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAE+SURBVHhe7ZpBDoMwDATJ/x9NK/XUCGVtrVGoO73GDsl6PRTIOOTvPGXIMmAML//e7MDiEAAHeCakBQJt5knsZAcWBwNggGOx43g8A1yLe/LsFujNAAQwexwHmArsZQQtAAOA4N/fBWaGKUEUtNx8xdTa+S+eBdwLuPkIIBSoFRgH+LfBmQnZCql41RJqfM2sgj9CCDC1kapoVjBVYTWOA5ZvvWgBIGg/C2R7OhuvelyNwwAYsPIIEASCQFBRtPd44NsgArRWAAe0Lm9gczggIFLrEBzQuryBzeGAgEitQ3BA6/IGNocDAiK1DsEB9eXNfhmqPp+Q29ENDkAAce5w9wmTb4fggFzHXEUry/tXWM+gHCWy/eUhwE+fNS5gAA7AAT5HnBmAoNXGVvKnbjAABjgd7OfCAKuNreQODHgBFSioQeX4pUIAAAAASUVORK5CYII="
var BLUE_SKIN []byte = Unwrap(base64.StdEncoding.DecodeString(BLUE_SKIN_BASE64_STRING))
var blueSkinHashBytes = blake3.Sum256(BLUE_SKIN)
var BLUE_SKIN_HASH = hex.EncodeToString(blueSkinHashBytes[:])
const INVALID_SKIN_BASE64_STRING = "iVBORw0KGgoAAAANSUhEUgAAAQAAAAABCAIAAAC+O+cgAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAD0lEQVQoz2NgGAWjYAQDAAMBAAGf4uJmAAAAAElFTkSuQmCC"
var INVALID_SKIN []byte = Unwrap(base64.StdEncoding.DecodeString(INVALID_SKIN_BASE64_STRING))
const RED_CAPE_BASE64_STRING = "iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAIAAAAt/+nTAAABcGlDQ1BpY2MAACiRdZG9S8NAGMafthZFK0UUFHHIUEWwhaIgjlqHLkVKrWDVJbkmrZCk4ZIixVVwcSg4iC5+Df4HugquCoKgCCJu7n4tUuJ7TaFF2jsu748n97zcPQf4Uzoz7K44YJgOzyQT0mpuTep+RxADGKY5JTPbWkinU+g4fh7hE/UhJnp13td29OVVmwG+HuJZZnGHeJ44teVYgveIh1hRzhOfEEc5HZD4VuiKx2+CCx5/CebZzCLgFz2lQgsrLcyK3CCeJI4Yepk1ziNuElLNlWWqo7TGYCODJBKQoKCMTehwEKNqUmbtffG6bwkl8jD6WqiAk6OAInmjpJapq0pVI12lqaMicv+fp63NTHvdQwkg+Oq6n+NA9z5Qq7ru76nr1s6AwAtwbTb9Jcpp7pv0alOLHAPhHeDypqkpB8DVLjDybMlcrksBWn5NAz4ugP4cMHgP9K57WTX+4/wJyG7TE90Bh0fABO0Pb/wB/+FoCgeBR+AAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAA0SURBVFjD7c8xDQAACAMw5l8008BJ0jpodn6LgICAgICAgICAgICAgICAgICAgICAgMBVAR+SIAECIeUGAAAAAElFTkSuQmCC"
var RED_CAPE []byte = Unwrap(base64.StdEncoding.DecodeString(RED_CAPE_BASE64_STRING))
var redCapeHashBytes = blake3.Sum256(RED_CAPE)
var RED_CAPE_HASH = hex.EncodeToString(redCapeHashBytes[:])
const BLUE_CAPE_BASE64_STRING = "iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAIAAAAt/+nTAAABcGlDQ1BpY2MAACiRdZG9S8NAGMafthZFK0UUFHHIUEWwhaIgjlqHLkVKrWDVJbkmrZCk4ZIixVVwcSg4iC5+Df4HugquCoKgCCJu7n4tUuJ7TaFF2jsu748n97zcPQf4Uzoz7K44YJgOzyQT0mpuTep+RxADGKY5JTPbWkinU+g4fh7hE/UhJnp13td29OVVmwG+HuJZZnGHeJ44teVYgveIh1hRzhOfEEc5HZD4VuiKx2+CCx5/CebZzCLgFz2lQgsrLcyK3CCeJI4Yepk1ziNuElLNlWWqo7TGYCODJBKQoKCMTehwEKNqUmbtffG6bwkl8jD6WqiAk6OAInmjpJapq0pVI12lqaMicv+fp63NTHvdQwkg+Oq6n+NA9z5Qq7ru76nr1s6AwAtwbTb9Jcpp7pv0alOLHAPhHeDypqkpB8DVLjDybMlcrksBWn5NAz4ugP4cMHgP9K57WTX+4/wJyG7TE90Bh0fABO0Pb/wB/+FoCgeBR+AAAAAJcEhZcwAACxIAAAsSAdLdfvwAAAA0SURBVFjD7c8xDQAACAOwzb9o0MBJ0jpok8lnFRAQEBAQEBAQEBAQEBAQEBAQEBAQEBC4Wt/DIAGQrpeYAAAAAElFTkSuQmCC"
var BLUE_CAPE []byte = Unwrap(base64.StdEncoding.DecodeString(BLUE_CAPE_BASE64_STRING))
var blueCapeHashBytes = blake3.Sum256(BLUE_CAPE)
var BLUE_CAPE_HASH = hex.EncodeToString(blueCapeHashBytes[:])
var GOD User = User{IsAdmin: true}
type TestSuite struct {
suite.Suite
App *App
Config *Config
StateDirectory string
Server *echo.Echo
AuxApp *App
AuxConfig *Config
AuxStateDirectory string
AuxServer *echo.Echo
}
func (ts *TestSuite) Setup(config *Config) {
log.SetOutput(io.Discard)
tempStateDirectory := Unwrap(os.MkdirTemp("", "tmp"))
ts.StateDirectory = tempStateDirectory
config.StateDirectory = tempStateDirectory
config.DataDirectory = "."
tsConfig := *config
ts.Config = &tsConfig
ts.App = setup(config)
go ts.App.Run()
ts.Server = ts.App.MakeServer()
go func() { Ignore(ts.Server.Start("")) }()
}
func (ts *TestSuite) SetupAux(config *Config) {
tempStateDirectory := Unwrap(os.MkdirTemp("", "tmp"))
ts.AuxStateDirectory = tempStateDirectory
config.StateDirectory = tempStateDirectory
config.DataDirectory = "."
auxConfig := *config
ts.AuxConfig = &auxConfig
ts.AuxApp = setup(config)
go ts.AuxApp.Run()
ts.AuxServer = ts.AuxApp.MakeServer()
go func() { Ignore(ts.AuxServer.Start("")) }()
// Wait until the server has a listen address... polling seems like the
// easiest way
timeout := 1000
for ts.AuxServer.Listener == nil && timeout > 0 {
time.Sleep(1 * time.Millisecond)
timeout -= 1
}
// Hack: patch these after we know the listen address
baseURL := fmt.Sprintf("http://localhost:%d/", ts.AuxServer.Listener.Addr().(*net.TCPAddr).Port)
ts.AuxApp.Config.BaseURL = baseURL
ts.AuxApp.FrontEndURL = baseURL
ts.AuxApp.AccountURL = Unwrap(url.JoinPath(baseURL, "account"))
ts.AuxApp.AuthURL = Unwrap(url.JoinPath(baseURL, "auth"))
ts.AuxApp.ServicesURL = Unwrap(url.JoinPath(baseURL, "services"))
ts.AuxApp.SessionURL = Unwrap(url.JoinPath(baseURL, "session"))
}
func (ts *TestSuite) ToFallbackAPIServer(app *App, nickname string) FallbackAPIServerConfig {
return FallbackAPIServerConfig{
Nickname: nickname,
SessionURL: app.SessionURL,
AccountURL: app.AccountURL,
ServicesURL: app.ServicesURL,
CacheTTLSeconds: 0,
}
}
func (ts *TestSuite) CheckAuthlibInjectorHeader(t *testing.T, app *App, rec *httptest.ResponseRecorder) {
assert.Equal(t, app.AuthlibInjectorURL, rec.Header().Get("X-Authlib-Injector-API-Location"))
}
func (ts *TestSuite) Teardown() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
servers := []*echo.Echo{
ts.Server,
ts.AuxServer,
}
for _, server := range servers {
if server != nil {
err := server.Shutdown(ctx)
Check(err)
}
}
err := os.RemoveAll(ts.StateDirectory)
Check(err)
}
func (ts *TestSuite) CreateTestUser(t *testing.T, app *App, server *echo.Echo, username string) (*User, *http.Cookie) {
user, err := app.CreateUser(
&GOD, // caller
username,
Ptr(TEST_PASSWORD), // password
PotentiallyInsecure[[]OIDCIdentitySpec]{Value: []OIDCIdentitySpec{}},
false,
false,
nil,
nil,
nil,
nil,
false, // existingPlayer
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
)
assert.Nil(t, err)
if err != nil {
fmt.Println(err.Error())
}
form := url.Values{}
form.Set("username", username)
form.Set("password", TEST_PASSWORD)
req := httptest.NewRequest(http.MethodPost, "/web/login", strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
assert.Nil(t, req.ParseForm())
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
browserToken := getCookie(rec, BROWSER_TOKEN_COOKIE_NAME)
assert.NotNil(t, browserToken)
assert.Nil(t, app.DB.First(&user, "username = ?", user.Username).Error)
return &user, browserToken
}
func (ts *TestSuite) Get(t *testing.T, server *echo.Echo, path string, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) Delete(t *testing.T, server *echo.Echo, path string, payload any, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
body, err := json.Marshal(payload)
assert.Nil(t, err)
req := httptest.NewRequest(http.MethodDelete, path, bytes.NewBuffer(body))
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) PostForm(t *testing.T, server *echo.Echo, path string, form url.Values, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
assert.Nil(t, req.ParseForm())
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) PostMultipart(t *testing.T, server *echo.Echo, path string, body io.Reader, writer *multipart.Writer, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
assert.Nil(t, writer.Close())
req := httptest.NewRequest(http.MethodPost, path, body)
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
req.Header.Add("Content-Type", writer.FormDataContentType())
rec := httptest.NewRecorder()
ts.Server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) PutMultipart(t *testing.T, server *echo.Echo, path string, body io.Reader, writer *multipart.Writer, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
assert.Nil(t, writer.Close())
req := httptest.NewRequest(http.MethodPut, path, body)
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
req.Header.Add("Content-Type", writer.FormDataContentType())
rec := httptest.NewRecorder()
ts.Server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) PostJSON(t *testing.T, server *echo.Echo, path string, payload any, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
body, err := json.Marshal(payload)
assert.Nil(t, err)
req := httptest.NewRequest(http.MethodPost, path, bytes.NewBuffer(body))
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func (ts *TestSuite) PatchJSON(t *testing.T, server *echo.Echo, path string, payload any, cookies []http.Cookie, accessToken *string) *httptest.ResponseRecorder {
body, err := json.Marshal(payload)
assert.Nil(t, err)
req := httptest.NewRequest(http.MethodPatch, path, bytes.NewBuffer(body))
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
if accessToken != nil {
req.Header.Add("Authorization", "Bearer "+*accessToken)
}
req.Header.Add("Content-Type", "application/json")
rec := httptest.NewRecorder()
server.ServeHTTP(rec, req)
ts.CheckAuthlibInjectorHeader(t, ts.App, rec)
return rec
}
func testConfig() *Config {
config := DefaultConfig()
config.BaseURL = "https://drasl.example.com"
config.Domain = "drasl.example.com"
noRateLimit := rateLimitConfig{Enable: false}
config.RateLimit = noRateLimit
config.FallbackAPIServers = []FallbackAPIServerConfig{}
config.LogRequests = false
return &config
}
func getCookie(rec *httptest.ResponseRecorder, cookieName string) *http.Cookie {
cookies := rec.Result().Cookies()
for i := range cookies {
if cookies[i].Name == cookieName {
return cookies[i]
}
}
return &http.Cookie{}
}