Artifact 62852489da4a40deb2381995bbf8bab033e8939b989200f3f56b27dd8fac1ee9:
- File
internal/sync/serve_http_test.go
— part of check-in
[89535a6c42]
at
2026-07-19 18:28:45
on branch trunk
— fix: store delta content against a phantomized base instead of discarding it (#83)
* fix: store delta content against a phantomized base instead of discarding it
A delta artifact arriving before its base is normal steady-state behavior during a Fossil transfer, not a fault. The receive path used to discard such deltas outright and phantomize the target instead, so a phantom only ever cleared when its base happened to already be present -- resolution advanced one delta-chain hop per round, making clones of deep-history repos provably unable to converge within MaxRounds.
Match canonical Fossil's content_put_ex/rid_from_uuid model: resolve the delta's source via a create-phantom-if-missing lookup, persist the delta bytes unconditionally (reading the target size straight out of the delta header, so the base never needs to be readable to store it), and record the delta-to-source link immediately. Availability resolves lazily via the existing content.IsAvailable chain walk and manifest.Crosslink's deferred retry -- both already correct and untouched here.
storeReceivedFile is the single call site shared by clone, sync-pull, and server-push, so fixing it here also closes out the delta-before-base sentinel handling on the pull and push paths (issue #57, folded into this fix): neither path needs to special-case the condition anymore because it stops being an error.
Verified against the pikchr corpus via a loopback fossil server: rounds dropped from 100 (exhausted) to 3, files received from 63,155 (22.2x) to 2,980 (1.05x), and the phantom table empties out completely.
* fix: converge delta storage on canonical, close integrity gap, harden wire parsing
Three defects from review, all in the raw-delta path added for the delta-before-base fix, all reachable from an untrusted peer:
1. delta.getInt accumulated v = v*64 + digit with no overflow check. A twelve-byte header of maximum-value digits wraps to exactly math.MaxUint64, which casts to int64(-1) -- the same sentinel blob.size uses for "phantom". That silently corrupted the row: real content reporting as a phantom, with no phantom-table entry to make it re-requestable. getInt now rejects overflow instead of wrapping, and parseTargetLen (shared by Apply and OutputSize) bounds the parsed target length to a sane maximum before it ever reaches an allocation or a size column.
2. StoreDeltaRaw panicked on a zero-length delta payload. storeReceivedFile guarded payload == nil but not len(payload) == 0, and nothing between wire decode and storage checked for it -- a peer sending an empty delta file card crashed the process. Wire data gets an error return, not an assertion; OutputSize and StoreDeltaRaw are now consistent with delta.Apply's existing "empty delta is an error" contract.
3. The receive-time split (store raw only when the base happens to be unavailable, otherwise eagerly expand and verify) left a gap an attacker chooses the timing of: withhold the base, and a delta claiming any UUID goes down the unverified raw path. Nothing downstream checked it either -- content.Expand applied deltas with no hash check, and content.Verify was reachable only from repo rebuild and one integration test.
Closed by converging fully on canonical's model: every delta is now stored raw and linked via a create-phantom-if-missing lookup, regardless of whether its base is currently available -- receive time no longer branches on availability at all. Verification moves to the one choke point every expansion path already goes through: content.Expand now hashes its result against the row's claimed UUID before returning it, catching a mismatch regardless of which caller or how the chain assembled. content.Verify becomes a thin wrapper over the same check.
Storage-layer and end-to-end regression tests added for all three, including the exact claim-one-UUID/ship-a-delta-for-another/withhold-the- base reproduction, guarded against degenerating into a no-op (delta must actually compress, base must be genuinely absent, rejection must be a real error rather than merely different bytes).
Re-verified against pikchr (2,842 artifacts) and wapp (1,039): pikchr converges in 3 rounds, 2,980 files, 0 phantoms; wapp converges in 3 rounds, 1,115 files, 1 phantom outstanding (pre-existing, unrelated -- clone.go has no DB-phantom rescan the way the pull path's loadDBPhantoms does; separately tracked). On-disk repository size is close to but slightly smaller than storing everything as raw delta bytes should produce (pikchr 6.81MB -> 6.73MB, wapp 5.64MB -> 5.46MB): zlib on full text already captures most of the redundancy an explicit delta would, so the win here is mainly integrity and convergence, not size.
* fix: bound delta allocation to actual work, validate delta source hex
Two defects from round-two review, plus a stray comment.
1. delta.Apply preallocated its output buffer directly from the delta header's claimed target length (make([]byte, 0, targetLen)). That claim only had to clear maxDeltaTargetSize (4 GiB) to be trusted as an allocation size, so a handful of wire bytes declaring a near-4 GiB target triggered an allocation sized to the claim, not to any work actually done. Harmless as a one-off parse spike; durable once a delta can be stored unverified (see blob.StoreDeltaRaw, this branch) -- a hostile peer plants one such delta and every later Expand of that row repeats the attempt. The initial capacity is now a small fixed bound; append grows it normally for legitimately large content instead of trusting the header's own claim about itself.
2. storeReceivedFile validated the target UUID's hex-ness (hash.IsValidHash) but not the delta source's. The blob table's CHECK constraint only bounds uuid length, not hex-ness, so a non-hex string of valid length passed straight through to blob.StorePhantom and became a permanent, unfillable row -- one the pull path's loadDBPhantoms would then re-request every sync round, forever. deltaSrc now gets the same check as the target uuid, at the same place.
Also deleted a stray doc-comment line left over from an earlier refactor.
Regression tests for both, RED-verified against reverted code before being fixed: the allocation test had to be corrected mid-way through -- delta headers encode their integer in Fossil's own base-64 alphabet, not decimal, so an initial fmt.Sprintf("%d", ...) fixture parsed as a different (still large but differently-bounded) value and passed vacuously; appendInt is the real encoder and is used directly now, with a round-trip sanity check against OutputSize guarding the fixture itself. (user: [email protected], size: 6525) [annotate] [blame] [check-ins using]
package sync import ( "context" "fmt" "net" "net/http" "strings" "testing" "time" "github.com/danmestas/libfossil/internal/hash" "github.com/danmestas/libfossil/internal/repo" "github.com/danmestas/libfossil/internal/xfer" ) func freePort(t *testing.T) string { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } addr := ln.Addr().String() ln.Close() return addr } func TestServeHTTPRoundTrip(t *testing.T) { r := setupSyncTestRepo(t) data := []byte("http test blob") uuid := hash.SHA1(data) storeReceivedFile(r, uuid, "", data) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) transport := &HTTPTransport{URL: fmt.Sprintf("http://%s", addr)} req := &xfer.Message{Cards: []xfer.Card{ &xfer.PullCard{ServerCode: "test", ProjectCode: "test"}, &xfer.GimmeCard{UUID: uuid}, }} resp, err := transport.Exchange(ctx, req) if err != nil { t.Fatalf("exchange: %v", err) } files := findCards[*xfer.FileCard](resp) found := false for _, f := range files { if f.UUID == uuid && string(f.Content) == string(data) { found = true } } if !found { t.Fatal("expected file card in HTTP response") } } func TestServeHTTPPushPull(t *testing.T) { r := setupSyncTestRepo(t) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) transport := &HTTPTransport{URL: fmt.Sprintf("http://%s", addr)} // Push a blob data := []byte("pushed via http") uuid := hash.SHA1(data) pushReq := &xfer.Message{Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "test", ProjectCode: "test"}, &xfer.FileCard{UUID: uuid, Content: data}, }} pushResp, err := transport.Exchange(ctx, pushReq) if err != nil { t.Fatalf("push exchange: %v", err) } errs := findCards[*xfer.ErrorCard](pushResp) if len(errs) > 0 { t.Fatalf("push error: %s", errs[0].Message) } // Pull it back pullReq := &xfer.Message{Cards: []xfer.Card{ &xfer.PullCard{ServerCode: "test", ProjectCode: "test"}, &xfer.GimmeCard{UUID: uuid}, }} pullResp, err := transport.Exchange(ctx, pullReq) if err != nil { t.Fatalf("pull exchange: %v", err) } files := findCards[*xfer.FileCard](pullResp) found := false for _, f := range files { if f.UUID == uuid && string(f.Content) == string(data) { found = true } } if !found { t.Fatal("pushed blob not available via pull") } } func TestServeHTTPGetProbe(t *testing.T) { r := setupSyncTestRepo(t) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) // GET should return HTML, not an error. resp, err := http.Get(fmt.Sprintf("http://%s/", addr)) if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatalf("GET status: %d", resp.StatusCode) } ct := resp.Header.Get("Content-Type") if ct != "text/html" { t.Fatalf("GET content-type: %s", ct) } } func TestServeHTTPEmptyPost(t *testing.T) { r := setupSyncTestRepo(t) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) // Empty POST should return an empty xfer response, not 400. resp, err := http.Post(fmt.Sprintf("http://%s/", addr), "application/x-fossil", nil) if err != nil { t.Fatalf("POST: %v", err) } defer resp.Body.Close() if resp.StatusCode != 200 { t.Fatalf("empty POST status: %d", resp.StatusCode) } } func TestServeHTTPBadPayload(t *testing.T) { r := setupSyncTestRepo(t) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) // Send binary garbage that isn't valid zlib or card data. // The Decode fallback to uncompressed will try to parse cards, // which may succeed on some text. Use NUL bytes to force failure. garbage := make([]byte, 50) for i := range garbage { garbage[i] = 0xFF } resp, err := http.Post( fmt.Sprintf("http://%s/", addr), "application/x-fossil", strings.NewReader(string(garbage)), ) if err != nil { t.Fatalf("POST: %v", err) } defer resp.Body.Close() // Decode fallback to uncompressed may produce empty cards or error. // Either 200 (empty response) or 400 (decode error) is acceptable // since the data has no valid cards. if resp.StatusCode != 200 && resp.StatusCode != 400 { t.Fatalf("bad payload status: %d, want 200 or 400", resp.StatusCode) } } func TestServeHTTPHandlerError(t *testing.T) { r := setupSyncTestRepo(t) addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Handler that always returns an error → server sends 500. failHandler := func(_ context.Context, _ *repo.Repo, _ *xfer.Message) (*xfer.Message, error) { return nil, fmt.Errorf("intentional handler failure") } go ServeHTTP(ctx, addr, r, failHandler) time.Sleep(100 * time.Millisecond) // Use raw HTTP to check the 500 status directly. body, _ := (&xfer.Message{Cards: []xfer.Card{ &xfer.PullCard{ServerCode: "test", ProjectCode: "test"}, }}).Encode() resp, err := http.Post( fmt.Sprintf("http://%s/", addr), "application/x-fossil", strings.NewReader(string(body)), ) if err != nil { t.Fatalf("POST: %v", err) } defer resp.Body.Close() if resp.StatusCode != 500 { t.Fatalf("handler error status: %d, want 500", resp.StatusCode) } } func TestServeHTTPClone(t *testing.T) { r := setupSyncTestRepo(t) stored := map[string]bool{} for i := 0; i < 3; i++ { data := []byte(fmt.Sprintf("clone http %d", i)) uuid := hash.SHA1(data) storeReceivedFile(r, uuid, "", data) stored[uuid] = true } addr := freePort(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go ServeHTTP(ctx, addr, r, HandleSync) time.Sleep(100 * time.Millisecond) transport := &HTTPTransport{URL: fmt.Sprintf("http://%s", addr)} req := &xfer.Message{Cards: []xfer.Card{ &xfer.CloneCard{Version: 1}, }} resp, err := transport.Exchange(ctx, req) if err != nil { t.Fatalf("clone exchange: %v", err) } files := findCards[*xfer.FileCard](resp) for _, f := range files { delete(stored, f.UUID) } if len(stored) > 0 { t.Fatalf("clone missing blobs: %v", stored) } }