diff --git a/dist/urbm-2026.11.22.r001-x86_64-1.txz b/dist/urbm-2026.11.22.r001-x86_64-1.txz new file mode 100644 index 0000000..6bae3f4 Binary files /dev/null and b/dist/urbm-2026.11.22.r001-x86_64-1.txz differ diff --git a/dist/urbm-2026.11.22.r001-x86_64-1.txz.sha256 b/dist/urbm-2026.11.22.r001-x86_64-1.txz.sha256 new file mode 100644 index 0000000..8ada57d --- /dev/null +++ b/dist/urbm-2026.11.22.r001-x86_64-1.txz.sha256 @@ -0,0 +1 @@ +80142b9de7ad7aa6ba980ec73e394198f2c8b6609430e7d2bfbb4ec65b3fca3c urbm-2026.11.22.r001-x86_64-1.txz diff --git a/dist/urbm.plg b/dist/urbm.plg index 15c72b1..0ea8de2 100644 --- a/dist/urbm.plg +++ b/dist/urbm.plg @@ -2,13 +2,19 @@ - + - + ]> +### 2026.11.22.r001 +- Pass --ignore-inode automatically for sources below /mnt/user and /mnt/user0, whose shfs inode numbers change after every reboot and previously forced Restic to re-read all data. +- Add a per-job "low priority" option that starts Restic and Rsync through ionice (idle class) and nice 19, so backups no longer starve containers and services. +- Group retention by host and job tags instead of host and paths, so snapshots from before a source change still expire under keep-within. +- Verify the Unraid CSRF token in the API bridge for all state-changing requests and reject unknown HTTP methods. + ### 2026.10.15.r001 - Parse carriage-return progress updates during Rsync space estimation instead of accumulating oversized lines. - Share the streaming parser with the copy runner and report output-read failures without blocking the child process. diff --git a/internal/model/model.go b/internal/model/model.go index 6a6ab64..67d56e1 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -59,6 +59,7 @@ type Job struct { Compression string `json:"compression"` CPUCores int `json:"cpuCores,omitempty"` ReadConcurrency int `json:"readConcurrency,omitempty"` + LowPriority bool `json:"lowPriority,omitempty"` Excludes []string `json:"excludes,omitempty"` Tags []string `json:"tags,omitempty"` FlashImage bool `json:"flashImage,omitempty"` diff --git a/internal/procprio/procprio.go b/internal/procprio/procprio.go new file mode 100644 index 0000000..3210bb5 --- /dev/null +++ b/internal/procprio/procprio.go @@ -0,0 +1,35 @@ +// Package procprio starts helper processes with reduced CPU and IO priority. +package procprio + +import "os/exec" + +// lookPath is replaceable in tests. +var lookPath = exec.LookPath + +// Command returns the executable and arguments to run binary with args. +// +// With low set, the process is started through ionice (idle IO class) and +// nice (level 19), so it only receives CPU time and disk bandwidth that no +// other process on the server needs. Both tools exec the target, so the PID, +// process group, signals and exit status stay those of binary. A tool that +// is not installed is skipped; without either tool the command is unchanged. +func Command(low bool, binary string, args []string) (string, []string) { + if !low { + return binary, args + } + var prefix []string + if path, err := lookPath("ionice"); err == nil { + prefix = append(prefix, path, "-c", "3") + } + if path, err := lookPath("nice"); err == nil { + prefix = append(prefix, path, "-n", "19") + } + if len(prefix) == 0 { + return binary, args + } + full := make([]string, 0, len(prefix)+len(args)) + full = append(full, prefix[1:]...) + full = append(full, binary) + full = append(full, args...) + return prefix[0], full +} diff --git a/internal/procprio/procprio_test.go b/internal/procprio/procprio_test.go new file mode 100644 index 0000000..8a5669e --- /dev/null +++ b/internal/procprio/procprio_test.go @@ -0,0 +1,49 @@ +package procprio + +import ( + "errors" + "reflect" + "testing" +) + +func withTools(t *testing.T, tools map[string]string) { + t.Helper() + previous := lookPath + lookPath = func(name string) (string, error) { + if path, ok := tools[name]; ok { + return path, nil + } + return "", errors.New("not found") + } + t.Cleanup(func() { lookPath = previous }) +} + +func TestCommandUnchangedWithoutLowPriority(t *testing.T) { + withTools(t, map[string]string{"ionice": "/usr/bin/ionice", "nice": "/usr/bin/nice"}) + name, args := Command(false, "/bin/restic", []string{"backup", "/src"}) + if name != "/bin/restic" || !reflect.DeepEqual(args, []string{"backup", "/src"}) { + t.Fatalf("got %q %q", name, args) + } +} + +func TestCommandWrapsWithIoniceAndNice(t *testing.T) { + withTools(t, map[string]string{"ionice": "/usr/bin/ionice", "nice": "/usr/bin/nice"}) + name, args := Command(true, "/bin/restic", []string{"backup", "/src"}) + want := []string{"-c", "3", "/usr/bin/nice", "-n", "19", "/bin/restic", "backup", "/src"} + if name != "/usr/bin/ionice" || !reflect.DeepEqual(args, want) { + t.Fatalf("got %q %q", name, args) + } +} + +func TestCommandSkipsMissingTools(t *testing.T) { + withTools(t, map[string]string{"nice": "/usr/bin/nice"}) + name, args := Command(true, "/bin/rsync", []string{"-a"}) + if name != "/usr/bin/nice" || !reflect.DeepEqual(args, []string{"-n", "19", "/bin/rsync", "-a"}) { + t.Fatalf("got %q %q", name, args) + } + withTools(t, map[string]string{}) + name, args = Command(true, "/bin/rsync", []string{"-a"}) + if name != "/bin/rsync" || !reflect.DeepEqual(args, []string{"-a"}) { + t.Fatalf("got %q %q", name, args) + } +} diff --git a/internal/restic/restic.go b/internal/restic/restic.go index 2d32163..1c1ff76 100644 --- a/internal/restic/restic.go +++ b/internal/restic/restic.go @@ -17,8 +17,15 @@ import ( "syscall" "git.casaderoll.de/michael/urbm/internal/model" + "git.casaderoll.de/michael/urbm/internal/procprio" ) +// procOptions are per-call settings for the restic process. +type procOptions struct { + env []string + lowPriority bool +} + type SecretGetter interface{ Get(string) (string, error) } type Runner struct { @@ -138,11 +145,11 @@ func (r *Runner) ChangePassword(ctx context.Context, repo model.Repository, curr return err } defer cleanup() - return r.runWithInputEnvPassword(ctx, repo, []string{"key", "passwd", "--new-password-file", newPasswordPath}, nil, nil, nil, nil, currentPassword) + return r.runWithInputEnvPassword(ctx, repo, []string{"key", "passwd", "--new-password-file", newPasswordPath}, nil, nil, nil, procOptions{}, currentPassword) } func (r *Runner) TestPassword(ctx context.Context, repo model.Repository, password string) error { - return r.runWithInputEnvPassword(ctx, repo, []string{"snapshots", "--json"}, nil, nil, nil, nil, password) + return r.runWithInputEnvPassword(ctx, repo, []string{"snapshots", "--json"}, nil, nil, nil, procOptions{}, password) } func (r *Runner) Backup(ctx context.Context, repo model.Repository, job model.Job, sources []string, progress ProgressCallback) (Summary, error) { @@ -150,6 +157,9 @@ func (r *Runner) Backup(ctx context.Context, repo model.Repository, job model.Jo if job.ReadConcurrency > 0 { args = append(args, "--read-concurrency", fmt.Sprint(job.ReadConcurrency)) } + if needsIgnoreInode(sources) { + args = append(args, "--ignore-inode") + } for _, tag := range append([]string{"urbm", "job:" + job.ID}, job.Tags...) { args = append(args, "--tag", tag) } @@ -170,7 +180,7 @@ func (r *Runner) Backup(ctx context.Context, repo model.Repository, job model.Jo if json.Unmarshal(line, &candidate) == nil && candidate.MessageType == "summary" { summary = candidate } - }, nil, backupEnvironment(job)) + }, nil, backupOptions(job)) return summary, err } @@ -192,12 +202,16 @@ func (r *Runner) BackupImage(ctx context.Context, repo model.Repository, job mod if json.Unmarshal(line, &candidate) == nil && candidate.MessageType == "summary" { summary = candidate } - }, nil, image, backupEnvironment(job)) + }, nil, image, backupOptions(job)) return summary, err } func (r *Runner) Forget(ctx context.Context, repo model.Repository, job model.Job) error { - args := []string{"forget", "--tag", "job:" + job.ID} + // Group by the job tags instead of restic's default host,paths. With + // path grouping, changing or adding a source starts a new group, and + // keep-within (relative to each group's latest snapshot) never expires + // the old group's snapshots. + args := []string{"forget", "--tag", "job:" + job.ID, "--group-by", "host,tags"} if job.Retention.KeepWithinDays > 0 { args = append(args, "--keep-within", fmt.Sprintf("%dd", job.Retention.KeepWithinDays)) } @@ -374,22 +388,22 @@ func (r *Runner) Restore(ctx context.Context, repo model.Repository, task model. } func (r *Runner) run(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte) error { - return r.runWithInputAndEnv(ctx, repo, args, onLine, capture, nil, nil) + return r.runWithInputAndEnv(ctx, repo, args, onLine, capture, nil, procOptions{}) } -func (r *Runner) runWithEnv(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, environment []string) error { - return r.runWithInputAndEnv(ctx, repo, args, onLine, capture, nil, environment) +func (r *Runner) runWithEnv(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, opts procOptions) error { + return r.runWithInputAndEnv(ctx, repo, args, onLine, capture, nil, opts) } -func (r *Runner) runWithInputAndEnv(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, input io.Reader, environment []string) error { +func (r *Runner) runWithInputAndEnv(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, input io.Reader, opts procOptions) error { password, err := r.Secrets.Get(repo.PasswordRef) if err != nil { return fmt.Errorf("authentication: load repository password: %w", err) } - return r.runWithInputEnvPassword(ctx, repo, args, onLine, capture, input, environment, password) + return r.runWithInputEnvPassword(ctx, repo, args, onLine, capture, input, opts, password) } -func (r *Runner) runWithInputEnvPassword(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, input io.Reader, environment []string, password string) error { +func (r *Runner) runWithInputEnvPassword(ctx context.Context, repo model.Repository, args []string, onLine func([]byte), capture *[]byte, input io.Reader, opts procOptions, password string) error { passwordPath, cleanup, err := r.writePasswordFile("restic-password-*", password) if err != nil { return err @@ -426,7 +440,8 @@ func (r *Runner) runWithInputEnvPassword(ctx context.Context, repo model.Reposit globalArgs = append(globalArgs, "-o", "sftp.command="+command) } fullArgs := append(globalArgs, args...) - cmd := exec.CommandContext(ctx, r.binary(), fullArgs...) + name, cmdArgs := procprio.Command(opts.lowPriority, r.binary(), fullArgs) + cmd := exec.CommandContext(ctx, name, cmdArgs...) cmd.Stdin = input cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { @@ -441,7 +456,7 @@ func (r *Runner) runWithInputEnvPassword(ctx context.Context, repo model.Reposit } return nil } - cmd.Env = append([]string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root", "RESTIC_PASSWORD_FILE=" + passwordPath}, environment...) + cmd.Env = append([]string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root", "RESTIC_PASSWORD_FILE=" + passwordPath}, opts.env...) stdout, err := cmd.StdoutPipe() if err != nil { return err @@ -540,11 +555,31 @@ func (r *Runner) writePasswordFile(pattern, password string) (string, func(), er return passwordPath, cleanup, nil } -func backupEnvironment(job model.Job) []string { - if job.CPUCores <= 0 { - return nil +func backupOptions(job model.Job) procOptions { + opts := procOptions{lowPriority: job.LowPriority} + if job.CPUCores > 0 { + opts.env = []string{"GOMAXPROCS=" + fmt.Sprint(job.CPUCores)} } - return []string{"GOMAXPROCS=" + fmt.Sprint(job.CPUCores)} + return opts +} + +// unstableInodeRoots are Unraid FUSE mounts (shfs) that hand out new inode +// numbers after every reboot or remount. +var unstableInodeRoots = []string{"/mnt/user", "/mnt/user0"} + +// needsIgnoreInode reports whether a source lies on a mount without stable +// inode numbers. Restic then compares only size and mtime, instead of +// treating every file as changed and re-reading all data after a reboot. +func needsIgnoreInode(sources []string) bool { + for _, source := range sources { + clean := filepath.Clean(source) + for _, root := range unstableInodeRoots { + if clean == root || strings.HasPrefix(clean, root+"/") { + return true + } + } + } + return false } func resticError(message string, commandErr error) error { diff --git a/internal/restic/restic_test.go b/internal/restic/restic_test.go index 21f61b4..be0e5df 100644 --- a/internal/restic/restic_test.go +++ b/internal/restic/restic_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -379,6 +380,9 @@ func TestForgetUsesAgeAndCalendarRetention(t *testing.T) { if strings.Contains(string(args), "--keep-daily") { t.Fatalf("disabled daily retention was included: %s", args) } + if !strings.Contains(string(args), "--group-by\nhost,tags\n") { + t.Fatalf("retention must group by job tags, not paths: %s", args) + } } func TestForgetUnlocksStaleRepositoryLockAndRetries(t *testing.T) { @@ -538,3 +542,81 @@ func TestRunnerPausesResumesAndCancelsProcessGroup(t *testing.T) { t.Fatal("paused process group was not cancelled") } } + +func TestNeedsIgnoreInodeOnlyForUnraidUserShares(t *testing.T) { + cases := map[string]bool{ + "/mnt/user": true, + "/mnt/user/Musik": true, + "/mnt/user0/Bilder": true, + "/mnt/user/../user/Musik": true, + "/mnt/sata-storage/Musik": false, + "/mnt/disk1/Musik": false, + "/mnt/username/Musik": false, + "/boot": false, + } + for source, want := range cases { + if got := needsIgnoreInode([]string{source}); got != want { + t.Errorf("needsIgnoreInode(%q) = %v, want %v", source, got, want) + } + } + if !needsIgnoreInode([]string{"/mnt/sata-storage/Musik", "/mnt/user/Bilder"}) { + t.Error("one /mnt/user source must enable --ignore-inode") + } +} + +func TestBackupPassesIgnoreInodeForUserShares(t *testing.T) { + for _, tc := range []struct { + source string + want bool + }{{"/mnt/user/Musik", true}, {"/mnt/sata-storage/Musik", false}} { + dir := t.TempDir() + argsPath := filepath.Join(dir, "args") + script := filepath.Join(dir, "restic") + body := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > '%s'\nprintf '%%s\\n' '{\"message_type\":\"summary\",\"snapshot_id\":\"ino\"}'\n", argsPath) + if err := os.WriteFile(script, []byte(body), 0700); err != nil { + t.Fatal(err) + } + runner := &Runner{Binary: script, RuntimeDir: dir, Secrets: fakeSecrets{"password": "secret"}} + repo := model.Repository{Type: model.RepositoryLocal, Location: "/repo", PasswordRef: "password"} + job := model.Job{ID: "job", Compression: "auto"} + if _, err := runner.Backup(context.Background(), repo, job, []string{tc.source}, nil); err != nil { + t.Fatal(err) + } + args, _ := os.ReadFile(argsPath) + if got := strings.Contains(string(args), "--ignore-inode\n"); got != tc.want { + t.Fatalf("source %s: --ignore-inode present = %v, want %v\n%s", tc.source, got, tc.want, args) + } + } +} + +func TestBackupRunsWithLowPriorityForThisJob(t *testing.T) { + if _, err := exec.LookPath("nice"); err != nil { + t.Skip("nice not installed") + } + for _, tc := range []struct { + low bool + want string + }{{true, "19"}, {false, "0"}} { + dir := t.TempDir() + nicePath := filepath.Join(dir, "nice") + script := filepath.Join(dir, "restic") + body := fmt.Sprintf("#!/bin/sh\nps -o nice= -p $$ | tr -d ' ' > '%s'\nprintf '%%s\\n' '{\"message_type\":\"summary\",\"snapshot_id\":\"prio\"}'\n", nicePath) + if err := os.WriteFile(script, []byte(body), 0700); err != nil { + t.Fatal(err) + } + runner := &Runner{Binary: script, RuntimeDir: dir, Secrets: fakeSecrets{"password": "secret"}} + repo := model.Repository{Type: model.RepositoryLocal, Location: "/repo", PasswordRef: "password"} + job := model.Job{ID: "job", Compression: "auto", LowPriority: tc.low} + summary, err := runner.Backup(context.Background(), repo, job, []string{"/source"}, nil) + if err != nil { + t.Fatal(err) + } + if summary.SnapshotID != "prio" { + t.Fatalf("summary not parsed through wrapper: %+v", summary) + } + value, _ := os.ReadFile(nicePath) + if strings.TrimSpace(string(value)) != tc.want { + t.Fatalf("lowPriority=%v: nice = %q, want %s", tc.low, value, tc.want) + } + } +} diff --git a/internal/rsync/rsync.go b/internal/rsync/rsync.go index b38ce18..950dd05 100644 --- a/internal/rsync/rsync.go +++ b/internal/rsync/rsync.go @@ -16,6 +16,7 @@ import ( "syscall" "git.casaderoll.de/michael/urbm/internal/model" + "git.casaderoll.de/michael/urbm/internal/procprio" ) type Runner struct { @@ -61,7 +62,8 @@ var ( func (r *Runner) Run(ctx context.Context, runID string, job model.Job, callback func(Progress)) (Summary, error) { args := Arguments(job) - cmd := exec.CommandContext(ctx, r.binary(), args...) + name, cmdArgs := procprio.Command(job.LowPriority, r.binary(), args) + cmd := exec.CommandContext(ctx, name, cmdArgs...) cmd.Env = append(os.Environ(), "LC_ALL=C", "LANG=C") cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { @@ -148,7 +150,8 @@ func (r *Runner) Estimate(ctx context.Context, runID string, job model.Job) (Sum args[index] = "--out-format=SPACE|%i|%l|%n" } } - cmd := exec.CommandContext(ctx, r.binary(), args...) + name, cmdArgs := procprio.Command(job.LowPriority, r.binary(), args) + cmd := exec.CommandContext(ctx, name, cmdArgs...) cmd.Env = append(os.Environ(), "LC_ALL=C", "LANG=C") cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { diff --git a/packaging/build-package.sh b/packaging/build-package.sh index 742f73b..e8fee47 100755 --- a/packaging/build-package.sh +++ b/packaging/build-package.sh @@ -30,7 +30,8 @@ fi bzip2 -dc "$RESTIC_ARCHIVE" > "$STAGE/usr/local/libexec/urbm/restic" chmod 0755 "$STAGE/usr/local/libexec/urbm/restic" "$STAGE/usr/local/sbin/urbmd" -sed "s/$PLUGIN_VERSION/$VERSION/g" "$ROOT/webgui/URBM.page" > "$STAGE/usr/local/emhttp/plugins/urbm/URBM.page" +sed -e "s/^\$urbmVersion = '[^']*';/\$urbmVersion = '$VERSION';/" -e "s/$PLUGIN_VERSION/$VERSION/g" "$ROOT/webgui/URBM.page" > "$STAGE/usr/local/emhttp/plugins/urbm/URBM.page" +grep -q "^\$urbmVersion = '$VERSION';" "$STAGE/usr/local/emhttp/plugins/urbm/URBM.page" || { echo "URBM.page version was not set to $VERSION" >&2; exit 1; } cp "$ROOT/webgui/api.php" "$STAGE/usr/local/emhttp/plugins/urbm/" cp "$ROOT/webgui/assets/"* "$STAGE/usr/local/emhttp/plugins/urbm/assets/" cp "$ROOT/webgui/images/"* "$STAGE/usr/local/emhttp/plugins/urbm/images/" diff --git a/plugin/urbm.plg b/plugin/urbm.plg index ea05da5..3bcbac3 100644 --- a/plugin/urbm.plg +++ b/plugin/urbm.plg @@ -2,13 +2,19 @@ - + ]> +### 2026.11.22.r001 +- Pass --ignore-inode automatically for sources below /mnt/user and /mnt/user0, whose shfs inode numbers change after every reboot and previously forced Restic to re-read all data. +- Add a per-job "low priority" option that starts Restic and Rsync through ionice (idle class) and nice 19, so backups no longer starve containers and services. +- Group retention by host and job tags instead of host and paths, so snapshots from before a source change still expire under keep-within. +- Verify the Unraid CSRF token in the API bridge for all state-changing requests and reject unknown HTTP methods. + ### 2026.10.15.r001 - Parse carriage-return progress updates during Rsync space estimation instead of accumulating oversized lines. - Share the streaming parser with the copy runner and report output-read failures without blocking the child process. diff --git a/scripts/check.sh b/scripts/check.sh index 356d0fb..6d9d2cc 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -7,5 +7,6 @@ cd "$ROOT" go test ./... go vet ./... node --check webgui/assets/urbm.js -bash -n plugin/rc.urbm packaging/build-package.sh scripts/check.sh +bash -n plugin/rc.urbm packaging/build-package.sh scripts/check.sh tests/api_csrf_test.sh tests/migration_test.sh +tests/api_csrf_test.sh diff --git a/tests/api_csrf_test.sh b/tests/api_csrf_test.sh new file mode 100755 index 0000000..686345c --- /dev/null +++ b/tests/api_csrf_test.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Checks that webgui/api.php rejects state-changing requests without the +# Unraid CSRF token. Runs api.php through the PHP CLI, which fills $_SERVER +# from the environment. A request that passes the check reaches the daemon +# socket test and fails with "Daemon läuft nicht" instead. +set -euo pipefail + +if ! command -v php >/dev/null 2>&1; then + echo "api_csrf_test: php not installed, skipped" + exit 0 +fi + +ROOT=$(cd "$(dirname "$0")/.." && pwd) +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +printf 'csrf_token="secret-token"\n' > "$WORK/var.ini" + +call() { + env -i PATH="$PATH" URBM_VAR_INI="${VAR_INI:-$WORK/var.ini}" "$@" php "$ROOT/webgui/api.php" 2>/dev/null +} + +fail=0 +expect() { + local name=$1 want=$2 got=$3 + if [[ "$got" != *"$want"* ]]; then + echo "FAIL: $name: expected '$want', got: $got" + fail=1 + fi +} + +expect "GET needs no token" "Daemon" "$(call REQUEST_METHOD=GET)" +expect "POST without token" "CSRF" "$(call REQUEST_METHOD=POST)" +expect "POST with wrong token" "CSRF" "$(call REQUEST_METHOD=POST HTTP_X_CSRF_TOKEN=wrong)" +expect "PUT without token" "CSRF" "$(call REQUEST_METHOD=PUT)" +expect "DELETE without token" "CSRF" "$(call REQUEST_METHOD=DELETE)" +expect "lowercase post is checked" "CSRF" "$(call REQUEST_METHOD=post)" +expect "POST with valid token" "Daemon" "$(call REQUEST_METHOD=POST HTTP_X_CSRF_TOKEN=secret-token)" +expect "PUT with valid token" "Daemon" "$(call REQUEST_METHOD=PUT HTTP_X_CSRF_TOKEN=secret-token)" +expect "unknown method" "method not allowed" "$(call REQUEST_METHOD=PATCH HTTP_X_CSRF_TOKEN=secret-token)" +expect "missing var.ini fails closed" "CSRF" "$(VAR_INI=$WORK/missing.ini call REQUEST_METHOD=POST HTTP_X_CSRF_TOKEN=)" + +if [[ $fail -ne 0 ]]; then + exit 1 +fi +echo "api_csrf_test: ok" diff --git a/webgui/URBM.page b/webgui/URBM.page index d70d9ce..7823fe5 100644 --- a/webgui/URBM.page +++ b/webgui/URBM.page @@ -8,7 +8,7 @@ Tag="URBM Unraid Restic Backup Manager backup snapshots restore" --- diff --git a/webgui/api.php b/webgui/api.php index 6969aba..d04acec 100644 --- a/webgui/api.php +++ b/webgui/api.php @@ -21,11 +21,34 @@ function urbm_json_error(int $status, string $message): void exit; } +// The Unraid session CSRF token. Unraid's own check only covers form posts +// ($_POST), not the JSON bodies this bridge forwards, so it is verified here. +function urbm_csrf_token(): string +{ + $file = getenv('URBM_VAR_INI') ?: '/var/local/emhttp/var.ini'; + $var = @parse_ini_file($file); + $token = is_array($var) ? ($var['csrf_token'] ?? '') : ''; + return is_string($token) ? $token : ''; +} + $socket = '/run/urbm/urbm.sock'; -$method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; +$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')); $path = $_GET['path'] ?? '/v1/health'; $isSnapshotFileRequest = preg_match('#/snapshots/[^/]+/files(?:\?|$)#', $path) === 1; +if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE'], true)) { + urbm_json_error(405, 'method not allowed'); +} + +if ($method !== 'GET') { + $expected = urbm_csrf_token(); + $provided = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; + if ($expected === '' || !is_string($provided) || !hash_equals($expected, $provided)) { + urbm_bridge_log('warn', 'rejected request without valid CSRF token', ['path' => $path, 'method' => $method]); + urbm_json_error(403, 'Ungültiges oder fehlendes CSRF-Token. Bitte die Seite neu laden.'); + } +} + if (!preg_match('#^/v1/[A-Za-z0-9_./?=&%:-]*$#', $path) || str_contains($path, '..')) { urbm_bridge_log('warn', 'invalid API path', ['path' => $path]); urbm_json_error(400, 'invalid API path'); diff --git a/webgui/assets/urbm.js b/webgui/assets/urbm.js index c9983aa..5b783f0 100644 --- a/webgui/assets/urbm.js +++ b/webgui/assets/urbm.js @@ -23,6 +23,7 @@ compression: 'Restic-Kompression. auto ist empfohlen; off spart CPU; max spart eher Speicher, benötigt aber mehr CPU-Zeit.', cpuCores: 'Begrenzt diesen Backup-Lauf über GOMAXPROCS auf die angegebene Anzahl CPU-Kerne. 0 verwendet wie bisher alle verfügbaren Kerne.', readConcurrency: 'Anzahl der Dateien, die Restic gleichzeitig liest. Höhere Werte können SSD- und NVMe-Quellen mit vielen kleinen Dateien beschleunigen, bei HDDs aber langsamer sein. 0 verwendet den Restic-Standard.', + lowPriority: 'Startet Restic bzw. Rsync mit niedrigster CPU-Priorität (nice 19) und IO-Klasse idle (ionice). Der Job bekommt dann nur Rechenzeit und Plattenzugriffe, die andere Dienste wie Home Assistant oder Docker-Container gerade nicht brauchen. Der Lauf kann dadurch länger dauern.', sources: 'Optionale manuelle Quellen, eine pro Zeile. Ordner wählst du einfacher über die Checkbox-Liste. Docker- oder VM-ID mit @ voranstellen, z. B. @HomeAssistant.', excludes: 'Muster für Dateien, die nicht gesichert werden. Ein Muster pro Zeile. Beispiele: *.tmp, cache/** oder /mnt/user/appdata/plex/Cache/**.', shutdownSecs: 'Maximale Wartezeit für einen kontrollierten Stopp. Beispiel: 120 wartet bis zu zwei Minuten; danach wird das Backup ohne Force-Stop abgebrochen.', @@ -539,7 +540,7 @@ const options = state.config.repositories.map(r => ``).join(''); content.innerHTML = `
Backup-Plan

Backup-Job ${job.id ? 'bearbeiten' : 'erstellen'}

Quelle, Ziel und Zeitplan in einem Sicherungsplan zusammenfassen.

Allgemein
-
+
Restic-Einstellungen
${scheduleFields(job)}
@@ -952,7 +953,7 @@ if(type==='rsync'&&!rsync.target) throw new Error('Wähle einen Zielordner für die Rsync-Kopie.'); if(type==='rsync'&&rsync.delete&&!await askConfirm({title:'Rsync-Löschungen aktivieren?',message:'Dateien am Ziel, die in der Quelle nicht mehr vorhanden sind, dürfen beim Lauf gelöscht werden.',accept:'Löschungen erlauben'})) return; if(type==='rsync'&&rsync.skipSpaceCheck&&!await askConfirm({title:'Kapazitätsprüfung abschalten?',message:'Der Rsync-Lauf kann das Ziel vollständig füllen und anschließend mit einem Schreibfehler abbrechen.',accept:'Prüfung abschalten'})) return; - const job={schemaVersion:1,id:f.get('id')||id('job'),name:f.get('name'),type,enabled:f.get('enabled')==='on',repositoryId:type==='rsync'?'':f.get('repositoryId'),sources,schedule:{cron:scheduleCron(f),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},consistency:{mode:f.get('consistency')||'live'},compression:type==='rsync'?'':f.get('compression'),cpuCores:type==='rsync'?0:Number(f.get('cpuCores')||0),readConcurrency:type==='rsync'?0:Number(f.get('readConcurrency')||0),excludes:lines(f.get('excludes')),tags:existing?.tags||[],flashImage:type==='flash'&&f.get('flashImage')==='on',retention:type==='rsync'?{}:retention,rsync,notifyOn:existing?.notifyOn||['success','warning','failed'],shutdownTimeoutSeconds:Number(f.get('shutdownSecs')||120)}; + const job={schemaVersion:1,id:f.get('id')||id('job'),name:f.get('name'),type,enabled:f.get('enabled')==='on',repositoryId:type==='rsync'?'':f.get('repositoryId'),sources,schedule:{cron:scheduleCron(f),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},consistency:{mode:f.get('consistency')||'live'},compression:type==='rsync'?'':f.get('compression'),cpuCores:type==='rsync'?0:Number(f.get('cpuCores')||0),readConcurrency:type==='rsync'?0:Number(f.get('readConcurrency')||0),lowPriority:f.get('lowPriority')==='on',excludes:lines(f.get('excludes')),tags:existing?.tags||[],flashImage:type==='flash'&&f.get('flashImage')==='on',retention:type==='rsync'?{}:retention,rsync,notifyOn:existing?.notifyOn||['success','warning','failed'],shutdownTimeoutSeconds:Number(f.get('shutdownSecs')||120)}; state.config.jobs=state.config.jobs.filter(j=>j.id!==job.id).concat(job); await saveConfig(); render(); } if (kind === 'submit-repo') {