Files
restic-manager/internal/server/http/jobs.go
T
steve f0dfa689fe 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.
2026-05-04 17:27:52 +01:00

161 lines
4.8 KiB
Go

package http
import (
"context"
"encoding/json"
stdhttp "net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/oklog/ulid/v2"
"gitea.dcglab.co.uk/steve/restic-manager/internal/api"
"gitea.dcglab.co.uk/steve/restic-manager/internal/auth"
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
)
// runNowRequest is the body of POST /api/hosts/:id/jobs.
type runNowRequest struct {
Kind api.JobKind `json:"kind"`
Args []string `json:"args,omitempty"` // restic CLI args (paths for backup, etc.)
}
type runNowResponse struct {
JobID string `json:"job_id"`
Status string `json:"status"` // "queued"
}
// handleRunNow dispatches a job to the named host. Authenticated;
// rejects if the host isn't connected (caller should retry once
// the agent comes back).
func (s *Server) handleRunNow(w stdhttp.ResponseWriter, r *stdhttp.Request) {
user, ok := s.requireUser(r)
if !ok {
writeJSONError(w, stdhttp.StatusUnauthorized, "unauthorised", "")
return
}
hostID := chi.URLParam(r, "id")
if hostID == "" {
writeJSONError(w, stdhttp.StatusBadRequest, "missing_host_id", "")
return
}
var req runNowRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
return
}
res, status, code, msg := s.dispatchJob(r.Context(), user, hostID, req.Kind, req.Args)
if code != "" {
writeJSONError(w, status, code, msg)
return
}
writeJSON(w, stdhttp.StatusAccepted, res)
}
// dispatchJob is the common path for HTTP-driven job dispatch. It
// validates the kind, checks the host is online, persists the job
// row, and ships command.run over the WS. Returns:
// - res: the queued-job response (job_id + status)
// - status: HTTP status to return on failure (or 0 on success)
// - code, msg: error code/message for the wire (empty on success)
//
// JSON callers wrap with writeJSONError; HTML callers translate to
// flash banner + redirect.
func (s *Server) dispatchJob(ctx context.Context, user *store.User,
hostID string, kind api.JobKind, args []string,
) (res runNowResponse, status int, code, msg string) {
return s.dispatchJobWithPayload(ctx, user, hostID, kind, api.CommandRunPayload{
Kind: kind,
Args: args,
})
}
// dispatchJobWithPayload is dispatchJob's variant that lets callers
// fill in structured fields (Includes/Excludes/Tag/ForgetGroups/RequiresAdminCreds)
// — used by the per-source-group Run-now path. JobID is filled in
// here; callers leave it zero on the input payload.
func (s *Server) dispatchJobWithPayload(ctx context.Context, user *store.User,
hostID string, kind api.JobKind, payload api.CommandRunPayload,
) (res runNowResponse, status int, code, msg string) {
if !validJobKind(kind) {
return res, stdhttp.StatusBadRequest, "invalid_kind",
"kind must be one of backup|forget|prune|check|unlock"
}
host, err := s.deps.Store.GetHost(ctx, hostID)
if err != nil {
return res, stdhttp.StatusNotFound, "host_not_found", ""
}
if !s.deps.Hub.Connected(host.ID) {
return res, stdhttp.StatusServiceUnavailable, "host_offline",
"agent is not currently connected; try again when it reconnects"
}
jobID := ulid.Make().String()
now := time.Now().UTC()
var actorID *string
actor := "system"
if user != nil {
actor = "user"
actorID = &user.ID
}
if err := s.deps.Store.CreateJob(ctx, store.Job{
ID: jobID,
HostID: host.ID,
Kind: string(kind),
ActorKind: actor,
ActorID: actorID,
CreatedAt: now,
}); err != nil {
return res, stdhttp.StatusInternalServerError, "internal", ""
}
payload.JobID = jobID
payload.Kind = kind
env, err := api.Marshal(api.MsgCommandRun, jobID, payload)
if err != nil {
return res, stdhttp.StatusInternalServerError, "internal", ""
}
if err := s.deps.Hub.Send(ctx, host.ID, env); err != nil {
return res, stdhttp.StatusServiceUnavailable, "host_offline", err.Error()
}
_ = s.deps.Store.AppendAudit(ctx, store.AuditEntry{
ID: ulid.Make().String(),
UserID: actorID,
Actor: actor,
Action: "job.run_now",
TargetKind: ptr("job"),
TargetID: &jobID,
TS: now,
})
return runNowResponse{JobID: jobID, Status: "queued"}, 0, "", ""
}
// requireUser resolves the session cookie to a user row. Stub of the
// session-auth middleware that lands in P1-04's full pass.
func (s *Server) requireUser(r *stdhttp.Request) (*store.User, bool) {
c, err := r.Cookie(sessionCookieName)
if err != nil {
return nil, false
}
sess, err := s.deps.Store.LookupSession(r.Context(), auth.HashToken(c.Value))
if err != nil {
return nil, false
}
u, err := s.deps.Store.GetUserByID(r.Context(), sess.UserID)
if err != nil {
return nil, false
}
return u, true
}
func validJobKind(k api.JobKind) bool {
switch k {
case api.JobBackup, api.JobInit, api.JobForget, api.JobPrune,
api.JobCheck, api.JobUnlock, api.JobRestore, api.JobDiff:
return true
}
return false
}