Artifact 291c0901fbbd7a1f281e048105df866e7cf098f4da1800c2c0c5a875dda642f2:
- File
internal/sync/handler_tablesync_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: 9407) [annotate] [blame] [check-ins using]
package sync import ( "context" "encoding/json" "testing" "github.com/danmestas/go-libfossil/internal/auth" "github.com/danmestas/go-libfossil/internal/repo" "github.com/danmestas/go-libfossil/internal/xfer" ) func TestHandleSchemaCard(t *testing.T) { r := setupSyncTestRepo(t) def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "peer_id", Type: "text", PK: true}}, Conflict: "mtime-wins", } defJSON, _ := json.Marshal(def) req := &xfer.Message{Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "s", ProjectCode: "p"}, &xfer.PullCard{ServerCode: "s", ProjectCode: "p"}, &xfer.SchemaCard{Table: "test_table", Version: 1, Hash: "abc", MTime: 100, Content: defJSON}, }} resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } _ = resp var count int if err := r.DB().QueryRow("SELECT count(*) FROM x_test_table").Scan(&count); err != nil { t.Fatalf("x_test_table should exist: %v", err) } } func TestHandleXIGotXGimmeXRow(t *testing.T) { r := setupSyncTestRepo(t) def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "id", Type: "text", PK: true}, {Name: "val", Type: "text"}}, Conflict: "mtime-wins", } repo.EnsureSyncSchema(r.DB()) repo.RegisterSyncedTable(r.DB(), "kv", def, 100) repo.UpsertXRow(r.DB(), "kv", map[string]any{"id": "local-key", "val": "local-val"}, 200) pkColDefs := []repo.ColumnDef{{Name: "id", Type: "text", PK: true}} localPK := repo.PKHash(pkColDefs, map[string]any{"id": "local-key"}) remotePK := repo.PKHash(pkColDefs, map[string]any{"id": "remote-key"}) req := &xfer.Message{Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "s", ProjectCode: "p"}, &xfer.PullCard{ServerCode: "s", ProjectCode: "p"}, &xfer.XIGotCard{Table: "kv", PKHash: remotePK, MTime: 300}, }} resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } gimmes := findCards[*xfer.XGimmeCard](resp) if len(gimmes) == 0 { t.Fatal("expected xgimme for missing remote row") } if gimmes[0].PKHash != remotePK { t.Fatalf("xgimme pk = %q, want %q", gimmes[0].PKHash, remotePK) } igots := findCards[*xfer.XIGotCard](resp) found := false for _, ig := range igots { if ig.PKHash == localPK { found = true } } if !found { t.Fatal("expected xigot for local row") } } func TestHandleXDelete(t *testing.T) { r := setupPushableTestRepo(t) def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "id", Type: "text", PK: true}, {Name: "val", Type: "text"}}, Conflict: "mtime-wins", } repo.EnsureSyncSchema(r.DB()) repo.RegisterSyncedTable(r.DB(), "kv", def, 100) // Seed a live row at mtime 1000. if err := repo.UpsertXRow(r.DB(), "kv", map[string]any{"id": "row1", "val": "hello"}, 1000); err != nil { t.Fatalf("UpsertXRow: %v", err) } pkColDefs := []repo.ColumnDef{{Name: "id", Type: "text", PK: true}} pkHash := repo.PKHash(pkColDefs, map[string]any{"id": "row1"}) req := &xfer.Message{Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "s", ProjectCode: "p"}, &xfer.PullCard{ServerCode: "s", ProjectCode: "p"}, &xfer.XDeleteCard{ Table: "kv", PKHash: pkHash, MTime: 2000, PKData: []byte(`{"id":"row1"}`), }, }} _, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } // Verify the row is now a tombstone with mtime 2000. row, mtime, err := repo.LookupXRow(r.DB(), "kv", def, pkHash) if err != nil { t.Fatalf("LookupXRow: %v", err) } if row == nil { t.Fatal("expected tombstone row, got nil") } if !repo.IsTombstone(def, row) { t.Fatalf("expected tombstone, got row with val=%v", row["val"]) } if mtime != 2000 { t.Fatalf("expected mtime=2000, got %d", mtime) } } func TestHandleXIGotEmitsXDeleteForTombstone(t *testing.T) { r := setupSyncTestRepo(t) def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "id", Type: "text", PK: true}, {Name: "val", Type: "text"}}, Conflict: "mtime-wins", } repo.EnsureSyncSchema(r.DB()) repo.RegisterSyncedTable(r.DB(), "kv", def, 100) // Seed a live row, then tombstone it at mtime 2000. if err := repo.UpsertXRow(r.DB(), "kv", map[string]any{"id": "row1", "val": "hello"}, 1000); err != nil { t.Fatalf("UpsertXRow: %v", err) } pkColDefs := []repo.ColumnDef{{Name: "id", Type: "text", PK: true}} pkHash := repo.PKHash(pkColDefs, map[string]any{"id": "row1"}) if _, err := repo.DeleteXRowByPKHash(r.DB(), "kv", def, pkHash, 2000); err != nil { t.Fatalf("DeleteXRowByPKHash: %v", err) } // Client claims it has the row at old mtime 1000. req := &xfer.Message{Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "s", ProjectCode: "p"}, &xfer.PullCard{ServerCode: "s", ProjectCode: "p"}, &xfer.XIGotCard{Table: "kv", PKHash: pkHash, MTime: 1000}, }} resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } // Response must contain an XDeleteCard (not an XRowCard) for this pkHash. xdeletes := findCards[*xfer.XDeleteCard](resp) if len(xdeletes) == 0 { t.Fatal("expected xdelete card in response for tombstoned row") } found := false for _, xd := range xdeletes { if xd.Table == "kv" && xd.PKHash == pkHash { found = true if xd.MTime != 2000 { t.Errorf("xdelete mtime = %d, want 2000", xd.MTime) } } } if !found { t.Fatalf("expected xdelete for pkHash %q, got: %+v", pkHash, xdeletes) } // Must NOT contain an XRowCard for the same pkHash. xrows := findCards[*xfer.XRowCard](resp) for _, xr := range xrows { if xr.Table == "kv" && xr.PKHash == pkHash { t.Fatalf("unexpected xrow card for tombstoned row %q", pkHash) } } } func TestHandleXDelete_SelfWriteOwnershipCheck(t *testing.T) { serverRepo := setupSyncTestRepo(t) pc := testProjectCode(t, serverRepo.DB()) // Create users alice (owner) and bob (non-owner) with push+pull caps. if err := auth.CreateUser(serverRepo.DB(), pc, "alice", "alicesecret", "oi"); err != nil { t.Fatalf("CreateUser alice: %v", err) } if err := auth.CreateUser(serverRepo.DB(), pc, "bob", "bobsecret", "oi"); err != nil { t.Fatalf("CreateUser bob: %v", err) } def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "peer_id", Type: "text", PK: true}, {Name: "status", Type: "text"}}, Conflict: "self-write", } repo.EnsureSyncSchema(serverRepo.DB()) repo.RegisterSyncedTable(serverRepo.DB(), "peers", def, 1000) // Insert row owned by "alice". repo.UpsertXRow(serverRepo.DB(), "peers", map[string]any{ "peer_id": "alice", "status": "online", "_owner": "alice", }, 1000) pkColDefs := []repo.ColumnDef{{Name: "peer_id", Type: "text", PK: true}} pkHash := repo.PKHash(pkColDefs, map[string]any{"peer_id": "alice"}) // "bob" tries to delete alice's row — should be rejected. msg := signedRequest(t, "bob", "bobsecret", pc, &xfer.PushCard{ServerCode: "sc", ProjectCode: "pc"}, &xfer.PullCard{ServerCode: "sc", ProjectCode: "pc"}, &xfer.XDeleteCard{ Table: "peers", PKHash: pkHash, MTime: 2000, PKData: []byte(`{"peer_id":"alice"}`), }, ) resp, err := HandleSync(context.Background(), serverRepo, msg) if err != nil { t.Fatalf("HandleSync: %v", err) } // bob's login must succeed, or the row survives for the wrong reason. for _, ec := range findCards[*xfer.ErrorCard](resp) { if ec.Message == "login failed" { t.Fatal("bob's login was refused; the ownership check never ran") } } // Row should still be alive — deletion rejected. row, mtime, _ := repo.LookupXRow(serverRepo.DB(), "peers", def, pkHash) if row == nil { t.Fatal("row should still exist") } if repo.IsTombstone(def, row) { t.Error("row should NOT be tombstone — bob is not the owner") } if mtime != 1000 { t.Errorf("mtime should be unchanged: got %d, want 1000", mtime) } } func TestHandleXDelete_PKDataHashMismatch(t *testing.T) { serverRepo := setupPushableTestRepo(t) def := repo.TableDef{ Columns: []repo.ColumnDef{{Name: "id", Type: "text", PK: true}, {Name: "data", Type: "text"}}, Conflict: "mtime-wins", } repo.EnsureSyncSchema(serverRepo.DB()) repo.RegisterSyncedTable(serverRepo.DB(), "test_tbl", def, 1000) // Send xdelete with PKHash for "k1" but PKData for "INJECTED". pkColDefs := []repo.ColumnDef{{Name: "id", Type: "text", PK: true}} realHash := repo.PKHash(pkColDefs, map[string]any{"id": "k1"}) msg := &xfer.Message{ Cards: []xfer.Card{ &xfer.PushCard{ServerCode: "sc", ProjectCode: "pc"}, &xfer.PullCard{ServerCode: "sc", ProjectCode: "pc"}, &xfer.XDeleteCard{ Table: "test_tbl", PKHash: realHash, MTime: 2000, PKData: []byte(`{"id":"INJECTED"}`), // Mismatched! }, }, } // applyXDeleteLocally returns an error on hash mismatch — HandleSync propagates it. _, err := HandleSync(context.Background(), serverRepo, msg) if err == nil { t.Fatal("expected error for PKData hash mismatch, got nil") } // Should NOT have inserted a tombstone for "INJECTED". injectedHash := repo.PKHash(pkColDefs, map[string]any{"id": "INJECTED"}) row, _, _ := repo.LookupXRow(serverRepo.DB(), "test_tbl", def, injectedHash) if row != nil { t.Error("should NOT have inserted tombstone for mismatched PKData") } // Should NOT have inserted a tombstone for "k1" either. row2, _, _ := repo.LookupXRow(serverRepo.DB(), "test_tbl", def, realHash) if row2 != nil { t.Error("should NOT have inserted any tombstone for mismatched PKData") } }