-
Notifications
You must be signed in to change notification settings - Fork 7
cgosqlite: add optional hook to verify ColumnBlob bytes are unmodified #124
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andrew-d
wants to merge
1
commit into
main
Choose a base branch
from
andrew/verify-rawbytes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+278
−45
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,7 +3,11 @@ package cgosqlite | |
| import ( | ||
| "bytes" | ||
| "path/filepath" | ||
| "runtime" | ||
| "sync" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/tailscale/sqlite/sqliteh" | ||
| ) | ||
|
|
@@ -28,47 +32,13 @@ func TestColumnBlob(t *testing.T) { | |
| } | ||
| defer db.Close() | ||
|
|
||
| mustRun := func(sql string) { | ||
| t.Helper() | ||
| stmt, _, err := db.Prepare(sql, 0) | ||
| if err != nil { | ||
| t.Fatalf("Prepare %q: %v", sql, err) | ||
| } | ||
| if _, err := stmt.Step(nil); err != nil { | ||
| t.Fatalf("Step: %v", err) | ||
| } | ||
| if err := stmt.Finalize(); err != nil { | ||
| t.Fatalf("Finalize: %v", err) | ||
| } | ||
| } | ||
|
|
||
| mustRun("CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)") | ||
| mustRun(`INSERT INTO t (id, data) VALUES (1, 'HELLOHELLOHELLOHELLOHELLOHELLO99')`) | ||
| mustRun(`INSERT INTO t (id, data) VALUES (2, '')`) | ||
| mustRun(`INSERT INTO t (id, data) VALUES (3, NULL)`) | ||
|
|
||
| // queryRow runs the given query and returns the *Stmt for the first row. | ||
| queryRow := func(t *testing.T, sql string) sqliteh.Stmt { | ||
| t.Helper() | ||
| stmt, _, err := db.Prepare(sql, 0) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| t.Cleanup(func() { | ||
| stmt.Finalize() | ||
| }) | ||
| row, err := stmt.Step(nil) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if !row { | ||
| t.Fatal("expected a row") | ||
| } | ||
| return stmt | ||
| } | ||
| mustRun(t, db, "CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)") | ||
| mustRun(t, db, `INSERT INTO t (id, data) VALUES (1, 'HELLOHELLOHELLOHELLOHELLOHELLO99')`) | ||
| mustRun(t, db, `INSERT INTO t (id, data) VALUES (2, '')`) | ||
| mustRun(t, db, `INSERT INTO t (id, data) VALUES (3, NULL)`) | ||
|
|
||
| t.Run("WithData", func(t *testing.T) { | ||
| stmt := queryRow(t, "SELECT data FROM t WHERE id = 1") | ||
| stmt := queryRow(t, db, "SELECT data FROM t WHERE id = 1") | ||
| data := stmt.ColumnBlob(0) | ||
|
|
||
| const want = "HELLOHELLOHELLOHELLOHELLOHELLO99" | ||
|
|
@@ -78,7 +48,7 @@ func TestColumnBlob(t *testing.T) { | |
| }) | ||
|
|
||
| t.Run("EmptyBlob", func(t *testing.T) { | ||
| stmt := queryRow(t, "SELECT data FROM t WHERE id = 2") | ||
| stmt := queryRow(t, db, "SELECT data FROM t WHERE id = 2") | ||
| data := stmt.ColumnBlob(0) | ||
| if len(data) != 0 { | ||
| t.Fatalf("got %d bytes, want 0 bytes", len(data)) | ||
|
|
@@ -91,7 +61,7 @@ func TestColumnBlob(t *testing.T) { | |
| }) | ||
|
|
||
| t.Run("NullBlob", func(t *testing.T) { | ||
| stmt := queryRow(t, "SELECT data FROM t WHERE id = 3") | ||
| stmt := queryRow(t, db, "SELECT data FROM t WHERE id = 3") | ||
| data := stmt.ColumnBlob(0) | ||
| if data != nil { | ||
| t.Fatalf("got %q, want nil", data) | ||
|
|
@@ -100,3 +70,196 @@ func TestColumnBlob(t *testing.T) { | |
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestColumnBlobModifiedHook(t *testing.T) { | ||
| // Disable the "always copy blob" option to test just the hook behavior | ||
| SetAlwaysCopyBlob(false) | ||
|
|
||
| // Write to this channel every time a cleanup function executes, so we | ||
| // can ensure they've run. | ||
| checkRun := make(chan struct{}, 10_000) // high enough to never block | ||
| blobCheckHook = func() { | ||
| checkRun <- struct{}{} | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. select {
case checkRun <- struct{}{}:
default:
panic("checkRun unexpectedly full")
} |
||
| } | ||
| t.Cleanup(func() { | ||
| blobCheckHook = nil | ||
| }) | ||
|
|
||
| // waitForCleanup waits for one cleanup to run. | ||
| waitForCleanup := func() { | ||
| timedOut := time.After(10 * time.Second) | ||
| for { | ||
| runtime.GC() | ||
| runtime.Gosched() | ||
|
|
||
| select { | ||
| case <-checkRun: | ||
| return | ||
| case <-t.Context().Done(): | ||
| t.Fatal("test context done while waiting for cleanup") | ||
| case <-timedOut: | ||
| t.Fatal("timeout waiting for cleanup") | ||
| case <-time.After(10 * time.Millisecond): | ||
| // retry | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Open a test database | ||
| db, err := Open(filepath.Join(t.TempDir(), "test.db"), sqliteh.OpenFlagsDefault, "") | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer db.Close() | ||
|
|
||
| // Create a table with some blob data | ||
| mustRun(t, db, "CREATE TABLE t (id INTEGER PRIMARY KEY, data BLOB)") | ||
|
|
||
| // Use a blob larger than 16 bytes to avoid tiny object optimization which | ||
| // can prevent cleanups from running (as mentioned in the documentation | ||
| // for [runtime.AddCleanup]). | ||
| mustRun(t, db, "INSERT INTO t (id, data) VALUES (1, CAST('HELLOHELLOHELLOHELLOHELLOHELLO99' AS BLOB))") | ||
|
|
||
| const testQuery = "SELECT data FROM t WHERE id = 1" | ||
|
|
||
| t.Run("UnmodifiedSliceDoesNotCallHook", func(t *testing.T) { | ||
| var hookCalls atomic.Int64 | ||
| SetColumnBlobModifiedHook(func(query string) { | ||
| hookCalls.Add(1) | ||
| }) | ||
| defer SetColumnBlobModifiedHook(nil) | ||
|
|
||
| func() { | ||
| stmt := queryRow(t, db, testQuery) | ||
| data := stmt.ColumnBlob(0) | ||
| if len(data) != 32 { | ||
| t.Fatalf("got len %d, want 32", len(data)) | ||
| } | ||
|
|
||
| // Don't modify data, just let it go out of scope | ||
| runtime.KeepAlive(data) | ||
| }() | ||
|
|
||
| waitForCleanup() | ||
| if got := hookCalls.Load(); got != 0 { | ||
| t.Errorf("hook called %d times, want 0", got) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("ModifiedSliceCallsHook", func(t *testing.T) { | ||
| var ( | ||
| hookCalls atomic.Int64 | ||
| receivedQuery atomic.Pointer[string] | ||
|
|
||
| calledOnce sync.Once | ||
| called = make(chan struct{}) | ||
| ) | ||
| SetColumnBlobModifiedHook(func(query string) { | ||
| hookCalls.Add(1) | ||
| receivedQuery.Store(&query) | ||
| calledOnce.Do(func() { close(called) }) | ||
| }) | ||
| defer SetColumnBlobModifiedHook(nil) | ||
|
|
||
| func() { | ||
| stmt := queryRow(t, db, testQuery) | ||
| data := stmt.ColumnBlob(0) | ||
| if len(data) != 32 { | ||
| t.Fatalf("got len %d, want 32", len(data)) | ||
| } | ||
|
|
||
| // Modify the data to trigger our hook. | ||
| data[0] = byte((int(data[0]) + 1) % 256) | ||
|
|
||
| runtime.KeepAlive(data) | ||
| }() | ||
|
|
||
| waitForCleanup() | ||
| <-called // need to synchronize separately since it's in another goroutine | ||
|
|
||
| if got := hookCalls.Load(); got != 1 { | ||
| t.Errorf("hook called %d times, want 1", got) | ||
| } | ||
| if q := receivedQuery.Load(); q == nil || *q != testQuery { | ||
| got := "" | ||
| if q != nil { | ||
| got = *q | ||
| } | ||
| t.Errorf("hook received query %q, want %q", got, testQuery) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("NilHook", func(t *testing.T) { | ||
| SetColumnBlobModifiedHook(nil) | ||
|
|
||
| // Ensure we start with an empty channel. | ||
| drain: | ||
| for { | ||
| select { | ||
| case <-checkRun: | ||
| default: | ||
| break drain | ||
| } | ||
| } | ||
|
|
||
| func() { | ||
| stmt := queryRow(t, db, testQuery) | ||
| data := stmt.ColumnBlob(0) | ||
| if len(data) != 32 { | ||
| t.Fatalf("got len %d, want 32", len(data)) | ||
| } | ||
|
|
||
| data[0] = 'Y' | ||
|
|
||
| runtime.KeepAlive(data) | ||
| }() | ||
|
|
||
| // Spin for a bit to try and trigger any cleanups to be executed. | ||
| for i := 0; i < 10; i++ { | ||
| runtime.GC() | ||
| runtime.Gosched() | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
|
|
||
| // We expect nothing in the channel, as no hook is set. | ||
| select { | ||
| case <-checkRun: | ||
| t.Fatal("unexpected cleanup hook call") | ||
| default: | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| func mustRun(t *testing.T, db sqliteh.DB, sql string) { | ||
| t.Helper() | ||
| stmt, _, err := db.Prepare(sql, 0) | ||
| if err != nil { | ||
| t.Fatalf("Prepare %q: %v", sql, err) | ||
| } | ||
| if _, err := stmt.Step(nil); err != nil { | ||
| t.Fatalf("Step: %v", err) | ||
| } | ||
| if err := stmt.Finalize(); err != nil { | ||
| t.Fatalf("Finalize: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // queryRow runs the given query and returns the *Stmt for the first row. | ||
| func queryRow(t *testing.T, db sqliteh.DB, sql string) sqliteh.Stmt { | ||
| t.Helper() | ||
| stmt, _, err := db.Prepare(sql, 0) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| t.Cleanup(func() { | ||
| stmt.Finalize() | ||
| }) | ||
| row, err := stmt.Step(nil) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if !row { | ||
| t.Fatal("expected a row") | ||
| } | ||
| return stmt | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Or instead of this bytes.Clone, maybe store a https://pkg.go.dev/hash/fnv#New64a hash of the original data?