db/sqliteconfig: add query_only to read-only connections

mode=ro still allows temp-table writes. ATTACH and VACUUM INTO
still write other files; callers running untrusted SQL must reject them.
This commit is contained in:
Kristoffer Dalby committed 2026-11-20 19:36:34 +01:00
1 parent 27e90f8692
commit dc0edca887
3 files changed
+91 -2

No files matched your search

+16 -2
View File
@@ -277,7 +277,7 @@ type Config struct {
Synchronous Synchronous // synchronous mode (affects durability vs performance)
ForeignKeys bool // enable foreign key constraints (data integrity)
TxLock TxLock // transaction lock mode (affects write concurrency)
ReadOnly bool // open with SQLite's mode=ro
ReadOnly bool // open with mode=ro and query_only, for untrusted readers
}
// Default returns the production configuration optimized for Headscale's usage patterns.
@@ -301,6 +301,20 @@ func Default(path string) *Config {
}
}
// ReadOnly returns a configuration for a connection that must never write the
// database: mode=ro opens the file read-only, query_only rejects writes at the
// statement level. No write pragmas are set. It does not stop ATTACH or VACUUM
// INTO from creating other files; callers running untrusted SQL must reject
// those statements themselves.
func ReadOnly(path string) *Config {
return &Config{
Path: path,
BusyTimeout: DefaultBusyTimeout,
WALAutocheckpoint: -1,
ReadOnly: true,
}
}
// Memory returns a configuration for in-memory databases.
func Memory() *Config {
return &Config{
@@ -395,7 +409,7 @@ func (c *Config) ToURL() (string, error) {
}
if c.ReadOnly {
queryParts = append(queryParts, "mode=ro")
queryParts = append(queryParts, "_pragma=query_only=1", "mode=ro")
}
if len(queryParts) > 0 {
+5
View File
@@ -266,6 +266,11 @@ func TestConfigToURL(t *testing.T) {
},
want: "file:/test.db?_pragma=busy_timeout=1000&_pragma=foreign_keys=ON",
},
{
name: "read-only",
config: ReadOnly("/test.db"),
want: "file:/test.db?_pragma=busy_timeout=10000&_pragma=query_only=1&mode=ro",
},
}
for _, tt := range tests {
@@ -327,3 +327,73 @@ func TestToURLOpensExactPath(t *testing.T) {
})
}
}
// TestReadOnlyRejectsWrites proves a ReadOnly connection cannot change the
// database, even when a statement lifts query_only. ATTACH and VACUUM INTO
// still create other files; see [ReadOnly].
func TestReadOnlyRejectsWrites(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
dbPath := filepath.Join(dir, "ro.db")
rwURL, err := Default(dbPath).ToURL()
if err != nil {
t.Fatalf("rw url: %v", err)
}
rw, err := sql.Open("sqlite", rwURL)
if err != nil {
t.Fatalf("open rw: %v", err)
}
defer rw.Close()
_, err = rw.ExecContext(ctx, "CREATE TABLE t (v INTEGER); INSERT INTO t VALUES (1)")
if err != nil {
t.Fatalf("seed: %v", err)
}
roURL, err := ReadOnly(dbPath).ToURL()
if err != nil {
t.Fatalf("ro url: %v", err)
}
ro, err := sql.Open("sqlite", roURL)
if err != nil {
t.Fatalf("open ro: %v", err)
}
defer ro.Close()
// One connection, so a PRAGMA in one statement carries to the next.
conn, err := ro.Conn(ctx)
if err != nil {
t.Fatalf("conn: %v", err)
}
defer conn.Close()
writes := []string{
"INSERT INTO t VALUES (2)",
"UPDATE t SET v = 3",
"DELETE FROM t",
"DROP TABLE t",
"CREATE TABLE x (a)",
"PRAGMA query_only = 0; DELETE FROM t",
"DELETE FROM t",
}
for _, q := range writes {
_, err := conn.ExecContext(ctx, q)
if err == nil {
t.Errorf("%q succeeded on a read-only connection", q)
}
}
var n int
err = conn.QueryRowContext(ctx, "SELECT count(*) FROM t WHERE v = 1").Scan(&n)
if err != nil {
t.Fatalf("read: %v", err)
}
if n != 1 {
t.Errorf("table changed: %d rows with v=1, want 1", n)
}
}