Trust boundary: handlePush previously verified that every hash in req.Chunks
existed in the blob store, but it trusted req.Chunks as the authoritative list
of chunks the pushed manifest references. A buggy or malicious client could:
(a) Push a manifest referencing chunk C while omitting C from req.Chunks →
hub commits a snapshot whose manifest references a blob that may not
exist → every subsequent pull 404s on C (dangling snapshot).
(b) Include in req.Chunks a chunk not referenced by the manifest →
refcount is bumped for a blob GC can never safely collect (phantom ref).
Fix: after confirming the manifest blob is present, we now fetch + unmarshal
it and derive the DISTINCT chunk hash set directly from Manifest.Entries[*].Chunks.
Each hash in that set is verified to exist in the store; any missing hash rejects
the push with 409 (same status as before). Only manifest-referenced hashes are
passed to db.AddSnapshot() for refcounting.
Size hint: meta.ChunkRef.Size is used only for metrics/dashboard totals and is
stored once (first INSERT; ON CONFLICT only bumps refcount, not size). GC
decisions are made on refcount, not size. We keep req.Chunks as a size-hint
lookup (reqSizes map): if the client is honest the size is correct; if a hash is
absent from req.Chunks the size defaults to 0, which is harmless.
Happy-path unchanged: an honest client (syncer.go) always derives req.Chunks
from the same manifest, so all hashes are present with correct sizes.
Tests: TestHubHappyPath updated to push a real manifest JSON (required now that
the hub parses it); TestPushManifestChunkIntegrity asserts the malicious pattern
is rejected and the head does not advance, then confirms an honest push succeeds.
- 📊 /metrics gains real WAN observability counters beyond the 4 gauges:
blob bytes in/out (the bandwidth signal now the hub is internet-reachable)
plus pushes/conflicts totals for sync churn. Atomic, incremented at the
blob + push handlers.
- 🩺 /healthz now reports the build version ("ok <version>") so a deploy can
curl-verify the new binary is actually live (SetVersion wired in serve).
Test: TestMetricsCountersAndHealthVersion (version in healthz; bytes_in/out
move on a real PUT/GET).
Now the hub is WAN-reachable, the transfer path needed real hardening:
- ⏱️ request timeout fix: replaced the 30s TOTAL http.Client.Timeout (which
killed a 256MiB blob mid-transfer over a slow link) with granular dial / TLS /
response-header timeouts + TCP keepalive. Body transfer is no longer wall-clocked.
- 🔁 retry + exponential backoff on transient blob transfers (network / 5xx),
3 attempts; 4xx fails fast. Blob GET/PUT are content-addressed (idempotent),
so retry is safe; control calls are left alone.
- 🚀 parallel blob uploads (push) and parallel chunk downloads (pull reassembly),
bounded pools (8), sharing the existing rate limiter. WAN is RTT-bound — this
keeps the pipe full instead of one-blob-at-a-time.
- 🗜️ download (response) gzip: round 1 compressed only uploads, but a clone is
download-heavy. Client negotiates gzip explicitly (so the rate limiter counts
wire bytes), hub streams the response through gzip, client decompresses
bomb-safely. Gated by the same settings.transfer.compress flag.
Tests: retry transient-then-success + 4xx-no-retry, gzip download round-trip.
All existing push/pull round-trips green under -race (refactors behavior-preserving).
The "changed my mind" feature: deferred as YAGNI on a LAN, but the hub is now
WAN-reachable (port-forwarded), so over-the-internet sync is a real path and
compression earns its keep.
- client (settings.transfer.compress, default off): gzip a blob upload only
when it actually shrinks — incompressible chunks (media, encrypted) go raw so
we never inflate the wire. Sets Content-Encoding: gzip. Wired into the daemon
sync loop and the initial `publish` upload.
- hub: decompresses gzip uploads before hashing, so dedup + content-address
integrity are unchanged. Bomb-safe — caps BOTH the compressed stream
(MaxBytesReader) and the decompressed size (LimitReader), rejecting a gzip
header over a non-gzip body.
Tests: client gzip-when-smaller / raw-when-not, hub decompress round-trip +
bad-gzip rejection. go test ./... -race clean, go vet clean.
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.
- Hub emits 3 new flow events: pull (head fetch/propagation, handleHead), conflict
(stale-parent push, handlePush), gc (in-process sweep). Opt-in periodic GC via
'serve --gc-every <dur>' (default off) self-maintains the hub AND animates each
sweep; runGC stays put (no risky refactor of mark-and-sweep).
- Server-side history ring: per-minute activity buckets (push/pull/conflict/gc +
bytes), last 60 min, in /api/state — the sparkline now survives a page reload
(was computed from the live stream only). Recorded under the Emit lock; race-clean.
- Frontend (index.html): pull = teal inbound pulse, conflict = red collision burst,
gc = amber hub sweep + toast; stacked per-minute history sparkline seeded from
/api/state and growing live. One file, no new deps.
- dashboard-fleet-verify.sh: rewritten — drives join·push·pull·conflict·gc and
asserts all 5 on the SSE stream + the history window; adds LOCAL=1 mode (native,
no Pi). Verified locally end-to-end. Tests: TestHistoryRing. go test ./... -race clean.
P2 adversarial audit (6 finders + skeptic verification, 13 agents). Two real
findings fixed with regression tests; rest documented as single-owner residuals.
- FIX (+s attenuation): MayGrant never constrained the GRANTED reshare bit, so an
invite could confer +s the caller didn't hold (req.Reshare copied verbatim).
MayGrant now takes grantReshare and rejects conferring +s you don't hold (owners
unconstrained) — attenuation is total over role + target + reshare.
- FIX (invite revocation): invites were unrevocable 24h bearer capabilities — no
way to kill a leaked/regretted one. Added meta.RevokeInvite (token+binding in one
tx), POST /v1/invite/revoke (only a caller who could mint it may revoke), and
'devbox invite revoke <token>'.
- Tests: TestMayGrant (+5 +s cases), TestInviteCannotGrantReshareCallerLacks,
TestInviteRevoke. go test ./... -race clean (18 pkgs).
- docs/M8a-audit.md: findings, confirmed defenses, accepted residuals.
Confirmed-defended under attack: single-use redeem (atomic CAS), role bounding,
revoke-at-auth (revoked=0 in bearer+role lookups), cross-share binding, PoP.
- LICENSE: MIT (enables the adoption push; public repo was all-rights-reserved).
- go.mod + all imports: git.shoemoney.ai/shoemoney/devbox -> github.com/shoemoney/devbox,
so outsiders can 'go install github.com/shoemoney/devbox/cmd/devbox@latest'. Forgejo
stays the self-hosted home; the registry (devbox-hub) + public dist (devbox-dist) are
unchanged. vet + build + go test -race all green after the rename.
- README: document the go install path.
Security: full git-history scan (manual blob sweep + gitleaks, 84 commits) found
ZERO secrets — Forgejo token never committed, no keys/passwords/private keys.
Optional, off by default: devbox-hub serve --dashboard [--dashboard-addr
127.0.0.1:8099]. A separate, loopback-by-default listener (never widens the
API surface; warns if bound non-loopback since it's unauthenticated read-only).
- internal/hub/dashboard: embedded UI (go:embed index.html) + GET /api/state
(hub/totals/devices/shares snapshot) + GET /api/events (SSE live flow stream).
A nil *Dashboard is Emit-safe so hub handlers call it unconditionally.
- meta reads for the snapshot: Devices(), ShareStats() (one rolled-up query),
SumChunkBytes(). 'online' is activity-tracked since hub start (2-min window).
- hub emits 'join' (device enrolled) and 'push' (device→share, bytes/chunks/
snapshot/new_head) flow events.
Tests: state reflects the DB + a push event reaches a live SSE subscriber +
nil-safe Emit. index.html here is a placeholder — the epic frontend lands next.
It only called EffectiveMember and dropped one return; its sole prod
caller (the push gate) discarded that return anyway. Inline it: the gate
calls EffectiveMember directly and the test now targets the real method.
Kept blobstore.Store (single impl, but the documented M9 S3/R2 seam) and
control.Daemon (single impl, but breaks the daemon->control import cycle).
Completes M8a's collaboration surface. A member mints an invite; the
invitee redeems it through the EXISTING /v1/join proof-of-possession flow
and lands enrolled + assigned the bound principal + granted the bound role.
- migration #3: invites table (token_hash → principal/share/role/+s),
chains 0→1→2→3 — verified on a copy of the real hub DB.
- POST /v1/invite (authed) enforces ATTENUATION server-side via the pure,
unit-tested meta.MayGrant: never grant above your own role, never touch a
principal who outranks you, viewers can't grant, editors need +s. On a
legacy share the inviter is seeded as owner before the explicit flip so
they (and their same-principal devices) never self-lock-out.
- /v1/join applies a redeemed invite's binding (plain token = v1 join).
- transport.Invite + devbox invite <share> <principal> <role> [--reshare].
Tests: MayGrant attenuation matrix, invite binding round-trip, and the
end-to-end TestInviteFlow (owner invites → flip preserves owner → invitee
redeems into editor → editor-without-+s denied). 18 pkgs -race green;
linux/amd64 + windows cross-build.
The read companion to devbox-hub member set/rm/list. Additive: new
PathMembers endpoint (authed; reads stay open in M8a — gating is M9),
proto.Member/MembersResponse, transport Members(), and a devbox members
<share> client command that prints 'legacy share' or the role grants
(principal, role, +s). Role name<->level mapping moved to meta
(ParseRole/RoleName) and the devbox-hub CLI deduped onto it; new
meta.ACLMode(share). Test: legacy reads empty, a grant flips it explicit
and lists bob/editor/+s. 18 pkgs -race green; windows cross-builds.
V2-SPEC §5.2 (write-side, staged before read-side M9). Migration #2 (rides
the M8 runner, chains 0→1→2 — verified on real .10 data, version 2, all
counts preserved):
- principals table + devices.principal_id (every v1 device backfills to one
synthetic 'owner' principal — byte-identical to v1 until a share opts in).
- members(share, principal_id, role, can_reshare) + shares.acl_mode. A share
with zero grants is 'legacy' (every device an implicit owner = v1); the
first grant flips it to 'explicit' = deny-by-default.
- EffectiveRole(device, share) resolves device→principal→role; legacy⇒owner.
- Push write gate: role>=editor AND the access.writable clamp (which can only
REMOVE write). Legacy shares reduce to the v1 writable bit exactly.
- devbox-hub member set/rm/list + principal <device> <principal> admin CLI —
the populate path, so the role layer has a real consumer now (no dead code).
Tests: legacy↔explicit lifecycle, deny-by-default, viewer<editor, HTTP push
gate (403 unmembered/viewer, opens at editor). 18 pkgs -race green; hub
cross-compiles linux/amd64; windows builds.
The device id is derived from the pubkey in JoinRequest, but the hub never
checked the joiner actually held that key — anyone with a token could enroll
claiming another device's identity. Now the client signs JoinChallenge(token,
pubkey) with its ed25519 private key and the hub verifies it (ed25519.Verify)
BEFORE redeeming the token — so a bad request can't burn a legitimate one-time
token either. proto gains a Signature field + the shared JoinChallenge helper.
Regression test: garbage/missing/wrong-key sigs all 401, token survives, valid
join enrolls.
The hub read request bodies with unbounded io.ReadAll / json.Decode and ran
http.ListenAndServe with zero timeouts — a single client could OOM it or hold
connections open (slowloris). Now:
- handleBlob caps the body at 256 MiB, decode() caps JSON at 8 MiB, both via
http.MaxBytesReader -> 413 when exceeded.
- serve uses an http.Server with ReadHeaderTimeout/ReadTimeout/IdleTimeout +
MaxHeaderBytes. WriteTimeout intentionally unset so the long-lived /v1/events
SSE stream isn't killed. [fanned-out subagent: harden-dos]
GET /v1/blob/{hash} and /v1/have passed the URL hash straight into filepath.Join
in the blob store. Go's ServeMux URL-decodes %2f/%2e in the wildcard, so
'..%2f..%2f..%2fetc%2fpasswd' (or a hash starting with '..') escaped the blob
root — any enrolled device could read arbitrary files incl. the hub token DB.
Defense in depth:
- hub: validHash() rejects non-(64 hex) keys at the HTTP boundary (404 on GET,
400 on /have) before any store call.
- blobstore: safeKey() rejects keys that aren't a bare, separator-free filename
in Has/Get/Put/Delete — the sink can't be escaped even if a caller forgets.
e2e + unit regression tests for both layers.
Code-review pass on M6.5+M7:
- pidfile: claim via O_CREATE|O_EXCL and arbitrate live-vs-stale, so two
`devbox start` invocations can't both win the guard and run concurrently
- hub: serialize publish (publishMu) so a case-clash check + create is atomic;
reject share names ending in '.' (Windows strips it → silent collision)
- daemon: reset SSE backoff only after a genuinely healthy stream (2m), not the
30s ceiling, so a hub that recycles connections doesn't pin a 30s event lag
- document that restore/deploy's delete pass is ignore/guard-filtered on purpose
(never delete a user's gitignored runtime files or local secrets)
- test: pidfile claim/refuse/stale-reclaim arbitration
- daemon: exponential backoff (1s→30s) + ±25% jitter on SSE reconnect so a fleet
that drops together doesn't reconnect in lockstep; a long-lived stream resets it
- hub: ValidateShareName rejects path separators, traversal, control/non-ASCII
chars, reserved Windows device names (CON/NUL/COM1…), and case-clashes with an
existing share (Foo vs foo would collide on case-insensitive filesystems)
- tests for both
- pkg/proto + internal/hub/events.go: SSE /v1/events with a broker; hub broadcasts
on genuine head ADVANCE only (idempotent re-push doesn't broadcast -> no storm)
- transport.Client.Events: SSE consumer (timeout-less, ctx-cancelled)
- internal/daemon: per-mount loop funnels watcher + SSE triggers into a serialized
Sync; read-only mounts pull-only; base snapshot persisted in state.json
- cmd/devbox: 'mount <share> <dir> [--ro]' (clone+sync) and 'start' (foreground daemon)
- fix: serialize chunk.Split — jotfs/fastcdc-go mutates a package global in
NewChunker, racing under concurrent chunking (caught by -race)
- test: two live daemons, an edit on one reaches the other automatically (race-clean)