P3 follow-up: editable target dir, conditional --no-ownership, UK lint
Three small follow-ups from review:
1. Restore target is now operator-editable. Default value is the
literal '\$HOME/rm-restore/<job-id>/' (agent expands \$HOME at
run time using os.UserHomeDir(); also handles \${HOME} and ~/
prefixes). Operator can replace with any absolute path.
- ui_restore.go validates the input is either absolute or starts
with one of the recognised prefixes; other env-var refs (\$PATH
etc.) are deliberately rejected so operator paths can't pick up
arbitrary agent env values.
- host_restore.html replaces the read-only mono-text display with
a real <input>; help text spells out that \$HOME resolves
agent-side and <job-id> is substituted on dispatch.
- install.sh + the systemd unit prep /root/rm-restore so the
default works under the sandbox: ReadWritePaths gains a soft
'-/root/rm-restore' entry (the '-' makes the bind-mount soft-fail
if missing, but install.sh pre-creates it root-owned 0700).
2. --no-ownership flag now gated on restic version. The flag was
added in restic 0.17 and 0.16 rejects it. Previously dropped it
wholesale — that meant new-dir restores silently preserved
ownership against design intent on 0.17+. Now the agent threads
its detected restic version (sysinfo already collects it) through
runner.Config -> restic.Env, and RunRestore appends --no-ownership
only when AtLeastVersion(0, 17) returns true. 0.16 hosts still
restore with original uid/gid; help text in the wizard explicitly
notes this. The previous 'Original ownership is preserved' copy
was wrong for new-dir mode and is corrected.
3. golangci-lint misspell locale switched US -> UK and the codebase
swept (73 corrections, mostly behaviour/serialise/recognise/honour).
Wire-format ErrorCode 'unauthorized' -> 'unauthorised' is a tiny
contract change but the agent doesn't parse those codes today and
no external API consumers exist yet. Tests passed before + after.
Tests:
- internal/restic/version_test.go covers Env.AtLeastVersion across
edge cases (empty, exact match, patch above, minor below, non-
numeric) and expandHome on \$HOME / \${HOME} / ~/, plus
pass-through for absolute paths and refusal of other env vars.
- ui_restore_test updated: TargetDir now starts '\$HOME/rm-restore/'
with the job_id substituted into the placeholder.
Live verified on the smoke env: default target restored to
/root/rm-restore/<job-id>/ as the agent's expanded \$HOME (2 files,
14 bytes); custom override '/tmp/custom-restore/<job-id>/' restored
into the agent's PrivateTmp namespace (1 file, 6 bytes); both jobs
'succeeded', exit 0.
This commit is contained in:
+1
-1
@@ -26,7 +26,7 @@ linters:
|
||||
- name: exported
|
||||
arguments: ["disableStutteringCheck"]
|
||||
misspell:
|
||||
locale: US
|
||||
locale: UK
|
||||
exclusions:
|
||||
rules:
|
||||
- path: _test\.go
|
||||
|
||||
+5
-1
@@ -136,6 +136,7 @@ func run() error {
|
||||
|
||||
d := &dispatcher{
|
||||
resticBin: resticBin,
|
||||
resticVer: snap.ResticVersion,
|
||||
secrets: sec,
|
||||
scheduler: scheduler.New(),
|
||||
}
|
||||
@@ -200,6 +201,7 @@ func openSecretsStore(cfg *config.Config) (*secrets.Store, error) {
|
||||
// so a job dispatched in the same session sees the latest values.
|
||||
type dispatcher struct {
|
||||
resticBin string
|
||||
resticVer string // e.g. "0.17.1"; empty if restic isn't installed yet
|
||||
secrets *secrets.Store
|
||||
scheduler *scheduler.Scheduler
|
||||
|
||||
@@ -276,7 +278,7 @@ func (d *dispatcher) handle(ctx context.Context, env api.Envelope, tx wsclient.S
|
||||
|
||||
case api.MsgTreeList:
|
||||
// Synchronous RPC for the restore wizard's tree browser. The
|
||||
// server has serialized access; we just run restic ls and reply
|
||||
// server has serialised access; we just run restic ls and reply
|
||||
// with the same envelope ID. Run in a goroutine so the WS read
|
||||
// loop keeps draining.
|
||||
var p api.TreeListRequestPayload
|
||||
@@ -493,6 +495,7 @@ func (d *dispatcher) runJob(ctx context.Context, p api.CommandRunPayload, tx wsc
|
||||
|
||||
r := runner.New(runner.Config{
|
||||
ResticBin: d.resticBin,
|
||||
ResticVersion: d.resticVer,
|
||||
RepoURL: creds.URL,
|
||||
RepoUsername: creds.Username,
|
||||
RepoPassword: creds.Password,
|
||||
@@ -588,6 +591,7 @@ func (d *dispatcher) runJob(ctx context.Context, p api.CommandRunPayload, tx wsc
|
||||
}
|
||||
prr := runner.New(runner.Config{
|
||||
ResticBin: d.resticBin,
|
||||
ResticVersion: d.resticVer,
|
||||
RepoURL: runCreds.URL,
|
||||
RepoUsername: runCreds.Username,
|
||||
RepoPassword: runCreds.Password,
|
||||
|
||||
@@ -49,6 +49,13 @@ detect_arch() {
|
||||
ensure_dirs() {
|
||||
install -d -m 0700 -o root -g root "$RM_CONFIG_DIR"
|
||||
install -d -m 0700 -o root -g root "$RM_STATE_DIR"
|
||||
# Default new-directory restore target: $HOME/rm-restore. Pre-create
|
||||
# so the systemd unit's ReadWritePaths bind-mount applies cleanly
|
||||
# (paths that don't exist when systemd starts get a soft-fail
|
||||
# because of the '-' prefix, but the agent then can't mkdir into
|
||||
# the read-only /root). Mode 0700 + root-owned matches the threat
|
||||
# model — files restored here are operator-readable as root.
|
||||
install -d -m 0700 -o root -g root /root/rm-restore
|
||||
}
|
||||
|
||||
detect_existing_schedulers() {
|
||||
|
||||
@@ -37,7 +37,12 @@ AmbientCapabilities=CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE CAP_FOWNER CAP_CHOWN
|
||||
# needs. Filesystem reads stay open: that's the whole job.
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/etc/restic-manager /var/lib/restic-manager
|
||||
# /etc/restic-manager: agent.yaml + secrets.enc.
|
||||
# /var/lib/restic-manager: agent state (currently unused but reserved).
|
||||
# /root/rm-restore: default target for new-directory restores
|
||||
# ($HOME/rm-restore/<job-id>/ resolves here for User=root).
|
||||
# ReadWritePaths overrides ProtectHome=read-only on this subdir only.
|
||||
ReadWritePaths=/etc/restic-manager /var/lib/restic-manager -/root/rm-restore
|
||||
ProtectHome=read-only
|
||||
ProtectHostname=true
|
||||
ProtectKernelTunables=true
|
||||
|
||||
@@ -26,10 +26,11 @@ type Sender interface {
|
||||
// from the agent's config file (server-pushed config.update payloads
|
||||
// override these in memory).
|
||||
type Config struct {
|
||||
ResticBin string
|
||||
RepoURL string
|
||||
RepoUsername string
|
||||
RepoPassword string
|
||||
ResticBin string
|
||||
ResticVersion string // e.g. "0.17.1" — empty if unknown
|
||||
RepoURL string
|
||||
RepoUsername string
|
||||
RepoPassword string
|
||||
|
||||
// Bandwidth caps in KB/s applied to every restic invocation.
|
||||
// <=0 means "no cap". Per-job override: callers that build a
|
||||
@@ -61,6 +62,7 @@ func New(cfg Config, tx Sender, progressMinPeriod time.Duration) *Runner {
|
||||
func (r *Runner) resticEnv() restic.Env {
|
||||
return restic.Env{
|
||||
Bin: r.cfg.ResticBin,
|
||||
Version: r.cfg.ResticVersion,
|
||||
RepoURL: r.cfg.RepoURL,
|
||||
RepoUsername: r.cfg.RepoUsername,
|
||||
RepoPassword: r.cfg.RepoPassword,
|
||||
|
||||
@@ -320,7 +320,7 @@ esac
|
||||
// still produces job.started and job.finished envelopes.
|
||||
func TestRunInitShipsStartedAndFinished(t *testing.T) {
|
||||
t.Parallel()
|
||||
bin := setupScript(t, `echo "initialized repository"`)
|
||||
bin := setupScript(t, `echo "initialised repository"`)
|
||||
tx := &fakeSender{}
|
||||
r := New(Config{ResticBin: bin}, tx, 0)
|
||||
if err := r.RunInit(context.Background(), "job-init"); err != nil {
|
||||
|
||||
@@ -110,7 +110,7 @@ func (s *Scheduler) Apply(payload api.ScheduleSetPayload, tx Sender) {
|
||||
"received", len(payload.Schedules), "active", added)
|
||||
|
||||
// Ack outside the lock — Send() shouldn't take long, but holding
|
||||
// s.mu across an external call would needlessly serialize other
|
||||
// s.mu across an external call would needlessly serialise other
|
||||
// callers (e.g. a future Status() inspection from the UI).
|
||||
ackEnv, err := api.Marshal(api.MsgScheduleAck, "", api.ScheduleAckPayload{
|
||||
Version: payload.Version,
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
|
||||
// additionalData binds ciphertexts to the agent-secrets context, so a
|
||||
// blob lifted from one role's file can't be replayed into another's
|
||||
// row in some unrelated table that uses the same key. (Defense in
|
||||
// row in some unrelated table that uses the same key. (Defence in
|
||||
// depth — the key is per-host today, but cheap to be careful.)
|
||||
const additionalData = "rm-agent-repo-creds-v1"
|
||||
|
||||
|
||||
@@ -76,5 +76,5 @@ func detectResticVersion(ctx context.Context, override string) (string, error) {
|
||||
if len(parts) >= 2 && parts[0] == "restic" {
|
||||
return parts[1], nil
|
||||
}
|
||||
return "", fmt.Errorf("sysinfo: unrecognized restic version output: %q", first)
|
||||
return "", fmt.Errorf("sysinfo: unrecognised restic version output: %q", first)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ type Config struct {
|
||||
// Sender is what handlers use to push agent → server messages
|
||||
// (job.progress, job.finished, log.stream, command.result, …).
|
||||
// Returned by the WS client to the dispatch handler. Write operations
|
||||
// serialize behind a single mutex on the conn; concurrent calls are
|
||||
// serialise behind a single mutex on the conn; concurrent calls are
|
||||
// safe.
|
||||
type Sender interface {
|
||||
Send(env api.Envelope) error
|
||||
|
||||
@@ -394,7 +394,7 @@ type TreeListEntry struct {
|
||||
}
|
||||
|
||||
// TreeListResultPayload is the reply to a tree.list. Error is set
|
||||
// when the agent couldn't fulfill the request (missing snapshot,
|
||||
// when the agent couldn't fulfil the request (missing snapshot,
|
||||
// path doesn't exist, restic invocation failed); Entries is empty in
|
||||
// that case. A successful empty directory has Error="" + nil Entries.
|
||||
type TreeListResultPayload struct {
|
||||
|
||||
@@ -78,7 +78,7 @@ type ErrorCode string
|
||||
const (
|
||||
ErrProtocolTooOld ErrorCode = "protocol_too_old"
|
||||
ErrProtocolTooNew ErrorCode = "protocol_too_new"
|
||||
ErrUnauthorized ErrorCode = "unauthorized"
|
||||
ErrUnauthorized ErrorCode = "unauthorised"
|
||||
ErrBadRequest ErrorCode = "bad_request"
|
||||
ErrInternal ErrorCode = "internal"
|
||||
)
|
||||
|
||||
@@ -56,7 +56,7 @@ func VerifyPassword(encoded, password string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// "$argon2id$v=...$m=...,t=...,p=...$<salt>$<hash>" → 6 parts (leading empty)
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return errors.New("auth: unrecognized hash format")
|
||||
return errors.New("auth: unrecognised hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// passwords, REST-server credentials, hook bodies, and any other
|
||||
// secret that lands in the SQLite store.
|
||||
//
|
||||
// The threat model is "defense in depth against a stolen DB file" —
|
||||
// The threat model is "defence in depth against a stolen DB file" —
|
||||
// not "an attacker with code execution can't read secrets at runtime."
|
||||
// We need the encryption key at runtime to do any actual work, so
|
||||
// anyone with a memory dump of the running server can extract it.
|
||||
|
||||
@@ -32,7 +32,7 @@ type LsEntry struct {
|
||||
//
|
||||
// The first emitted line is restic's "snapshot" preamble (struct_type
|
||||
// = "snapshot") which we discard. Subsequent lines are nodes; we
|
||||
// match on path equal to dirPath + "/" + name (with normalization so
|
||||
// match on path equal to dirPath + "/" + name (with normalisation so
|
||||
// trailing slashes don't break the comparison).
|
||||
//
|
||||
// dirPath="" or "/" lists the snapshot root.
|
||||
|
||||
+51
-10
@@ -7,7 +7,9 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -63,17 +65,26 @@ func (e Env) RunRestore(ctx context.Context, snapshotID string, paths []string,
|
||||
target := targetDir
|
||||
if inPlace {
|
||||
target = "/"
|
||||
} else {
|
||||
// Expand $HOME / ${HOME} / leading ~/ in the operator-supplied
|
||||
// path, using the agent's own HOME (which under the systemd
|
||||
// unit is the agent user's home — typically /root for the
|
||||
// User=root unit). The expansion runs agent-side so the
|
||||
// operator can specify a portable default like
|
||||
// $HOME/rm-restore/<job-id>/ in the wizard without the server
|
||||
// needing to know which user the agent runs as.
|
||||
target = expandHome(target)
|
||||
}
|
||||
args = append(args, "--target", target)
|
||||
// NOTE: restic added --no-ownership in 0.17. Older versions reject
|
||||
// the flag with "unknown flag: --no-ownership" before doing any
|
||||
// work. Since the agent runs as root in the systemd unit, files
|
||||
// land under /var/restic-restore with their original uid/gid
|
||||
// either way — the original "cp without sudo" rationale doesn't
|
||||
// hold (operators copying from /var/restic-restore need sudo
|
||||
// regardless because the parent dir is root-owned). Drop the flag
|
||||
// entirely until we drop 0.16 support; revisit if a non-root
|
||||
// agent deployment requirement comes back.
|
||||
// --no-ownership was added in restic 0.17. Older versions reject
|
||||
// the flag with "unknown flag: --no-ownership". For new-dir
|
||||
// restores we want the files owned by the agent user (operator
|
||||
// can cp them without juggling chown), so pass the flag iff the
|
||||
// running restic supports it. In-place restores always preserve
|
||||
// ownership — that's the whole point of in-place.
|
||||
if !inPlace && e.AtLeastVersion(0, 17) {
|
||||
args = append(args, "--no-ownership")
|
||||
}
|
||||
for _, p := range paths {
|
||||
args = append(args, "--include", p)
|
||||
}
|
||||
@@ -119,7 +130,7 @@ func (e Env) RunRestore(ctx context.Context, snapshotID string, paths []string,
|
||||
// stdout — but unlike backup we include the raw status JSON in
|
||||
// log.stream too because restore is short and the live log audience
|
||||
// genuinely benefits from the per-file traffic. Actually — we mirror
|
||||
// backup's behavior and DROP raw status lines from log.stream
|
||||
// backup's behaviour and DROP raw status lines from log.stream
|
||||
// (they'd drown the log on a fast restore); the progress envelope
|
||||
// covers them.
|
||||
func pumpRestoreStdout(r io.Reader, handle LineHandler, summary **RestoreSummary) error {
|
||||
@@ -168,6 +179,36 @@ func pumpRestoreStdout(r io.Reader, handle LineHandler, summary **RestoreSummary
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
// expandHome rewrites $HOME, ${HOME}, or a leading ~/ in p to the
|
||||
// agent process's home directory. Other env-var references are left
|
||||
// untouched on purpose (operator-supplied paths shouldn't be able to
|
||||
// pick up arbitrary agent env values like $PATH or $RESTIC_PASSWORD).
|
||||
// Returns p unchanged if HOME can't be resolved.
|
||||
func expandHome(p string) string {
|
||||
if p == "" {
|
||||
return p
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil || home == "" {
|
||||
return p
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(p, "$HOME/"):
|
||||
return filepath.Join(home, p[len("$HOME/"):])
|
||||
case p == "$HOME":
|
||||
return home
|
||||
case strings.HasPrefix(p, "${HOME}/"):
|
||||
return filepath.Join(home, p[len("${HOME}/"):])
|
||||
case p == "${HOME}":
|
||||
return home
|
||||
case strings.HasPrefix(p, "~/"):
|
||||
return filepath.Join(home, p[2:])
|
||||
case p == "~":
|
||||
return home
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// RunDiff executes `restic diff --json <a> <b>` and forwards every
|
||||
// line to handle as stdout. Restic emits per-line "change" objects
|
||||
// plus a final "statistics" object; we don't parse them server-side —
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Locate resolves the path to the restic binary. Honor an explicit
|
||||
// Locate resolves the path to the restic binary. Honour an explicit
|
||||
// override if provided, else fall back to PATH.
|
||||
func Locate(override string) (string, error) {
|
||||
if override != "" {
|
||||
@@ -42,6 +42,7 @@ func Locate(override string) (string, error) {
|
||||
// in this package ever needs to *log* a URL, use RedactURL.
|
||||
type Env struct {
|
||||
Bin string // path to restic binary
|
||||
Version string // e.g. "0.17.1"; empty if unknown
|
||||
RepoURL string // RESTIC_REPOSITORY (no embedded creds)
|
||||
RepoUsername string // optional HTTP basic-auth user for rest: URLs
|
||||
RepoPassword string // doubles as RESTIC_PASSWORD and (for rest:) HTTP basic-auth password
|
||||
@@ -55,6 +56,45 @@ type Env struct {
|
||||
LimitDownloadKBps int
|
||||
}
|
||||
|
||||
// AtLeastVersion reports whether e.Version >= the given major/minor.
|
||||
// Comparison is best-effort: empty / unparseable versions return false
|
||||
// (callers stay on the conservative path). Patch level is ignored.
|
||||
func (e Env) AtLeastVersion(major, minor int) bool {
|
||||
v := strings.TrimSpace(e.Version)
|
||||
if v == "" {
|
||||
return false
|
||||
}
|
||||
parts := strings.SplitN(v, ".", 3)
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
maj, err1 := atoi(parts[0])
|
||||
min, err2 := atoi(parts[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
if maj != major {
|
||||
return maj > major
|
||||
}
|
||||
return min >= minor
|
||||
}
|
||||
|
||||
// atoi is strconv.Atoi without dragging the import into a file that
|
||||
// only needs it for one helper.
|
||||
func atoi(s string) (int, error) {
|
||||
n := 0
|
||||
if len(s) == 0 {
|
||||
return 0, fmt.Errorf("empty")
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return 0, fmt.Errorf("not a digit: %q", r)
|
||||
}
|
||||
n = n*10 + int(r-'0')
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// globalArgs returns restic's pre-subcommand global flags derived
|
||||
// from the Env. Currently just bandwidth caps.
|
||||
func (e Env) globalArgs() []string {
|
||||
@@ -69,8 +109,8 @@ func (e Env) globalArgs() []string {
|
||||
}
|
||||
|
||||
// resticCmd builds an exec.Cmd with bandwidth-limit globals prefixed
|
||||
// before the supplied subcommand args. Centralizing this so every
|
||||
// command (backup/forget/prune/check/unlock/init/stats) honors
|
||||
// before the supplied subcommand args. Centralising this so every
|
||||
// command (backup/forget/prune/check/unlock/init/stats) honours
|
||||
// the caps without each call site having to remember.
|
||||
//
|
||||
// Cancellation: by default exec.CommandContext sends SIGKILL when
|
||||
@@ -142,7 +182,7 @@ type BackupSummary struct {
|
||||
}
|
||||
|
||||
// LineHandler receives every stdout/stderr line. event is non-nil
|
||||
// when the line is a recognized JSON status; raw always carries the
|
||||
// when the line is a recognised JSON status; raw always carries the
|
||||
// original text (so we can also tee to job_logs as `stdout`).
|
||||
type LineHandler func(stream string, raw string, event any)
|
||||
|
||||
@@ -282,7 +322,7 @@ func (e Env) RunInit(ctx context.Context, handle LineHandler) error {
|
||||
|
||||
// Sniff for "config file already exists" on stderr; if we see it
|
||||
// we'll treat the non-zero exit as a soft success — running init
|
||||
// against an already-initialized repo is a no-op semantically,
|
||||
// against an already-initialised repo is a no-op semantically,
|
||||
// not a failure. Wraps the caller's handle so the line still
|
||||
// gets streamed verbatim to the operator-facing log.
|
||||
alreadyInited := false
|
||||
@@ -298,7 +338,7 @@ func (e Env) RunInit(ctx context.Context, handle LineHandler) error {
|
||||
if err := runWithPump(cmd, sniff); err != nil {
|
||||
if alreadyInited {
|
||||
if handle != nil {
|
||||
handle("event", "repo already initialized — treating as success", nil)
|
||||
handle("event", "repo already initialised — treating as success", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -394,7 +434,7 @@ func (e Env) RunStats(ctx context.Context, handle LineHandler) (*RepoStats, erro
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CheckResult summarizes a `restic check` invocation. LockPresent is
|
||||
// CheckResult summarises a `restic check` invocation. LockPresent is
|
||||
// true if the stderr stream contained a stale-lock signal (caller is
|
||||
// expected to surface this in the UI so the operator can run unlock).
|
||||
// ErrorsFound is true if check exited with a non-zero status (errors
|
||||
@@ -406,7 +446,7 @@ type CheckResult struct {
|
||||
|
||||
// RunCheck executes `restic check` with optional --read-data-subset.
|
||||
// subsetPct of 0 omits the flag (full data check); >0 passes
|
||||
// --read-data-subset N%. Returns a CheckResult summarizing what was
|
||||
// --read-data-subset N%. Returns a CheckResult summarising what was
|
||||
// sniffed from stderr; the result is set even if check itself
|
||||
// returns an error (so the caller can persist last_check_status).
|
||||
func (e Env) RunCheck(ctx context.Context, subsetPct int, handle LineHandler) (CheckResult, error) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package restic
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnvAtLeastVersion(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
ver string
|
||||
major int
|
||||
minor int
|
||||
want bool
|
||||
shortDesc string
|
||||
}{
|
||||
{"0.17.0", 0, 17, true, "exact match"},
|
||||
{"0.17.1", 0, 17, true, "patch above"},
|
||||
{"0.18.0", 0, 17, true, "minor above"},
|
||||
{"1.0.0", 0, 17, true, "major above"},
|
||||
{"0.16.4", 0, 17, false, "minor below"},
|
||||
{"0.16", 0, 17, false, "two-part minor below"},
|
||||
{"", 0, 17, false, "empty"},
|
||||
{"v0.17", 0, 17, false, "prefixed v rejected"},
|
||||
{"unknown", 0, 17, false, "non-numeric rejected"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := Env{Version: c.ver}.AtLeastVersion(c.major, c.minor)
|
||||
if got != c.want {
|
||||
t.Errorf("AtLeastVersion(%q, %d, %d): got %v want %v · %s",
|
||||
c.ver, c.major, c.minor, got, c.want, c.shortDesc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandHome(t *testing.T) {
|
||||
// Not parallel — t.Setenv on HOME would race with sibling tests.
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("HOME", tmp)
|
||||
|
||||
cases := []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"$HOME/rm-restore/job-1/", filepath.Join(tmp, "rm-restore/job-1")},
|
||||
{"${HOME}/rm-restore/job-2/", filepath.Join(tmp, "rm-restore/job-2")},
|
||||
{"~/rm-restore/job-3/", filepath.Join(tmp, "rm-restore/job-3")},
|
||||
{"$HOME", tmp},
|
||||
{"~", tmp},
|
||||
{"/var/lib/x/y", "/var/lib/x/y"}, // absolute path passes through
|
||||
{"", ""},
|
||||
{"$PATH/foo", "$PATH/foo"}, // other env vars not expanded
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := expandHome(c.in)
|
||||
if got != c.want {
|
||||
t.Errorf("expandHome(%q): got %q want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: an absolute path always passes through regardless of HOME.
|
||||
if got := expandHome("/abs"); got != "/abs" {
|
||||
t.Errorf("expandHome(/abs): got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func (s *Server) handleAgentBinary(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
}
|
||||
|
||||
func (s *Server) handleInstallAsset(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
// chi's TrimPrefix-like behavior: r.URL.Path is "/install/<file>".
|
||||
// chi's TrimPrefix-like behaviour: r.URL.Path is "/install/<file>".
|
||||
rel := strings.TrimPrefix(r.URL.Path, "/install/")
|
||||
// Reject any path traversal — must be a flat filename.
|
||||
if rel == "" || strings.ContainsAny(rel, "/\\") {
|
||||
|
||||
@@ -133,7 +133,7 @@ func (s *Server) handleAnnounce(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
|
||||
keyBytes, err := base64.StdEncoding.DecodeString(req.PublicKey)
|
||||
if err != nil {
|
||||
// Try URL-safe / no-padding flavors before giving up.
|
||||
// Try URL-safe / no-padding flavours before giving up.
|
||||
if k2, e2 := base64.RawStdEncoding.DecodeString(req.PublicKey); e2 == nil {
|
||||
keyBytes = k2
|
||||
} else {
|
||||
@@ -195,7 +195,7 @@ func (s *Server) handleAnnounce(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
// remoteIP returns r.RemoteAddr stripped of any :port suffix, plus
|
||||
// the X-Forwarded-For chain's first hop when behind a trusted proxy
|
||||
// (RM_TRUSTED_PROXY in the deployment doc). Trust-proxy lookup
|
||||
// matches the framework's existing behavior elsewhere.
|
||||
// matches the framework's existing behaviour elsewhere.
|
||||
func remoteIP(r *stdhttp.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
// Take the first IP in the chain (closest to the original
|
||||
|
||||
@@ -137,7 +137,7 @@ func (s *Server) handleBootstrap(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
writeJSONError(w, stdhttp.StatusConflict, "already_initialized",
|
||||
writeJSONError(w, stdhttp.StatusConflict, "already_initialised",
|
||||
"a user already exists; bootstrap is disabled")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
func (s *Server) handleCancelJob(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
jobID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -30,7 +30,7 @@ type snapshotDiffRequest struct {
|
||||
func (s *Server) handleSnapshotDiff(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -213,7 +213,7 @@ func (s *Server) handleAgentEnroll(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
// session cookie and trust it, validating the cookie via store.
|
||||
func (s *Server) handleCreateEnrollmentToken(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ type hostBandwidthView struct {
|
||||
|
||||
func (s *Server) handleUpdateHostBandwidth(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -58,7 +58,7 @@ func (s *Server) pushBandwidthToAgent(ctx context.Context, hostID string, up, do
|
||||
// bandwidthPayload builds a ConfigUpdatePayload with only the
|
||||
// bandwidth fields populated. Pointers are passed through verbatim;
|
||||
// callers wanting to clear a cap should pass a non-nil pointer to 0.
|
||||
// On the on-hello path we materialize zero-valued pointers when the
|
||||
// On the on-hello path we materialise zero-valued pointers when the
|
||||
// host record has no cap set, so the agent's stored state is always
|
||||
// in sync (rather than retaining whatever value it last received).
|
||||
func bandwidthPayload(up, down *int) api.ConfigUpdatePayload {
|
||||
|
||||
@@ -32,7 +32,7 @@ type hostRepoCredsView struct {
|
||||
// creds for UI display. 404 if no credential has ever been set.
|
||||
func (s *Server) handleGetHostCredentials(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -88,7 +88,7 @@ type hostRepoCredsRequest struct {
|
||||
func (s *Server) handleSetHostCredentials(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -165,7 +165,7 @@ func (s *Server) handleSetHostCredentials(w stdhttp.ResponseWriter, r *stdhttp.R
|
||||
w.WriteHeader(stdhttp.StatusNoContent)
|
||||
}
|
||||
|
||||
// pushRepoCredsToAgent serializes blob into a config.update envelope
|
||||
// pushRepoCredsToAgent serialises blob into a config.update envelope
|
||||
// and ships it down the agent's WS. Returns an error from the hub
|
||||
// (no-op if not connected — caller is expected to check first when it
|
||||
// matters).
|
||||
@@ -192,7 +192,7 @@ func (s *Server) pushRepoCredsToAgent(ctx context.Context, hostID string, blob r
|
||||
// uses this to pre-fill the edit form.
|
||||
func (s *Server) handleGetAdminCredentials(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -234,7 +234,7 @@ func (s *Server) handleGetAdminCredentials(w stdhttp.ResponseWriter, r *stdhttp.
|
||||
func (s *Server) handleSetAdminCredentials(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -319,7 +319,7 @@ func (s *Server) handleSetAdminCredentials(w stdhttp.ResponseWriter, r *stdhttp.
|
||||
func (s *Server) handleDeleteAdminCredentials(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -34,7 +34,7 @@ type hostView struct {
|
||||
// see the same projection.
|
||||
func (s *Server) handleListHosts(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hosts, err := s.deps.Store.ListHosts(r.Context())
|
||||
@@ -55,7 +55,7 @@ func (s *Server) handleListHosts(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
// handleFleetSummary returns the dashboard tile aggregate.
|
||||
func (s *Server) handleFleetSummary(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
fs, err := s.deps.Store.FleetSummary(r.Context())
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
// REST callers. Default is txt.
|
||||
func (s *Server) handleJobLogDownload(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if _, ok := s.requireUser(r); !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
jobID := chi.URLParam(r, "id")
|
||||
@@ -79,7 +79,7 @@ func (s *Server) handleJobLogDownload(w stdhttp.ResponseWriter, r *stdhttp.Reque
|
||||
|
||||
// writeLogsText renders the logs in the same shape the live page shows:
|
||||
// "HH:MM:SS.mmm TAG payload". Adds a small header so the file is
|
||||
// useful as a standalone artifact (operator pastes it into a ticket).
|
||||
// useful as a standalone artefact (operator pastes it into a ticket).
|
||||
func writeLogsText(w stdhttp.ResponseWriter, job *store.Job, logs []store.JobLogLine) {
|
||||
bw := bufio.NewWriter(w)
|
||||
defer func() { _ = bw.Flush() }()
|
||||
|
||||
@@ -31,7 +31,7 @@ type runNowResponse struct {
|
||||
func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -81,7 +81,7 @@ func drainUntil(t *testing.T, c *websocket.Conn, wantType api.MessageType) api.E
|
||||
return api.Envelope{}
|
||||
}
|
||||
|
||||
// enrolHostForWS pre-enrolls a host with bound repo creds so the server
|
||||
// enrolHostForWS pre-enrols a host with bound repo creds so the server
|
||||
// will treat it as ready to receive command.run.
|
||||
func enrolHostForWS(t *testing.T, srv *Server, st *store.Store, name string) (hostID, token string) {
|
||||
t.Helper()
|
||||
|
||||
@@ -506,12 +506,12 @@ func TestEnqueueOnDispatchFailure(t *testing.T) {
|
||||
func TestDrainPendingSerializesPerHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv, ts, st := rawTestServer(t)
|
||||
hostID, token := enrolHostForWS(t, srv, st, "serialize-host")
|
||||
hostID, token := enrolHostForWS(t, srv, st, "serialise-host")
|
||||
gid, sid := seedSchedAndGroup(t, st, hostID, 10)
|
||||
|
||||
// Connect the agent so DrainPending can dispatch.
|
||||
c := agentDial(t, srv, ts, hostID, token)
|
||||
sendHello(t, c, "serialize-host")
|
||||
sendHello(t, c, "serialise-host")
|
||||
// Drain the on-hello goroutine's pass first (no pending rows yet),
|
||||
// then wait for the schedule.set so the connection is fully settled.
|
||||
_ = drainUntil(t, c, api.MsgScheduleSet)
|
||||
|
||||
@@ -214,7 +214,7 @@ type acceptForm struct {
|
||||
func (s *Server) handleAcceptPendingHost(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
pendingID := chi.URLParam(r, "id")
|
||||
@@ -315,7 +315,7 @@ func (s *Server) handleAcceptPendingHost(w stdhttp.ResponseWriter, r *stdhttp.Re
|
||||
func (s *Server) handleRejectPendingHost(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
user, ok := s.requireUser(r)
|
||||
if !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
pendingID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -41,7 +41,7 @@ func toRepoMaintenanceView(m store.HostRepoMaintenance) repoMaintenanceView {
|
||||
|
||||
func (s *Server) handleGetRepoMaintenance(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -84,7 +84,7 @@ type repoMaintenanceWriteRequest struct {
|
||||
|
||||
func (s *Server) handleUpdateRepoMaintenance(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -26,7 +26,7 @@ func (s *Server) handleRunRepoPrune(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
stdhttp.Redirect(w, r, "/login", stdhttp.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -72,7 +72,7 @@ func (s *Server) handleRunRepoCheck(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
stdhttp.Redirect(w, r, "/login", stdhttp.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -125,7 +125,7 @@ func (s *Server) handleRunRepoUnlock(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
stdhttp.Redirect(w, r, "/login", stdhttp.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -53,7 +53,7 @@ func (s *Server) handleRunSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Reque
|
||||
stdhttp.Redirect(w, r, "/login", stdhttp.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -61,7 +61,7 @@ var cronParser = cron.NewParser(
|
||||
|
||||
func (s *Server) handleListSchedules(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -89,7 +89,7 @@ func (s *Server) handleListSchedules(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
|
||||
func (s *Server) handleCreateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -126,7 +126,7 @@ func (s *Server) handleCreateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Reque
|
||||
|
||||
func (s *Server) handleUpdateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -173,7 +173,7 @@ func (s *Server) handleUpdateSchedule(w stdhttp.ResponseWriter, r *stdhttp.Reque
|
||||
|
||||
func (s *Server) handleDeleteSchedule(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -43,7 +43,7 @@ type Server struct {
|
||||
srv *stdhttp.Server
|
||||
deps Deps
|
||||
|
||||
// drainLocks serializes DrainPending per host. The on-hello
|
||||
// drainLocks serialises DrainPending per host. The on-hello
|
||||
// goroutine and the 30s ticker can otherwise race for the same
|
||||
// host, double-dispatching every pending row. Map of hostID →
|
||||
// sync.Mutex; checked-and-locked atomically via drainLocksMu.
|
||||
@@ -257,7 +257,7 @@ func (s *Server) routes(r chi.Router) {
|
||||
// Durable post-Add-host page (operator can refresh / come
|
||||
// back; password decrypted from the token row each render).
|
||||
// Polled fragment under /awaiting flips to "connected" once
|
||||
// the agent enrolls.
|
||||
// the agent enrols.
|
||||
r.Get("/hosts/pending/{token}", s.handleUIPendingHost)
|
||||
r.Get("/hosts/pending/{token}/awaiting", s.handleUIPendingAwaiting)
|
||||
// Host detail (Snapshots tab is the default).
|
||||
|
||||
@@ -35,7 +35,7 @@ type listSnapshotsResponse struct {
|
||||
// onto whatever the server most recently received.
|
||||
func (s *Server) handleListHostSnapshots(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if _, ok := s.requireUser(r); !ok {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ type sourceGroupWriteRequest struct {
|
||||
|
||||
func (s *Server) handleListSourceGroups(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -90,7 +90,7 @@ func (s *Server) handleListSourceGroups(w stdhttp.ResponseWriter, r *stdhttp.Req
|
||||
|
||||
func (s *Server) handleGetSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -109,7 +109,7 @@ func (s *Server) handleGetSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Reque
|
||||
|
||||
func (s *Server) handleCreateSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -152,7 +152,7 @@ func (s *Server) handleCreateSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Re
|
||||
|
||||
func (s *Server) handleUpdateSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
@@ -207,7 +207,7 @@ func (s *Server) handleUpdateSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Re
|
||||
// the UI can offer "remove from these schedules first."
|
||||
func (s *Server) handleDeleteSourceGroup(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if !s.authedUser(r) {
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorized", "")
|
||||
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
|
||||
return
|
||||
}
|
||||
hostID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -276,7 +276,7 @@ type addHostPage struct {
|
||||
}
|
||||
|
||||
// pendingHostPage is the GET /hosts/pending/{token} view. Lives
|
||||
// for as long as the token does (1h ttl); once the agent enrolls,
|
||||
// for as long as the token does (1h ttl); once the agent enrols,
|
||||
// the handler redirects to /hosts/{host_id} and this page is gone.
|
||||
type pendingHostPage struct {
|
||||
Token string
|
||||
@@ -377,7 +377,7 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
|
||||
// handleUIPendingHost serves the durable Add-host result page —
|
||||
// shown after a successful POST /hosts/new and reachable until the
|
||||
// agent enrolls (the page redirects to /hosts/{id} once that
|
||||
// agent enrols (the page redirects to /hosts/{id} once that
|
||||
// happens) or the token expires (1h ttl). The password is
|
||||
// re-decrypted from the encrypted token row on every render so
|
||||
// the operator can refresh, bookmark, navigate away and come back.
|
||||
@@ -730,7 +730,7 @@ func (s *Server) handleUIJobDetail(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
// same way our Go code does.
|
||||
func (s *Server) handleJobStream(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
if u, _ := s.sessionUser(r); u == nil {
|
||||
stdhttp.Error(w, "unauthorized", stdhttp.StatusUnauthorized)
|
||||
stdhttp.Error(w, "unauthorised", stdhttp.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
jobID := chi.URLParam(r, "id")
|
||||
|
||||
@@ -49,7 +49,7 @@ func (s *Server) handleUIRepoReinit(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
}
|
||||
if !s.deps.Hub.Connected(host.ID) {
|
||||
s.renderRepoPage(w, r, u, host,
|
||||
"Host is offline — bring the agent back up before re-initializing.",
|
||||
"Host is offline — bring the agent back up before re-initialising.",
|
||||
"", "", "")
|
||||
return
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func (s *Server) handleUIRepoReinit(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
if _, err := s.deps.Store.GetHostCredentials(r.Context(), host.ID, store.CredKindRepo); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
s.renderRepoPage(w, r, u, host,
|
||||
"Bind repo credentials before re-initializing.",
|
||||
"Bind repo credentials before re-initialising.",
|
||||
"", "", "")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
stdhttp "net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -197,10 +196,18 @@ func (s *Server) handleUIRestorePost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// New-directory mode: server picks the path so the operator
|
||||
// can't escape /var/restic-restore. Operator-supplied
|
||||
// target_dir is intentionally ignored.
|
||||
targetDir = ""
|
||||
// New-directory mode: trust the operator's chosen target.
|
||||
// Empty falls back to the default. Validate it's either
|
||||
// absolute or starts with $HOME / ~/ (the agent expands
|
||||
// these at run time).
|
||||
if targetDir == "" {
|
||||
targetDir = defaultRestoreTargetDir()
|
||||
}
|
||||
if !looksLikeRestoreTarget(targetDir) {
|
||||
rerender("Target must be an absolute path, or start with $HOME or ~/.",
|
||||
stdhttp.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if !s.deps.Hub.Connected(host.ID) {
|
||||
@@ -210,13 +217,12 @@ func (s *Server) handleUIRestorePost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
}
|
||||
|
||||
// Build a new job id up-front so we can substitute it into the
|
||||
// new-directory target path. The dispatch helper will use this
|
||||
// same id (mint=now → reuse via dispatchJobWithPayload's
|
||||
// signature requires the id, so do it here and pass on).
|
||||
// new-directory target path. The agent will additionally expand
|
||||
// $HOME / ~/ before invoking restic.
|
||||
jobID := ulid.Make().String()
|
||||
finalTarget := ""
|
||||
if !inPlace {
|
||||
finalTarget = path.Join(defaultRestoreTargetRoot(), jobID)
|
||||
finalTarget = strings.ReplaceAll(targetDir, "<job-id>", jobID)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
@@ -383,22 +389,37 @@ func (s *Server) handleUIRestoreTree(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
}
|
||||
}
|
||||
|
||||
// defaultRestoreTargetRoot is the parent of the per-job restore
|
||||
// directory. The agent's systemd unit pins ReadWritePaths to
|
||||
// /etc/restic-manager + /var/lib/restic-manager (with ProtectSystem=
|
||||
// strict making the rest of /var read-only); restore writes have to
|
||||
// land inside one of those, so we keep them under
|
||||
// /var/lib/restic-manager/restore where the agent is already allowed
|
||||
// to write. The /restore subdir is created by the agent on demand.
|
||||
func defaultRestoreTargetRoot() string {
|
||||
return "/var/lib/restic-manager/restore"
|
||||
// defaultRestoreTargetDir is the placeholder shown on the step-3
|
||||
// New-directory radio card and the value used when the operator
|
||||
// leaves the field blank. $HOME resolves agent-side (typically /root
|
||||
// for the systemd-as-root unit); <job-id> is substituted at dispatch.
|
||||
// The systemd unit pins ReadWritePaths to include the agent user's
|
||||
// home/rm-restore subdir so this default actually works under the
|
||||
// sandbox.
|
||||
func defaultRestoreTargetDir() string {
|
||||
return "$HOME/rm-restore/<job-id>/"
|
||||
}
|
||||
|
||||
// defaultRestoreTargetDir surfaces the placeholder path shown on the
|
||||
// step-3 New-directory radio card. The "<job-id>" is not substituted
|
||||
// here — that happens at dispatch time.
|
||||
func defaultRestoreTargetDir() string {
|
||||
return defaultRestoreTargetRoot() + "/<job-id>/"
|
||||
// looksLikeRestoreTarget validates the operator-supplied target dir
|
||||
// is a shape the agent can sensibly resolve. We accept absolute
|
||||
// paths and a couple of agent-side expansions ($HOME, ~/). Other env
|
||||
// vars are deliberately rejected — operator-supplied paths shouldn't
|
||||
// be able to pick up arbitrary agent env values.
|
||||
func looksLikeRestoreTarget(p string) bool {
|
||||
if p == "" {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(p, "/"):
|
||||
return true
|
||||
case strings.HasPrefix(p, "$HOME/"), p == "$HOME":
|
||||
return true
|
||||
case strings.HasPrefix(p, "${HOME}/"), p == "${HOME}":
|
||||
return true
|
||||
case strings.HasPrefix(p, "~/"), p == "~":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sessionIDFromCookie returns the operator's session cookie value,
|
||||
|
||||
@@ -302,8 +302,12 @@ func TestRestorePostHappyPathDispatches(t *testing.T) {
|
||||
if cp.Restore.InPlace {
|
||||
t.Fatal("expected new-directory mode (in_place=false)")
|
||||
}
|
||||
if !strings.HasPrefix(cp.Restore.TargetDir, "/var/lib/restic-manager/restore/") {
|
||||
t.Fatalf("target_dir: got %q, want prefix /var/lib/restic-manager/restore/", cp.Restore.TargetDir)
|
||||
if !strings.HasPrefix(cp.Restore.TargetDir, "$HOME/rm-restore/") {
|
||||
t.Fatalf("target_dir: got %q, want prefix $HOME/rm-restore/", cp.Restore.TargetDir)
|
||||
}
|
||||
// <job-id> placeholder substituted with the dispatched job_id.
|
||||
if !strings.Contains(cp.Restore.TargetDir, "/01") {
|
||||
t.Errorf("target_dir: expected job_id substituted into the path; got %q", cp.Restore.TargetDir)
|
||||
}
|
||||
if len(cp.Restore.Paths) != 2 {
|
||||
t.Fatalf("paths: got %d, want 2", len(cp.Restore.Paths))
|
||||
|
||||
@@ -54,7 +54,7 @@ func AgentHandler(deps HandlerDeps) stdhttp.Handler {
|
||||
return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
host, ok := authenticateAgent(r, deps.Store)
|
||||
if !ok {
|
||||
stdhttp.Error(w, "unauthorized", stdhttp.StatusUnauthorized)
|
||||
stdhttp.Error(w, "unauthorised", stdhttp.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ func dispatchAgentMessage(ctx context.Context, c *Conn, hostID string, env api.E
|
||||
string(p.Status), p.ExitCode, p.Stats, errMsg, p.FinishedAt); err != nil {
|
||||
slog.Warn("ws: mark job finished", "job_id", p.JobID, "err", err)
|
||||
}
|
||||
// repo_initialized_at projection has been removed — auto-init
|
||||
// repo_initialised_at projection has been removed — auto-init
|
||||
// at host enrolment makes "is the repo init'd" derivable from
|
||||
// the latest init job's status, no separate column needed.
|
||||
if deps.JobHub != nil {
|
||||
|
||||
@@ -23,7 +23,7 @@ type Hub struct {
|
||||
conns map[string]*Conn // hostID → conn
|
||||
|
||||
// rpcs tracks in-flight synchronous RPC calls (e.g. tree.list).
|
||||
// See rpc.go for details. Lazy-initialized via the registry's
|
||||
// See rpc.go for details. Lazy-initialised via the registry's
|
||||
// own register() so callers don't have to juggle a constructor.
|
||||
rpcs rpcRegistry
|
||||
}
|
||||
@@ -105,7 +105,7 @@ func NewConn(hostID string, c *websocket.Conn) *Conn {
|
||||
}
|
||||
|
||||
// Send writes an envelope as a JSON text message. Concurrent calls
|
||||
// are serialized; the underlying socket is not safe for parallel
|
||||
// are serialised; the underlying socket is not safe for parallel
|
||||
// writers.
|
||||
func (c *Conn) Send(ctx context.Context, env api.Envelope) error {
|
||||
c.writeMu.Lock()
|
||||
|
||||
@@ -38,7 +38,7 @@ func (s *Store) GetHostRepoStats(ctx context.Context, hostID string) (*HostRepoS
|
||||
|
||||
// getHostRepoStatsTx is identical to GetHostRepoStats but runs on an
|
||||
// existing transaction so the fetch-merge-upsert in UpsertHostRepoStats
|
||||
// is fully serialized.
|
||||
// is fully serialised.
|
||||
func getHostRepoStatsTx(ctx context.Context, tx *sql.Tx, hostID string) (*HostRepoStats, error) {
|
||||
row := tx.QueryRowContext(ctx,
|
||||
`SELECT host_id, total_size_bytes, raw_size_bytes, unique_files,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -167,14 +167,21 @@
|
||||
<div class="text-[14px] font-medium text-ink">New directory</div>
|
||||
<div class="text-[12px] text-ink-mute mt-1 leading-[1.55]">
|
||||
Files restore into a fresh path on the host. Original files untouched.
|
||||
Original ownership (uid/gid/mode) is preserved.
|
||||
Restored as the agent user — original uid/gid is dropped (restic ≥ 0.17;
|
||||
older versions preserve it).
|
||||
</div>
|
||||
<div class="mt-3 px-3 py-[9px] rounded-[5px] mono text-[12px] text-ink flex items-center gap-2.5"
|
||||
style="background: var(--bg); border: 1px solid var(--line-soft);">
|
||||
<span class="text-ink-fade">→</span>
|
||||
<span>{{$page.DefaultTargetDir}}</span>
|
||||
<div class="mt-3 flex items-center gap-2.5">
|
||||
<span class="text-ink-fade mono text-[12px]">→</span>
|
||||
<input type="text" name="target_dir" id="target-dir-input"
|
||||
class="field mono text-[12px] flex-1"
|
||||
value="{{if $page.FormTargetDir}}{{$page.FormTargetDir}}{{else}}{{$page.DefaultTargetDir}}{{end}}"
|
||||
placeholder="$HOME/rm-restore/<job-id>/" />
|
||||
</div>
|
||||
<div class="text-[11.5px] text-ink-fade mt-1.5">
|
||||
<span class="mono">$HOME</span> resolves to the agent user's home;
|
||||
<span class="mono"><job-id></span> is substituted on dispatch.
|
||||
Edit if you want a specific directory.
|
||||
</div>
|
||||
<div class="text-[11.5px] text-ink-fade mt-1.5">Final job-id slug substituted on dispatch.</div>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
Reference in New Issue
Block a user