Artifact 53337a53b2cc928f27cdbe81081e3b595a696386f4781482b14f247ed12a3d3f:
- File
README.md
— 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: 10224) [annotate] [blame] [check-ins using]
go-libfossil
Pure-Go library and CLI for Fossil repositories. Drop-in compatible with Fossil's .fossil SQLite format, with no CGo and no upstream fossil binary required.
The repository and module path are go-libfossil (
go get github.com/danmestas/go-libfossil), but the Go package is still imported aslibfossiland the CLI installs as thelibfossilcommand. Only the path moved; the package and binary names are unchanged.
Why libfossil
- Pure Go, no CGo. Static binaries, trivial cross-compilation, works under
GOOS=wasip1 GOARCH=wasm. - Drop-in compatible. Repositories produced by upstream Fossil are readable, and vice versa — it's the same SQLite schema.
- Embeddable. Use the full
RepoAPI directly in your Go service. No subprocess calls, no temp files. - Instrumented. Sync and checkout observer interfaces make OpenTelemetry (or your own metrics) a few lines of code.
- Deterministically testable. Deterministic simulation testing (DST) with BUGGIFY fault injection.
Installation
CLI
go install github.com/danmestas/go-libfossil/cmd/libfossil@latest
The binary is named libfossil to avoid $PATH collisions with upstream fossil.
Library
go get github.com/danmestas/go-libfossil
CLI quick start
libfossil repo new my.fossil
libfossil -R my.fossil repo ci -m "first commit" hello.txt
libfossil -R my.fossil repo timeline
libfossil -R my.fossil repo ls
libfossil -R my.fossil repo annotate hello.txt
libfossil -R my.fossil repo verify
Full command list: libfossil --help. See docs/migration-from-fossil.md for a command-by-command comparison with upstream Fossil.
Library quick start
package main
import (
"log"
libfossil "github.com/danmestas/go-libfossil"
_ "github.com/danmestas/go-libfossil/db/driver/modernc"
)
func main() {
r, err := libfossil.Create("my.fossil", libfossil.CreateOpts{User: "admin"})
if err != nil {
log.Fatal(err)
}
defer r.Close()
rid, uuid, err := r.Commit(libfossil.CommitOpts{
Files: []libfossil.FileToCommit{{Name: "hello.txt", Content: []byte("hello")}},
Comment: "initial commit",
User: "admin",
})
if err != nil {
log.Fatal(err)
}
log.Printf("committed rid=%d uuid=%s", rid, uuid[:12])
entries, err := r.Timeline(libfossil.TimelineOpts{Limit: 10})
if err != nil {
log.Fatal(err)
}
for _, e := range entries {
log.Printf(" %s %s", e.UUID[:12], e.Comment)
}
}
Working example: examples/embed-repo-api/.
Sync
// Sync with a remote Fossil server.
result, err := r.Sync(ctx,
libfossil.NewHTTPTransport("http://host/repo"),
libfossil.SyncOpts{Push: true, Pull: true},
)
// Serve the sync protocol (e.g. for leaf agents, bridges, mirrors).
http.Handle("/", r.XferHandler())
Served repositories enforce the user table the way fossil does. A request
without credentials runs as nobody, which a new repository lets clone and
pull but not push. Give clients an account, or grant nobody more with
r.SetCaps("nobody", ...).
The Transport interface is pluggable — swap HTTP for NATS, WebSocket, libp2p, or anything that delivers bytes round-trip.
Embedding the CLI
cli/ exposes Kong command structs you can mount inside your own CLI:
import (
"github.com/alecthomas/kong"
"github.com/danmestas/go-libfossil/cli"
_ "github.com/danmestas/go-libfossil/db/driver/modernc"
)
type MyCLI struct {
cli.Globals
Repo cli.RepoCmd `cmd:"" help:"Fossil repo operations"`
// Add your own commands here.
}
func main() {
var c MyCLI
ctx := kong.Parse(&c)
ctx.FatalIfErrorf(ctx.Run(&c.Globals))
}
Project layout
| Package | Purpose |
|---|---|
root (libfossil) |
Repo handle, Transport, SyncObserver, CheckoutObserver |
cli/ |
Embeddable Kong command structs for the repo subcommands |
cmd/libfossil/ |
Standalone CLI binary |
db/ |
SQLite abstraction with pluggable drivers |
db/driver/modernc |
Pure-Go SQLite driver (default) |
db/driver/ncruces |
wasm-capable SQLite driver |
observer/otel/ |
Optional OpenTelemetry observer (separate submodule) |
dst/ |
Deterministic simulation tests + BUGGIFY harness |
simio/ |
Clock, Rand, Storage interfaces for deterministic testing |
testutil/ |
Shared test helpers |
Deep dive: docs/architecture.md.
SQLite drivers
| Driver | Import | When to use |
|---|---|---|
modernc (default) |
_ "github.com/danmestas/go-libfossil/db/driver/modernc" |
Default for any server, CLI, or desktop use |
ncruces |
_ "github.com/danmestas/go-libfossil/db/driver/ncruces" |
wasm targets (GOOS=wasip1 or browser/OPFS) |
Library embedders select exactly one driver with a blank import at link time; importing both panics. The shipped cmd/libfossil CLI uses modernc by default; go build -tags test_ncruces ./cmd/libfossil selects ncruces. See docs/extension-points.md for the registration contract.
Observers
// Built-in, zero dependencies.
libfossil.NopSyncObserver() // silent
libfossil.StdoutSyncObserver() // human-readable stderr
// Optional OpenTelemetry (separate submodule — no OTel deps in core).
import "github.com/danmestas/go-libfossil/observer/otel"
obs := otel.NewSyncObserver()
Both SyncObserver and CheckoutObserver are small interfaces you can implement directly. Details: docs/extension-points.md.
WASI / wasm
libfossil compiles to a generic WASI Preview 1 module via the ncruces driver:
GOOS=wasip1 GOARCH=wasm go build -o libfossil.wasm ./examples/wasm/
See examples/wasm/ for a runnable demo and current runtime caveats (the non-js ncruces driver variant has a known locking-mode quirk under wasmtime).
Testing
make test— unit tests with the defaultmoderncdrivermake test-drivers— unit tests against bothmoderncandncrucesmake test-otel— OTel submodule tests (runs withGOWORK=off)make test-all— everything, including the binary buildmake setup-hooks— install the pre-commit hook (~45s/commit)
Test strategy — unit tests, dual-driver matrix, and deterministic simulation (DST) with BUGGIFY fault injection: docs/testing.md.
Documentation
Full documentation: https://libfossil-docs.daniel-mestas.workers.dev.
Local preview: make docs-serve, then visit http://localhost:1313/.
Markdown sources: docs/site/content/.
| Doc | Audience |
|---|---|
| docs/architecture.md | Contributors learning the codebase |
| docs/testing.md | Contributors writing or debugging tests |
| docs/extension-points.md | Consumers adding observers or custom drivers |
| docs/migration-from-fossil.md | Users coming from upstream fossil |
| CONTRIBUTING.md | Anyone submitting a PR |
| CHANGELOG.md | Release notes |
Contributing
See CONTRIBUTING.md.
Acknowledgements
This project stands on the work of others.
- Stephan Beal — author of libfossil, the C library that gives this project its name. This is an indirect Go port: it follows the shape and intent of Stephan's libfossil rather than transliterating it, and leans on the original as a reference for how a Fossil library ought to be organized.
- Dr. D. Richard Hipp and the Fossil SCM project — the Fossil source code was the implementation guide of record. Where this library and upstream Fossil had to agree on the bytes — SQLite schema, manifest format, delta and sync wire formats — Fossil's source was the authority.
- TigerBeetle and TigerStyle — the testing philosophy: assertions everywhere, bounded everything, and treating tests as a first-class engineering surface.
- John Ousterhout and A Philosophy of Software Design — the engineering principles for keeping modules deep and interfaces narrow as the codebase grew.
- Antithesis and deterministic simulation testing — the model behind this project's own DST harness, where time, randomness, and faults are controlled so that every failure is perfectly reproducible.
License
MIT — see LICENSE.