Repository navigation
Expand file tree
/
Copy pathscripts_base_path_test.go
More file actions
437 lines (425 loc) · 15.7 KB
/
Copy pathscripts_base_path_test.go
File metadata and controls
437 lines (425 loc) · 15.7 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
)
func scriptFunction(t *testing.T, script, name string) string {
t.Helper()
source, err := os.ReadFile(script)
if err != nil {
t.Fatal(err)
}
_, body, ok := strings.Cut("\n"+string(source), "\n"+name+"() {\n")
if !ok {
t.Fatalf("%s: missing function %s", script, name)
}
body, _, ok = strings.Cut(body, "\n}\n")
if !ok {
t.Fatalf("%s: missing closing brace for %s", script, name)
}
return name + "() {\n" + body + "\n}\n"
}
const settingsCLIMock = `#!/bin/bash
set -eu
state=$TEST_SETTINGS_DIR
if [[ "$1" == migrate ]]; then
printf 'migrate\n' >> "$state/lifecycle"
if [[ "$TEST_READ_MODE" == migration_failure ]]; then exit 1; fi
exit 0
fi
shift
case "$1" in
-show)
case "$TEST_READ_MODE" in
failure) exit 1 ;;
empty) exit 0 ;;
diagnostic) echo 'get webBasePath failed, error info: database unavailable' ;;
esac
echo 'current panel settings as follows:'
echo "hasDefaultCredential: $(cat "$state/default")"
echo "port: $(cat "$state/port")"
case "$TEST_READ_MODE" in
missing_field) ;;
malformed) echo 'webBasePath: not-an-absolute-path' ;;
duplicate) printf 'webBasePath: /\nwebBasePath: /a/\n' ;;
*)
path=$(cat "$state/path")
printf 'webBasePath: %s\n' "${path:-/}" ;;
esac
exit 0 ;;
-getCert)
if [[ "$TEST_READ_MODE" == ssl_failure ]]; then
echo 'cert:'
else
echo 'cert: /tmp/panel.example/fullchain.pem'
fi
exit 0 ;;
-getApiToken) echo 'apiToken: test-token'; exit 0 ;;
esac
printf 'write\n' >> "$state/writes"
said_port= said_user= said_path=
while [[ $# -gt 0 ]]; do
key=$1 value=$2
shift 2
case "$key" in
-webBasePath)
said_path=1
printf '%s\n' "$value" >> "$state/path-writes"
[[ "$value" == /* ]] || value="/$value"
[[ "$value" == */ ]] || value="$value/"
printf '%s' "$value" > "$state/path" ;;
-username) said_user=1; printf '%s' "$value" > "$state/username" ;;
-password) said_user=1; printf '%s' "$value" > "$state/password" ;;
-port) said_port=$value; printf '%s' "$value" > "$state/port" ;;
*) echo "unexpected setting: $key" >&2; exit 98 ;;
esac
done
if [[ "$(cat "$state/username")" != admin && "$(cat "$state/password")" != admin ]]; then
echo false > "$state/default"
fi
[[ -z "$said_port" ]] || echo "Port set successfully: $said_port"
[[ -z "$said_user" ]] || echo 'Username and password updated successfully'
[[ -z "$said_path" ]] || echo 'Base URI path set successfully'
`
func runScriptConfig(t *testing.T, script, path string, defaults bool, mode string, runs int, continueSetup bool) (string, string, error) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("installer regressions require a POSIX environment; run them under WSL")
}
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("bash is required for the isolated installer regression tests")
}
dir := t.TempDir()
username, password := "custom-user", "custom-password"
if defaults {
username, password = "admin", "admin"
}
for name, value := range map[string]string{
"path": path, "username": username, "password": password,
"default": fmt.Sprint(defaults), "port": "54321", "x-ui": settingsCLIMock,
"writes": "", "path-writes": "", "restarts": "", "lifecycle": "", "x-ui.service": "test unit",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o700); err != nil {
t.Fatal(err)
}
}
function := "config_after_update"
if script == "install.sh" {
function = "config_after_install"
}
driver := `set -u
red= green= yellow= blue= plain=
xui_folder=$TEST_SETTINGS_DIR
xui_service=$TEST_SETTINGS_DIR
tag_version=test
script_ref=main
NONINTERACTIVE=1
release=ubuntu
SSL_SCHEME=https
SSL_HOST=panel.example
curl() { printf '203.0.113.10\n200\n'; }
systemctl() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
rc-service() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
prompt_and_setup_ssl() {
printf '%s\n' "$*" > "$TEST_SETTINGS_DIR/ssl"
if [[ "$TEST_READ_MODE" == ssl_failure ]]; then
printf 'ssl\n' >> "$TEST_SETTINGS_DIR/lifecycle"
return 1
fi
}
write_install_result() { printf '%s\n' "$@" > "$TEST_SETTINGS_DIR/result"; }
install_postgres_local() { echo 'unexpected PostgreSQL installation' >&2; exit 97; }
chown() { :; }
chmod() { :; }
[() { if [[ "${2:-}" == /etc/* ]]; then return 1; fi; builtin [ "$@"; }
_install_xui_service_unit() { printf 'unit\n' >> "$TEST_SETTINGS_DIR/lifecycle"; }
setup_fail2ban() { printf 'fail2ban\n' >> "$TEST_SETTINGS_DIR/lifecycle"; }
fail2ban_mode=install
`
driver += scriptFunction(t, script, "gen_random_string") + scriptFunction(t, script, function)
if script == "install.sh" {
for _, helper := range []string{"is_port_in_use", "normalize_panel_port", "select_panel_port"} {
driver += scriptFunction(t, script, helper)
}
}
if continueSetup {
parent := "update_x-ui"
if script == "install.sh" {
parent = "install_x-ui"
}
body := scriptFunction(t, script, parent)
startCall := function
if script == "update.sh" {
startCall = `echo -e "${green}Migrating database...${plain}"`
driver += scriptFunction(t, script, "_fail")
}
start := strings.Index(body, "\n "+startCall)
if start < 0 {
t.Fatalf("%s: missing configuration call in %s", script, parent)
}
driver += "finish_setup() {" + body[start:] + "finish_setup\n"
} else {
driver += fmt.Sprintf("for ((i=0; i<%d; i++)); do %s || exit $?; done\n", runs, function)
}
cmd := exec.Command(bash, "-c", driver)
cmd.Dir = dir
for _, value := range os.Environ() {
if !strings.HasPrefix(value, "XUI_") && !strings.HasPrefix(value, "TEST_") {
cmd.Env = append(cmd.Env, value)
}
}
cmd.Env = append(cmd.Env, "TEST_SETTINGS_DIR="+dir, "TEST_READ_MODE="+mode,
"XUI_DB_TYPE=sqlite", "XUI_PANEL_PORT=41234")
out, err := cmd.CombinedOutput()
return dir, string(out), err
}
func readScriptState(t *testing.T, dir, name string) string {
t.Helper()
value, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
return string(value)
}
func TestScriptConfigPreservesCustomBasePaths(t *testing.T) {
for _, script := range []string{"install.sh", "update.sh"} {
for _, path := range []string{"/", "", "/a/", "/ab/", "/abc/", "/mypanel/", "/failed/", "/my panel/"} {
for _, defaults := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/path=%q/defaults=%t", script, path, defaults), func(t *testing.T) {
dir, out, err := runScriptConfig(t, script, path, defaults, "", 2, false)
if err != nil {
t.Fatalf("configure twice: %v\n%s", err, out)
}
actualPath := readScriptState(t, dir, "path")
initialize := path == "" || path == "/"
if initialize {
if !regexp.MustCompile(`^/[A-Za-z0-9]{18}/$`).MatchString(actualPath) {
t.Errorf("initialized path = %q, want secure 18-character path", actualPath)
}
if n := strings.Count(readScriptState(t, dir, "path-writes"), "\n"); n != 1 {
t.Errorf("path initialized %d times across two runs, want once", n)
}
} else if actualPath != path || readScriptState(t, dir, "path-writes") != "" {
t.Errorf("custom path %q became %q; writes=%q", path, actualPath, readScriptState(t, dir, "path-writes"))
}
for _, field := range []string{"username", "password"} {
actual := readScriptState(t, dir, field)
if defaults && script == "install.sh" {
if !regexp.MustCompile(`^[A-Za-z0-9]{10}$`).MatchString(actual) || actual == "admin" {
t.Errorf("%s was not securely initialized: %q", field, actual)
}
} else {
want := "admin"
if !defaults {
want = "custom-" + field
if field == "username" {
want = "custom-user"
}
}
if actual != want {
t.Errorf("%s = %q, want preserved %q", field, actual, want)
}
}
}
wantRestarts := ""
if initialize && script == "update.sh" {
wantRestarts = "restart x-ui\n"
}
if actual := readScriptState(t, dir, "restarts"); actual != wantRestarts {
t.Errorf("path-related restarts = %q, want %q", actual, wantRestarts)
}
wantWrites := 0
if initialize || (defaults && script == "install.sh") {
wantWrites = 1
}
if n := strings.Count(readScriptState(t, dir, "writes"), "\n"); n != wantWrites {
t.Errorf("configuration writes = %d, want %d across two runs", n, wantWrites)
}
wantPort := "54321"
if initialize && defaults && script == "install.sh" {
wantPort = "41234"
}
if actual := readScriptState(t, dir, "port"); actual != wantPort {
t.Errorf("port = %q, want %q", actual, wantPort)
}
if !initialize {
if _, err := os.Stat(filepath.Join(dir, "ssl")); !os.IsNotExist(err) {
t.Errorf("configured TLS should not be reinitialized: %v", err)
}
}
})
}
}
}
}
func TestScriptConfigRejectsUnreadableSettings(t *testing.T) {
for _, script := range []string{"install.sh", "update.sh"} {
for _, mode := range []string{"failure", "empty", "missing_field", "malformed", "duplicate", "diagnostic"} {
t.Run(script+"/"+mode, func(t *testing.T) {
dir, out, err := runScriptConfig(t, script, "/", true, mode, 1, false)
if err == nil || !strings.Contains(out, "Unable to read webBasePath") {
t.Errorf("settings read should stop with an actionable error; got %v\n%s", err, out)
}
for name, want := range map[string]string{"path": "/", "username": "admin", "password": "admin", "writes": "", "restarts": ""} {
if actual := readScriptState(t, dir, name); actual != want {
t.Errorf("failed settings read changed %s to %q, want %q", name, actual, want)
}
}
})
}
}
}
func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) {
for _, script := range []string{"install.sh", "update.sh"} {
t.Run(script, func(t *testing.T) {
dir, out, err := runScriptConfig(t, script, "/a/", true, "failure", 1, true)
if err != nil || !strings.Contains(out, "Unable to read webBasePath") {
t.Errorf("service setup should continue after the settings warning: %v\n%s", err, out)
}
wantLifecycle, wantServices := "migrate\nfail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n"
if script == "install.sh" {
wantServices = "daemon-reload\nenable x-ui\nrestart x-ui\n"
}
for name, want := range map[string]string{
"path": "/a/", "username": "admin", "password": "admin", "writes": "",
"lifecycle": wantLifecycle, "restarts": wantServices,
} {
if actual := readScriptState(t, dir, name); actual != want {
t.Errorf("%s = %q, want %q", name, actual, want)
}
}
})
}
}
func TestInstallerSSLFailureKeepsServiceSetup(t *testing.T) {
dir, out, err := runScriptConfig(t, "install.sh", "/a/", true, "ssl_failure", 1, true)
if err != nil {
t.Fatalf("a failed certificate must not abort the install: %v\n%s", err, out)
}
if _, err := os.Stat(filepath.Join(dir, "ssl")); err != nil {
t.Fatalf("SSL setup was not attempted: %v\n%s", err, out)
}
for name, want := range map[string]string{
"lifecycle": "ssl\nmigrate\nfail2ban\nunit\n", "restarts": "daemon-reload\nenable x-ui\nrestart x-ui\n",
} {
if actual := readScriptState(t, dir, name); actual != want {
t.Errorf("%s after a failed certificate = %q, want %q: the panel must still be installed and started", name, actual, want)
}
}
}
func TestInstallMigrationFailurePreventsServiceStart(t *testing.T) {
dir, out, err := runScriptConfig(t, "install.sh", "/a/", false, "migration_failure", 1, true)
if err == nil || !strings.Contains(out, "Database migration failed") {
t.Fatalf("migration failure should abort the update: %v\n%s", err, out)
}
if got := readScriptState(t, dir, "restarts"); got != "" {
t.Fatalf("service started after a failed migration: %q", got)
}
if got := readScriptState(t, dir, "lifecycle"); got != "migrate\n" {
t.Fatalf("lifecycle after failed migration: %q", got)
}
}
func TestUpdateMigrationFailureKeepsServiceUnitForRetry(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("updater regression requires a POSIX environment")
}
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("bash is required for the isolated updater regression")
}
for _, distro := range []struct {
name, unit, stopped, started string
}{
{"ubuntu", "systemd/x-ui.service", "systemctl stop x-ui\nsystemctl disable x-ui\n", "systemctl daemon-reload\nsystemctl enable x-ui\nsystemctl start x-ui\n"},
{"alpine", "init.d/x-ui", "rc-service x-ui stop\nrc-update del x-ui\n", "rc-update add x-ui\nrc-service x-ui start\n"},
} {
t.Run(distro.name, func(t *testing.T) {
dir := t.TempDir()
for _, folder := range []string{"x-ui", "systemd", "init.d", "release/x-ui", "bin"} {
if err := os.MkdirAll(filepath.Join(dir, folder), 0o700); err != nil {
t.Fatal(err)
}
}
const binary = `#!/bin/bash
if [[ $1 == migrate ]]; then
printf 'migrate\n' >> "$TEST_ROOT/events"
[[ $TEST_FAIL_MIGRATION == 0 ]]
else
printf 'test version\n'
fi
`
for name, value := range map[string]string{
distro.unit: "old unit\n", "x-ui/x-ui": binary, "release/x-ui/x-ui": binary,
"release/x-ui/x-ui.sh": "#!/bin/bash\n", "release/x-ui/x-ui.service": "new unit\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o700); err != nil {
t.Fatal(err)
}
}
driver := `red= green= yellow= blue= plain=
xui_folder="$TEST_ROOT/x-ui"
xui_service="$TEST_ROOT/systemd"
release="$TEST_DISTRO"
XUI_UPDATE_TAG=test
curl_bin=fake_curl
load_xui_env() { :; }
setup_fail2ban() { :; }
config_after_update() { :; }
_xui_service_write_paths_dropin() { :; }
_xui_warn_unsupported_hardening() { :; }
chown() { :; }
pkill() { :; }
systemctl() { printf 'systemctl %s\n' "$*" >> "$TEST_ROOT/events"; }
rc-service() { printf 'rc-service %s\n' "$*" >> "$TEST_ROOT/events"; }
rc-update() { printf 'rc-update %s\n' "$*" >> "$TEST_ROOT/events"; }
fake_curl() {
case "$*" in
*.sha256) printf 404 ;;
*/x-ui.rc) printf 'new unit\n' > "$2" ;;
*) tar -czf "$2" -C "$TEST_ROOT/release" x-ui ;;
esac
}
`
driver += scriptFunction(t, "update.sh", "_fail") + scriptFunction(t, "update.sh", "_install_xui_service_unit")
driver += strings.NewReplacer(
"/etc/init.d/x-ui", "$TEST_ROOT/init.d/x-ui",
"/usr/bin/x-ui", "$TEST_ROOT/bin/x-ui",
"/var/log/x-ui", "$TEST_ROOT/log",
).Replace(scriptFunction(t, "update.sh", "update_x-ui"))
driver += "update_x-ui\n"
run := func(failMigration string) (string, error) {
t.Helper()
cmd := exec.Command(bash, "-c", driver)
cmd.Dir = dir
cmd.Env = append(os.Environ(), "TEST_ROOT="+dir, "TEST_DISTRO="+distro.name, "TEST_FAIL_MIGRATION="+failMigration)
out, err := cmd.CombinedOutput()
return string(out), err
}
if out, err := run("1"); err == nil || !strings.Contains(out, "Database migration failed") {
t.Fatalf("first update should fail in migration: %v\n%s", err, out)
}
if unit := readScriptState(t, dir, distro.unit); unit != "old unit\n" {
t.Fatalf("failed update changed the service unit: %q", unit)
}
if got := readScriptState(t, dir, "events"); got != distro.stopped+"migrate\n" {
t.Fatalf("failed update service actions: %q", got)
}
if out, err := run("0"); err != nil {
t.Fatalf("ordinary update retry failed: %v\n%s", err, out)
}
if unit := readScriptState(t, dir, distro.unit); unit != "new unit\n" {
t.Fatalf("retry did not install the replacement unit: %q", unit)
}
if got := readScriptState(t, dir, "events"); got != strings.Repeat(distro.stopped+"migrate\n", 2)+distro.started {
t.Fatalf("retry service actions: %q", got)
}
})
}
}