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:
2026-05-04 17:27:52 +01:00
parent a2398d0b66
commit f0dfa689fe
49 changed files with 315 additions and 120 deletions
+1 -1
View File
@@ -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, "/\\") {
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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 {
+6 -6
View File
@@ -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")
+2 -2
View File
@@ -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())
+2 -2
View File
@@ -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() }()
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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()
+2 -2
View File
@@ -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)
+2 -2
View File
@@ -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")
+2 -2
View File
@@ -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")
+3 -3
View File
@@ -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")
+1 -1
View File
@@ -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")
+4 -4
View File
@@ -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")
+2 -2
View File
@@ -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).
+1 -1
View File
@@ -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
}
+5 -5
View File
@@ -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")
+3 -3
View File
@@ -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")
+2 -2
View File
@@ -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
}
+44 -23
View File
@@ -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,
+6 -2
View File
@@ -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))