From 3cfef72a88b2c0c77d2ecda6252dfd47913358b7 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Mon, 22 Jun 2026 23:54:55 -0500 Subject: [PATCH] =?UTF-8?q?harden(M2->M3):=20parent-aware=20push=20+=20has?= =?UTF-8?q?hed=20bearers=20+=20blob=20download=20=F0=9F=94=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the M2 ponytail review (the load-bearing findings): - hub push now enforces parent==head: re-push=idempotent, parent==head=fast-forward, else Conflict (never clobbers head) โ€” the foundation M3 conflict resolution needs - bearers stored as sha256 (like join tokens), no plaintext creds at rest / timing oracle - GET /v1/blob/{hash} download + client.GetBlob โ€” pull needs it - randHex propagates crypto/rand errors (no silent low-entropy tokens) - syncer/publish are head-aware and surface conflicts - tests: conflict-when-behind (head not clobbered), manifest download+parse Kept rw-by-default (intentional single-owner v1 per spec ยง6). --- cmd/devbox-hub/main.go | 13 +++-- cmd/devbox/main.go | 9 +++- internal/hub/server.go | 42 +++++++++++++++- internal/syncer/syncer.go | 2 + internal/syncer/syncer_test.go | 90 ++++++++++++++++++++++++++++++++++ internal/transport/client.go | 22 +++++++++ 6 files changed, 171 insertions(+), 7 deletions(-) diff --git a/cmd/devbox-hub/main.go b/cmd/devbox-hub/main.go index e93cebb..8a3494c 100644 --- a/cmd/devbox-hub/main.go +++ b/cmd/devbox-hub/main.go @@ -87,7 +87,10 @@ func tokenCmd() *cobra.Command { return err } defer db.Close() - raw := randHex(16) + raw, err := randHex(16) + if err != nil { + return err + } if err := db.CreateToken(hub.HashToken(raw), time.Now().Add(ttl).Unix()); err != nil { return err } @@ -152,8 +155,10 @@ func revokeCmd() *cobra.Command { return cmd } -func randHex(n int) string { +func randHex(n int) (string, error) { b := make([]byte, n) - rand.Read(b) - return hex.EncodeToString(b) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil } diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index a62d357..7c62dfb 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -121,10 +121,17 @@ func publishCmd() *cobra.Command { if err != nil { return err } - res, err := syncer.Push(c, root, share, ig, guard, "") + head, err := c.Head(share) if err != nil { return err } + res, err := syncer.Push(c, root, share, ig, guard, head) + if err != nil { + return err + } + if res.Conflict { + return fmt.Errorf("share %q advanced on the hub (head %s) โ€” pull/merge lands in M3", share, short(res.Head)) + } out := cmd.OutOrStdout() fmt.Fprintf(out, "๐Ÿ“ค pushed %d files to %q\n", res.Files, share) diff --git a/internal/hub/server.go b/internal/hub/server.go index 0ca5039..a7cfdff 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -8,6 +8,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -39,6 +40,13 @@ func HashToken(token string) string { return hex.EncodeToString(sum[:]) } +// hashBearer hashes a bearer the same way, so the hub stores only the hash (no +// plaintext credentials at rest) and lookup compares fixed-width hashes. +func hashBearer(bearer string) string { + sum := sha256.Sum256([]byte(bearer)) + return hex.EncodeToString(sum[:]) +} + // Handler returns the hub's HTTP routes. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() @@ -46,6 +54,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST "+proto.PathPublish, s.auth(s.handlePublish)) mux.HandleFunc("POST "+proto.PathHave, s.auth(s.handleHave)) mux.HandleFunc("PUT "+proto.PathBlob+"{hash}", s.auth(s.handleBlob)) + mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob)) mux.HandleFunc("POST "+proto.PathPush, s.auth(s.handlePush)) mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead)) mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics) @@ -63,7 +72,7 @@ func (s *Server) auth(next func(http.ResponseWriter, *http.Request, string)) htt writeErr(w, http.StatusUnauthorized, "missing bearer token") return } - deviceID, ok, err := s.db.DeviceByBearer(h[len(prefix):]) + deviceID, ok, err := s.db.DeviceByBearer(hashBearer(h[len(prefix):])) if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return @@ -102,7 +111,7 @@ func (s *Server) handleJoin(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, err.Error()) return } - if err := s.db.IssueBearer(deviceID, bearer); err != nil { + if err := s.db.IssueBearer(deviceID, hashBearer(bearer)); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } @@ -140,6 +149,21 @@ func (s *Server) handleHave(w http.ResponseWriter, r *http.Request, _ string) { writeJSON(w, http.StatusOK, proto.HaveResponse{Missing: missing}) } +// handleGetBlob serves a blob's bytes for download (pull fetches manifests + chunks). +func (s *Server) handleGetBlob(w http.ResponseWriter, r *http.Request, _ string) { + b, err := s.store.Get(r.PathValue("hash")) + if errors.Is(err, blobstore.ErrNotFound) { + writeErr(w, http.StatusNotFound, "no such blob") + return + } + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Write(b) +} + func (s *Server) handleBlob(w http.ResponseWriter, r *http.Request, _ string) { hash := r.PathValue("hash") body, err := io.ReadAll(r.Body) @@ -173,6 +197,20 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID str return } + // Conflict detection: a push must extend the current head (or replay it). + // Re-pushing the existing head is idempotent; a push whose parent IS the + // current head fast-forwards; anything else means the device is behind and + // must pull + reconcile (M3) before pushing again โ€” we never clobber head. + head, _, err := s.db.ShareHead(req.Share) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if req.ManifestHash != head && req.Parent != head { + writeJSON(w, http.StatusOK, proto.PushResponse{Head: head, Conflict: true}) + return + } + // The manifest blob and every referenced chunk must already be uploaded. if missing, err := s.missingBlob(req.ManifestHash); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) diff --git a/internal/syncer/syncer.go b/internal/syncer/syncer.go index dcd0bdb..c48d4ea 100644 --- a/internal/syncer/syncer.go +++ b/internal/syncer/syncer.go @@ -23,6 +23,7 @@ type Result struct { Blocked []string // secret files refused upload Uploaded int // blobs actually uploaded (the hub lacked) Files int // files in the manifest + Conflict bool // hub rejected the push: device is behind head (pull + reconcile) } // Push builds a manifest of root (filtered by ig + guard), uploads any blobs the @@ -94,6 +95,7 @@ func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *se Blocked: blocked, Uploaded: len(missing), Files: len(m.Entries), + Conflict: resp.Conflict, }, nil } diff --git a/internal/syncer/syncer_test.go b/internal/syncer/syncer_test.go index b13a51a..c64ad68 100644 --- a/internal/syncer/syncer_test.go +++ b/internal/syncer/syncer_test.go @@ -12,10 +12,29 @@ import ( "git.shoemoney.ai/shoemoney/devbox/internal/hub" "git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore" "git.shoemoney.ai/shoemoney/devbox/internal/hub/meta" + "git.shoemoney.ai/shoemoney/devbox/internal/manifest" "git.shoemoney.ai/shoemoney/devbox/internal/secret" "git.shoemoney.ai/shoemoney/devbox/internal/transport" ) +// joinDevice enrolls a fresh device against srv with a freshly-minted token. +func joinDevice(t *testing.T, db *meta.DB, baseURL, name string) *transport.Client { + t.Helper() + tok := name + "-tok" + if err := db.CreateToken(hub.HashToken(tok), time.Now().Unix()+3600); err != nil { + t.Fatal(err) + } + c := transport.New(baseURL) + pub, _, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + if _, err := c.Join(tok, name, pub); err != nil { + t.Fatalf("join %s: %v", name, err) + } + return c +} + func writeFile(t *testing.T, root, rel, content string) { t.Helper() p := filepath.Join(root, filepath.FromSlash(rel)) @@ -102,6 +121,19 @@ func TestPushEndToEnd(t *testing.T) { t.Fatalf("hub head %q != pushed snapshot %q", head, res.Snapshot) } + // Pull foundation: the manifest blob downloads and parses back to 3 entries. + manBytes, err := c.GetBlob(res.Snapshot) + if err != nil { + t.Fatalf("get manifest blob: %v", err) + } + gotManifest, err := manifest.Unmarshal(manBytes) + if err != nil { + t.Fatalf("unmarshal manifest: %v", err) + } + if len(gotManifest.Entries) != 3 { + t.Fatalf("downloaded manifest has %d entries, want 3", len(gotManifest.Entries)) + } + // Second push of the unchanged tree: dedup means zero blobs uploaded and the // same content-addressed snapshot id. res2, err := Push(c, root, "projects", ig, guard, res.Head) @@ -115,3 +147,61 @@ func TestPushEndToEnd(t *testing.T) { t.Fatalf("identical tree gave different snapshot: %q vs %q", res2.Snapshot, res.Snapshot) } } + +// TestPushConflictWhenBehind proves the M3 invariant: a device that is behind the +// share head cannot clobber it โ€” the hub returns a conflict and keeps the head. +func TestPushConflictWhenBehind(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() + + guard, _ := secret.New(nil) + ig, _ := LoadIgnore(t.TempDir()) // empty matcher + + // Device A publishes and pushes treeA -> head = snapA. + a := joinDevice(t, db, srv.URL, "alice") + if err := a.Publish("shared"); err != nil { + t.Fatal(err) + } + rootA := t.TempDir() + writeFile(t, rootA, "a.txt", "from alice\n") + resA, err := Push(a, rootA, "shared", ig, guard, "") + if err != nil { + t.Fatalf("A push: %v", err) + } + if resA.Conflict { + t.Fatal("A's first push should not conflict") + } + + // Device B, unaware of A's snapshot, pushes a different tree with parent="". + b := joinDevice(t, db, srv.URL, "bob") + rootB := t.TempDir() + writeFile(t, rootB, "b.txt", "from bob\n") + resB, err := Push(b, rootB, "shared", ig, guard, "") + if err != nil { + t.Fatalf("B push: %v", err) + } + if !resB.Conflict { + t.Fatal("B is behind head and must get a conflict, not clobber A's head") + } + if resB.Head != resA.Snapshot { + t.Fatalf("conflict head = %q, want A's snapshot %q", resB.Head, resA.Snapshot) + } + + // A's head must be intact โ€” B did not clobber it. + head, err := a.Head("shared") + if err != nil { + t.Fatal(err) + } + if head != resA.Snapshot { + t.Fatalf("head clobbered: %q, want %q", head, resA.Snapshot) + } +} diff --git a/internal/transport/client.go b/internal/transport/client.go index 92748aa..1e1a603 100644 --- a/internal/transport/client.go +++ b/internal/transport/client.go @@ -73,6 +73,28 @@ func (c *Client) PutBlob(hash string, data []byte) error { return c.raw(http.MethodPut, proto.PathBlob+hash, data) } +// GetBlob downloads one blob's raw bytes by content hash (used by pull). +func (c *Client) GetBlob(hash string) ([]byte, error) { + req, err := http.NewRequest(http.MethodGet, c.base+proto.PathBlob+hash, nil) + if err != nil { + return nil, err + } + req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer) + resp, err := c.hc.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, apiError(resp.StatusCode, body) + } + return body, nil +} + // Push commits a snapshot. Its manifest and chunk blobs must already be uploaded. func (c *Client) Push(req proto.PushRequest) (proto.PushResponse, error) { var resp proto.PushResponse