feat(hub): gc --dry-run, dashboard token auth, /healthz + /readyz 🛡️🧹

Three hub-side operability/security closures:

- 🧹 `devbox-hub gc --dry-run`: previews the exact snapshots + chunks the
  sweep would remove (computed from reachability — same set the real run
  deletes) without mutating a thing. Cheap insurance before a destructive GC.
- 🔐 dashboard token auth (`--dashboard-token`): a non-loopback bind was
  unauthenticated (warning only) and leaked device names/activity. Token is
  accepted via ?token=, Authorization: Bearer, or an HttpOnly cookie pinned
  on first ?token= — so EventSource/fetch authenticate with index.html
  untouched. Constant-time compare.
- 🩺 `/healthz` (liveness) + `/readyz` (DB-ping → 503 when unreachable): real
  probes for the compose selfheal profile / LBs, which only had /metrics.

Tests: TestGCDryRun (accurate + non-destructive), TestDashboardAuth.
This commit is contained in:
shoemoney 2026-06-30 12:14:54 -05:00
parent 7e13eca8ad
commit 5440054a41
6 changed files with 243 additions and 10 deletions

View file

@ -78,7 +78,7 @@ func TestGCKeepsChunksSharedAcrossShares(t *testing.T) {
} }
// GC keeping only each share's head. // GC keeping only each share's head.
if _, _, err := runGC(db, store, 1); err != nil { if _, _, err := runGC(db, store, 1, false); err != nil {
t.Fatalf("gc: %v", err) t.Fatalf("gc: %v", err)
} }

View file

@ -98,7 +98,7 @@ func TestGCDropsOldUniqueChunks(t *testing.T) {
} }
// gc keeping only the newest snapshot (v2 == head): v1 is pruned. // gc keeping only the newest snapshot (v2 == head): v1 is pruned.
snaps, chunks, err := runGC(db, store, 1) snaps, chunks, err := runGC(db, store, 1, false)
if err != nil { if err != nil {
t.Fatalf("gc: %v", err) t.Fatalf("gc: %v", err)
} }
@ -143,6 +143,82 @@ func TestGCDropsOldUniqueChunks(t *testing.T) {
} }
} }
// TestGCDryRun asserts --dry-run reports the same counts the real sweep would
// remove while deleting nothing, then that the real run matches those counts.
func TestGCDryRun(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
store, err := blobstore.NewDisk(t.TempDir())
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(hub.NewServer(db, store).Handler())
defer srv.Close()
if err := db.CreateToken(hub.HashToken("tok"), time.Now().Unix()+3600); err != nil {
t.Fatal(err)
}
c := transport.New(srv.URL)
pub, priv, _ := ed25519.GenerateKey(rand.Reader)
if _, err := c.Join("tok", "dev", pub, priv); err != nil {
t.Fatal(err)
}
if err := c.Publish("proj"); err != nil {
t.Fatal(err)
}
guard, _ := secret.New(nil)
root := t.TempDir()
ig, _ := syncer.LoadIgnore(root)
writeFile(t, root, "shared.txt", "stable content\n")
writeFile(t, root, "only-v1.txt", "this file vanishes in v2\n")
v1, err := syncer.Push(c, root, "proj", "", ig, guard, "", nil)
if err != nil {
t.Fatalf("push v1: %v", err)
}
if err := os.Remove(filepath.Join(root, "only-v1.txt")); err != nil {
t.Fatal(err)
}
writeFile(t, root, "only-v2.txt", "fresh in v2\n")
v2, err := syncer.Push(c, root, "proj", "", ig, guard, v1.Head, nil)
if err != nil {
t.Fatalf("push v2: %v", err)
}
uniqueV1 := diff(manifestChunksOrFail(t, store, v1.Snapshot), manifestChunksOrFail(t, store, v2.Snapshot))
if len(uniqueV1) == 0 {
t.Fatal("test setup: expected at least one v1-only chunk")
}
// Dry-run reports what would go, deletes nothing.
dSnaps, dChunks, err := runGC(db, store, 1, true)
if err != nil {
t.Fatalf("dry-run gc: %v", err)
}
if dSnaps != 1 || dChunks != len(uniqueV1) {
t.Fatalf("dry-run reported %d snaps / %d chunks, want 1 / %d", dSnaps, dChunks, len(uniqueV1))
}
if has, _ := store.Has(v1.Snapshot); !has {
t.Fatal("dry-run must NOT delete the v1 manifest blob")
}
for _, h := range uniqueV1 {
if has, _ := store.Has(h); !has {
t.Fatalf("dry-run must NOT delete chunk %s", h)
}
}
// Real run matches the dry-run prediction.
rSnaps, rChunks, err := runGC(db, store, 1, false)
if err != nil {
t.Fatalf("gc: %v", err)
}
if rSnaps != dSnaps || rChunks != dChunks {
t.Fatalf("real gc removed %d snaps / %d chunks, dry-run predicted %d / %d", rSnaps, rChunks, dSnaps, dChunks)
}
}
func manifestChunksOrFail(t *testing.T, store blobstore.Store, id string) []string { func manifestChunksOrFail(t *testing.T, store blobstore.Store, id string) []string {
t.Helper() t.Helper()
hs, err := manifestChunks(store, id) hs, err := manifestChunks(store, id)

View file

@ -72,7 +72,7 @@ func openDB(data string) (*meta.DB, error) {
} }
func serveCmd() *cobra.Command { func serveCmd() *cobra.Command {
var data, listen, dashAddr string var data, listen, dashAddr, dashToken string
var dash bool var dash bool
var gcEvery time.Duration var gcEvery time.Duration
var gcKeep int var gcKeep int
@ -96,9 +96,14 @@ func serveCmd() *cobra.Command {
var d *dashboard.Dashboard var d *dashboard.Dashboard
if dash { if dash {
d = dashboard.New(db, version) d = dashboard.New(db, version)
if dashToken != "" {
d.SetToken(dashToken)
}
srv.WithDashboard(d) srv.WithDashboard(d)
if !isLoopback(dashAddr) { if dashToken != "" {
fmt.Fprintf(out, "⚠️ dashboard on %s is UNAUTHENTICATED and not loopback — anyone who can reach it sees hub activity. SSH-tunnel instead, or you accept this.\n", dashAddr) fmt.Fprintf(out, "🔐 dashboard requires a token — open http://%s/?token=<token>\n", dashAddr)
} else if !isLoopback(dashAddr) {
fmt.Fprintf(out, "⚠️ dashboard on %s is UNAUTHENTICATED and not loopback — anyone who can reach it sees hub activity. Pass --dashboard-token, SSH-tunnel instead, or you accept this.\n", dashAddr)
} }
go func() { go func() {
ds := &http.Server{Addr: dashAddr, Handler: d.Handler(), ReadHeaderTimeout: 10 * time.Second} ds := &http.Server{Addr: dashAddr, Handler: d.Handler(), ReadHeaderTimeout: 10 * time.Second}
@ -118,7 +123,7 @@ func serveCmd() *cobra.Command {
t := time.NewTicker(gcEvery) t := time.NewTicker(gcEvery)
defer t.Stop() defer t.Stop()
for range t.C { for range t.C {
snaps, chunks, err := runGC(db, store, gcKeep) snaps, chunks, err := runGC(db, store, gcKeep, false)
if err != nil { if err != nil {
fmt.Fprintf(out, "gc sweep error: %v\n", err) fmt.Fprintf(out, "gc sweep error: %v\n", err)
continue continue
@ -150,6 +155,7 @@ func serveCmd() *cobra.Command {
cmd.Flags().StringVar(&listen, "listen", ":8080", "listen address") cmd.Flags().StringVar(&listen, "listen", ":8080", "listen address")
cmd.Flags().BoolVar(&dash, "dashboard", false, "serve the live web dashboard") cmd.Flags().BoolVar(&dash, "dashboard", false, "serve the live web dashboard")
cmd.Flags().StringVar(&dashAddr, "dashboard-addr", "127.0.0.1:8099", "dashboard listen address (loopback by default — unauthenticated)") cmd.Flags().StringVar(&dashAddr, "dashboard-addr", "127.0.0.1:8099", "dashboard listen address (loopback by default — unauthenticated)")
cmd.Flags().StringVar(&dashToken, "dashboard-token", "", "require this token to view the dashboard (recommended for non-loopback binds)")
cmd.Flags().DurationVar(&gcEvery, "gc-every", 0, "run in-process GC on this interval (0 = off; e.g. 24h) — animates on the dashboard") cmd.Flags().DurationVar(&gcEvery, "gc-every", 0, "run in-process GC on this interval (0 = off; e.g. 24h) — animates on the dashboard")
cmd.Flags().IntVar(&gcKeep, "gc-keep", 10, "snapshots to keep per share when --gc-every sweeps") cmd.Flags().IntVar(&gcKeep, "gc-keep", 10, "snapshots to keep per share when --gc-every sweeps")
return cmd return cmd
@ -354,6 +360,7 @@ func principalCmd() *cobra.Command {
func gcCmd() *cobra.Command { func gcCmd() *cobra.Command {
var data string var data string
var keep int var keep int
var dryRun bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "gc", Use: "gc",
Short: "🧹 prune old snapshots and unreferenced chunks", Short: "🧹 prune old snapshots and unreferenced chunks",
@ -367,16 +374,21 @@ func gcCmd() *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
snaps, chunks, err := runGC(db, store, keep) snaps, chunks, err := runGC(db, store, keep, dryRun)
if err != nil { if err != nil {
return err return err
} }
if dryRun {
fmt.Fprintf(cmd.OutOrStdout(), "🔍 gc --dry-run: would remove %d snapshots, %d chunks (nothing deleted)\n", snaps, chunks)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "🧹 gc: removed %d snapshots, %d chunks (freed)\n", snaps, chunks) fmt.Fprintf(cmd.OutOrStdout(), "🧹 gc: removed %d snapshots, %d chunks (freed)\n", snaps, chunks)
}
return nil return nil
}, },
} }
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory") cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
cmd.Flags().IntVar(&keep, "keep", 10, "snapshots to keep per share (newest)") cmd.Flags().IntVar(&keep, "keep", 10, "snapshots to keep per share (newest)")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "show what would be pruned without deleting anything")
return cmd return cmd
} }
@ -386,7 +398,7 @@ func gcCmd() *cobra.Command {
// regardless of refcounts. That makes GC safe even when refcounts are off — e.g. // regardless of refcounts. That makes GC safe even when refcounts are off — e.g.
// content-addressed snapshot ids are shared across shares, so a naive per-share // content-addressed snapshot ids are shared across shares, so a naive per-share
// refcount can undercount a chunk that two share heads both need. // refcount can undercount a chunk that two share heads both need.
func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err error) { func runGC(db *meta.DB, store blobstore.Store, keep int, dryRun bool) (snaps, chunks int, err error) {
shares, err := db.ShareNames() shares, err := db.ShareNames()
if err != nil { if err != nil {
return 0, 0, err return 0, 0, err
@ -447,6 +459,39 @@ func runGC(db *meta.DB, store blobstore.Store, keep int) (snaps, chunks int, err
} }
} }
// --dry-run: report what WOULD be pruned without mutating. Deletable chunks are
// those a pruned manifest references but no kept snapshot does, plus any
// pre-existing orphan (refcount<=0) that's also unreachable — the same set the
// real sweep removes, computed from reachability (refcount ground truth).
if dryRun {
del := map[string]bool{}
for _, p := range prunable {
if keptSnaps[p.id] {
continue
}
snaps++
hashes, err := manifestChunks(store, p.id)
if err != nil && err != blobstore.ErrNotFound {
return 0, 0, err
}
for _, h := range hashes {
if !reachable[h] {
del[h] = true
}
}
}
unref, err := db.UnreferencedChunks()
if err != nil {
return 0, 0, err
}
for _, h := range unref {
if !reachable[h] {
del[h] = true
}
}
return snaps, len(del), nil
}
// Prune each (share, id): delete that share's row and decrement its chunks. The // Prune each (share, id): delete that share's row and decrement its chunks. The
// same content id in another share keeps its own row and counts. Delete the // same content id in another share keeps its own row and counts. Delete the
// shared manifest blob at most once, and only when it's unreachable from any // shared manifest blob at most once, and only when it's unreachable from any

View file

@ -6,10 +6,12 @@
package dashboard package dashboard
import ( import (
"crypto/subtle"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"strings"
"sync" "sync"
"time" "time"
@ -57,6 +59,7 @@ type Dashboard struct {
version string version string
started time.Time started time.Time
broker *broker broker *broker
token string // optional shared secret; "" = unauthenticated (loopback default)
mu sync.Mutex mu sync.Mutex
lastSeen map[string]int64 // deviceID -> unix seconds of its last activity lastSeen map[string]int64 // deviceID -> unix seconds of its last activity
@ -68,6 +71,11 @@ func New(db *meta.DB, version string) *Dashboard {
return &Dashboard{db: db, version: version, started: time.Now(), broker: newBroker(), lastSeen: map[string]int64{}} return &Dashboard{db: db, version: version, started: time.Now(), broker: newBroker(), lastSeen: map[string]int64{}}
} }
// SetToken requires callers to present the token (so a non-loopback dashboard
// isn't world-readable). Empty token leaves it open. Must be called before
// Handler.
func (d *Dashboard) SetToken(tok string) { d.token = tok }
// Emit records device activity and fans the event out to connected dashboards. // Emit records device activity and fans the event out to connected dashboards.
// Safe on a nil receiver (dashboard disabled) so hub handlers call it freely. // Safe on a nil receiver (dashboard disabled) so hub handlers call it freely.
func (d *Dashboard) Emit(ev Event) { func (d *Dashboard) Emit(ev Event) {
@ -141,7 +149,47 @@ func (d *Dashboard) Handler() http.Handler {
}) })
mux.HandleFunc("GET /api/state", d.handleState) mux.HandleFunc("GET /api/state", d.handleState)
mux.HandleFunc("GET /api/events", d.handleEvents) mux.HandleFunc("GET /api/events", d.handleEvents)
return mux return d.withAuth(mux)
}
const dashCookie = "devbox_dash"
// withAuth gates the dashboard behind d.token when one is set. The token may be
// presented as `?token=`, an `Authorization: Bearer` header (for scripts), or a
// cookie. A `?token=` on any request pins an HttpOnly cookie so the embedded
// page's fetch()/EventSource calls — which can't set headers — authenticate
// automatically; this keeps index.html untouched. Open (no token) → pass-through.
func (d *Dashboard) withAuth(next http.Handler) http.Handler {
if d.token == "" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if q := r.URL.Query().Get("token"); q != "" && tokenEqual(q, d.token) {
http.SetCookie(w, &http.Cookie{Name: dashCookie, Value: d.token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode})
if r.URL.Path == "/" { // drop the secret from the address bar / history
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
return
}
const bp = "Bearer "
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, bp) && tokenEqual(h[len(bp):], d.token) {
next.ServeHTTP(w, r)
return
}
if ck, err := r.Cookie(dashCookie); err == nil && tokenEqual(ck.Value, d.token) {
next.ServeHTTP(w, r)
return
}
w.Header().Set("WWW-Authenticate", `Bearer realm="devbox dashboard"`)
http.Error(w, "unauthorized — open the dashboard with ?token=<dashboard token>", http.StatusUnauthorized)
})
}
// tokenEqual compares in constant time so a wrong guess leaks no length/prefix timing.
func tokenEqual(a, b string) bool {
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
} }
type stateResp struct { type stateResp struct {

View file

@ -91,6 +91,48 @@ func TestStateAndEvents(t *testing.T) {
t.Fatal("did not receive the push event over SSE") t.Fatal("did not receive the push event over SSE")
} }
// TestDashboardAuth covers SetToken: open API calls are rejected, while the
// token via query param or Authorization header is accepted (and a wrong one isn't).
func TestDashboardAuth(t *testing.T) {
db, err := meta.Open(":memory:")
if err != nil {
t.Fatal(err)
}
defer db.Close()
d := New(db, "t")
d.SetToken("s3cret")
srv := httptest.NewServer(d.Handler())
defer srv.Close()
c := srv.Client()
get := func(url string, bearer string) int {
req, _ := http.NewRequest(http.MethodGet, url, nil)
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
r, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
r.Body.Close()
return r.StatusCode
}
if code := get(srv.URL+"/api/state", ""); code != http.StatusUnauthorized {
t.Fatalf("no token: got %d, want 401", code)
}
if code := get(srv.URL+"/api/state", "wrong"); code != http.StatusUnauthorized {
t.Fatalf("wrong bearer: got %d, want 401", code)
}
if code := get(srv.URL+"/api/state", "s3cret"); code != http.StatusOK {
t.Fatalf("correct bearer: got %d, want 200", code)
}
if code := get(srv.URL+"/api/state?token=s3cret", ""); code != http.StatusOK {
t.Fatalf("query token: got %d, want 200", code)
}
}
// TestEmitNilSafe documents that hub handlers can Emit unconditionally. // TestEmitNilSafe documents that hub handlers can Emit unconditionally.
func TestEmitNilSafe(t *testing.T) { func TestEmitNilSafe(t *testing.T) {
var d *Dashboard var d *Dashboard

View file

@ -79,9 +79,31 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST "+proto.PathInvite, s.auth(s.handleInvite)) mux.HandleFunc("POST "+proto.PathInvite, s.auth(s.handleInvite))
mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents)) mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents))
mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics) mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics)
mux.HandleFunc("GET /healthz", s.handleHealthz)
mux.HandleFunc("GET /readyz", s.handleReadyz)
return mux return mux
} }
// handleHealthz is a liveness probe: the process is up and serving. No auth, no
// I/O — for Docker HEALTHCHECK and load balancers (the compose selfheal profile
// restarts on unhealthy). /readyz is the deeper check.
func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "ok")
}
// handleReadyz is a readiness probe: 200 only if the metadata DB answers a cheap
// query, else 503 so an orchestrator can hold traffic off a hub that's up but
// whose DB is locked/unreachable (which /metrics, also a Count, can't signal as 503).
func (s *Server) handleReadyz(w http.ResponseWriter, _ *http.Request) {
if _, err := s.db.Count("devices"); err != nil {
http.Error(w, "not ready: "+err.Error(), http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, "ready")
}
// auth wraps a handler, requiring a valid "Authorization: Bearer <tok>" that // auth wraps a handler, requiring a valid "Authorization: Bearer <tok>" that
// resolves to a non-revoked device. The device id is stashed in the request // resolves to a non-revoked device. The device id is stashed in the request
// context for the wrapped handler. // context for the wrapped handler.