P1 polish: Host.default_paths interim + restic env hygiene + job_id JS quoting
Two fixes that close the loop on dashboard run-now and harden the
agent's restic invocation.
Default paths (interim until P2-01 schedules):
- 0003 migration adds default_paths TEXT NOT NULL DEFAULT '[]'
to hosts and to enrollment_tokens.
- Operator types paths in the Add-host form (textarea, one per
line). They ride on the enrol_token row alongside the
encrypted creds (paths aren't secret — plain JSON column).
- On consume, ConsumeEnrollmentToken still just burns the token;
the new GetEnrollmentTokenAttachments returns both the
re-bindable creds and the path list in one round trip, the
handler transfers them onto the new host row inside CreateHost.
- The dashboard's Run-now and host-detail's "Run backup now"
button now read Host.DefaultPaths and pass them to dispatchJob.
A host with no default paths returns 400 with a friendly
"no paths set" message instead of dispatching a doomed
`restic backup` with no positional args.
- Doc comments explicitly call this out as a Phase 1 interim —
schedules supersede.
Restic env hygiene:
- envSlice() previously omitted HOME / XDG_CACHE_HOME, which
bit the smoke runs whenever the agent was launched outside
systemd (restic refused to start: "neither $XDG_CACHE_HOME
nor $HOME are defined"). Now both are set explicitly: prefer
Env.ExtraEnv overrides, fall back to the agent process's own
HOME, and finally to /var/lib/restic-manager.
- Comment makes the env policy explicit: parent's RESTIC_* /
AWS_* / B2_* env is filtered out by design — control-plane
is the unambiguous source of truth.
JS bug fix in the live log page:
- {{$job.ID | printf "%q"}} produced a literal-quoted JS string,
which then went into the WS URL as ".../jobs/"<ID>"/stream"
→ 404. Switched to '{{$job.ID}}' inside the literal so
html/template's auto-escape does the right thing. Verified
end-to-end: dashboard "Run now" → live progress + log lines
arrive over the WS → succeeded pill renders.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -140,14 +141,41 @@ func (e Env) RunBackup(ctx context.Context, paths, excludes, tags []string, hand
|
|||||||
}
|
}
|
||||||
|
|
||||||
// envSlice converts Env's typed fields into the os/exec env shape.
|
// envSlice converts Env's typed fields into the os/exec env shape.
|
||||||
|
//
|
||||||
|
// Deliberately does NOT inherit the parent process's environment:
|
||||||
|
// any RESTIC_* / AWS_* / B2_* vars in the operator's shell or the
|
||||||
|
// systemd unit's Environment= clause are filtered out so the
|
||||||
|
// control-plane is the unambiguous source of truth.
|
||||||
|
//
|
||||||
|
// HOME / XDG_CACHE_HOME are set explicitly because restic insists
|
||||||
|
// on one or the other for its cache dir; without it the command
|
||||||
|
// fails before ever talking to the repo.
|
||||||
func (e Env) envSlice() []string {
|
func (e Env) envSlice() []string {
|
||||||
|
home := "/var/lib/restic-manager"
|
||||||
|
if h, ok := e.ExtraEnv["HOME"]; ok && h != "" {
|
||||||
|
home = h
|
||||||
|
} else if h := os.Getenv("HOME"); h != "" {
|
||||||
|
home = h
|
||||||
|
}
|
||||||
|
xdg := home + "/.cache"
|
||||||
|
if x, ok := e.ExtraEnv["XDG_CACHE_HOME"]; ok && x != "" {
|
||||||
|
xdg = x
|
||||||
|
} else if x := os.Getenv("XDG_CACHE_HOME"); x != "" {
|
||||||
|
xdg = x
|
||||||
|
}
|
||||||
out := []string{
|
out := []string{
|
||||||
"RESTIC_REPOSITORY=" + e.RepoURL,
|
"RESTIC_REPOSITORY=" + e.RepoURL,
|
||||||
"RESTIC_PASSWORD=" + e.RepoPassword,
|
"RESTIC_PASSWORD=" + e.RepoPassword,
|
||||||
// Feed restic via env-only — keeps creds off ps(1).
|
// Feed restic via env-only — keeps creds off ps(1).
|
||||||
"PATH=/usr/local/bin:/usr/bin:/bin",
|
"PATH=/usr/local/bin:/usr/bin:/bin",
|
||||||
|
"HOME=" + home,
|
||||||
|
"XDG_CACHE_HOME=" + xdg,
|
||||||
}
|
}
|
||||||
for k, v := range e.ExtraEnv {
|
for k, v := range e.ExtraEnv {
|
||||||
|
// HOME / XDG_CACHE_HOME already merged in above.
|
||||||
|
if k == "HOME" || k == "XDG_CACHE_HOME" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
out = append(out, k+"="+v)
|
out = append(out, k+"="+v)
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
|
|||||||
@@ -56,6 +56,12 @@ type enrollOperatorRequest struct {
|
|||||||
RepoURL string `json:"repo_url"`
|
RepoURL string `json:"repo_url"`
|
||||||
RepoUsername string `json:"repo_username"`
|
RepoUsername string `json:"repo_username"`
|
||||||
RepoPassword string `json:"repo_password"`
|
RepoPassword string `json:"repo_password"`
|
||||||
|
// DefaultPaths lands on the host row at consume time. Used by
|
||||||
|
// run-now buttons (the dashboard's per-row Run, the host
|
||||||
|
// detail's Run backup now). When schedules ship in P2-01 they
|
||||||
|
// supersede this — until then, this is the only source of paths
|
||||||
|
// for run-now jobs.
|
||||||
|
DefaultPaths []string `json:"default_paths,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type enrollOperatorResponse struct {
|
type enrollOperatorResponse struct {
|
||||||
@@ -94,12 +100,13 @@ func (s *Server) handleAgentEnroll(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
|||||||
// is already burned. That's acceptable — operator just regens.
|
// is already burned. That's acceptable — operator just regens.
|
||||||
tokHash := auth.HashToken(req.Token)
|
tokHash := auth.HashToken(req.Token)
|
||||||
|
|
||||||
// If the token carries repo creds, re-encrypt them under the new
|
// Pull every operator-supplied attachment off the token row in one
|
||||||
// host_id so the host_credentials row is bound to the host (not
|
// query: encrypted repo creds (rebound under the new host_id) plus
|
||||||
// the token, which is about to disappear).
|
// the default-paths list. Both transferred onto the new host row
|
||||||
encForHost, err := s.rebindTokenCreds(r.Context(), tokHash, hostID)
|
// after consume.
|
||||||
|
attachments, encForHost, err := s.rebindTokenAttachments(r.Context(), tokHash, hostID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Warn("enrollment: rebind token creds failed", "err", err)
|
slog.Warn("enrollment: rebind token attachments failed", "err", err)
|
||||||
writeJSONError(w, stdhttp.StatusUnauthorized, "invalid_token",
|
writeJSONError(w, stdhttp.StatusUnauthorized, "invalid_token",
|
||||||
"token unknown, expired, or already used")
|
"token unknown, expired, or already used")
|
||||||
return
|
return
|
||||||
@@ -127,6 +134,7 @@ func (s *Server) handleAgentEnroll(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
|||||||
AgentVersion: req.AgentVersion,
|
AgentVersion: req.AgentVersion,
|
||||||
ResticVersion: req.ResticVersion,
|
ResticVersion: req.ResticVersion,
|
||||||
EnrolledAt: time.Now().UTC(),
|
EnrolledAt: time.Now().UTC(),
|
||||||
|
DefaultPaths: attachments.DefaultPaths,
|
||||||
}
|
}
|
||||||
if err := s.deps.Store.CreateHost(r.Context(), host,
|
if err := s.deps.Store.CreateHost(r.Context(), host,
|
||||||
auth.HashToken(agentToken), ""); err != nil {
|
auth.HashToken(agentToken), ""); err != nil {
|
||||||
@@ -195,7 +203,7 @@ func (s *Server) handleCreateEnrollmentToken(w stdhttp.ResponseWriter, r *stdhtt
|
|||||||
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token, expiresAt, err := s.mintEnrollmentToken(r.Context(), req.RepoURL, req.RepoUsername, req.RepoPassword)
|
token, expiresAt, err := s.mintEnrollmentToken(r.Context(), req.RepoURL, req.RepoUsername, req.RepoPassword, req.DefaultPaths)
|
||||||
switch err {
|
switch err {
|
||||||
case nil:
|
case nil:
|
||||||
writeJSON(w, stdhttp.StatusCreated, enrollOperatorResponse{Token: token, ExpiresAt: expiresAt})
|
writeJSON(w, stdhttp.StatusCreated, enrollOperatorResponse{Token: token, ExpiresAt: expiresAt})
|
||||||
@@ -218,7 +226,7 @@ var errMissingRepoCreds = errAuth("missing_repo_creds")
|
|||||||
// token (shown to the operator exactly once) and the expiry time.
|
// token (shown to the operator exactly once) and the expiry time.
|
||||||
//
|
//
|
||||||
// Shared by the JSON endpoint and the HTML "Add host" flow.
|
// Shared by the JSON endpoint and the HTML "Add host" flow.
|
||||||
func (s *Server) mintEnrollmentToken(ctx context.Context, repoURL, repoUsername, repoPassword string) (string, time.Time, error) {
|
func (s *Server) mintEnrollmentToken(ctx context.Context, repoURL, repoUsername, repoPassword string, defaultPaths []string) (string, time.Time, error) {
|
||||||
if repoURL == "" || repoPassword == "" {
|
if repoURL == "" || repoPassword == "" {
|
||||||
return "", time.Time{}, errMissingRepoCreds
|
return "", time.Time{}, errMissingRepoCreds
|
||||||
}
|
}
|
||||||
@@ -235,34 +243,44 @@ func (s *Server) mintEnrollmentToken(ctx context.Context, repoURL, repoUsername,
|
|||||||
return "", time.Time{}, err
|
return "", time.Time{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if defaultPaths == nil {
|
||||||
|
defaultPaths = []string{}
|
||||||
|
}
|
||||||
|
pathsJSON, err := json.Marshal(defaultPaths)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("marshal default_paths: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
const ttl = time.Hour
|
const ttl = time.Hour
|
||||||
if err := s.deps.Store.CreateEnrollmentToken(ctx, tokHash, ttl, enc); err != nil {
|
if err := s.deps.Store.CreateEnrollmentToken(ctx, tokHash, ttl, enc, string(pathsJSON)); err != nil {
|
||||||
return "", time.Time{}, err
|
return "", time.Time{}, err
|
||||||
}
|
}
|
||||||
return token, time.Now().Add(ttl).UTC(), nil
|
return token, time.Now().Add(ttl).UTC(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// rebindTokenCreds decrypts the creds attached to the token (if any),
|
// rebindTokenAttachments fetches every operator-supplied attachment
|
||||||
// re-encrypts under the new host_id, and returns the new ciphertext.
|
// off the token row, re-encrypting the repo-creds blob under the
|
||||||
// Empty return = the token had no creds attached, which we treat as
|
// new host_id (the additional-data binding moves with the cred so
|
||||||
// a hard error today (the operator must supply creds at mint time).
|
// a token-row dump can't be replayed against a different host's
|
||||||
func (s *Server) rebindTokenCreds(ctx context.Context, tokHash, hostID string) (string, error) {
|
// row). Returns the attachments (sans the rebind work), the
|
||||||
enc, err := s.deps.Store.GetEnrollmentTokenCreds(ctx, tokHash)
|
// re-encrypted ciphertext for SetHostCredentials, and any error.
|
||||||
|
func (s *Server) rebindTokenAttachments(ctx context.Context, tokHash, hostID string) (store.EnrollmentTokenAttachments, string, error) {
|
||||||
|
att, err := s.deps.Store.GetEnrollmentTokenAttachments(ctx, tokHash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return store.EnrollmentTokenAttachments{}, "", err
|
||||||
}
|
}
|
||||||
if enc == "" {
|
if att.EncRepoCreds == "" {
|
||||||
return "", nil
|
return att, "", nil
|
||||||
}
|
}
|
||||||
plain, err := s.deps.AEAD.Decrypt(enc, []byte("token:"+tokHash))
|
plain, err := s.deps.AEAD.Decrypt(att.EncRepoCreds, []byte("token:"+tokHash))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("decrypt token creds: %w", err)
|
return att, "", fmt.Errorf("decrypt token creds: %w", err)
|
||||||
}
|
}
|
||||||
out, err := s.deps.AEAD.Encrypt(plain, []byte("host:"+hostID))
|
out, err := s.deps.AEAD.Encrypt(plain, []byte("host:"+hostID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("re-encrypt for host: %w", err)
|
return att, "", fmt.Errorf("re-encrypt for host: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return att, out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// encryptRepoCreds JSON-encodes blob and seals it with the given
|
// encryptRepoCreds JSON-encodes blob and seals it with the given
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ func TestEnrollmentHappyPath(t *testing.T) {
|
|||||||
// Issue a token directly via the store (skipping the operator UI).
|
// Issue a token directly via the store (skipping the operator UI).
|
||||||
rawToken, _ := auth.NewToken()
|
rawToken, _ := auth.NewToken()
|
||||||
if err := st.CreateEnrollmentToken(context.Background(),
|
if err := st.CreateEnrollmentToken(context.Background(),
|
||||||
auth.HashToken(rawToken), 5*time.Minute, ""); err != nil {
|
auth.HashToken(rawToken), 5*time.Minute, "", ""); err != nil {
|
||||||
t.Fatalf("issue: %v", err)
|
t.Fatalf("issue: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,14 +28,14 @@ func TestEnrollmentTransfersRepoCreds(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("encrypt: %v", err)
|
t.Fatalf("encrypt: %v", err)
|
||||||
}
|
}
|
||||||
if err := st.CreateEnrollmentToken(ctx, tokHash, 1<<20, enc); err != nil {
|
if err := st.CreateEnrollmentToken(ctx, tokHash, 1<<20, enc, ""); err != nil {
|
||||||
t.Fatalf("create token: %v", err)
|
t.Fatalf("create token: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rebind under host_id, then consume (this is what the agent
|
// Rebind under host_id, then consume (this is what the agent
|
||||||
// enroll handler does inline).
|
// enroll handler does inline).
|
||||||
const hostID = "h-fixture"
|
const hostID = "h-fixture"
|
||||||
encForHost, err := srv.rebindTokenCreds(ctx, tokHash, hostID)
|
_, encForHost, err := srv.rebindTokenAttachments(ctx, tokHash, hostID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("rebind: %v", err)
|
t.Fatalf("rebind: %v", err)
|
||||||
}
|
}
|
||||||
@@ -93,14 +93,14 @@ func TestEnrollmentTokenWithoutCreds(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
const tokHash = "no-creds-token"
|
const tokHash = "no-creds-token"
|
||||||
if err := st.CreateEnrollmentToken(ctx, tokHash, 1<<20, ""); err != nil {
|
if err := st.CreateEnrollmentToken(ctx, tokHash, 1<<20, "", ""); err != nil {
|
||||||
t.Fatalf("create: %v", err)
|
t.Fatalf("create: %v", err)
|
||||||
}
|
}
|
||||||
enc, err := st.GetEnrollmentTokenCreds(ctx, tokHash)
|
att, err := st.GetEnrollmentTokenAttachments(ctx, tokHash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("get token creds: %v", err)
|
t.Fatalf("get token attachments: %v", err)
|
||||||
}
|
}
|
||||||
if enc != "" {
|
if att.EncRepoCreds != "" {
|
||||||
t.Errorf("token without creds should return empty blob; got %q", enc)
|
t.Errorf("token without creds should return empty blob; got %q", att.EncRepoCreds)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -159,7 +159,26 @@ func (s *Server) handleUIRunBackup(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
|||||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
res, status, code, msg := s.dispatchJob(r.Context(), storeUser, hostID, api.JobBackup, nil)
|
host, err := s.deps.Store.GetHost(r.Context(), hostID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
stdhttp.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(host.DefaultPaths) == 0 {
|
||||||
|
// Tell the user with HX-Redirect via a friendly toast — for
|
||||||
|
// now, just an HTTP error: HTMX surfaces the response body
|
||||||
|
// to the operator's console, and a future toast component
|
||||||
|
// will lift it into the UI.
|
||||||
|
stdhttp.Error(w,
|
||||||
|
"this host has no default backup paths set — edit the host or wait for schedules (P2)",
|
||||||
|
stdhttp.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, status, code, msg := s.dispatchJob(r.Context(), storeUser, hostID, api.JobBackup, host.DefaultPaths)
|
||||||
if code != "" {
|
if code != "" {
|
||||||
stdhttp.Error(w, msg, status)
|
stdhttp.Error(w, msg, status)
|
||||||
return
|
return
|
||||||
@@ -188,6 +207,9 @@ type addHostPage struct {
|
|||||||
Tags string
|
Tags string
|
||||||
RepoURL string
|
RepoURL string
|
||||||
RepoUsername string
|
RepoUsername string
|
||||||
|
// Paths is the textarea-as-typed default-paths input. One path
|
||||||
|
// per line, blanks ignored.
|
||||||
|
Paths string
|
||||||
|
|
||||||
// Server URL the operator should paste into the install
|
// Server URL the operator should paste into the install
|
||||||
// command. Resolved from RM_BASE_URL falling back to the
|
// command. Resolved from RM_BASE_URL falling back to the
|
||||||
@@ -235,6 +257,7 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
|||||||
Tags: strings.TrimSpace(r.PostForm.Get("tags")),
|
Tags: strings.TrimSpace(r.PostForm.Get("tags")),
|
||||||
RepoURL: strings.TrimSpace(r.PostForm.Get("repo_url")),
|
RepoURL: strings.TrimSpace(r.PostForm.Get("repo_url")),
|
||||||
RepoUsername: strings.TrimSpace(r.PostForm.Get("repo_username")),
|
RepoUsername: strings.TrimSpace(r.PostForm.Get("repo_username")),
|
||||||
|
Paths: r.PostForm.Get("paths"),
|
||||||
ServerURL: s.publicURL(r),
|
ServerURL: s.publicURL(r),
|
||||||
}
|
}
|
||||||
repoPassword := r.PostForm.Get("repo_password")
|
repoPassword := r.PostForm.Get("repo_password")
|
||||||
@@ -245,8 +268,10 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
|||||||
page.Error = "Repo URL and password are both required so the agent can back up the moment it comes online."
|
page.Error = "Repo URL and password are both required so the agent can back up the moment it comes online."
|
||||||
}
|
}
|
||||||
|
|
||||||
|
defaultPaths := splitPaths(page.Paths)
|
||||||
|
|
||||||
if page.Error == "" {
|
if page.Error == "" {
|
||||||
token, expires, err := s.mintEnrollmentToken(r.Context(), page.RepoURL, page.RepoUsername, repoPassword)
|
token, expires, err := s.mintEnrollmentToken(r.Context(), page.RepoURL, page.RepoUsername, repoPassword, defaultPaths)
|
||||||
switch err {
|
switch err {
|
||||||
case nil:
|
case nil:
|
||||||
page.Token = token
|
page.Token = token
|
||||||
@@ -330,6 +355,19 @@ func (s *Server) handleUIHostDetail(w stdhttp.ResponseWriter, r *stdhttp.Request
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// splitPaths parses the textarea content into a clean []string —
|
||||||
|
// one path per line, leading/trailing whitespace trimmed, blanks
|
||||||
|
// dropped.
|
||||||
|
func splitPaths(s string) []string {
|
||||||
|
out := []string{}
|
||||||
|
for _, line := range strings.Split(s, "\n") {
|
||||||
|
if p := strings.TrimSpace(line); p != "" {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// publicURL is what the operator should paste into the install
|
// publicURL is what the operator should paste into the install
|
||||||
// command. Prefers RM_BASE_URL (set by the operator's reverse
|
// command. Prefers RM_BASE_URL (set by the operator's reverse
|
||||||
// proxy config) and falls back to scheme + Host of the inbound
|
// proxy config) and falls back to scheme + Host of the inbound
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package store
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
@@ -17,19 +18,27 @@ import (
|
|||||||
// host_credentials row. Empty string = operator chose to set creds
|
// host_credentials row. Empty string = operator chose to set creds
|
||||||
// later via PUT /api/hosts/{id}/repo-credentials; the agent will
|
// later via PUT /api/hosts/{id}/repo-credentials; the agent will
|
||||||
// refuse backup jobs until that lands.
|
// refuse backup jobs until that lands.
|
||||||
func (s *Store) CreateEnrollmentToken(ctx context.Context, tokenHash string, ttl time.Duration, encRepoCreds string) error {
|
//
|
||||||
|
// defaultPaths is the JSON-encoded path list (the agent invokes
|
||||||
|
// `restic backup` with these on a run-now without explicit paths).
|
||||||
|
// Empty string is treated as "[]". Not encrypted — paths aren't
|
||||||
|
// secret.
|
||||||
|
func (s *Store) CreateEnrollmentToken(ctx context.Context, tokenHash string, ttl time.Duration, encRepoCreds, defaultPaths string) error {
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
var enc any = nil
|
var enc any = nil
|
||||||
if encRepoCreds != "" {
|
if encRepoCreds != "" {
|
||||||
enc = encRepoCreds
|
enc = encRepoCreds
|
||||||
}
|
}
|
||||||
|
if defaultPaths == "" {
|
||||||
|
defaultPaths = "[]"
|
||||||
|
}
|
||||||
_, err := s.db.ExecContext(ctx,
|
_, err := s.db.ExecContext(ctx,
|
||||||
`INSERT INTO enrollment_tokens (token_hash, created_at, expires_at, enc_repo_creds)
|
`INSERT INTO enrollment_tokens (token_hash, created_at, expires_at, enc_repo_creds, default_paths)
|
||||||
VALUES (?, ?, ?, ?)`,
|
VALUES (?, ?, ?, ?, ?)`,
|
||||||
tokenHash,
|
tokenHash,
|
||||||
now.Format(time.RFC3339Nano),
|
now.Format(time.RFC3339Nano),
|
||||||
now.Add(ttl).Format(time.RFC3339Nano),
|
now.Add(ttl).Format(time.RFC3339Nano),
|
||||||
enc)
|
enc, defaultPaths)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("store: create enrollment token: %w", err)
|
return fmt.Errorf("store: create enrollment token: %w", err)
|
||||||
}
|
}
|
||||||
@@ -62,30 +71,49 @@ func (s *Store) ConsumeEnrollmentToken(ctx context.Context, tokenHash, hostID st
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetEnrollmentTokenCreds returns the encrypted repo-creds blob the
|
// EnrollmentTokenAttachments is everything the enrolment handler
|
||||||
// operator stashed when creating the token, or ("", ErrNotFound) if
|
// needs from a token row at consume time, fetched in one round-trip.
|
||||||
// the token is gone / consumed / expired / had no creds attached.
|
type EnrollmentTokenAttachments struct {
|
||||||
|
// EncRepoCreds is the AEAD ciphertext bound (additional-data) to
|
||||||
|
// "token:" + token_hash. Empty if no creds were stashed.
|
||||||
|
EncRepoCreds string
|
||||||
|
// DefaultPaths is the operator's run-now path list. Always
|
||||||
|
// non-nil (empty slice if none were set).
|
||||||
|
DefaultPaths []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEnrollmentTokenAttachments returns the operator-supplied
|
||||||
|
// attachments on a still-valid enrolment token: the encrypted repo
|
||||||
|
// creds and the default-paths list. Returns ErrNotFound if the
|
||||||
|
// token is gone / consumed / expired.
|
||||||
//
|
//
|
||||||
// The caller decrypts using token_hash as the AEAD additional data,
|
// The caller decrypts EncRepoCreds using token_hash as AEAD
|
||||||
// then re-encrypts using host_id as additional data before passing
|
// additional data, then re-encrypts using host_id as additional
|
||||||
// to ConsumeEnrollmentToken.
|
// data before passing to ConsumeEnrollmentToken.
|
||||||
func (s *Store) GetEnrollmentTokenCreds(ctx context.Context, tokenHash string) (string, error) {
|
func (s *Store) GetEnrollmentTokenAttachments(ctx context.Context, tokenHash string) (EnrollmentTokenAttachments, error) {
|
||||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||||
row := s.db.QueryRowContext(ctx,
|
row := s.db.QueryRowContext(ctx,
|
||||||
`SELECT enc_repo_creds FROM enrollment_tokens
|
`SELECT enc_repo_creds, default_paths FROM enrollment_tokens
|
||||||
WHERE token_hash = ? AND consumed_at IS NULL AND expires_at > ?`,
|
WHERE token_hash = ? AND consumed_at IS NULL AND expires_at > ?`,
|
||||||
tokenHash, now)
|
tokenHash, now)
|
||||||
var enc sql.NullString
|
var (
|
||||||
if err := row.Scan(&enc); err != nil {
|
enc sql.NullString
|
||||||
|
defaultPaths string
|
||||||
|
)
|
||||||
|
if err := row.Scan(&enc, &defaultPaths); err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return "", ErrNotFound
|
return EnrollmentTokenAttachments{}, ErrNotFound
|
||||||
}
|
}
|
||||||
return "", fmt.Errorf("store: get enrollment token creds: %w", err)
|
return EnrollmentTokenAttachments{}, fmt.Errorf("store: get enrollment token attachments: %w", err)
|
||||||
}
|
}
|
||||||
if !enc.Valid {
|
out := EnrollmentTokenAttachments{DefaultPaths: []string{}}
|
||||||
return "", nil
|
if enc.Valid {
|
||||||
|
out.EncRepoCreds = enc.String
|
||||||
}
|
}
|
||||||
return enc.String, nil
|
if defaultPaths != "" {
|
||||||
|
_ = json.Unmarshal([]byte(defaultPaths), &out.DefaultPaths)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// PurgeExpiredEnrollmentTokens deletes long-expired token rows. Tokens
|
// PurgeExpiredEnrollmentTokens deletes long-expired token rows. Tokens
|
||||||
|
|||||||
+19
-7
@@ -17,17 +17,25 @@ func (s *Store) CreateHost(ctx context.Context, h Host, agentTokenHash, certPinS
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("store: marshal tags: %w", err)
|
return fmt.Errorf("store: marshal tags: %w", err)
|
||||||
}
|
}
|
||||||
|
if h.DefaultPaths == nil {
|
||||||
|
h.DefaultPaths = []string{}
|
||||||
|
}
|
||||||
|
defaultPaths, err := json.Marshal(h.DefaultPaths)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("store: marshal default_paths: %w", err)
|
||||||
|
}
|
||||||
_, err = s.db.ExecContext(ctx,
|
_, err = s.db.ExecContext(ctx,
|
||||||
`INSERT INTO hosts (
|
`INSERT INTO hosts (
|
||||||
id, name, os, arch, agent_version, restic_version, protocol_version,
|
id, name, os, arch, agent_version, restic_version, protocol_version,
|
||||||
enrolled_at, status, tags,
|
enrolled_at, status, tags,
|
||||||
agent_token_hash, cert_pin_sha256
|
agent_token_hash, cert_pin_sha256, default_paths
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'offline', ?, ?, ?)`,
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'offline', ?, ?, ?, ?)`,
|
||||||
h.ID, h.Name, h.OS, h.Arch,
|
h.ID, h.Name, h.OS, h.Arch,
|
||||||
h.AgentVersion, h.ResticVersion, h.ProtocolVersion,
|
h.AgentVersion, h.ResticVersion, h.ProtocolVersion,
|
||||||
h.EnrolledAt.UTC().Format(time.RFC3339Nano),
|
h.EnrolledAt.UTC().Format(time.RFC3339Nano),
|
||||||
string(tags),
|
string(tags),
|
||||||
agentTokenHash, certPinSHA256)
|
agentTokenHash, certPinSHA256,
|
||||||
|
string(defaultPaths))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("store: create host: %w", err)
|
return fmt.Errorf("store: create host: %w", err)
|
||||||
}
|
}
|
||||||
@@ -42,7 +50,7 @@ func (s *Store) LookupHostByAgentToken(ctx context.Context, tokenHash string) (*
|
|||||||
enrolled_at, last_seen_at, status, repo_id, tags,
|
enrolled_at, last_seen_at, status, repo_id, tags,
|
||||||
current_job_id, last_backup_at, last_backup_status,
|
current_job_id, last_backup_at, last_backup_status,
|
||||||
repo_size_bytes, snapshot_count, open_alert_count,
|
repo_size_bytes, snapshot_count, open_alert_count,
|
||||||
applied_schedule_version
|
applied_schedule_version, default_paths
|
||||||
FROM hosts WHERE agent_token_hash = ?`,
|
FROM hosts WHERE agent_token_hash = ?`,
|
||||||
tokenHash)
|
tokenHash)
|
||||||
return scanHost(row)
|
return scanHost(row)
|
||||||
@@ -55,7 +63,7 @@ func (s *Store) GetHost(ctx context.Context, id string) (*Host, error) {
|
|||||||
enrolled_at, last_seen_at, status, repo_id, tags,
|
enrolled_at, last_seen_at, status, repo_id, tags,
|
||||||
current_job_id, last_backup_at, last_backup_status,
|
current_job_id, last_backup_at, last_backup_status,
|
||||||
repo_size_bytes, snapshot_count, open_alert_count,
|
repo_size_bytes, snapshot_count, open_alert_count,
|
||||||
applied_schedule_version
|
applied_schedule_version, default_paths
|
||||||
FROM hosts WHERE id = ?`, id)
|
FROM hosts WHERE id = ?`, id)
|
||||||
return scanHost(row)
|
return scanHost(row)
|
||||||
}
|
}
|
||||||
@@ -116,7 +124,7 @@ func (s *Store) ListHosts(ctx context.Context) ([]Host, error) {
|
|||||||
enrolled_at, last_seen_at, status, repo_id, tags,
|
enrolled_at, last_seen_at, status, repo_id, tags,
|
||||||
current_job_id, last_backup_at, last_backup_status,
|
current_job_id, last_backup_at, last_backup_status,
|
||||||
repo_size_bytes, snapshot_count, open_alert_count,
|
repo_size_bytes, snapshot_count, open_alert_count,
|
||||||
applied_schedule_version
|
applied_schedule_version, default_paths
|
||||||
FROM hosts ORDER BY name`)
|
FROM hosts ORDER BY name`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("store: list hosts: %w", err)
|
return nil, fmt.Errorf("store: list hosts: %w", err)
|
||||||
@@ -154,13 +162,14 @@ func scanHostRow(s hostScanner) (*Host, error) {
|
|||||||
repoID, currentJob, lastBkSt sql.NullString
|
repoID, currentJob, lastBkSt sql.NullString
|
||||||
enrolled string
|
enrolled string
|
||||||
tags string
|
tags string
|
||||||
|
defaultPaths string
|
||||||
)
|
)
|
||||||
err := s.Scan(&h.ID, &h.Name, &h.OS, &h.Arch,
|
err := s.Scan(&h.ID, &h.Name, &h.OS, &h.Arch,
|
||||||
&h.AgentVersion, &h.ResticVersion, &h.ProtocolVersion,
|
&h.AgentVersion, &h.ResticVersion, &h.ProtocolVersion,
|
||||||
&enrolled, &lastSeen, &h.Status, &repoID, &tags,
|
&enrolled, &lastSeen, &h.Status, &repoID, &tags,
|
||||||
¤tJob, &lastBackupAt, &lastBkSt,
|
¤tJob, &lastBackupAt, &lastBkSt,
|
||||||
&h.RepoSizeBytes, &h.SnapshotCount, &h.OpenAlertCount,
|
&h.RepoSizeBytes, &h.SnapshotCount, &h.OpenAlertCount,
|
||||||
&h.AppliedScheduleVersion)
|
&h.AppliedScheduleVersion, &defaultPaths)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, ErrNotFound
|
return nil, ErrNotFound
|
||||||
@@ -201,5 +210,8 @@ func scanHostRow(s hostScanner) (*Host, error) {
|
|||||||
if tags != "" {
|
if tags != "" {
|
||||||
_ = json.Unmarshal([]byte(tags), &h.Tags)
|
_ = json.Unmarshal([]byte(tags), &h.Tags)
|
||||||
}
|
}
|
||||||
|
if defaultPaths != "" {
|
||||||
|
_ = json.Unmarshal([]byte(defaultPaths), &h.DefaultPaths)
|
||||||
|
}
|
||||||
return &h, nil
|
return &h, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- 0003_default_paths.sql
|
||||||
|
--
|
||||||
|
-- Per-host "default backup paths" — what the agent backs up when an
|
||||||
|
-- operator hits "Run now" without specifying paths explicitly. Phase
|
||||||
|
-- 1 interim until schedules (P2-01) provide a richer source. Once
|
||||||
|
-- Schedule rows exist, run-now will dispatch the host's primary
|
||||||
|
-- schedule's paths and this column becomes a fallback / migration
|
||||||
|
-- source.
|
||||||
|
--
|
||||||
|
-- Stored as JSON text (same shape as Host.tags) so we can grow to
|
||||||
|
-- excludes/tags later without a column-per-field schema churn.
|
||||||
|
|
||||||
|
ALTER TABLE hosts
|
||||||
|
ADD COLUMN default_paths TEXT NOT NULL DEFAULT '[]';
|
||||||
|
|
||||||
|
-- Operators set the paths at "Add host" time, alongside repo creds.
|
||||||
|
-- Stashed on the enrolment-token row (no encryption — paths aren't
|
||||||
|
-- secret) and copied to the host on consume.
|
||||||
|
ALTER TABLE enrollment_tokens
|
||||||
|
ADD COLUMN default_paths TEXT NOT NULL DEFAULT '[]';
|
||||||
@@ -58,6 +58,10 @@ type Host struct {
|
|||||||
SnapshotCount int
|
SnapshotCount int
|
||||||
OpenAlertCount int
|
OpenAlertCount int
|
||||||
AppliedScheduleVersion int64
|
AppliedScheduleVersion int64
|
||||||
|
// DefaultPaths is what `restic backup` is invoked with when an
|
||||||
|
// operator hits "Run now" without supplying paths. Phase 1
|
||||||
|
// interim — schedules (P2-01) supersede this.
|
||||||
|
DefaultPaths []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// EnrollmentToken is the issuer's view of a one-time token. The
|
// EnrollmentToken is the issuer's view of a one-time token. The
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ func TestEnrollmentTokenSingleUse(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
hash := "tok-hash"
|
hash := "tok-hash"
|
||||||
if err := s.CreateEnrollmentToken(ctx, hash, time.Hour, ""); err != nil {
|
if err := s.CreateEnrollmentToken(ctx, hash, time.Hour, "", ""); err != nil {
|
||||||
t.Fatalf("create: %v", err)
|
t.Fatalf("create: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -43,6 +43,17 @@
|
|||||||
<div class="field-help">Free-form. Used for filtering and grouping on the dashboard.</div>
|
<div class="field-help">Free-form. Used for filtering and grouping on the dashboard.</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<h3 class="text-[13px] font-semibold uppercase tracking-[0.08em] text-ink-mute mb-4 pt-6 border-t border-line-soft">Default backup paths</h3>
|
||||||
|
<div class="mb-7">
|
||||||
|
<label class="field-label" for="ah-paths">Paths <span class="text-ink-fade font-normal">· one per line</span></label>
|
||||||
|
<textarea id="ah-paths" name="paths" rows="3" class="field mono"
|
||||||
|
style="resize: vertical;"
|
||||||
|
placeholder="/etc /home /var/lib/postgresql">{{$page.Paths}}</textarea>
|
||||||
|
<div class="field-help">
|
||||||
|
What <span class="mono text-ink-mid">restic backup</span> runs against when an operator hits “Run now”. Until schedules ship in Phase 2, this is the only source of paths for run-now jobs — leave it empty if you’ll dispatch via the JSON API instead.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<h3 class="text-[13px] font-semibold uppercase tracking-[0.08em] text-ink-mute mb-4 pt-6 border-t border-line-soft">Restic repository</h3>
|
<h3 class="text-[13px] font-semibold uppercase tracking-[0.08em] text-ink-mute mb-4 pt-6 border-t border-line-soft">Restic repository</h3>
|
||||||
<div class="mb-5">
|
<div class="mb-5">
|
||||||
<label class="field-label" for="ah-url">Repo URL</label>
|
<label class="field-label" for="ah-url">Repo URL</label>
|
||||||
|
|||||||
@@ -144,7 +144,7 @@
|
|||||||
{{if $page.IsActive}}
|
{{if $page.IsActive}}
|
||||||
<script>
|
<script>
|
||||||
(function() {
|
(function() {
|
||||||
const jobID = {{$job.ID | printf "%q"}};
|
const jobID = '{{$job.ID}}';
|
||||||
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
|
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||||
const ws = new WebSocket(`${wsProto}://${location.host}/api/jobs/${jobID}/stream`);
|
const ws = new WebSocket(`${wsProto}://${location.host}/api/jobs/${jobID}/stream`);
|
||||||
const stream = document.getElementById('log-stream');
|
const stream = document.getElementById('log-stream');
|
||||||
|
|||||||
Reference in New Issue
Block a user