Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,11 @@ Run race detection:
make test-race
```

## E2Engine
## Links

This repository is part of E2Engine.

- [core](https://github.com/e2engine/core) — core domain model, execution logic, and public APIs
- [repository](https://github.com/e2engine/repository) — persistence implementations
- [runner-local](https://github.com/e2engine/runner-local) — local test execution
- [cli](https://github.com/e2engine/cli) — command-line interface
- [tests](https://github.com/e2engine/tests) — end-to-end tests for E2Engine
- [demo](https://github.com/e2engine/demo) — executable demonstration system and E2Engine usage examples
- [instrumentation-go](https://github.com/e2engine/instrumentation-go) — Go instrumentation library for E2Engine
- [E2Engine website](https://e2engine.dev)
- [E2Engine documentation](https://e2engine.dev/docs)
- [E2Engine on GitHub](https://github.com/e2engine)

## License

Expand Down
2 changes: 2 additions & 0 deletions errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ var (
ErrCannotConfigureDB = errorc.New("cannot configure database")
ErrCannotMigrateDB = errorc.New("cannot migrate database")
ErrEmptyDBPath = errorc.New("db path is empty")
ErrUnsafeDBPath = errorc.New("unsafe db path")
ErrInvalidDBFilename = errorc.New("invalid db filename")
ErrFailedToEnableWALMode = errorc.New("failed to enable WAL mode")
)
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ module github.com/e2engine/repository
go 1.27

require (
github.com/e2engine/core v0.3.1
github.com/e2engine/core v0.3.2
github.com/golang-migrate/migrate/v4 v4.20.1
github.com/ygrebnov/errorc v0.6.1
github.com/ygrebnov/keys v0.2.0
github.com/ygrebnov/model v0.8.1
modernc.org/sqlite v1.62.0
)

Expand All @@ -18,12 +19,11 @@ require (
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/ygrebnov/log v0.5.1 // indirect
github.com/ygrebnov/model v0.8.1 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/net v0.63.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/grpc v1.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
12 changes: 6 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/e2engine/core v0.3.1 h1:18Jhe5KlMCzw/wJRp7yybEKmzd5IALHhuOyqhl72Vb4=
github.com/e2engine/core v0.3.1/go.mod h1:QcayHlh4J9gTOJGJrs5Ca4NTZ5MLaOA+EvswFdjq+W8=
github.com/e2engine/core v0.3.2 h1:6CUOMzVfwLlSS+O1uzBYXjVyb45THfSXy8nqyO3edfY=
github.com/e2engine/core v0.3.2/go.mod h1:pQTg3FaajaO4OKt3exuEpSasr1BoS5JcBNgW+2FK+o8=
github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU=
github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
Expand Down Expand Up @@ -42,8 +42,8 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
Expand All @@ -54,8 +54,8 @@ golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
Expand Down
1 change: 1 addition & 0 deletions keys/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ import "github.com/ygrebnov/keys"

var (
JournalMode = keys.New("journal.mode")
Filename = keys.New("filename")
)
71 changes: 70 additions & 1 deletion sqlite/config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,77 @@
package config

import (
"strings"

"github.com/ygrebnov/errorc"
modellib "github.com/ygrebnov/model"

"github.com/e2engine/repository/errors"
"github.com/e2engine/repository/keys"
)

type Config struct {
Name string `yaml:"name" default:"e2engine.sqlite" validate:"min(3)"`
Name string `yaml:"name" default:"e2engine.sqlite" validate:"dbfilename"`
Driver string `yaml:"driver" default:"sqlite" validate:"oneof(sqlite)"`
MaxOpenConns int `yaml:"max_open_conns" default:"1" validate:"min(1)"`
MaxIdleConns int `yaml:"max_idle_conns" default:"1" validate:"min(1)"`
}

// GetValidationRules returns a fresh set of database config rules.
func GetValidationRules() []modellib.Rule {
return []modellib.Rule{getDBFilenameRule()}
}

func getDBFilenameRule() modellib.Rule {
return modellib.NewRule[string]("dbfilename", func(name string, _ ...string) error {
return validateDBFilename(name)
})
}

// validateDBFilename keeps the database filename within its configured data directory
// and prevents filename characters from being interpreted as SQLite DSN options.
func validateDBFilename(name string) error {
if len(name) < 3 || len(name) > 255 {
return errorc.With(
errors.ErrInvalidDBFilename,
errorc.String(keys.Filename, name),
)
}

if strings.HasSuffix(name, ".") {
return errorc.With(
errors.ErrInvalidDBFilename,
errorc.String(keys.Filename, name),
)
}

for i, r := range name {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') ||
(r >= '0' && r <= '9') || (i > 0 && (r == '.' || r == '_' || r == '-')) {
continue
}
return errorc.With(
errors.ErrInvalidDBFilename,
errorc.String(keys.Filename, name),
)
}

base := strings.ToUpper(strings.SplitN(name, ".", 2)[0])
switch base {
case "CON", "PRN", "AUX", "NUL":
return errorc.With(
errors.ErrInvalidDBFilename,
errorc.String(keys.Filename, name),
)
}

if len(base) == 4 &&
(strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) &&
base[3] >= '1' && base[3] <= '9' {
return errorc.With(
errors.ErrInvalidDBFilename,
errorc.String(keys.Filename, name),
)
}
return nil
}
70 changes: 70 additions & 0 deletions sqlite/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package config

import (
"errors"
"strings"
"testing"

modellib "github.com/ygrebnov/model"

repositoryerrors "github.com/e2engine/repository/errors"
)

func TestValidateDBFilename(t *testing.T) {
tests := []struct {
name string
valid bool
}{
{name: "abc", valid: true},
{name: "e2engine.sqlite", valid: true},
{name: "A_2-backup.sqlite", valid: true},
{name: strings.Repeat("a", 255), valid: true},
{name: ""},
{name: "ab"},
{name: strings.Repeat("a", 256)},
{name: ".db"},
{name: "db."},
{name: "../outside.sqlite"},
{name: `..\outside.sqlite`},
{name: "/tmp/outside.sqlite"},
{name: "data.sqlite?mode=memory"},
{name: "data.sqlite#fragment"},
{name: "data%2esqlite"},
{name: "data base.sqlite"},
{name: "é.sqlite"},
{name: "CON.sqlite"},
{name: "aux.sqlite"},
{name: "COM1.sqlite"},
{name: "lpt9.sqlite"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateDBFilename(tt.name)
if tt.valid {
if err != nil {
t.Fatalf("validateDBFilename(%q) = %v", tt.name, err)
}
return
}
if !errors.Is(err, repositoryerrors.ErrInvalidDBFilename) {
t.Fatalf("validateDBFilename(%q) = %v, want ErrInvalidDBFilename", tt.name, err)
}
})
}
}

func TestDBFilenameValidationRule(t *testing.T) {
binding, err := modellib.NewBinding[Config](modellib.WithRules(GetValidationRules()...))
if err != nil {
t.Fatal(err)
}
valid := Config{Name: "e2engine.sqlite", Driver: "sqlite", MaxOpenConns: 1, MaxIdleConns: 1}
if err := binding.Validate(t.Context(), &valid); err != nil {
t.Fatalf("valid config: %v", err)
}
valid.Name = "../outside.sqlite"
if err := binding.Validate(t.Context(), &valid); err == nil {
t.Fatal("binding accepted invalid db filename")
}
}
23 changes: 13 additions & 10 deletions sqlite/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,6 @@ import (
"github.com/e2engine/repository/sqlite/migrate"
)

func GetPath(dataPath string, cfg *config.Config) string {
// Default location stays under the config directory.
dbPath := filepath.Join(dataPath, cfg.Name)

return strings.TrimSpace(dbPath)
}

// Open opens a SQLite database connection, configures the connection pool, and runs migrations.
func Open(ctx context.Context, path string, cfg *config.Config) (*sql.DB, error) {
dbConn, err := openDB(path, cfg)
Expand All @@ -35,10 +28,10 @@ func Open(ctx context.Context, path string, cfg *config.Config) (*sql.DB, error)

configureDB(dbConn, cfg)

if err := configureSQLite(ctx, dbConn); err != nil {
if errConfigure := configureSQLite(ctx, dbConn); errConfigure != nil {
return nil, nativeerrors.Join(
errors.ErrCannotConfigureDB,
err,
errConfigure,
dbConn.Close(),
)
}
Expand All @@ -58,8 +51,18 @@ func openDB(path string, cfg *config.Config) (*sql.DB, error) {
if path == "" {
return nil, errors.ErrEmptyDBPath
}
if strings.ContainsRune(path, '?') || strings.HasPrefix(path, "file:") {
return nil, errors.ErrUnsafeDBPath
}

if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, err
}
if info, err := os.Lstat(path); err == nil {
if !info.Mode().IsRegular() {
return nil, errors.ErrUnsafeDBPath
}
} else if !os.IsNotExist(err) {
return nil, err
}

Expand Down
76 changes: 33 additions & 43 deletions sqlite/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,50 +12,27 @@ import (
"github.com/e2engine/repository/sqlite/config"
)

func TestGetPath(t *testing.T) {
testCases := []struct {
name string
dataPath string
dbName string
expected string
}{
{
name: "default",
dataPath: "/tmp/e2engine",
dbName: "e2engine.sqlite",
expected: filepath.Join("/tmp/e2engine", "e2engine.sqlite"),
},
{
name: "relative path",
dataPath: "data",
dbName: "e2engine.sqlite",
expected: filepath.Join("data", "e2engine.sqlite"),
},
{
name: "whitespace",
dataPath: " data ",
dbName: " e2engine.sqlite ",
expected: strings.TrimSpace(
filepath.Join(" data ", " e2engine.sqlite "),
),
},
func TestOpenDBRejectsSymlink(t *testing.T) {
dir := t.TempDir()
target := filepath.Join(dir, "target.sqlite")
if err := os.WriteFile(target, []byte("preserve"), 0o600); err != nil {
t.Fatal(err)
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
actual := GetPath(
testCase.dataPath,
&config.Config{Name: testCase.dbName},
)

if actual != testCase.expected {
t.Fatalf(
"Expected path %q, got %q",
testCase.expected,
actual,
)
}
})
link := filepath.Join(dir, "link.sqlite")
if err := os.Symlink(target, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
db, err := openDB(link, &config.Config{Driver: "sqlite"})
if db != nil {
_ = db.Close()
t.Fatal("opened a symlink database")
}
if !errors.Is(err, repositoryerrors.ErrUnsafeDBPath) {
t.Fatalf("error = %v, want ErrUnsafeDBPath", err)
}
content, err := os.ReadFile(target)
if err != nil || string(content) != "preserve" {
t.Fatalf("target changed: %q, %v", content, err)
}
}

Expand All @@ -76,6 +53,19 @@ func TestOpenDBEmptyPath(t *testing.T) {
}
}

func TestOpenDBRejectsDSNPath(t *testing.T) {
for _, path := range []string{"data.sqlite?mode=memory", "file:data.sqlite"} {
db, err := openDB(path, &config.Config{Driver: "sqlite"})
if db != nil {
_ = db.Close()
t.Fatalf("opened unsafe path %q", path)
}
if !errors.Is(err, repositoryerrors.ErrUnsafeDBPath) {
t.Fatalf("path %q: error = %v, want ErrUnsafeDBPath", path, err)
}
}
}

func TestOpenDB(t *testing.T) {
testCases := []struct {
name string
Expand Down
Loading