feat(M7): SSE reconnect backoff + share-name validation 🛡️
- 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
This commit is contained in:
parent
4e194ea342
commit
38766fdcd5
7 changed files with 230 additions and 3 deletions
34
internal/daemon/backoff.go
Normal file
34
internal/daemon/backoff.go
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
package daemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Reconnect backoff bounds: start at 1s, double to a 30s ceiling.
|
||||||
|
const (
|
||||||
|
backoffBase = 1 * time.Second
|
||||||
|
backoffMax = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// nextBackoff returns the next clean (un-jittered) backoff: base, then doubling
|
||||||
|
// up to backoffMax. Pass the previous clean value; pass <=0 to (re)start at base.
|
||||||
|
func nextBackoff(prev time.Duration) time.Duration {
|
||||||
|
switch {
|
||||||
|
case prev <= 0:
|
||||||
|
return backoffBase
|
||||||
|
case prev*2 >= backoffMax:
|
||||||
|
return backoffMax
|
||||||
|
default:
|
||||||
|
return prev * 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// jittered spreads a backoff by ±25% so a fleet that all lost the hub at once
|
||||||
|
// doesn't reconnect in lockstep (thundering herd). Returns 0 unchanged.
|
||||||
|
func jittered(d time.Duration) time.Duration {
|
||||||
|
if d <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return d + time.Duration(rand.Int63n(int64(d/2))) - d/4
|
||||||
|
}
|
||||||
39
internal/daemon/backoff_test.go
Normal file
39
internal/daemon/backoff_test.go
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
package daemon
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNextBackoffDoublesAndCaps(t *testing.T) {
|
||||||
|
// Starts at base, doubles, then saturates at the ceiling.
|
||||||
|
want := []time.Duration{
|
||||||
|
1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second,
|
||||||
|
16 * time.Second, 30 * time.Second, 30 * time.Second,
|
||||||
|
}
|
||||||
|
got := time.Duration(0)
|
||||||
|
for i, w := range want {
|
||||||
|
got = nextBackoff(got)
|
||||||
|
if got != w {
|
||||||
|
t.Fatalf("step %d: nextBackoff = %s, want %s", i, got, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A non-positive input restarts at base (used to reset after a healthy stream).
|
||||||
|
if d := nextBackoff(0); d != backoffBase {
|
||||||
|
t.Fatalf("reset: nextBackoff(0) = %s, want %s", d, backoffBase)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJitteredStaysWithinBand(t *testing.T) {
|
||||||
|
const d = 8 * time.Second
|
||||||
|
lo, hi := d-d/4, d+d/4 // ±25%
|
||||||
|
for i := 0; i < 1000; i++ {
|
||||||
|
j := jittered(d)
|
||||||
|
if j < lo || j >= hi {
|
||||||
|
t.Fatalf("jittered(%s) = %s, want in [%s,%s)", d, j, lo, hi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if jittered(0) != 0 {
|
||||||
|
t.Fatal("jittered(0) should be 0")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -127,18 +127,27 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) {
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hub change events -> sync (reconnect with backoff).
|
// Hub change events -> sync (reconnect with exponential backoff + jitter).
|
||||||
go func() {
|
go func() {
|
||||||
|
backoff := time.Duration(0)
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
|
start := time.Now()
|
||||||
err := c.Events(ctx, m.Share, func(proto.Event) { nudge() })
|
err := c.Events(ctx, m.Share, func(proto.Event) { nudge() })
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
d.logf("events %s reconnecting: %v", m.Share, err)
|
// A stream that lived a while is a transient drop, not a hard failure:
|
||||||
|
// reset so the retry is prompt instead of inheriting a grown delay.
|
||||||
|
if time.Since(start) > backoffMax {
|
||||||
|
backoff = 0
|
||||||
|
}
|
||||||
|
backoff = nextBackoff(backoff)
|
||||||
|
wait := jittered(backoff)
|
||||||
|
d.logf("events %s reconnecting in ~%s: %v", m.Share, wait.Round(time.Millisecond), err)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
case <-time.After(2 * time.Second):
|
case <-time.After(wait):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
|
||||||
|
|
@ -127,6 +127,15 @@ func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID
|
||||||
if !decode(w, r, &req) {
|
if !decode(w, r, &req) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
existing, err := s.db.ShareNames()
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := ValidateShareName(req.Share, existing); err != nil {
|
||||||
|
writeErr(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := s.db.CreateShare(req.Share, deviceID, time.Now().Unix()); err != nil {
|
if err := s.db.CreateShare(req.Share, deviceID, time.Now().Unix()); err != nil {
|
||||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
|
|
|
||||||
54
internal/hub/sharename.go
Normal file
54
internal/hub/sharename.go
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
package hub
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// reservedNames are Windows device names a share must not use (case-insensitive):
|
||||||
|
// a share name can become a directory on a Windows client, where these are magic.
|
||||||
|
var reservedNames = func() map[string]bool {
|
||||||
|
m := map[string]bool{"con": true, "prn": true, "aux": true, "nul": true}
|
||||||
|
for i := 1; i <= 9; i++ {
|
||||||
|
m[fmt.Sprintf("com%d", i)] = true
|
||||||
|
m[fmt.Sprintf("lpt%d", i)] = true
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}()
|
||||||
|
|
||||||
|
// ValidateShareName rejects share names that are unsafe as a path component or
|
||||||
|
// would collide with an existing share on a case-insensitive filesystem (macOS,
|
||||||
|
// Windows). existing is the set of names already on the hub; an exact match is
|
||||||
|
// allowed (publish is idempotent) — only a different-case clash is rejected.
|
||||||
|
func ValidateShareName(name string, existing []string) error {
|
||||||
|
switch {
|
||||||
|
case name == "":
|
||||||
|
return fmt.Errorf("share name is empty")
|
||||||
|
case strings.TrimSpace(name) != name:
|
||||||
|
return fmt.Errorf("share name %q has leading/trailing whitespace", name)
|
||||||
|
case len(name) > 128:
|
||||||
|
return fmt.Errorf("share name %q is too long (max 128 bytes)", name)
|
||||||
|
case name == "." || name == "..":
|
||||||
|
return fmt.Errorf("share name %q is reserved", name)
|
||||||
|
case strings.HasPrefix(name, ".") || strings.HasPrefix(name, "-"):
|
||||||
|
return fmt.Errorf("share name %q must not start with '.' or '-'", name)
|
||||||
|
}
|
||||||
|
for _, r := range name {
|
||||||
|
switch {
|
||||||
|
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||||
|
case r == '.', r == '_', r == '-':
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("share name %q has invalid character %q (allowed: letters, digits, . _ -)", name, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reservedNames[strings.ToLower(name)] {
|
||||||
|
return fmt.Errorf("share name %q is a reserved device name", name)
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(name)
|
||||||
|
for _, e := range existing {
|
||||||
|
if e != name && strings.ToLower(e) == lower {
|
||||||
|
return fmt.Errorf("share name %q case-clashes with existing share %q (collides on case-insensitive filesystems)", name, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
38
internal/hub/sharename_test.go
Normal file
38
internal/hub/sharename_test.go
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
package hub
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateShareName(t *testing.T) {
|
||||||
|
existing := []string{"projects", "Repos"}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"projects", true}, // exact match of an existing share is fine (idempotent publish)
|
||||||
|
{"my-app_2", true}, // letters, digits, dash, underscore
|
||||||
|
{"web.staging", true},
|
||||||
|
{"", false}, // empty
|
||||||
|
{" lead", false}, // whitespace
|
||||||
|
{"trail ", false},
|
||||||
|
{"a/b", false}, // path separator (sub-paths are mount-side, not in the name)
|
||||||
|
{"a\\b", false}, // backslash
|
||||||
|
{"..", false}, // traversal
|
||||||
|
{".hidden", false}, // leading dot
|
||||||
|
{"-flag", false}, // leading dash
|
||||||
|
{"sp ace", false}, // interior space
|
||||||
|
{"emoji🎉", false}, // non-ASCII
|
||||||
|
{"CON", false}, // reserved Windows device name
|
||||||
|
{"lpt3", false}, // reserved (case-insensitive)
|
||||||
|
{"repos", false}, // case-clashes with existing "Repos"
|
||||||
|
{"REPOS", false}, // case-clash
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
err := ValidateShareName(c.name, existing)
|
||||||
|
if c.ok && err != nil {
|
||||||
|
t.Errorf("ValidateShareName(%q) = %v, want ok", c.name, err)
|
||||||
|
}
|
||||||
|
if !c.ok && err == nil {
|
||||||
|
t.Errorf("ValidateShareName(%q) = ok, want error", c.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
44
scripts/build-release.sh
Executable file
44
scripts/build-release.sh
Executable file
|
|
@ -0,0 +1,44 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Cross-compile both devbox binaries for all release targets.
|
||||||
|
# Override version: VERSION=v1.2.3 ./scripts/build-release.sh
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}"
|
||||||
|
LDFLAGS="-s -w -X main.version=$VERSION"
|
||||||
|
|
||||||
|
BINS=(devbox devbox-hub)
|
||||||
|
TARGETS=(linux/amd64 darwin/arm64 darwin/amd64 windows/amd64)
|
||||||
|
|
||||||
|
rm -rf dist && mkdir -p dist
|
||||||
|
|
||||||
|
echo "Building version: $VERSION"
|
||||||
|
|
||||||
|
for bin in "${BINS[@]}"; do
|
||||||
|
for target in "${TARGETS[@]}"; do
|
||||||
|
os="${target%/*}"
|
||||||
|
arch="${target#*/}"
|
||||||
|
out="dist/${bin}_${VERSION}_${os}_${arch}"
|
||||||
|
[ "$os" = "windows" ] && out="${out}.exe"
|
||||||
|
echo " -> $out"
|
||||||
|
CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" \
|
||||||
|
go build -ldflags "$LDFLAGS" -o "$out" "./cmd/${bin}"
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
# Generate checksums.
|
||||||
|
echo "Generating dist/SHA256SUMS"
|
||||||
|
(
|
||||||
|
cd dist
|
||||||
|
if command -v shasum >/dev/null 2>&1; then
|
||||||
|
shasum -a 256 * > SHA256SUMS
|
||||||
|
else
|
||||||
|
sha256sum * > SHA256SUMS
|
||||||
|
fi
|
||||||
|
)
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Done. Artifacts in dist/:"
|
||||||
|
ls -lh dist/
|
||||||
Loading…
Reference in a new issue