Skip to content

Commit

Permalink
Replace viper
Browse files Browse the repository at this point in the history
  • Loading branch information
GGP1 committed Mar 2, 2021
1 parent 1f5c5f9 commit 1a58e31
Show file tree
Hide file tree
Showing 32 changed files with 909 additions and 352 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Moving forward to the configuration file itself, in it we can specify the clipbo

> Paths inside the file must be **absolute**.
*Formats supported*: JSON, TOML, YAML, HCL, envfile and Java properties. [Samples](/docs/configuration/samples).
*Formats supported*: JSON, TOML, YAML. [Samples](/docs/configuration/samples).

### Requirements

Expand Down
26 changes: 12 additions & 14 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import (
"strings"

cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/config"
"github.com/GGP1/kure/crypt"
"github.com/GGP1/kure/db/auth"
authDB "github.com/GGP1/kure/db/auth"

"github.com/awnumar/memguard"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
bolt "go.etcd.io/bbolt"
)

Expand All @@ -32,7 +32,7 @@ const keyfilePath string = "keyfile.path"
func Login(db *bolt.DB) cmdutil.RunEFunc {
return func(cmd *cobra.Command, args []string) error {
// If auth is not nil it means the user is already logged in (session)
if auth := viper.Get("auth"); auth != nil {
if auth := config.Get("auth"); auth != nil {
return nil
}

Expand Down Expand Up @@ -112,25 +112,25 @@ func askArgon2Params(r io.Reader) (iterations, memory, threads uint32, err error

fmt.Println("Set argon2 parameters, leave blank to use the default value")
fmt.Println("For more information visit https://github.com/GGP1/kure/wiki/Authentication")
scanner := bufio.NewScanner(r)
reader := bufio.NewReader(r)

if iter := cmdutil.Scanln(scanner, " Iterations"); iter != "" {
if iter := cmdutil.Scanln(reader, " Iterations"); iter != "" {
i, err := strconv.Atoi(iter)
if err != nil || i < 1 {
return 0, 0, 0, errors.New("invalid iterations number")
}
iterations = uint32(i)
}

if mem := cmdutil.Scanln(scanner, " Memory"); mem != "" {
if mem := cmdutil.Scanln(reader, " Memory"); mem != "" {
m, err := strconv.Atoi(mem)
if err != nil || m < 1 {
return 0, 0, 0, errors.New("invalid memory number")
}
memory = uint32(m)
}

if th := cmdutil.Scanln(scanner, " Threads"); th != "" {
if th := cmdutil.Scanln(reader, " Threads"); th != "" {
t, err := strconv.Atoi(th)
if err != nil || t < 1 {
return 0, 0, 0, errors.New("invalid threads number")
Expand All @@ -148,13 +148,13 @@ func askKeyfile(r io.Reader) (bool, error) {
if cmdutil.Confirm(r, "Would you like to use a key file?") {
use = true

if viper.GetString(keyfilePath) != "" {
if config.GetString(keyfilePath) != "" {
if !cmdutil.Confirm(r,
"Would you like to use the path specified in the configuration file?") {

// Overwrite the path value in the configuration file
viper.Set(keyfilePath, "")
if err := viper.WriteConfigAs(viper.ConfigFileUsed()); err != nil {
config.Set(keyfilePath, "")
if err := config.Write(config.FileUsed(), false); err != nil {
return false, errors.Wrap(err, "writing the configuration file")
}
}
Expand All @@ -165,11 +165,9 @@ func askKeyfile(r io.Reader) (bool, error) {
}

func combineKeys(r io.Reader, password *memguard.Enclave) (*memguard.Enclave, error) {
path := viper.GetString(keyfilePath)
path := config.GetString(keyfilePath)
if path == "" {
fmt.Print("Enter key file path: ")
fmt.Fscanln(r, &path)

path = cmdutil.Scanln(bufio.NewReader(r), "Enter key file path")
path = strings.Trim(path, "\"")
if path == "" || path == "." {
return nil, errors.New("invalid key file path")
Expand Down Expand Up @@ -209,5 +207,5 @@ func setAuthToConfig(password *memguard.Enclave, params auth.Parameters) {
"memory": params.Memory,
"threads": params.Threads,
}
viper.Set("auth", auth)
config.Set("auth", auth)
}
31 changes: 14 additions & 17 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import (
"testing"

cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/config"
"github.com/GGP1/kure/db/auth"

"github.com/awnumar/memguard"
"github.com/spf13/cobra"
"github.com/spf13/viper"
bolt "go.etcd.io/bbolt"
)

Expand Down Expand Up @@ -43,7 +43,7 @@ func TestAskArgon2Params(t *testing.T) {
}{
{
desc: "Custom values",
input: "3\n2500000\n6\n",
input: "3\n2500000\n6",
expectedIters: 3,
expectedMem: 2500000,
expectedThreads: 6,
Expand Down Expand Up @@ -112,8 +112,6 @@ func TestArgon2ParamsErrors(t *testing.T) {
}

func TestAskKeyfile(t *testing.T) {
viper.Reset()

cases := []struct {
desc string
expected bool
Expand All @@ -140,13 +138,12 @@ func TestAskKeyfile(t *testing.T) {
},
}

viper.SetConfigFile("testdata/mock_config.yaml")
viper.SetConfigType("yaml")
config.Load("testdata/mock_config.yaml")

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
// Set the key file path to the configuration
viper.Set(keyfilePath, "./testdata/test-32.key")
config.Set(keyfilePath, "./testdata/test-32.key")
buf := bytes.NewBufferString(tc.input)

got, err := askKeyfile(buf)
Expand All @@ -158,16 +155,16 @@ func TestAskKeyfile(t *testing.T) {
t.Errorf("Expected %v, got %v", tc.expected, got)
}

cfgPath := viper.Get(keyfilePath)
cfgPath := config.Get(keyfilePath)
if cfgPath != tc.expectedCfgPath {
t.Errorf("Expected %q, got %q", tc.expectedCfgPath, cfgPath)
}
})
}

t.Run("Error", func(t *testing.T) {
viper.Reset() // Unset config file and type
viper.Set(keyfilePath, "./testdata/test-default.key")
config.Reset() // Unset config file and type
config.Set(keyfilePath, "./testdata/test-default.key")

buf := bytes.NewBufferString("y\nn\n")
if _, err := askKeyfile(buf); err == nil {
Expand Down Expand Up @@ -196,7 +193,7 @@ func TestCombineKeys(t *testing.T) {

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
viper.Set(keyfilePath, tc.path)
config.Set(keyfilePath, tc.path)

enclave, err := combineKeys(nil, memguard.NewEnclave([]byte("test")))
if err != nil {
Expand Down Expand Up @@ -230,7 +227,7 @@ func TestCombineKeys(t *testing.T) {
}

func TestCombineKeysRequestPath(t *testing.T) {
viper.Reset()
config.Reset()
path := "./testdata/test-32.key"
buf := bytes.NewBufferString(path)

Expand Down Expand Up @@ -258,22 +255,22 @@ func TestCombineKeysRequestPath(t *testing.T) {
}

func TestCombineKeysErrors(t *testing.T) {
viper.Set("keyfile.path", "non-existent")
config.Set("keyfile.path", "non-existent")

if _, err := combineKeys(nil, memguard.NewEnclave([]byte("test"))); err == nil {
t.Error("Expected an error and got nil")
}

t.Run("Invalid path", func(t *testing.T) {
viper.Reset()
if _, err := combineKeys(bytes.NewBufferString(""), nil); err == nil {
config.Reset()
if _, err := combineKeys(bytes.NewBufferString("\n"), nil); err == nil {
t.Errorf("Expected an error and got nil")
}
})
}

func TestSetAuthToConfig(t *testing.T) {
defer viper.Reset()
defer config.Reset()

expPassword := memguard.NewEnclave([]byte("test"))
var (
Expand All @@ -291,7 +288,7 @@ func TestSetAuthToConfig(t *testing.T) {
setAuthToConfig(expPassword, authParams)

// reflect.DeepEqual does not work
got := viper.Get("auth").(map[string]interface{})
got := config.Get("auth").(map[string]interface{})
gotPassword := got["password"]
gotMem := got["memory"].(uint32)
gotIter := got["iterations"].(uint32)
Expand Down
2 changes: 1 addition & 1 deletion auth/testdata/mock_config.yaml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
keyfile:
path: ""
path: ""
4 changes: 2 additions & 2 deletions commands/backup/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import (

"github.com/GGP1/kure/auth"
cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/config"
"github.com/GGP1/kure/sig"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
bolt "go.etcd.io/bbolt"
)

Expand Down Expand Up @@ -153,7 +153,7 @@ func fileBackup(db *bolt.DB, path string) error {

// httpBackup writes a consistent view of the database to a http endpoint.
func httpBackup(db *bolt.DB) http.HandlerFunc {
name := filepath.Base(viper.GetString("database.path"))
name := filepath.Base(config.GetString("database.path"))
disposition := fmt.Sprintf(`attachment; filename="%s"`, name)

return func(w http.ResponseWriter, r *http.Request) {
Expand Down
4 changes: 2 additions & 2 deletions commands/card/copy/copy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"testing"

cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/config"
"github.com/GGP1/kure/db/card"
"github.com/GGP1/kure/pb"
"github.com/spf13/viper"
)

func TestCopy(t *testing.T) {
Expand Down Expand Up @@ -41,7 +41,7 @@ func TestCopy(t *testing.T) {

cmd := NewCmd(db)
f := cmd.Flags()
viper.Set("clipboard.timeout", "1ns") // Set default
config.Set("clipboard.timeout", "1ns") // Set default

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
Expand Down
6 changes: 4 additions & 2 deletions commands/config/argon2/argon2.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package argon2
import (
"fmt"

"github.com/GGP1/kure/auth"
cmdutil "github.com/GGP1/kure/commands"
"github.com/GGP1/kure/commands/config/argon2/test"
"github.com/GGP1/kure/db/auth"
authDB "github.com/GGP1/kure/db/auth"

"github.com/spf13/cobra"
bolt "go.etcd.io/bbolt"
Expand All @@ -21,6 +22,7 @@ func NewCmd(db *bolt.DB) *cobra.Command {
Short: "Display currently used argon2 parameters",
Aliases: []string{"argon"},
Example: argon2Example,
PreRunE: auth.Login(db),
RunE: runArgon2(db),
}

Expand All @@ -31,7 +33,7 @@ func NewCmd(db *bolt.DB) *cobra.Command {

func runArgon2(db *bolt.DB) cmdutil.RunEFunc {
return func(cmd *cobra.Command, args []string) error {
params, err := auth.GetParameters(db)
params, err := authDB.GetParameters(db)
if err != nil {
return err
}
Expand Down
4 changes: 2 additions & 2 deletions commands/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import (
argon2cmd "github.com/GGP1/kure/commands/config/argon2"
"github.com/GGP1/kure/commands/config/create"
"github.com/GGP1/kure/commands/config/edit"
"github.com/GGP1/kure/config"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
bolt "go.etcd.io/bbolt"
)

Expand All @@ -40,7 +40,7 @@ func NewCmd(db *bolt.DB, r io.Reader) *cobra.Command {

func runConfig(db *bolt.DB, r io.Reader) cmdutil.RunEFunc {
return func(cmd *cobra.Command, args []string) error {
path := viper.ConfigFileUsed()
path := config.FileUsed()
data, err := os.ReadFile(path)
if err != nil {
return errors.Wrap(err, "reading configuration file")
Expand Down
7 changes: 3 additions & 4 deletions commands/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import (
"testing"

cmdutil "github.com/GGP1/kure/commands"

"github.com/spf13/viper"
"github.com/GGP1/kure/config"
)

func TestRead(t *testing.T) {
db := cmdutil.SetContext(t, "../../db/testdata/database")
viper.SetConfigFile("./testdata/mock_config.yaml")
config.SetFile("./testdata/mock_config.yaml")

cmd := NewCmd(db, nil)
if err := cmd.Execute(); err != nil {
Expand All @@ -20,7 +19,7 @@ func TestRead(t *testing.T) {

func TestReadError(t *testing.T) {
db := cmdutil.SetContext(t, "../../db/testdata/database")
viper.SetConfigFile("")
config.SetFile("")

cmd := NewCmd(db, nil)
if err := cmd.Execute(); err == nil {
Expand Down
Loading

0 comments on commit 1a58e31

Please sign in to comment.