Allow to create config file next to binary (#701)

Force to use the proper temp dir

If we do not define the configDir then the Go
create a random temp dir for copy routine.
It is not optimal from security purpose.
This commit is contained in:
Zoltan Papp 2023-02-28 17:01:38 +01:00 committed by GitHub
parent 5bb875a0fa
commit 462a86cfcc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 5 deletions

View File

@ -11,8 +11,7 @@ import (
// The output JSON is pretty-formatted
func WriteJson(file string, obj interface{}) error {
configDir, configFileName := filepath.Split(file)
err := os.MkdirAll(configDir, 0750)
configDir, configFileName, err := prepareConfigFileDir(file)
if err != nil {
return err
}
@ -100,3 +99,13 @@ func CopyFileContents(src, dst string) (err error) {
err = out.Sync()
return
}
func prepareConfigFileDir(file string) (string, string, error) {
configDir, configFileName := filepath.Split(file)
if configDir == "" {
return filepath.Dir(file), configFileName, nil
}
err := os.MkdirAll(configDir, 0750)
return configDir, configFileName, err
}

View File

@ -3,11 +3,13 @@ package util_test
import (
"crypto/md5"
"encoding/hex"
"github.com/netbirdio/netbird/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/netbirdio/netbird/util"
)
var _ = Describe("Client", func() {
@ -102,4 +104,23 @@ var _ = Describe("Client", func() {
})
})
})
Describe("Handle config file without full path", func() {
Context("config file handling", func() {
It("should be successful", func() {
written := &TestConfig{
SomeField: 123,
}
cfgFile := "test_cfg.json"
defer os.Remove(cfgFile)
err := util.WriteJson(cfgFile, written)
Expect(err).NotTo(HaveOccurred())
read, err := util.ReadJson(cfgFile, &TestConfig{})
Expect(err).NotTo(HaveOccurred())
Expect(read).NotTo(BeNil())
})
})
})
})