Skip to content

Commit

Permalink
Check RW permissions in datadir (#3478)
Browse files Browse the repository at this point in the history
* Check RW permissions in datadir

* fix file permission bits
  • Loading branch information
gerardsn authored Oct 14, 2024
1 parent 3c758a1 commit 5d334e5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
36 changes: 36 additions & 0 deletions storage/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -147,6 +148,12 @@ func (e *engine) Shutdown() error {

func (e *engine) Configure(config core.ServerConfig) error {
e.datadir = config.Datadir
err := confirmWriteAccess(e.datadir)
if err != nil {
return err
}

// KV-storage
if e.config.Redis.isConfigured() {
redisDB, err := createRedisDatabase(e.config.Redis)
if err != nil {
Expand All @@ -163,10 +170,12 @@ func (e *engine) Configure(config core.ServerConfig) error {
}
e.databases = append(e.databases, bboltDB)

// SQL storage
if err := e.initSQLDatabase(); err != nil {
return fmt.Errorf("failed to initialize SQL database: %w", err)
}

// session storage
redisConfig := e.config.Session.Redis
if redisConfig.isConfigured() {
redisDB, err := createRedisDatabase(redisConfig)
Expand Down Expand Up @@ -367,6 +376,33 @@ func (p *provider) getStore(moduleName string, name string, adapter database) (s
return store, err
}

func confirmWriteAccess(datadir string) error {
// Make sure the data directory exists
err := os.MkdirAll(path.Dir(datadir+string(os.PathSeparator)), os.ModePerm)
if err != nil {
// log error: "unable to create datadir (dir=./data): mkdir ./data: read-only file system"
return err
}
filename := filepath.Join(datadir, "rw-access-test-file")
// open/create file with read-write permission
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
// log error: "unable to configure Storage: open data/rw-access-test-file: read-only file system"
return err
}
// cleanup
err = file.Close()
if err != nil {
return err
}
// removing the file could cause issues if it was a pre-existing user file
err = os.Remove(filename)
if err != nil {
return err
}
return nil
}

type logrusInfoLogWriter struct {
}

Expand Down
3 changes: 2 additions & 1 deletion storage/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ func Test_engine_sqlDatabase(t *testing.T) {
dataDir := io.TestDirectory(t)
require.NoError(t, os.Remove(dataDir))
e := New()
err := e.Configure(core.ServerConfig{Datadir: dataDir})
e.(*engine).datadir = dataDir
err := e.(*engine).initSQLDatabase()
assert.ErrorContains(t, err, "unable to open database file")
})
t.Run("sqlite is restricted to 1 connection", func(t *testing.T) {
Expand Down

0 comments on commit 5d334e5

Please sign in to comment.