Artifact 3a970101ab2c7fc9e810ef107ec903ba3c55fabe8e6f838a21eca33b167b4b60:
- File
internal/sync/handler_login_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: 7544) [annotate] [blame] [check-ins using]
package sync import ( "context" "testing" "github.com/danmestas/go-libfossil/internal/auth" "github.com/danmestas/go-libfossil/internal/blob" "github.com/danmestas/go-libfossil/internal/hash" "github.com/danmestas/go-libfossil/internal/repo" "github.com/danmestas/go-libfossil/internal/xfer" ) // signedRequest returns the request a client logged in as user would send: // cards behind a login card whose nonce covers their wire bytes, decoded the // way the server decodes a request, so the login card carries its tail. func signedRequest( t *testing.T, user, password, projectCode string, cards ...xfer.Card, ) *xfer.Message { t.Helper() payload, err := encodeCards(cards) if err != nil { t.Fatalf("encodeCards: %v", err) } return wireRequest(t, computeLogin(user, password, projectCode, payload), cards...) } // wireRequest puts login ahead of cards, encodes the message and decodes it // again, as the request arrives at a server. func wireRequest(t *testing.T, login *xfer.LoginCard, cards ...xfer.Card) *xfer.Message { t.Helper() all := append([]xfer.Card{login}, cards...) wire, err := (&xfer.Message{Cards: all}).Encode() if err != nil { t.Fatalf("Encode: %v", err) } msg, err := xfer.Decode(wire, xfer.ContentTypeCompressed) if err != nil { t.Fatalf("Decode: %v", err) } return msg } // loginRepo returns a repo whose nobody may only pull and whose "alice" may // only push, so each test can tell which capabilities a request ran with. func loginRepo(t *testing.T) (*repo.Repo, string) { t.Helper() r := setupSyncTestRepo(t) pc := testProjectCode(t, r.DB()) if _, err := r.DB().Exec("UPDATE user SET cap='o' WHERE login='nobody'"); err != nil { t.Fatalf("set nobody caps: %v", err) } if err := auth.CreateUser(r.DB(), pc, "alice", "secret", "i"); err != nil { t.Fatalf("CreateUser: %v", err) } return r, pc } // requireLoginRefused asserts that resp is the whole of a refused login: the // one error card fossil sends (src/xfer.c page_xfer resets the reply and // emits "error login\sfailed"), and nothing processed after it. func requireLoginRefused(t *testing.T, resp *xfer.Message, want string) { t.Helper() if len(resp.Cards) != 1 { t.Fatalf("reply has %d cards, want only the error: %#v", len(resp.Cards), resp.Cards) } ec, ok := resp.Cards[0].(*xfer.ErrorCard) if !ok || ec.Message != want { t.Fatalf("reply = %#v, want error %q", resp.Cards[0], want) } } // A login card captured from one request must not authenticate another body. // The nonce is the SHA-1 of the body that followed the login line (§6.2), and // the server has to check it, or the signature proves nothing about the body. func TestHandleReplayedLoginRefused(t *testing.T) { r, pc := loginRepo(t) captured := signedRequest(t, "alice", "secret", pc, &xfer.PullCard{ServerCode: "sc", ProjectCode: pc}, ).Cards[0].(*xfer.LoginCard) data := []byte("pushed under a replayed login") replay := wireRequest(t, captured, &xfer.PushCard{ServerCode: "sc", ProjectCode: pc}, &xfer.FileCard{UUID: hash.SHA1(data), Content: data}, ) resp, err := HandleSync(context.Background(), r, replay) if err != nil { t.Fatalf("HandleSync: %v", err) } requireLoginRefused(t, resp, "login failed") if _, ok := blob.Exists(r.DB(), hash.SHA1(data)); ok { t.Fatal("a replayed login card stored a pushed file") } } // A login card that was never decoded from a request has no body tail, so it // cannot vouch for one. func TestHandleUndecodedLoginRefused(t *testing.T) { r, pc := loginRepo(t) payload := []byte("anything") req := &xfer.Message{Cards: []xfer.Card{ computeLogin("alice", "secret", pc, payload), &xfer.PullCard{ServerCode: "sc", ProjectCode: pc}, }} resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } requireLoginRefused(t, resp, "login failed") } // A failed login ends the exchange: fossil does not carry on as nobody. func TestHandleFailedLoginIsFatal(t *testing.T) { r, pc := loginRepo(t) storeTestBlob(t, r, []byte("visible to nobody")) req := signedRequest(t, "alice", "wrong", pc, &xfer.PullCard{ServerCode: "sc", ProjectCode: pc}, ) resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } requireLoginRefused(t, resp, "login failed") } // A successful login adds the user's capabilities to nobody's; it does not // replace them (src/xfer.c check_login calls login_set_capabilities, which // only sets flags). alice may push, nobody may pull, so alice may do both. func TestHandleLoginAddsToNobodyCaps(t *testing.T) { r, pc := loginRepo(t) storeTestBlob(t, r, []byte("already on the server")) data := []byte("pushed by alice") req := signedRequest(t, "alice", "secret", pc, &xfer.PushCard{ServerCode: "sc", ProjectCode: pc}, &xfer.PullCard{ServerCode: "sc", ProjectCode: pc}, &xfer.FileCard{UUID: hash.SHA1(data), Content: data}, ) resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } if errs := findCards[*xfer.ErrorCard](resp); len(errs) > 0 { t.Fatalf("unexpected error: %s", errs[0].Message) } if _, ok := blob.Exists(r.DB(), hash.SHA1(data)); !ok { t.Fatal("alice's push was not stored") } if len(findCards[*xfer.IGotCard](resp)) == 0 { t.Fatal("alice lost nobody's pull capability by logging in") } } // One login per request (§6.1). A second card is fatal even when both verify. func TestHandleMultipleLoginCardsRefused(t *testing.T) { r, pc := loginRepo(t) pull := &xfer.PullCard{ServerCode: "sc", ProjectCode: pc} payload, err := encodeCards([]xfer.Card{pull}) if err != nil { t.Fatalf("encodeCards: %v", err) } second := computeLogin("alice", "secret", pc, payload) req := signedRequest(t, "alice", "secret", pc, second, pull) resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } requireLoginRefused(t, resp, "multiple login cards") } // Anybody may sync as nobody or anonymous (src/xfer.c check_login): the login // succeeds without a password and leaves nobody's capabilities in force. func TestHandleAnonymousLoginKeepsNobodyCaps(t *testing.T) { r, pc := loginRepo(t) storeTestBlob(t, r, []byte("visible to nobody")) req := signedRequest(t, "anonymous", "", pc, &xfer.PullCard{ServerCode: "sc", ProjectCode: pc}, ) resp, err := HandleSync(context.Background(), r, req) if err != nil { t.Fatalf("HandleSync: %v", err) } if errs := findCards[*xfer.ErrorCard](resp); len(errs) > 0 { t.Fatalf("unexpected error: %s", errs[0].Message) } if len(findCards[*xfer.IGotCard](resp)) == 0 { t.Fatal("an anonymous login lost nobody's pull capability") } } // A user row with no password cannot be logged into (src/xfer.c check_login // requires length(pw)>0): its signature would be SHA1(nonce) alone, which // anyone can compute. func TestHandleEmptyPasswordLoginRefused(t *testing.T) { r, pc := loginRepo(t) if _, err := r.DB().Exec("UPDATE user SET pw='' WHERE login='alice'"); err != nil { t.Fatalf("clear pw: %v", err) } pull := &xfer.PullCard{ServerCode: "sc", ProjectCode: pc} payload, err := encodeCards([]xfer.Card{pull}) if err != nil { t.Fatalf("encodeCards: %v", err) } nonce := sha1Hex(payload) login := &xfer.LoginCard{User: "alice", Nonce: nonce, Signature: sha1Hex([]byte(nonce))} resp, err := HandleSync(context.Background(), r, wireRequest(t, login, pull)) if err != nil { t.Fatalf("HandleSync: %v", err) } requireLoginRefused(t, resp, "login failed") }