Artifact 4b88c27d9b07422b11d7a845300748af9e70f94df4be1027036906392520e6d1:
- File
dst/e2e_test.go
— part of check-in
[3a6126c3e9]
at
2026-10-11 01:34:31
on branch trunk
— fix: harden sync and repository defaults (security) (#282)
* fix(xfer): reject non-decimal card sizes and bound payload memory
A payload card's size was parsed with strconv.Atoi, so a peer sending `file HASH -1` reached readPayload's negative-size assertion and panicked the client or server decoding the message, and a signed size such as `+5` was accepted. Sizes now go through parseSize, which follows the sync draft's `decimal = 1*DIGIT` grammar and fossil's 32-bit limit and returns a decoding error for anything else. uvfile FLAGS use the same parser, so negative FLAGS are rejected as the draft requires. The assertion stays, now unreachable from peer input.
readPayload no longer allocates the declared size up front: its buffer grows with the bytes read, so a large size over a short message fails after allocating about what was sent.
A cfile payload may inflate only to its USIZE (a margin above it for a delta) and not past its 4-byte size prefix, and all cfile payloads in one message share a MaxCFileInflateBytes (1 GiB) budget, so a few megabytes of zlib cannot inflate to tens of gigabytes.
FuzzDecode exercises the decoder over both framings.
* fix(sync): refuse malformed xrow payloads and cap HTTP reply bodies
An xrow payload or xdelete PKData from a peer was decoded into a map and used as is. JSON null gave a nil map that reached coerceJSONNumbers' assertion, and a primary-key value of the wrong type or a nested value reached normalizeValue's, panicking the client or server. Both directions now decode through decodeRowJSON: one JSON object, nothing after it, and repo.ValidateRow's rules, which require scalar values and primary-key values that PKHash can normalize. A client refuses an xrow for a table it has not registered. Column types match case-insensitively, as table creation accepts them.
Both HTTP transports read replies through xfer.ReadBody, which stops at MaxBodyBytes (MaxDecompressedBytes plus framing headroom) and returns ErrBodyTooLarge, untagged for retry, instead of reading an endless body into memory.
FuzzTableSyncPayload drives the server handler and client over arbitrary payloads.
* fix(sync): check synced-table rows and identifiers before building SQL
repo.UpsertXRow wrote a row's map keys into its INSERT as column names, and the rows of an xrow payload or xdelete PKData come from the peer, so a key such as "val, mtime) VALUES(...) --" chose the statement's columns and values, and a key could select from other tables into a synced one. This held on the server for pushed rows and tombstones, and on the client for a server's rows.
A peer's row must now use exactly the table's declared columns: repo.ValidateRow refuses any other key, which also keeps a peer from setting _owner. UpsertXRow no longer trusts its caller: it reads the table's registered schema and refuses any key it does not declare, apart from _owner on an ownership-mode table. ListXRows, LookupXRowOwner and DeleteXRowByPKHash validate the table name and the column names they interpolate, so no synced-table identifier reaches SQL text unchecked.
* fix(sync): answer reqconfig only with fossil's transferable config
The sync server answered reqconfig NAME with any row of the config table, for any requester, including one with no capabilities, so project-code, server-code and every local setting could be read by anyone who could reach the sync endpoint.
handleReqConfig now follows fossil's page_xfer and configure.c. It answers only a /GROUP name, only for a requester with Read, matches the group by prefix in fossil's table order, and sends only the names fossil transfers in that group, in fossil's encoding. The user and subscriber tables also need Admin, which counts only for a verified login, and the concealed table needs RdAddr. A refused request gets no cards and no error.
The groups, their names and their capability rules live in one place, config_groups.go. A differential test answers the same requests with fossil's own server and with HandleSync on the same repository and requires identical config cards.
* test(sync): keep fossil http from leaving a backoffice process
* fix(sync): check the login nonce against the request body
The server verified a login card's signature over its nonce but never checked that the nonce was the SHA-1 of the request body after the login line, as fossil's check_tail_hash does (draft-fossil-sync-protocol-00 ยง6.2). A login card captured from one request therefore authenticated any other request body.
The decoder now records, for each login card, the SHA-1 of the decompressed bytes after the card's line, and VerifyLogin refuses a card whose nonce does not match it. A login card that was never decoded has no tail and is refused.
Login handling otherwise follows fossil's page_xfer and check_login: - a refused login ends the exchange with "error login failed" instead of continuing as nobody; - a second login card is refused with "multiple login cards"; - a successful login adds the user's capabilities to nobody's instead of replacing them; - nobody and anonymous log in without a password, and the reserved developer and reader logins and accounts with an empty password cannot be logged into.
Fixes GHSA-2g5p-q5f3-477p.
* fix(repo): seed nobody with fossil's default capabilities
A new repository seeded the nobody user with "cghijknorswy", so every request without a login card could push check-ins and unversioned files, write wiki pages and tickets, and held Setup. Seed the four built-in users `fossil new` creates, with fossil's capabilities: nobody "gjorz", anonymous "hz", developer "ei" and reader "kptw".
Setup and Admin now include check-in, read and clone, as they do in fossil, so the creating user can sync once given a password. A login to an account with no stored password is refused, as fossil's check_login refuses it; the creator starts with none, and the signature would otherwise be the SHA-1 of the nonce alone.
Tests that push without credentials grant nobody push explicitly. Existing repositories keep their stored capabilities.
* test(auth): reserved-login test updates the seeded developer and reader rows
New repositories now seed developer and reader as fossil does, so the test gives the existing rows a password instead of inserting them.
* docs(changelog): group the sync hardening fixes under Security
* test(sync): reqconfig tests sign their logins over the request body
The login nonce now has to cover the request body, so the reqconfig tests build their admin requests with signedRequest instead of a bare login card. (user: [email protected], size: 6786) [annotate] [blame] [check-ins using]
package dst import ( "path/filepath" "testing" "time" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/auth" "github.com/danmestas/go-libfossil/internal/blob" "github.com/danmestas/go-libfossil/internal/repo" "github.com/danmestas/go-libfossil/simio" _ "github.com/danmestas/go-libfossil/internal/testdriver" ) func createMasterRepo(t *testing.T) *repo.Repo { t.Helper() path := filepath.Join(t.TempDir(), "master.fossil") r, err := repo.Create(path, "master", simio.CryptoRand{}, "") if err != nil { t.Fatalf("repo.Create master: %v", err) } t.Cleanup(func() { r.Close() }) grantLeavesPush(t, r) return r } // grantLeavesPush lets the simulated leaves, which sync without a login // card, push artifacts (i) and unversioned files (y) to the master. A new // repository grants nobody only fossil's "gjorz". func grantLeavesPush(t *testing.T, r *repo.Repo) { t.Helper() if err := auth.UpdateCaps(r.DB(), "nobody", "gijoryz"); err != nil { t.Fatalf("grant nobody push: %v", err) } } // TestE2EPullFromMaster seeds artifacts in the mock fossil master, // runs the simulation, and verifies that all leaves converge. func TestE2EPullFromMaster(t *testing.T) { masterRepo := createMasterRepo(t) mf := NewMockFossil(masterRepo) // Seed 5 artifacts in the master. seeded := make(map[string][]byte) for i := range 5 { data := []byte("master artifact " + string(rune('A'+i))) uuid, err := mf.StoreArtifact(data) if err != nil { t.Fatalf("StoreArtifact %d: %v", i, err) } seeded[uuid] = data } sim, err := New(SimConfig{ Seed: 42, NumLeaves: 2, PollInterval: 5 * time.Second, TmpDir: t.TempDir(), Upstream: mf, }) if err != nil { t.Fatalf("New: %v", err) } defer sim.Close() // Run enough steps for convergence (each leaf needs ~3 rounds per sync: // round 1: pull โ igot; round 2: gimme โ file; round 3: converge). if err := sim.Run(20); err != nil { t.Fatalf("Run: %v", err) } t.Logf("Simulation: %d steps, %d syncs, %d errors", sim.Steps, sim.TotalSyncs, sim.TotalErrors) // Verify: every seeded artifact should be in every leaf repo. for _, leafID := range sim.LeafIDs() { leafRepo := sim.Leaf(leafID).Repo() for uuid := range seeded { _, exists := blob.Exists(leafRepo.DB(), uuid) if !exists { t.Errorf("leaf %s missing artifact %s", leafID, uuid) } } } } // TestE2EPushFromLeaf stores an artifact in a leaf repo, runs the simulation, // and verifies it arrives at the master. func TestE2EPushFromLeaf(t *testing.T) { masterRepo := createMasterRepo(t) mf := NewMockFossil(masterRepo) sim, err := New(SimConfig{ Seed: 99, NumLeaves: 1, PollInterval: 5 * time.Second, TmpDir: t.TempDir(), Upstream: mf, }) if err != nil { t.Fatalf("New: %v", err) } defer sim.Close() // Store an artifact directly in the leaf's repo. leafID := sim.LeafIDs()[0] leafRepo := sim.Leaf(leafID).Repo() data := []byte("artifact pushed from leaf") var uuid string err = leafRepo.WithTx(func(tx *db.Tx) error { rid, u, err := blob.Store(tx, data) if err != nil { return err } uuid = u _, err = tx.Exec("INSERT OR IGNORE INTO unsent(rid) VALUES(?)", rid) return err }) if err != nil { t.Fatalf("store in leaf: %v", err) } // Run simulation. if err := sim.Run(20); err != nil { t.Fatalf("Run: %v", err) } t.Logf("Simulation: %d steps, %d syncs, %d errors", sim.Steps, sim.TotalSyncs, sim.TotalErrors) // Verify: artifact should be in the master repo. _, exists := blob.Exists(mf.Repo().DB(), uuid) if !exists { t.Errorf("master missing artifact %s pushed from leaf", uuid) } } // TestE2EBidirectional tests both push and pull in the same simulation. func TestE2EBidirectional(t *testing.T) { masterRepo := createMasterRepo(t) mf := NewMockFossil(masterRepo) // Seed artifact in master. masterData := []byte("from master for bidirectional") masterUUID, _ := mf.StoreArtifact(masterData) sim, err := New(SimConfig{ Seed: 7, NumLeaves: 2, PollInterval: 5 * time.Second, TmpDir: t.TempDir(), Upstream: mf, }) if err != nil { t.Fatalf("New: %v", err) } defer sim.Close() // Seed artifact in leaf-0. leaf0Repo := sim.Leaf("leaf-0").Repo() leafData := []byte("from leaf-0 for bidirectional") var leafUUID string leaf0Repo.WithTx(func(tx *db.Tx) error { rid, u, err := blob.Store(tx, leafData) if err != nil { return err } leafUUID = u tx.Exec("INSERT OR IGNORE INTO unsent(rid) VALUES(?)", rid) return nil }) // Run enough steps. if err := sim.Run(40); err != nil { t.Fatalf("Run: %v", err) } t.Logf("Simulation: %d steps, %d syncs, %d errors", sim.Steps, sim.TotalSyncs, sim.TotalErrors) // Master artifact should be in both leaves. for _, id := range sim.LeafIDs() { _, exists := blob.Exists(sim.Leaf(id).Repo().DB(), masterUUID) if !exists { t.Errorf("leaf %s missing master artifact %s", id, masterUUID) } } // Leaf-0 artifact should be in master. _, exists := blob.Exists(mf.Repo().DB(), leafUUID) if !exists { t.Errorf("master missing leaf-0 artifact %s", leafUUID) } // Leaf-0 artifact should also be in leaf-1 (via master relay). // This requires leaf-1 to pull after master received it from leaf-0. _, exists = blob.Exists(sim.Leaf("leaf-1").Repo().DB(), leafUUID) if !exists { t.Logf("NOTE: leaf-1 hasn't received leaf-0's artifact yet (may need more rounds)") } } // TestE2EPartitionAndHeal tests that a partitioned leaf catches up after healing. func TestE2EPartitionAndHeal(t *testing.T) { masterRepo := createMasterRepo(t) mf := NewMockFossil(masterRepo) masterData := []byte("artifact before partition") masterUUID, _ := mf.StoreArtifact(masterData) sim, err := New(SimConfig{ Seed: 123, NumLeaves: 2, PollInterval: 5 * time.Second, TmpDir: t.TempDir(), Upstream: mf, }) if err != nil { t.Fatalf("New: %v", err) } defer sim.Close() // Partition leaf-1. sim.Network().Partition("leaf-1") // Run some steps โ leaf-0 should sync, leaf-1 should fail. sim.Run(10) // leaf-0 should have the artifact. _, exists := blob.Exists(sim.Leaf("leaf-0").Repo().DB(), masterUUID) if !exists { t.Fatal("leaf-0 should have master artifact after 10 steps") } // leaf-1 should NOT have the artifact. _, exists = blob.Exists(sim.Leaf("leaf-1").Repo().DB(), masterUUID) if exists { t.Fatal("leaf-1 should NOT have master artifact while partitioned") } // Heal and run more steps. sim.Network().Heal("leaf-1") sim.Run(10) // Now leaf-1 should have caught up. _, exists = blob.Exists(sim.Leaf("leaf-1").Repo().DB(), masterUUID) if !exists { t.Error("leaf-1 should have master artifact after healing") } }