Ignore shfs inodes, add low-priority jobs, fix retention grouping and CSRF; release 2026.11.22.r001

- Pass --ignore-inode for sources below /mnt/user and /mnt/user0. shfs hands
  out new inode numbers after every reboot, which made Restic re-read all
  data on the first run after a restart.
- Add a per-job lowPriority option that starts Restic and Rsync through
  ionice (idle) and nice 19 via the new internal/procprio package.
- Run restic forget with --group-by host,tags. Grouping by paths split a job
  into a new group whenever its sources changed, and keep-within never
  expired the old group's snapshots.
- Verify the Unraid CSRF token in webgui/api.php for POST, PUT and DELETE
  and reject other methods; Unraid's own check only covers form posts.
- Set $urbmVersion in URBM.page during the package build and fail the build
  if it does not match, so the page always loads the packaged JS asset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mikei386andClaude Opus 5.5 committed 2026-11-22 09:23:01 +01:00
1 parent a7dbd77492
commit ac055497b7
16 files changed
+317 -28

No files matched your search

Binary file not shown.
+1
View File
@@ -0,0 +1 @@
80142b9de7ad7aa6ba980ec73e394198f2c8b6609430e7d2bfbb4ec65b3fca3c urbm-2026.11.22.r001-x86_64-1.txz
+8 -2
View File
@@ -2,13 +2,19 @@
<!DOCTYPE PLUGIN [
<!ENTITY name "urbm">
<!ENTITY author "Michael Roll">
<!ENTITY version "2026.10.15.r001">
<!ENTITY version "2026.11.22.r001">
<!ENTITY pluginURL "https://git.casaderoll.de/michael/URBM/raw/branch/main/dist/urbm.plg">
<!ENTITY packageURL "https://git.casaderoll.de/michael/URBM/raw/branch/main/dist/urbm-&version;-x86_64-1.txz">
<!ENTITY packageSHA256 "e4a9906820384c0bff708c02d81a8915b7d5e034984052e42bf7c09761a47a31">
<!ENTITY packageSHA256 "80142b9de7ad7aa6ba980ec73e394198f2c8b6609430e7d2bfbb4ec65b3fca3c">
]>
<PLUGIN name="&name;" author="&author;" version="&version;" pluginURL="&pluginURL;" min="7.0.0" support="https://git.casaderoll.de/michael/URBM/issues" icon="urbm.png">
<CHANGES>
### 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.
+1
View File
@@ -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"`
+35
View File
@@ -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
}
+49
View File
@@ -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)
}
}
+52 -17
View File
@@ -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 {
+82
View File
@@ -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)
}
}
}
+5 -2
View File
@@ -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 {
+2 -1
View File
@@ -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/"
+7 -1
View File
@@ -2,13 +2,19 @@
<!DOCTYPE PLUGIN [
<!ENTITY name "urbm">
<!ENTITY author "Michael Roll">
<!ENTITY version "2026.10.15.r001">
<!ENTITY version "2026.11.22.r001">
<!ENTITY pluginURL "https://git.casaderoll.de/michael/URBM/raw/branch/main/dist/urbm.plg">
<!ENTITY packageURL "https://git.casaderoll.de/michael/URBM/raw/branch/main/dist/urbm-&version;-x86_64-1.txz">
<!ENTITY packageSHA256 "REPLACE_DURING_RELEASE">
]>
<PLUGIN name="&name;" author="&author;" version="&version;" pluginURL="&pluginURL;" min="7.0.0" support="https://git.casaderoll.de/michael/URBM/issues" icon="urbm.png">
<CHANGES>
### 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.
+2 -1
View File
@@ -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
+45
View File
@@ -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"
+1 -1
View File
@@ -8,7 +8,7 @@ Tag="URBM Unraid Restic Backup Manager backup snapshots restore"
---
<?php
$pluginRoot = '/plugins/urbm';
$urbmVersion = '2026.10.15.r001';
$urbmVersion = '2026.11.22.r001';
$urbmAssetVersion = preg_replace('/[^A-Za-z0-9]/', '', $urbmVersion);
?>
<link rel="stylesheet" href="<?= $pluginRoot ?>/assets/urbm.css?v=<?= $urbmAssetVersion ?>">
+24 -1
View File
@@ -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');
+3 -2
View File
@@ -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 => `<option value="${esc(r.id)}" ${r.id===job.repositoryId?'selected':''}>${esc(r.name)}</option>`).join('');
content.innerHTML = `<section class="bu-card bu-form-card"><div class="bu-form-heading"><span class="bu-eyebrow">Backup-Plan</span><h2>Backup-Job ${job.id ? 'bearbeiten' : 'erstellen'}</h2><p class="bu-muted">Quelle, Ziel und Zeitplan in einem Sicherungsplan zusammenfassen.</p></div><form id="bu-job-form" class="bu-form">
<input type="hidden" name="id" value="${esc(job.id || '')}"><fieldset class="wide bu-fieldset"><legend>Allgemein</legend><div class="bu-form-grid"><label>Name<input name="name" required value="${esc(job.name || '')}"></label>
<label>Typ<select name="type">${['share','appdata','docker','vm','flash','rsync'].map(v=>`<option value="${v}" ${v===job.type?'selected':''}>${esc(typeLabels[v])}</option>`).join('')}</select></label><label class="wide bu-inline-check"><input name="enabled" type="checkbox" ${job.enabled !== false?'checked':''}><span>Automatische Ausführung aktiviert</span></label></div></fieldset>
<label>Typ<select name="type">${['share','appdata','docker','vm','flash','rsync'].map(v=>`<option value="${v}" ${v===job.type?'selected':''}>${esc(typeLabels[v])}</option>`).join('')}</select></label><label class="wide bu-inline-check"><input name="enabled" type="checkbox" ${job.enabled !== false?'checked':''}><span>Automatische Ausführung aktiviert</span></label><label class="wide bu-inline-check"><input name="lowPriority" type="checkbox" ${job.lowPriority===true?'checked':''}><span>Mit niedriger Priorität ausführen (nice/ionice)</span></label></div></fieldset>
<fieldset id="bu-restic-job-settings" class="wide bu-fieldset"><legend>Restic-Einstellungen</legend><div class="bu-form-grid"><label>Repository<select name="repositoryId">${options}</select></label><label>Kompression<select name="compression"><option value="auto" ${(job.compression||'auto')==='auto'?'selected':''}>Automatisch</option><option value="off" ${job.compression==='off'?'selected':''}>Aus</option><option value="max" ${job.compression==='max'?'selected':''}>Maximal</option></select></label><label>CPU-Kerne für dieses Backup<input name="cpuCores" type="number" min="0" max="256" value="${Number(job.cpuCores||0)}"><span class="bu-muted">0 = alle verfügbaren Kerne</span></label><label>Gleichzeitig gelesene Dateien<input name="readConcurrency" type="number" min="0" max="64" value="${Number(job.readConcurrency||0)}"><span class="bu-muted">0 = Restic-Standard</span></label></div></fieldset>
${scheduleFields(job)}
<div id="bu-job-specific" class="wide"></div>
@@ -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') {