feat(M2): hub server + transport client + push engine + CLI 🛰️
- internal/hub: HTTP server (join/publish/have/blob/push/head/metrics), bearer auth, blob hash-verify, hand-rolled Prometheus /metrics (no dep) - internal/transport: device HTTP client for the full wire contract - internal/syncer: device push engine (build manifest -> upload missing blobs -> commit snapshot) + .devignore loader; in-process e2e test (join->publish->push) - meta: idempotent AddSnapshot (content-addressed re-push advances head, no double refcount) + busy_timeout for multi-process CLI access - cmd/devbox-hub: serve/token/readonly/revoke; cmd/devbox: real join + publish/push - config: persist bearer + device id Verified end-to-end with real binaries: secret blocked, node_modules ignored, re-publish dedups to 0 uploads.
This commit is contained in:
parent
f6e1f91d67
commit
55175fa2ac
11 changed files with 1346 additions and 16 deletions
|
|
@ -2,10 +2,19 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
||||
)
|
||||
|
||||
var version = "0.0.0-dev"
|
||||
|
|
@ -23,8 +32,10 @@ func main() {
|
|||
Short: "print version",
|
||||
Run: func(c *cobra.Command, _ []string) { fmt.Fprintln(c.OutOrStdout(), "devbox-hub", version) },
|
||||
},
|
||||
hubStub("serve", "🚀 run the hub server", "M2"),
|
||||
hubStub("token", "🎟️ mint/rotate the join token", "M2"),
|
||||
serveCmd(),
|
||||
tokenCmd(),
|
||||
readonlyCmd(),
|
||||
revokeCmd(),
|
||||
)
|
||||
if err := root.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
|
|
@ -32,12 +43,117 @@ func main() {
|
|||
}
|
||||
}
|
||||
|
||||
func hubStub(use, short, milestone string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use,
|
||||
Short: short,
|
||||
RunE: func(*cobra.Command, []string) error {
|
||||
return fmt.Errorf("%q not implemented yet (arrives in %s)", use, milestone)
|
||||
// openDB opens the hub metadata DB under data/.
|
||||
func openDB(data string) (*meta.DB, error) {
|
||||
if err := os.MkdirAll(data, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meta.Open(filepath.Join(data, "devbox-hub.db"))
|
||||
}
|
||||
|
||||
func serveCmd() *cobra.Command {
|
||||
var data, listen string
|
||||
cmd := &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "🚀 run the hub server",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
db, err := openDB(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store, err := blobstore.NewDisk(filepath.Join(data, "blobs"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := hub.NewServer(db, store)
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "🛰️ devbox-hub listening on %s (data: %s)\n", listen, data)
|
||||
return http.ListenAndServe(listen, srv.Handler())
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||
cmd.Flags().StringVar(&listen, "listen", ":8080", "listen address")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func tokenCmd() *cobra.Command {
|
||||
var data string
|
||||
var ttl time.Duration
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
Short: "🎟️ mint a one-time join token",
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
db, err := openDB(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
raw := randHex(16)
|
||||
if err := db.CreateToken(hub.HashToken(raw), time.Now().Add(ttl).Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(cmd.OutOrStdout(), raw)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||
cmd.Flags().DurationVar(&ttl, "ttl", time.Hour, "token validity window")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func readonlyCmd() *cobra.Command {
|
||||
var data string
|
||||
var rw bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "readonly <device> <share>",
|
||||
Short: "🔒 make a device read-only on a share (--rw to restore)",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
db, err := openDB(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.SetWritable(args[0], args[1], rw); err != nil {
|
||||
return err
|
||||
}
|
||||
mode := "read-only"
|
||||
if rw {
|
||||
mode = "read-write"
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "device %s is now %s on %s\n", args[0], mode, args[1])
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||
cmd.Flags().BoolVar(&rw, "rw", false, "restore read-write instead")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func revokeCmd() *cobra.Command {
|
||||
var data string
|
||||
cmd := &cobra.Command{
|
||||
Use: "revoke <device>",
|
||||
Short: "❌ revoke a device (its bearer dies immediately)",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
db, err := openDB(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Revoke(args[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(cmd.OutOrStdout(), "revoked %s\n", args[0])
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func randHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,9 @@ import (
|
|||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/config"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/identity"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/secret"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/syncer"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||
)
|
||||
|
||||
var version = "0.0.0-dev"
|
||||
|
|
@ -23,11 +26,11 @@ func main() {
|
|||
}
|
||||
root.AddCommand(
|
||||
joinCmd(),
|
||||
publishCmd(),
|
||||
statusCmd(),
|
||||
versionCmd(),
|
||||
stub("start", "▶️ run the sync daemon", "M3"),
|
||||
stub("stop", "⏹️ stop the sync daemon", "M3"),
|
||||
stub("publish", "📂 create a share from a local folder", "M2"),
|
||||
)
|
||||
if err := root.Execute(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
|
|
@ -51,6 +54,7 @@ func joinCmd() *cobra.Command {
|
|||
Short: "🎟️ enroll this device against a hub",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
hubURL, token := args[0], args[1]
|
||||
dir, err := config.Dir()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -59,18 +63,76 @@ func joinCmd() *cobra.Command {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name, _ := os.Hostname()
|
||||
|
||||
c := transport.New(hubURL)
|
||||
resp, err := c.Join(token, name, id.Pub)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d, err := config.LoadDaemon(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.Hub = args[0]
|
||||
d.Hub, d.DeviceID, d.Bearer = hubURL, resp.DeviceID, resp.Bearer
|
||||
if err := config.SaveDaemon(dir, d); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
out := cmd.OutOrStdout()
|
||||
fmt.Fprintf(out, "device fingerprint: %s\n", id.Fingerprint())
|
||||
fmt.Fprintf(out, "hub: %s\n", args[0])
|
||||
fmt.Fprintln(out, "✅ identity ready. (hub handshake lands in M2)")
|
||||
fmt.Fprintf(out, "device: %s\n", resp.DeviceID)
|
||||
fmt.Fprintf(out, "hub: %s\n", hubURL)
|
||||
fmt.Fprintln(out, "✅ joined")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func publishCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "publish <localdir> <share>",
|
||||
Short: "📂 create a share from a local folder and push it",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
root, share := args[0], args[1]
|
||||
dir, err := config.Dir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := config.LoadDaemon(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Hub == "" || d.Bearer == "" {
|
||||
return fmt.Errorf("not joined — run: devbox join <hub> <token>")
|
||||
}
|
||||
|
||||
c := transport.New(d.Hub)
|
||||
c.SetBearer(d.Bearer)
|
||||
if err := c.Publish(share); err != nil {
|
||||
return err
|
||||
}
|
||||
ig, err := syncer.LoadIgnore(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
guard, err := secret.New(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := syncer.Push(c, root, share, ig, guard, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
out := cmd.OutOrStdout()
|
||||
fmt.Fprintf(out, "📤 pushed %d files to %q\n", res.Files, share)
|
||||
fmt.Fprintf(out, "🧊 uploaded %d blobs (rest deduped)\n", res.Uploaded)
|
||||
if len(res.Blocked) > 0 {
|
||||
fmt.Fprintf(out, "🔐 %d secret(s) blocked from upload: %v\n", len(res.Blocked), res.Blocked)
|
||||
}
|
||||
fmt.Fprintf(out, "📸 snapshot %s\n", short(res.Snapshot))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
|
@ -117,6 +179,13 @@ func orNone(s string) string {
|
|||
return s
|
||||
}
|
||||
|
||||
func short(s string) string {
|
||||
if len(s) > 12 {
|
||||
return s[:12]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func stub(use, short, milestone string) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: use,
|
||||
|
|
|
|||
|
|
@ -40,10 +40,13 @@ type Mount struct {
|
|||
ReadOnly bool `toml:"readonly,omitempty"`
|
||||
}
|
||||
|
||||
// Daemon is daemon.toml: which hub this device joined and what it mounts.
|
||||
// Daemon is daemon.toml: which hub this device joined (with its bearer token and
|
||||
// device id) and what it mounts.
|
||||
type Daemon struct {
|
||||
Hub string `toml:"hub,omitempty"`
|
||||
Mounts []Mount `toml:"mount"`
|
||||
Hub string `toml:"hub,omitempty"`
|
||||
DeviceID string `toml:"device_id,omitempty"`
|
||||
Bearer string `toml:"bearer,omitempty"`
|
||||
Mounts []Mount `toml:"mount"`
|
||||
}
|
||||
|
||||
func daemonPath(dir string) string { return filepath.Join(dir, "daemon.toml") }
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import (
|
|||
|
||||
const schema = `
|
||||
PRAGMA journal_mode=WAL;
|
||||
PRAGMA busy_timeout=5000;
|
||||
PRAGMA foreign_keys=ON;
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
id TEXT PRIMARY KEY,
|
||||
|
|
@ -233,6 +234,20 @@ func (d *DB) AddSnapshot(s Snapshot, chunks []ChunkRef) error {
|
|||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Snapshots are content-addressed, so re-pushing an unchanged tree (or
|
||||
// reverting to a prior state) replays an existing id. That's idempotent:
|
||||
// advance the head to it, but never re-insert or double-count chunk refs.
|
||||
var one int
|
||||
switch err := tx.QueryRow(`SELECT 1 FROM snapshots WHERE id=?`, s.ID).Scan(&one); {
|
||||
case err == nil:
|
||||
if _, err := tx.Exec(`UPDATE shares SET head_snapshot=? WHERE name=?`, s.ID, s.Share); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(
|
||||
`INSERT INTO snapshots (id, share, parent_id, device_id, created_at, manifest_hash)
|
||||
VALUES (?,?,?,?,?,?)`,
|
||||
|
|
|
|||
|
|
@ -109,4 +109,16 @@ func TestSharesSnapshotsRefcounts(t *testing.T) {
|
|||
if head, _, _ := db.ShareHead("projects"); head != "snap2" {
|
||||
t.Fatalf("head = %q, want snap2", head)
|
||||
}
|
||||
|
||||
// Re-adding an existing snapshot is idempotent: no error, no double-count,
|
||||
// but it advances head (a revert to snap1's content).
|
||||
if err := db.AddSnapshot(s1, []ChunkRef{{"h1", 5}, {"h2", 6}}); err != nil {
|
||||
t.Fatalf("idempotent re-add failed: %v", err)
|
||||
}
|
||||
if rc, _ := db.ChunkRefcount("h1"); rc != 2 {
|
||||
t.Fatalf("h1 refcount = %d after re-add, want 2 (no double-count)", rc)
|
||||
}
|
||||
if head, _, _ := db.ShareHead("projects"); head != "snap1" {
|
||||
t.Fatalf("head = %q after re-add, want snap1 (revert)", head)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
277
internal/hub/server.go
Normal file
277
internal/hub/server.go
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
// Package hub is the devbox hub HTTP server: device enrollment, content-addressed
|
||||
// blob upload, snapshot push, and head queries over JSON/HTTP with bearer auth.
|
||||
package hub
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/chunk"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/identity"
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// Server is the devbox hub: metadata in db, blob bytes in store.
|
||||
type Server struct {
|
||||
db *meta.DB
|
||||
store blobstore.Store
|
||||
}
|
||||
|
||||
// NewServer builds a hub server over the given metadata store and blob store.
|
||||
func NewServer(db *meta.DB, store blobstore.Store) *Server {
|
||||
return &Server{db: db, store: store}
|
||||
}
|
||||
|
||||
// HashToken returns hex(sha256(token)); the token-mint CLI reuses it so the hub
|
||||
// only ever stores token hashes, never the tokens themselves.
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Handler returns the hub's HTTP routes.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST "+proto.PathJoin, s.handleJoin)
|
||||
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("POST "+proto.PathPush, s.auth(s.handlePush))
|
||||
mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead))
|
||||
mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics)
|
||||
return mux
|
||||
}
|
||||
|
||||
// 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
|
||||
// context for the wrapped handler.
|
||||
func (s *Server) auth(next func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
const prefix = "Bearer "
|
||||
h := r.Header.Get(proto.AuthHeader)
|
||||
if len(h) <= len(prefix) || h[:len(prefix)] != prefix {
|
||||
writeErr(w, http.StatusUnauthorized, "missing bearer token")
|
||||
return
|
||||
}
|
||||
deviceID, ok, err := s.db.DeviceByBearer(h[len(prefix):])
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "invalid bearer token")
|
||||
return
|
||||
}
|
||||
next(w, r, deviceID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleJoin(w http.ResponseWriter, r *http.Request) {
|
||||
var req proto.JoinRequest
|
||||
if !decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
deviceID := identity.FingerprintOf(ed25519.PublicKey(req.Pubkey))
|
||||
|
||||
ok, err := s.db.RedeemToken(HashToken(req.Token), now)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
writeErr(w, http.StatusUnauthorized, "invalid or expired join token")
|
||||
return
|
||||
}
|
||||
if err := s.db.AddDevice(deviceID, req.Name, req.Pubkey, now); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
bearer, err := randomBearer()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.db.IssueBearer(deviceID, bearer); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, proto.JoinResponse{DeviceID: deviceID, Bearer: bearer})
|
||||
}
|
||||
|
||||
func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID string) {
|
||||
var req proto.PublishRequest
|
||||
if !decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if err := s.db.CreateShare(req.Share, deviceID, time.Now().Unix()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s *Server) handleHave(w http.ResponseWriter, r *http.Request, _ string) {
|
||||
var req proto.HaveRequest
|
||||
if !decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
var missing []string
|
||||
for _, h := range req.Hashes {
|
||||
has, err := s.store.Has(h)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if !has {
|
||||
missing = append(missing, h)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, proto.HaveResponse{Missing: missing})
|
||||
}
|
||||
|
||||
func (s *Server) handleBlob(w http.ResponseWriter, r *http.Request, _ string) {
|
||||
hash := r.PathValue("hash")
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if chunk.Hash(body) != hash {
|
||||
writeErr(w, http.StatusBadRequest, "body does not match hash")
|
||||
return
|
||||
}
|
||||
if err := s.store.Put(hash, body); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (s *Server) handlePush(w http.ResponseWriter, r *http.Request, deviceID string) {
|
||||
var req proto.PushRequest
|
||||
if !decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
writable, err := s.db.Writable(deviceID, req.Share)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if !writable {
|
||||
writeErr(w, http.StatusForbidden, "device is read-only on this share")
|
||||
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())
|
||||
return
|
||||
} else if missing {
|
||||
writeErr(w, http.StatusConflict, "missing manifest blob "+req.ManifestHash)
|
||||
return
|
||||
}
|
||||
chunks := make([]meta.ChunkRef, 0, len(req.Chunks))
|
||||
for _, c := range req.Chunks {
|
||||
if missing, err := s.missingBlob(c.Hash); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
} else if missing {
|
||||
writeErr(w, http.StatusConflict, "missing chunk blob "+c.Hash)
|
||||
return
|
||||
}
|
||||
chunks = append(chunks, meta.ChunkRef{Hash: c.Hash, Size: c.Size})
|
||||
}
|
||||
|
||||
snapshotID := req.ManifestHash
|
||||
snap := meta.Snapshot{
|
||||
ID: snapshotID,
|
||||
Share: req.Share,
|
||||
ParentID: req.Parent,
|
||||
DeviceID: deviceID,
|
||||
ManifestHash: req.ManifestHash,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
if err := s.db.AddSnapshot(snap, chunks); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, proto.PushResponse{Snapshot: snapshotID, Head: snapshotID, Conflict: false})
|
||||
}
|
||||
|
||||
// missingBlob reports whether the store lacks a blob with this hash.
|
||||
func (s *Server) missingBlob(hash string) (bool, error) {
|
||||
has, err := s.store.Has(hash)
|
||||
return !has, err
|
||||
}
|
||||
|
||||
func (s *Server) handleHead(w http.ResponseWriter, r *http.Request, _ string) {
|
||||
head, _, err := s.db.ShareHead(r.URL.Query().Get("share"))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, proto.HeadResponse{Head: head})
|
||||
}
|
||||
|
||||
func (s *Server) handleMetrics(w http.ResponseWriter, _ *http.Request) {
|
||||
gauges := []struct {
|
||||
name, table, help string
|
||||
}{
|
||||
{"devbox_devices", "devices", "Number of enrolled devices."},
|
||||
{"devbox_shares", "shares", "Number of shares."},
|
||||
{"devbox_snapshots", "snapshots", "Number of snapshots."},
|
||||
{"devbox_chunks", "chunks", "Number of distinct chunks."},
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
||||
for _, g := range gauges {
|
||||
n, err := s.db.Count(g.table)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "# HELP %s %s\n", g.name, g.help)
|
||||
fmt.Fprintf(w, "# TYPE %s gauge\n", g.name)
|
||||
fmt.Fprintf(w, "%s %s\n", g.name, strconv.FormatInt(n, 10))
|
||||
}
|
||||
}
|
||||
|
||||
// randomBearer returns 32 random bytes hex-encoded.
|
||||
func randomBearer() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// decode reads a JSON request body into v, writing a 400 on failure.
|
||||
func decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// writeJSON writes v as JSON with the given status.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// writeErr writes a proto.Error JSON body with the given status.
|
||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, proto.Error{Error: msg})
|
||||
}
|
||||
225
internal/hub/server_test.go
Normal file
225
internal/hub/server_test.go
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
package hub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/chunk"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/blobstore"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/hub/meta"
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// testHub spins a live httptest.Server backed by an in-memory meta DB and a
|
||||
// temp-dir blobstore. It returns the base URL and the DB for assertions.
|
||||
func testHub(t *testing.T) (string, *meta.DB) {
|
||||
t.Helper()
|
||||
db, err := meta.Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("meta.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
store, err := blobstore.NewDisk(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("NewDisk: %v", err)
|
||||
}
|
||||
srv := httptest.NewServer(NewServer(db, store).Handler())
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL, db
|
||||
}
|
||||
|
||||
// do issues a request and returns its status and body. authBearer is sent as a
|
||||
// Bearer token when non-empty.
|
||||
func do(t *testing.T, method, url, authBearer string, body []byte) (int, []byte) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
rdr = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequest(method, url, rdr)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRequest: %v", err)
|
||||
}
|
||||
if authBearer != "" {
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+authBearer)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v", method, url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, b
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, v any) []byte {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestHubHappyPath(t *testing.T) {
|
||||
base, db := testHub(t)
|
||||
now := time.Now().Unix()
|
||||
|
||||
// 1. Mint a join token, then join with a real ed25519 pubkey.
|
||||
if err := db.CreateToken(HashToken("jointok"), now+3600); err != nil {
|
||||
t.Fatalf("CreateToken: %v", err)
|
||||
}
|
||||
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKey: %v", err)
|
||||
}
|
||||
status, body := do(t, "POST", base+proto.PathJoin, "", mustJSON(t, proto.JoinRequest{
|
||||
Token: "jointok",
|
||||
Name: "laptop",
|
||||
Pubkey: pub,
|
||||
}))
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("join status = %d, body = %s", status, body)
|
||||
}
|
||||
var join proto.JoinResponse
|
||||
if err := json.Unmarshal(body, &join); err != nil {
|
||||
t.Fatalf("decode join: %v", err)
|
||||
}
|
||||
if join.DeviceID == "" || join.Bearer == "" {
|
||||
t.Fatalf("join returned empty fields: %+v", join)
|
||||
}
|
||||
bearer := join.Bearer
|
||||
|
||||
if n, err := db.Count("devices"); err != nil || n != 1 {
|
||||
t.Fatalf("device count = %d (err %v), want 1", n, err)
|
||||
}
|
||||
|
||||
// 2. Publish a share; then have/upload two chunk blobs.
|
||||
const share = "proj"
|
||||
if status, body := do(t, "POST", base+proto.PathPublish, bearer, mustJSON(t, proto.PublishRequest{Share: share})); status != http.StatusOK {
|
||||
t.Fatalf("publish status = %d, body = %s", status, body)
|
||||
}
|
||||
|
||||
blobA := bytes.Repeat([]byte("a"), 100)
|
||||
blobB := bytes.Repeat([]byte("b"), 200)
|
||||
hashA, hashB := chunk.Hash(blobA), chunk.Hash(blobB)
|
||||
|
||||
status, body = do(t, "POST", base+proto.PathHave, bearer, mustJSON(t, proto.HaveRequest{Hashes: []string{hashA, hashB}}))
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("have status = %d, body = %s", status, body)
|
||||
}
|
||||
var have proto.HaveResponse
|
||||
if err := json.Unmarshal(body, &have); err != nil {
|
||||
t.Fatalf("decode have: %v", err)
|
||||
}
|
||||
if len(have.Missing) != 2 {
|
||||
t.Fatalf("missing = %v, want both", have.Missing)
|
||||
}
|
||||
|
||||
for h, b := range map[string][]byte{hashA: blobA, hashB: blobB} {
|
||||
if status, body := do(t, "PUT", base+proto.PathBlob+h, bearer, b); status != http.StatusOK {
|
||||
t.Fatalf("PUT blob %s status = %d, body = %s", h, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
status, body = do(t, "POST", base+proto.PathHave, bearer, mustJSON(t, proto.HaveRequest{Hashes: []string{hashA, hashB}}))
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("have2 status = %d, body = %s", status, body)
|
||||
}
|
||||
have = proto.HaveResponse{}
|
||||
if err := json.Unmarshal(body, &have); err != nil {
|
||||
t.Fatalf("decode have2: %v", err)
|
||||
}
|
||||
if len(have.Missing) != 0 {
|
||||
t.Fatalf("missing after upload = %v, want none", have.Missing)
|
||||
}
|
||||
|
||||
// 3. Upload the manifest blob, then push the snapshot.
|
||||
manifest := []byte("manifest-bytes")
|
||||
manifestHash := chunk.Hash(manifest)
|
||||
if status, body := do(t, "PUT", base+proto.PathBlob+manifestHash, bearer, manifest); status != http.StatusOK {
|
||||
t.Fatalf("PUT manifest status = %d, body = %s", status, body)
|
||||
}
|
||||
|
||||
status, body = do(t, "POST", base+proto.PathPush, bearer, mustJSON(t, proto.PushRequest{
|
||||
Share: share,
|
||||
Parent: "",
|
||||
ManifestHash: manifestHash,
|
||||
Chunks: []proto.ChunkRef{{Hash: hashA, Size: 100}, {Hash: hashB, Size: 200}},
|
||||
}))
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("push status = %d, body = %s", status, body)
|
||||
}
|
||||
var push proto.PushResponse
|
||||
if err := json.Unmarshal(body, &push); err != nil {
|
||||
t.Fatalf("decode push: %v", err)
|
||||
}
|
||||
if push.Snapshot != manifestHash || push.Head != manifestHash || push.Conflict {
|
||||
t.Fatalf("push response = %+v, want snapshot/head == %s", push, manifestHash)
|
||||
}
|
||||
|
||||
// GET head reflects the new snapshot.
|
||||
status, body = do(t, "GET", base+proto.PathHead+"?share="+share, bearer, nil)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("head status = %d, body = %s", status, body)
|
||||
}
|
||||
var head proto.HeadResponse
|
||||
if err := json.Unmarshal(body, &head); err != nil {
|
||||
t.Fatalf("decode head: %v", err)
|
||||
}
|
||||
if head.Head != manifestHash {
|
||||
t.Fatalf("head = %q, want %q", head.Head, manifestHash)
|
||||
}
|
||||
|
||||
// /metrics exposes the gauges.
|
||||
status, body = do(t, "GET", base+proto.PathMetrics, "", nil)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("metrics status = %d", status)
|
||||
}
|
||||
metrics := string(body)
|
||||
for _, want := range []string{"# TYPE devbox_devices gauge", "devbox_devices 1", "devbox_shares 1", "devbox_snapshots 1", "devbox_chunks 2"} {
|
||||
if !strings.Contains(metrics, want) {
|
||||
t.Fatalf("metrics missing %q in:\n%s", want, metrics)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubAuthAndHashErrors(t *testing.T) {
|
||||
base, db := testHub(t)
|
||||
|
||||
// No bearer -> 401.
|
||||
if status, _ := do(t, "POST", base+proto.PathPublish, "", mustJSON(t, proto.PublishRequest{Share: "x"})); status != http.StatusUnauthorized {
|
||||
t.Fatalf("no-bearer status = %d, want 401", status)
|
||||
}
|
||||
|
||||
// Join to get a valid bearer so we can reach the blob handler.
|
||||
now := time.Now().Unix()
|
||||
if err := db.CreateToken(HashToken("tok2"), now+3600); err != nil {
|
||||
t.Fatalf("CreateToken: %v", err)
|
||||
}
|
||||
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateKey: %v", err)
|
||||
}
|
||||
status, body := do(t, "POST", base+proto.PathJoin, "", mustJSON(t, proto.JoinRequest{Token: "tok2", Name: "n", Pubkey: pub}))
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("join status = %d, body = %s", status, body)
|
||||
}
|
||||
var join proto.JoinResponse
|
||||
if err := json.Unmarshal(body, &join); err != nil {
|
||||
t.Fatalf("decode join: %v", err)
|
||||
}
|
||||
|
||||
// Blob body that does not match {hash} -> 400.
|
||||
if status, _ := do(t, "PUT", base+proto.PathBlob+"deadbeef", join.Bearer, []byte("not-deadbeef")); status != http.StatusBadRequest {
|
||||
t.Fatalf("mismatched blob status = %d, want 400", status)
|
||||
}
|
||||
}
|
||||
110
internal/syncer/syncer.go
Normal file
110
internal/syncer/syncer.go
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
// Package syncer drives the device-side push: build a content-addressed manifest
|
||||
// of a tree (filtered by .devignore and the secret guard), upload only the blobs
|
||||
// the hub is missing, and commit a snapshot.
|
||||
package syncer
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/chunk"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/ignore"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/manifest"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/secret"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// Result summarizes a push.
|
||||
type Result struct {
|
||||
Snapshot string
|
||||
Head string
|
||||
Blocked []string // secret files refused upload
|
||||
Uploaded int // blobs actually uploaded (the hub lacked)
|
||||
Files int // files in the manifest
|
||||
}
|
||||
|
||||
// Push builds a manifest of root (filtered by ig + guard), uploads any blobs the
|
||||
// hub is missing (chunks + the manifest blob), then commits a snapshot on share.
|
||||
// parent is the device's last-known head ("" if none).
|
||||
func Push(c *transport.Client, root, share string, ig *ignore.Matcher, guard *secret.Guard, parent string) (Result, error) {
|
||||
m, blocked, err := manifest.Build(root, ig, guard)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
// Gather the bytes of every distinct chunk, plus the manifest blob itself.
|
||||
blobs := map[string][]byte{}
|
||||
refs := map[string]int64{} // distinct chunk hash -> size
|
||||
for _, e := range m.Entries {
|
||||
data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(e.Path)))
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
cs, err := chunk.Split(data)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
for _, ch := range cs {
|
||||
if _, ok := blobs[ch.Hash]; !ok {
|
||||
blobs[ch.Hash] = data[ch.Offset : ch.Offset+ch.Size]
|
||||
refs[ch.Hash] = ch.Size
|
||||
}
|
||||
}
|
||||
}
|
||||
manBytes, err := m.Marshal()
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
manHash := m.ID()
|
||||
blobs[manHash] = manBytes
|
||||
|
||||
// Upload only what the hub lacks.
|
||||
all := make([]string, 0, len(blobs))
|
||||
for h := range blobs {
|
||||
all = append(all, h)
|
||||
}
|
||||
missing, err := c.Have(all)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
for _, h := range missing {
|
||||
if err := c.PutBlob(h, blobs[h]); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
}
|
||||
|
||||
chunks := make([]proto.ChunkRef, 0, len(refs))
|
||||
for h, sz := range refs {
|
||||
chunks = append(chunks, proto.ChunkRef{Hash: h, Size: sz})
|
||||
}
|
||||
resp, err := c.Push(proto.PushRequest{
|
||||
Share: share,
|
||||
Parent: parent,
|
||||
ManifestHash: manHash,
|
||||
Chunks: chunks,
|
||||
})
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
return Result{
|
||||
Snapshot: resp.Snapshot,
|
||||
Head: resp.Head,
|
||||
Blocked: blocked,
|
||||
Uploaded: len(missing),
|
||||
Files: len(m.Entries),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoadIgnore compiles root/.devignore (an empty matcher if the file is absent).
|
||||
func LoadIgnore(root string) (*ignore.Matcher, error) {
|
||||
b, err := os.ReadFile(filepath.Join(root, ".devignore"))
|
||||
if os.IsNotExist(err) {
|
||||
return ignore.Compile(nil)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ignore.Compile(strings.Split(string(b), "\n"))
|
||||
}
|
||||
117
internal/syncer/syncer_test.go
Normal file
117
internal/syncer/syncer_test.go
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
package syncer
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/secret"
|
||||
"git.shoemoney.ai/shoemoney/devbox/internal/transport"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, root, rel, content string) {
|
||||
t.Helper()
|
||||
p := filepath.Join(root, filepath.FromSlash(rel))
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPushEndToEnd exercises the full M2 stack in-process:
|
||||
// hub server + transport client + syncer, join -> publish -> push.
|
||||
func TestPushEndToEnd(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()
|
||||
|
||||
const tok = "jointoken"
|
||||
if err := db.CreateToken(hub.HashToken(tok), time.Now().Unix()+3600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A device tree: 2 real files, a synced .devignore, a secret, and ignored junk.
|
||||
root := t.TempDir()
|
||||
writeFile(t, root, "main.go", "package main\n")
|
||||
writeFile(t, root, "sub/util.go", "package sub\n")
|
||||
writeFile(t, root, ".devignore", "node_modules/\n")
|
||||
writeFile(t, root, ".env", "SECRET=1\n") // secret -> blocked
|
||||
writeFile(t, root, "node_modules/x.js", "junk()\n") // ignored
|
||||
|
||||
c := transport.New(srv.URL)
|
||||
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Join(tok, "testdev", pub); err != nil {
|
||||
t.Fatalf("join: %v", err)
|
||||
}
|
||||
if c.Bearer() == "" {
|
||||
t.Fatal("join did not set a bearer")
|
||||
}
|
||||
if err := c.Publish("projects"); err != nil {
|
||||
t.Fatalf("publish: %v", err)
|
||||
}
|
||||
|
||||
ig, err := LoadIgnore(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
guard, err := secret.New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
res, err := Push(c, root, "projects", ig, guard, "")
|
||||
if err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
// .devignore + main.go + sub/util.go = 3 synced files; node_modules excluded.
|
||||
if res.Files != 3 {
|
||||
t.Fatalf("Files = %d, want 3 (node_modules must be ignored)", res.Files)
|
||||
}
|
||||
if len(res.Blocked) != 1 || res.Blocked[0] != ".env" {
|
||||
t.Fatalf("Blocked = %v, want [.env]", res.Blocked)
|
||||
}
|
||||
if res.Snapshot == "" {
|
||||
t.Fatal("empty snapshot id")
|
||||
}
|
||||
head, err := c.Head("projects")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head != res.Snapshot {
|
||||
t.Fatalf("hub head %q != pushed snapshot %q", head, res.Snapshot)
|
||||
}
|
||||
|
||||
// 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)
|
||||
if err != nil {
|
||||
t.Fatalf("second push: %v", err)
|
||||
}
|
||||
if res2.Uploaded != 0 {
|
||||
t.Fatalf("second push uploaded %d blobs, want 0 (hub already has them)", res2.Uploaded)
|
||||
}
|
||||
if res2.Snapshot != res.Snapshot {
|
||||
t.Fatalf("identical tree gave different snapshot: %q vs %q", res2.Snapshot, res.Snapshot)
|
||||
}
|
||||
}
|
||||
164
internal/transport/client.go
Normal file
164
internal/transport/client.go
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// Package transport is devbox's device-side HTTP client for talking to the hub.
|
||||
//
|
||||
// It speaks the wire contract in pkg/proto: JSON over HTTP for control calls,
|
||||
// raw bytes for blob uploads, one bearer token for auth. Join is the only
|
||||
// unauthenticated call; redeeming a token yields the bearer used by everything
|
||||
// else (stashed via SetBearer so the caller doesn't have to thread it through).
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// Client talks to one hub. The zero value is not usable; call New.
|
||||
type Client struct {
|
||||
base string // hub base URL, e.g. "http://host:8080"
|
||||
bearer string // device bearer token; empty until Join
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
// New returns a Client for the hub at base (e.g. "http://host:8080").
|
||||
func New(base string) *Client {
|
||||
return &Client{
|
||||
base: strings.TrimRight(base, "/"),
|
||||
hc: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// SetBearer sets the device bearer token used for authenticated requests.
|
||||
func (c *Client) SetBearer(b string) { c.bearer = b }
|
||||
|
||||
// Bearer returns the current device bearer token.
|
||||
func (c *Client) Bearer() string { return c.bearer }
|
||||
|
||||
// Join redeems a one-time token and enrolls this device. It is unauthenticated;
|
||||
// on success it stashes the returned bearer via SetBearer.
|
||||
func (c *Client) Join(token, name string, pubkey []byte) (proto.JoinResponse, error) {
|
||||
var resp proto.JoinResponse
|
||||
err := c.do(http.MethodPost, proto.PathJoin, false, proto.JoinRequest{
|
||||
Token: token, Name: name, Pubkey: pubkey,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return proto.JoinResponse{}, err
|
||||
}
|
||||
c.SetBearer(resp.Bearer)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Publish creates a share owned by this device.
|
||||
func (c *Client) Publish(share string) error {
|
||||
return c.do(http.MethodPost, proto.PathPublish, true, proto.PublishRequest{Share: share}, nil)
|
||||
}
|
||||
|
||||
// Have asks the hub which of hashes it is missing (and must be uploaded).
|
||||
func (c *Client) Have(hashes []string) ([]string, error) {
|
||||
var resp proto.HaveResponse
|
||||
if err := c.do(http.MethodPost, proto.PathHave, true, proto.HaveRequest{Hashes: hashes}, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.Missing, nil
|
||||
}
|
||||
|
||||
// PutBlob uploads one blob's raw bytes under its content hash.
|
||||
func (c *Client) PutBlob(hash string, data []byte) error {
|
||||
return c.raw(http.MethodPut, proto.PathBlob+hash, data)
|
||||
}
|
||||
|
||||
// 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
|
||||
if err := c.do(http.MethodPost, proto.PathPush, true, req, &resp); err != nil {
|
||||
return proto.PushResponse{}, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Head returns the current head snapshot id of share ("" if none).
|
||||
func (c *Client) Head(share string) (string, error) {
|
||||
var resp proto.HeadResponse
|
||||
path := proto.PathHead + "?" + url.Values{"share": {share}}.Encode()
|
||||
if err := c.do(http.MethodGet, path, true, nil, &resp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resp.Head, nil
|
||||
}
|
||||
|
||||
// do sends a JSON request (nil body for GET) and decodes a JSON response into
|
||||
// out (nil out discards the body). It sets the bearer header when auth is true.
|
||||
func (c *Client) do(method, path string, auth bool, body, out any) error {
|
||||
var rdr io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rdr = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, c.base+path, rdr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if auth {
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return apiError(resp.StatusCode, data)
|
||||
}
|
||||
if out != nil {
|
||||
return json.Unmarshal(data, out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// raw sends raw bytes (used for blob uploads) with the bearer header set.
|
||||
func (c *Client) raw(method, path string, data []byte) error {
|
||||
req, err := http.NewRequest(method, c.base+path, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
req.Header.Set(proto.AuthHeader, "Bearer "+c.bearer)
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return apiError(resp.StatusCode, body)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// apiError turns a non-2xx body into an error, preferring proto.Error's message.
|
||||
func apiError(code int, body []byte) error {
|
||||
var e proto.Error
|
||||
if json.Unmarshal(body, &e) == nil && e.Error != "" {
|
||||
return fmt.Errorf("devbox: %s (status %d)", e.Error, code)
|
||||
}
|
||||
return fmt.Errorf("devbox: %s (status %d)", strings.TrimSpace(string(body)), code)
|
||||
}
|
||||
222
internal/transport/client_test.go
Normal file
222
internal/transport/client_test.go
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
package transport
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.shoemoney.ai/shoemoney/devbox/pkg/proto"
|
||||
)
|
||||
|
||||
// writeJSON is a tiny helper for the stub hub.
|
||||
func writeJSON(t *testing.T, w http.ResponseWriter, code int, v any) {
|
||||
t.Helper()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
t.Fatalf("encode response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJoinSetsBearer(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != proto.PathJoin {
|
||||
t.Fatalf("Join: got %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if h := r.Header.Get(proto.AuthHeader); h != "" {
|
||||
t.Fatalf("Join must not send auth header, got %q", h)
|
||||
}
|
||||
var req proto.JoinRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Fatalf("decode JoinRequest: %v", err)
|
||||
}
|
||||
if req.Token != "tok" || req.Name != "laptop" || string(req.Pubkey) != "PUB" {
|
||||
t.Fatalf("unexpected JoinRequest: %+v", req)
|
||||
}
|
||||
writeJSON(t, w, http.StatusOK, proto.JoinResponse{DeviceID: "dev1", Bearer: "secret"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
resp, err := c.Join("tok", "laptop", []byte("PUB"))
|
||||
if err != nil {
|
||||
t.Fatalf("Join: %v", err)
|
||||
}
|
||||
if resp.DeviceID != "dev1" || resp.Bearer != "secret" {
|
||||
t.Fatalf("unexpected JoinResponse: %+v", resp)
|
||||
}
|
||||
if c.Bearer() != "secret" {
|
||||
t.Fatalf("Join should have set bearer, got %q", c.Bearer())
|
||||
}
|
||||
}
|
||||
|
||||
// requireBearer asserts an authenticated request carries the expected header.
|
||||
func requireBearer(t *testing.T, r *http.Request) {
|
||||
t.Helper()
|
||||
if h := r.Header.Get(proto.AuthHeader); h != "Bearer secret" {
|
||||
t.Fatalf("%s %s: bad auth header %q", r.Method, r.URL.Path, h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublish(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != proto.PathPublish {
|
||||
t.Fatalf("Publish: got %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
requireBearer(t, r)
|
||||
var req proto.PublishRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Fatalf("decode PublishRequest: %v", err)
|
||||
}
|
||||
if req.Share != "proj" {
|
||||
t.Fatalf("unexpected share %q", req.Share)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
if err := c.Publish("proj"); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHave(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != proto.PathHave {
|
||||
t.Fatalf("Have: got %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
requireBearer(t, r)
|
||||
var req proto.HaveRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Fatalf("decode HaveRequest: %v", err)
|
||||
}
|
||||
if len(req.Hashes) != 2 || req.Hashes[0] != "a" || req.Hashes[1] != "b" {
|
||||
t.Fatalf("unexpected hashes: %v", req.Hashes)
|
||||
}
|
||||
writeJSON(t, w, http.StatusOK, proto.HaveResponse{Missing: []string{"b"}})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
missing, err := c.Have([]string{"a", "b"})
|
||||
if err != nil {
|
||||
t.Fatalf("Have: %v", err)
|
||||
}
|
||||
if len(missing) != 1 || missing[0] != "b" {
|
||||
t.Fatalf("unexpected missing: %v", missing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutBlob(t *testing.T) {
|
||||
const hash = "deadbeef"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut {
|
||||
t.Fatalf("PutBlob: got method %s", r.Method)
|
||||
}
|
||||
if r.URL.Path != proto.PathBlob+hash {
|
||||
t.Fatalf("PutBlob: got path %s, want %s", r.URL.Path, proto.PathBlob+hash)
|
||||
}
|
||||
requireBearer(t, r)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read blob body: %v", err)
|
||||
}
|
||||
if string(body) != "blobby" {
|
||||
t.Fatalf("PutBlob: got body %q, want %q", body, "blobby")
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
if err := c.PutBlob(hash, []byte("blobby")); err != nil {
|
||||
t.Fatalf("PutBlob: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPush(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.URL.Path != proto.PathPush {
|
||||
t.Fatalf("Push: got %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
requireBearer(t, r)
|
||||
var req proto.PushRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Fatalf("decode PushRequest: %v", err)
|
||||
}
|
||||
if req.Share != "proj" || req.ManifestHash != "mhash" || len(req.Chunks) != 1 {
|
||||
t.Fatalf("unexpected PushRequest: %+v", req)
|
||||
}
|
||||
writeJSON(t, w, http.StatusOK, proto.PushResponse{Snapshot: "snap1", Head: "snap1"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
resp, err := c.Push(proto.PushRequest{
|
||||
Share: "proj",
|
||||
ManifestHash: "mhash",
|
||||
Chunks: []proto.ChunkRef{{Hash: "a", Size: 3}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Push: %v", err)
|
||||
}
|
||||
if resp.Snapshot != "snap1" || resp.Head != "snap1" {
|
||||
t.Fatalf("unexpected PushResponse: %+v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHead(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != proto.PathHead {
|
||||
t.Fatalf("Head: got %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
requireBearer(t, r)
|
||||
if got := r.URL.Query().Get("share"); got != "proj" {
|
||||
t.Fatalf("Head: got share %q, want proj", got)
|
||||
}
|
||||
writeJSON(t, w, http.StatusOK, proto.HeadResponse{Head: "snap1"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
head, err := c.Head("proj")
|
||||
if err != nil {
|
||||
t.Fatalf("Head: %v", err)
|
||||
}
|
||||
if head != "snap1" {
|
||||
t.Fatalf("Head: got %q, want snap1", head)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorSurfaced(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, http.StatusConflict, proto.Error{Error: "share exists"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL)
|
||||
c.SetBearer("secret")
|
||||
|
||||
err := c.Publish("proj")
|
||||
if err == nil {
|
||||
t.Fatal("Publish: expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "share exists") || !strings.Contains(err.Error(), "409") {
|
||||
t.Fatalf("Publish error missing message/status: %v", err)
|
||||
}
|
||||
|
||||
if _, err := c.Push(proto.PushRequest{Share: "proj"}); err == nil {
|
||||
t.Fatal("Push: expected error, got nil")
|
||||
} else if !strings.Contains(err.Error(), "share exists") {
|
||||
t.Fatalf("Push error missing message: %v", err)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue