diff --git a/go.mod b/go.mod index c9c01fc62..750d5010d 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,7 @@ require ( golang.org/x/term v0.44.0 golang.org/x/text v0.39.0 gopkg.in/yaml.v3 v3.0.1 + modernc.org/libc v1.67.6 modernc.org/sqlite v1.44.3 ) @@ -53,7 +54,6 @@ require ( github.com/tidwall/pretty v1.2.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect - modernc.org/libc v1.67.6 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect ) diff --git a/internal/agent/cindy.go b/internal/agent/cindy.go index 400406616..824e58205 100644 --- a/internal/agent/cindy.go +++ b/internal/agent/cindy.go @@ -21,7 +21,7 @@ import ( "strings" "github.com/yetone/magpie/internal/gateway" - _ "modernc.org/sqlite" + _ "github.com/yetone/magpie/internal/sqlitedb" ) // CindyScheme begins every Cindy import link. diff --git a/internal/provider/importapps.go b/internal/provider/importapps.go index 13dc70708..8dcd2cdd7 100644 --- a/internal/provider/importapps.go +++ b/internal/provider/importapps.go @@ -26,7 +26,7 @@ import ( "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/settings" - _ "modernc.org/sqlite" + _ "github.com/yetone/magpie/internal/sqlitedb" ) // AppSource is one app magpie can import from, with what it holds. diff --git a/internal/sqlitedb/main_test.go b/internal/sqlitedb/main_test.go new file mode 100644 index 000000000..29dd6c184 --- /dev/null +++ b/internal/sqlitedb/main_test.go @@ -0,0 +1,9 @@ +package sqlitedb + +import ( + "testing" + + "github.com/yetone/magpie/internal/testenv" +) + +func TestMain(m *testing.M) { testenv.Main(m) } diff --git a/internal/sqlitedb/sqlitedb.go b/internal/sqlitedb/sqlitedb.go new file mode 100644 index 000000000..97da8fd61 --- /dev/null +++ b/internal/sqlitedb/sqlitedb.go @@ -0,0 +1,45 @@ +// Package sqlitedb is the one way magpie reaches SQLite: a package that +// opens a database imports it, blank, in place of modernc.org/sqlite. +// +// import _ "github.com/yetone/magpie/internal/sqlitedb" +// +// modernc's SQLite runs on modernc's libc, which keeps its own copy of the +// environment, taken from os.Environ at the first getenv. On macOS, +// Windows and the BSDs that libc's getenv ends the whole process when it +// meets an entry with no "=" in it: it prints "libc.go:…:getenv: +// TODOTODO …" and calls os.Exit(1), where every real libc skips the entry. +// SQLite's first open reads SQLITE_TMPDIR, so a magpie started with such +// an entry quit at its first session scan, about two seconds after launch, +// with no crash report (#2327: a DLP tool's injected dylib left a fragment +// of its own path in the environment of apps Alfred started). Before +// anything can open a database, this package hands libc a copy with those +// entries left out. +package sqlitedb + +import ( + "os" + "strings" + + "modernc.org/libc" + _ "modernc.org/sqlite" +) + +// init runs before any of magpie's own code, and before any goroutine of +// it, so libc's copy is taken once, here: modernc's SetEnviron isn't safe +// to race with a first getenv. +func init() { + libc.SetEnviron(nil, wellFormed(os.Environ())) +} + +// wellFormed is env without the entries that aren't NAME=value. An entry +// whose name is empty after a leading "=" (Windows' "=C:=C:\…") has one, +// and getenv reads it without harm, so it stays. +func wellFormed(env []string) []string { + out := make([]string, 0, len(env)) + for _, kv := range env { + if strings.Contains(kv, "=") { + out = append(out, kv) + } + } + return out +} diff --git a/internal/sqlitedb/sqlitedb_test.go b/internal/sqlitedb/sqlitedb_test.go new file mode 100644 index 000000000..3bea78e59 --- /dev/null +++ b/internal/sqlitedb/sqlitedb_test.go @@ -0,0 +1,107 @@ +package sqlitedb + +import ( + "context" + "database/sql" + "go/parser" + "go/token" + "io/fs" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" +) + +// childDB names the database the started-again test binary opens; only +// that child runs TestOpenInChild. +const childDB = "MAGPIE_SQLITEDB_CHILD" + +// The environment #2327's reporter's magpie was started with: a fragment +// of a DLP tool's dylib path, with no "=", ahead of everything else. The +// first SQLite open reads SQLITE_TMPDIR, and modernc's getenv used to +// print TODOTODO and os.Exit(1) on that entry (on macOS, Windows and the +// BSDs; Linux's musl-based getenv skips it). Now the open works. +func TestSQLiteSurvivesMalformedEnv(t *testing.T) { + db := filepath.Join(t.TempDir(), "x.db") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + child := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestOpenInChild$", "-test.count=1", "-test.v") + child.Env = append([]string{"hains/MacSec/libesafenet.dylib"}, os.Environ()...) + child.Env = append(child.Env, childDB+"="+db) + out, err := child.CombinedOutput() + if err != nil || strings.Contains(string(out), "TODOTODO") || !strings.Contains(string(out), "opened 1") { + t.Fatalf("a magpie started with an entry with no \"=\" couldn't open SQLite: %v\n%s", err, out) + } +} + +// TestOpenInChild is the started-again binary's half of +// TestSQLiteSurvivesMalformedEnv: it opens a database and reads from it. +func TestOpenInChild(t *testing.T) { + path := os.Getenv(childDB) + if path == "" { + t.Skip("run by TestSQLiteSurvivesMalformedEnv") + } + if !slices.Contains(os.Environ(), "hains/MacSec/libesafenet.dylib") { + t.Fatal("the child wasn't handed the entry with no \"=\"") + } + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var n int + if err := db.QueryRow("SELECT 1").Scan(&n); err != nil { + t.Fatal(err) + } + t.Log("opened " + strconv.Itoa(n)) +} + +func TestWellFormed(t *testing.T) { + in := []string{"PATH=/bin", "hains/MacSec/libesafenet.dylib", "", "=C:=C:\\x", "EMPTY=", "A=b=c"} + want := []string{"PATH=/bin", "=C:=C:\\x", "EMPTY=", "A=b=c"} + if got := wellFormed(in); !slices.Equal(got, want) { + t.Fatalf("wellFormed(%q) = %q, want %q", in, got, want) + } +} + +// Every SQLite open goes through this package, so libc's environment is +// cleaned before any of them: no other package's own code imports +// modernc's driver or its libc. A test file may, to build its fixtures. +func TestOnlyThisPackageReachesSQLite(t *testing.T) { + root, _ := filepath.Abs(filepath.Join("..", "..")) + self := filepath.Join(root, "internal", "sqlitedb") + fset := token.NewFileSet() + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if path != root && (strings.HasPrefix(d.Name(), ".") || d.Name() == "node_modules" || d.Name() == "testdata" || path == self) { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly) + if err != nil { + return err + } + for _, im := range f.Imports { + p, _ := strconv.Unquote(im.Path.Value) + if p == "modernc.org/sqlite" || strings.HasPrefix(p, "modernc.org/sqlite/") || p == "modernc.org/libc" { + rel, _ := filepath.Rel(root, path) + t.Errorf("%s imports %s; import internal/sqlitedb instead, which cleans libc's environment first (#2327)", rel, p) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } +}