Artifact 735b67bd3787b5d6e0395ad29c76941ef0c8b687f6b6489dd94b9710804f204d:
- File
internal/repo/repo.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: 5536) [annotate] [blame] [check-ins using]
package repo import ( "fmt" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/content" libfossil "github.com/danmestas/go-libfossil/internal/fsltype" "github.com/danmestas/go-libfossil/simio" ) type Repo struct { db *db.DB path string } // Create creates a new repo at path, seeded with the given user. // If projectCode is empty, a fresh project-code is generated; otherwise // projectCode must already be valid (40-char lowercase hex) — validation // is enforced at the libfossil.Create boundary. func Create(path string, user string, rng simio.Rand, projectCode string) (*Repo, error) { env := simio.RealEnv() env.Rand = rng return CreateWithEnv(path, user, env, projectCode) } func CreateWithEnv(path string, user string, env *simio.Env, projectCode string) (*Repo, error) { if path == "" { panic("repo.CreateWithEnv: path must not be empty") } if env == nil { env = simio.RealEnv() } if env.Rand == nil { panic("repo.CreateWithEnv: env.Rand must not be nil") } if env.Storage == nil { env.Storage = simio.OSStorage{} } if _, err := env.Storage.Stat(path); err == nil { return nil, fmt.Errorf("repo.CreateWithEnv: file already exists: %s", path) } d, err := db.Open(path) if err != nil { return nil, fmt.Errorf("repo.CreateWithEnv open: %w", err) } if err := db.CreateRepoSchema(d); err != nil { d.Close() if rmErr := env.Storage.Remove(path); rmErr != nil { return nil, fmt.Errorf("repo.CreateWithEnv: %w (cleanup failed: %v)", err, rmErr) } return nil, fmt.Errorf("repo.CreateWithEnv schema: %w", err) } if err := db.SeedUser(d, user); err != nil { d.Close() if rmErr := env.Storage.Remove(path); rmErr != nil { return nil, fmt.Errorf("repo.CreateWithEnv: %w (cleanup failed: %v)", err, rmErr) } return nil, fmt.Errorf("repo.CreateWithEnv seed user: %w", err) } if err := db.SeedConfig(d, env.Rand, projectCode); err != nil { d.Close() if rmErr := env.Storage.Remove(path); rmErr != nil { return nil, fmt.Errorf("repo.CreateWithEnv: %w (cleanup failed: %v)", err, rmErr) } return nil, fmt.Errorf("repo.CreateWithEnv seed config: %w", err) } // After SeedConfig, so a seeded Rand still yields the project and server // codes it did before these users were added. if err := db.SeedDefaultUsers(d, env.Rand); err != nil { d.Close() if rmErr := env.Storage.Remove(path); rmErr != nil { return nil, fmt.Errorf("repo.CreateWithEnv: %w (cleanup failed: %v)", err, rmErr) } return nil, fmt.Errorf("repo.CreateWithEnv seed default users: %w", err) } return &Repo{db: d, path: path}, nil } func Open(path string) (*Repo, error) { return OpenWithEnv(path, nil) } func OpenWithEnv(path string, env *simio.Env) (*Repo, error) { if path == "" { panic("repo.OpenWithEnv: path must not be empty") } if env == nil { env = simio.RealEnv() } if env.Storage == nil { env.Storage = simio.OSStorage{} } if err := checkExists(env, path); err != nil { return nil, fmt.Errorf("repo.OpenWithEnv: %w", err) } d, err := db.Open(path) if err != nil { return nil, fmt.Errorf("repo.OpenWithEnv: %w", err) } id, err := d.ApplicationID() if err != nil { d.Close() return nil, fmt.Errorf("repo.OpenWithEnv application_id: %w", err) } if id != libfossil.FossilApplicationID { d.Close() return nil, fmt.Errorf("repo.OpenWithEnv: not a fossil repo (application_id=%d, want %d)", id, libfossil.FossilApplicationID) } return &Repo{db: d, path: path}, nil } func (r *Repo) Close() error { return r.db.Close() } // Checkpoint runs PRAGMA wal_checkpoint(<mode>) against the repo's database. // See db.DB.Checkpoint for semantics. func (r *Repo) Checkpoint(mode db.CheckpointMode) error { return r.db.Checkpoint(mode) } func (r *Repo) Path() string { return r.path } func (r *Repo) DB() *db.DB { return r.db } func (r *Repo) WithTx(fn func(tx *db.Tx) error) error { return r.db.WithTx(fn) } // Config reads a configuration value from the repo's config table. func (r *Repo) Config(key string) (string, error) { var value string err := r.db.QueryRow("SELECT value FROM config WHERE name=?", key).Scan(&value) if err != nil { return "", fmt.Errorf("repo.Config %q: %w", key, err) } return value, nil } // UUIDByRID returns the UUID (manifest hash) of the artifact with the given // rid by querying the blob table. Returns sql.ErrNoRows (wrapped) when no // blob row exists for the rid. func (r *Repo) UUIDByRID(rid int64) (string, error) { var uuid string err := r.db.QueryRow("SELECT uuid FROM blob WHERE rid=?", rid).Scan(&uuid) if err != nil { return "", fmt.Errorf("repo.UUIDByRID rid=%d: %w", rid, err) } return uuid, nil } // SetConfig writes a configuration value to the repo's config table. func (r *Repo) SetConfig(key, value string) error { _, err := r.db.Exec( "INSERT OR REPLACE INTO config(name, value, mtime) VALUES(?, ?, julianday('now'))", key, value, ) if err != nil { return fmt.Errorf("repo.SetConfig %q: %w", key, err) } return nil } func (r *Repo) Verify() error { if r == nil { panic("repo.Verify: receiver must not be nil") } rows, err := r.db.Query("SELECT rid FROM blob WHERE size >= 0") if err != nil { return fmt.Errorf("repo.Verify query: %w", err) } defer rows.Close() for rows.Next() { var rid int64 if err := rows.Scan(&rid); err != nil { return fmt.Errorf("repo.Verify scan: %w", err) } if err := content.Verify(r.db, libfossil.FslID(rid)); err != nil { return err } } return rows.Err() }