carlos / platform Public

lease: a SQLite header counts only under its whole 16-byte signature

Astra R2 P1-2 on sqlite-integrity-safe. sourceHeader, like
lease.ChangeCounter, checked 15 of the 16 signature bytes, so a source
SQLite refuses (its terminating NUL damaged) could still count as
current in the box drill and not_stale in the hibernate drill.

Enforced in one place: lease.ReadHeader reads the counter and journal
mode bytes in one read and requires "SQLite format 3\x00" whole.
ChangeCounter returns its counter, and the freshness check reads the
source through it (ops.sourceHeader is gone). A source failing the
check is "source header unreadable: not a SQLite database": unknown.
No new user-facing string.

Guard tests: TestReadHeaderNeedsTheWholeSignature (ReadHeader and
ChangeCounter refuse the damaged NUL); a source with only the NUL
damaged and a clean level copy is unknown in the box drill
(TestRestoreVerifyUnknownIsNotCurrent) and passed/unknown through the
hibernate drill's mapping.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a67d0b45c80d9b2028da64b4436d205be40fb93f parent a50575c
5 files changed, +112 −32
  • internal/lease/check.go +26 −5
  • internal/lease/check_test.go +31 −0
  • internal/ops/freshness.go +2 −26
  • internal/ops/freshness_test.go +36 −1
  • internal/ops/hibernate_verify_test.go +17 −0
diff --git a/internal/lease/check.go b/internal/lease/check.go
index 16ca1ffe0..88ac30b10 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -397,20 +397,41 @@ func verifyRestored(ctx context.Context, prefix, dir string, restore func(out st
// harmless: it can only make a stale replica look current (a missed alarm),
// never a current replica look stale (a false one).
func ChangeCounter(path string) (uint32, error) {
+ h, err := ReadHeader(path)
+ return h.Counter, err
+}
+
+// Header is what the drills read from a SQLite file's header.
+type Header struct {
+ // Counter is the file change counter, bytes 24-27.
+ Counter uint32
+ // Mode is bytes 18 and 19, the file format write and read versions:
+ // 1 and 1 for a rollback journal, 2 and 2 for WAL.
+ Mode [2]byte
+}
+
+// sqliteSignature is the 16 bytes every SQLite database begins with.
+const sqliteSignature = "SQLite format 3\x00"
+
+// ReadHeader reads path's SQLite header in one read. Nothing in it is
+// evidence unless the file carries SQLite's whole 16-byte signature, which
+// SQLite itself requires. An error opening the file is returned as it is,
+// so os.IsNotExist sees it.
+func ReadHeader(path string) (Header, error) {
f, err := os.Open(path)
if err != nil {
- return 0, err
+ return Header{}, err
}
defer f.Close()
var header [28]byte
if _, err := io.ReadFull(f, header[:]); err != nil {
- return 0, fmt.Errorf("read header: %w", err)
+ return Header{}, fmt.Errorf("read header: %w", err)
}
- if string(header[:15]) != "SQLite format 3" {
- return 0, fmt.Errorf("not a SQLite database")
+ if string(header[:len(sqliteSignature)]) != sqliteSignature {
+ return Header{}, fmt.Errorf("not a SQLite database")
}
- return binary.BigEndian.Uint32(header[24:28]), nil
+ return Header{Counter: binary.BigEndian.Uint32(header[24:28]), Mode: [2]byte{header[18], header[19]}}, nil
}
// HasReplica reports whether the host at s3://bucket/prefix has a replica
diff --git a/internal/lease/check_test.go b/internal/lease/check_test.go
index 22715bf2f..bcbc8366f 100644
--- a/internal/lease/check_test.go
+++ b/internal/lease/check_test.go
@@ -246,6 +246,37 @@ func TestCheckDBContextHonoursCancellation(t *testing.T) {
}
}
+// The counter and journal mode are evidence only under SQLite's whole
+// 16-byte signature, "SQLite format 3\x00": with its NUL damaged, SQLite
+// refuses the file, and so does ReadHeader (and ChangeCounter through it).
+func TestReadHeaderNeedsTheWholeSignature(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "h.db")
+ seedDB(t, path)
+ h, err := ReadHeader(path)
+ if err != nil {
+ t.Fatalf("ReadHeader(clean) = %v", err)
+ }
+ if h.Mode != [2]byte{2, 2} {
+ t.Fatalf("seedDB is in WAL mode, ReadHeader says %v", h.Mode)
+ }
+ f, err := os.OpenFile(path, os.O_RDWR, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.WriteAt([]byte{1}, 15); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ReadHeader(path); err == nil {
+ t.Fatal("ReadHeader accepted a file whose signature lacks its NUL")
+ }
+ if _, err := ChangeCounter(path); err == nil {
+ t.Fatal("ChangeCounter accepted a file whose signature lacks its NUL")
+ }
+}
+
// replicatedBatches replicates seedDB's rows and then two more batches of
// writes to a litestream file replica, syncing after each, and returns the
// replica directory and the TXID each batch ended at. Every batch also sets
diff --git a/internal/ops/freshness.go b/internal/ops/freshness.go
index 53560214f..3386b70c3 100644
--- a/internal/ops/freshness.go
+++ b/internal/ops/freshness.go
@@ -25,10 +25,7 @@ package ops
// process just read.
import (
- "encoding/binary"
- "errors"
"fmt"
- "io"
"os"
"time"
@@ -102,7 +99,8 @@ func replicaFreshness(srcPath, restoredPath string, srcModTime time.Time) (fresh
// hibernation drill, where lease.VerifyReplica reads the counter and then
// sweeps its throwaway copy in the same call.
func replicaFreshnessCounter(srcPath string, restoredCounter uint32, srcModTime time.Time) (freshness, string) {
- srcCounter, mode, err := sourceHeader(srcPath)
+ src, err := lease.ReadHeader(srcPath)
+ srcCounter, mode := src.Counter, src.Mode
if os.IsNotExist(err) {
return freshnessNoSource, "source database is not on disk — this replica can never advance again"
}
@@ -135,28 +133,6 @@ func replicaFreshnessCounter(srcPath string, restoredCounter uint32, srcModTime
restoredCounter, srcCounter, srcModTime.UTC().Format(time.RFC3339))
}
-// sourceHeader reads the source database's change counter (header bytes
-// 24-27, as lease.ChangeCounter) and its journal mode (header bytes 18 and
-// 19, the file format write and read versions: 1 and 1 for a rollback
-// journal, 2 and 2 for WAL), in one read. An error opening the file is
-// returned as it is, so os.IsNotExist sees it.
-func sourceHeader(path string) (counter uint32, mode [2]byte, err error) {
- f, err := os.Open(path)
- if err != nil {
- return 0, mode, err
- }
- defer f.Close()
-
- var header [28]byte
- if _, err := io.ReadFull(f, header[:]); err != nil {
- return 0, mode, fmt.Errorf("read header: %w", err)
- }
- if string(header[:15]) != "SQLite format 3" {
- return 0, mode, errors.New("not a SQLite database")
- }
- return binary.BigEndian.Uint32(header[24:28]), [2]byte{header[18], header[19]}, nil
-}
-
// sourceModTime is the source database's mtime, or the zero time when it
// cannot be stated (which replicaFreshness will treat through its own paths).
func sourceModTime(path string) time.Time {
diff --git a/internal/ops/freshness_test.go b/internal/ops/freshness_test.go
index f6f8955d6..ec7f6fbbc 100644
--- a/internal/ops/freshness_test.go
+++ b/internal/ops/freshness_test.go
@@ -55,6 +55,23 @@ func writeMixedCounterDB(t *testing.T, path string, writes int) {
}
}
+// damageSignatureNUL sets byte 15 of a SQLite file, the NUL that ends the
+// 16-byte signature "SQLite format 3\x00", to 1. SQLite refuses such a file
+// as not a database; its counter and mode bytes are untouched.
+func damageSignatureNUL(t *testing.T, path string) {
+ t.Helper()
+ f, err := os.OpenFile(path, os.O_RDWR, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.WriteAt([]byte{1}, 15); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+}
+
// Every row of the freshness table (spec §5.3): only affirmative evidence
// is current. A copy behind a recently written source, and any copy of a
// WAL-mode source that is not behind, could not be judged.
@@ -131,15 +148,20 @@ func TestRestoreVerifyUnknownIsNotCurrent(t *testing.T) {
writeCounterDB(t, busy, 5)
mixed := filepath.Join(srcDir, "mixed.db")
writeMixedCounterDB(t, mixed, 3)
+ damaged := filepath.Join(srcDir, "damaged.db")
+ writeCounterDB(t, damaged, 3)
copies := map[string][]byte{busy: busyCopy}
- for _, p := range []string{journal, wal, mixed} {
+ for _, p := range []string{journal, wal, mixed, damaged} {
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
copies[p] = b
}
+ // The copy is the clean file; only the source's signature is damaged,
+ // so its (1,1) mode and level counter are no evidence.
+ damageSignatureNUL(t, damaged)
var mu sync.Mutex
restores := map[string]int{}
prev := restoreAndCheckFn
@@ -200,6 +222,19 @@ func TestRestoreVerifyUnknownIsNotCurrent(t *testing.T) {
}
}
+ out, err = run(journal, damaged)
+ if err != nil {
+ t.Fatalf("RestoreVerify with a damaged source signature = %v, want nil", err)
+ }
+ for _, line := range []string{
+ "ok " + damaged + " (restored clean, freshness unknown: source header unreadable: not a SQLite database)",
+ "restore-verify: all 2 replicas restore clean; 1 are current, 1 could not be judged",
+ } {
+ if !strings.Contains(out, line+"\n") {
+ t.Errorf("output lacks %q:\n%s", line, out)
+ }
+ }
+
out, err = run(journal)
if err != nil {
t.Fatalf("RestoreVerify of a current replica = %v", err)
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go
index cf916ac2b..dce2f573e 100644
--- a/internal/ops/hibernate_verify_test.go
+++ b/internal/ops/hibernate_verify_test.go
@@ -1035,6 +1035,23 @@ func TestVerifyHibernatingFreshnessOnlyOnLeaseHolder(t *testing.T) {
}
return p, n
},
+ "source signature damaged, level": func(t *testing.T) (string, uint32) {
+ p := filepath.Join(t.TempDir(), "damaged.db")
+ writeCounterDB(t, p, 30)
+ old := time.Now().Add(-2 * time.Hour)
+ if err := os.Chtimes(p, old, old); err != nil {
+ t.Fatal(err)
+ }
+ n, err := ChangeCounter(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ damageSignatureNUL(t, p)
+ if err := os.Chtimes(p, old, old); err != nil {
+ t.Fatal(err)
+ }
+ return p, n
+ },
"mixed-version source, level": func(t *testing.T) (string, uint32) {
p := filepath.Join(t.TempDir(), "mixed.db")
writeMixedCounterDB(t, p, 30)