Skip to content

Commit

Permalink
unit tests for pkg/core + in memory filesystem for filesystem unit te…
Browse files Browse the repository at this point in the history
…sting
  • Loading branch information
gusmin committed Dec 26, 2019
1 parent 3f69529 commit 883d0f3
Show file tree
Hide file tree
Showing 11 changed files with 471 additions and 90 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ require (
github.com/pelletier/go-toml v1.4.0 // indirect
github.com/pkg/errors v0.8.1
github.com/sirupsen/logrus v1.4.2
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/afero v1.2.2
github.com/spf13/cobra v0.0.4
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/viper v1.3.2
Expand Down
2 changes: 1 addition & 1 deletion magefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func Lint() {
// Test Run tests
func Test() error {
fmt.Println("[>] Testing")
return goTest("-v", "-coverprofile=cover.out", "./...")
return goTest("-v", "-race", "-coverprofile=cover.out", "./...")
}

// Check Run tests and linter
Expand Down
15 changes: 8 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,20 @@ import (
"github.com/sirupsen/logrus"
)

const (
configFile = "config"
logFile = "/var/log/securegate/gate/gate.log"
translationsDir = "/var/lib/securegate/gate/translations"
)
var version string

func main() {
cfg, err := config.FromFile(configFile)
var (
configPath = "/etc/securegate/gate/config.json"
logFile = "/var/log/securegate/gate/gate.log"
translationsDir = "/var/lib/securegate/gate/translations"
)

cfg, err := config.FromFile(configPath)
if err != nil {
logrus.Fatal(err)
}

// open DB
repo := database.NewSecureGateBoltRepository(cfg.DBPath)
err = repo.OpenDatabase()
if err != nil {
Expand Down
21 changes: 11 additions & 10 deletions pkg/commands/commands_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package commands

import (
"io/ioutil"
"os"
"testing"

"github.com/gusmin/gate/pkg/backend"
"github.com/gusmin/gate/pkg/core"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -65,6 +64,7 @@ func TestExecute(t *testing.T) {
}

func TestMe(t *testing.T) {
fs := afero.NewMemMapFs()
assert := require.New(t)

user := backend.User{
Expand All @@ -75,11 +75,11 @@ func TestMe(t *testing.T) {
Job: "gopher",
}

f, err := ioutil.TempFile("", "")
file, err := afero.TempFile(fs, "", "")
assert.NoError(err)
defer os.Remove(f.Name())
defer fs.Remove(file.Name())

logrus.SetOutput(f)
logrus.SetOutput(file)
logrus.SetFormatter(&logrus.TextFormatter{
DisableTimestamp: true,
})
Expand All @@ -88,14 +88,15 @@ func TestMe(t *testing.T) {

const expected = "level=info msg=\"+-------------------+-----------+----------+--------+\\n| EMAIL | FIRSTNAME | LASTNAME | JOB |\\n+-------------------+-----------+----------+--------+\\n| foo.bar@gmail.com | foo | bar | gopher |\\n+-------------------+-----------+----------+--------+\\nMeCaption\\n\\n\" user=foobar42\n"

b, err := ioutil.ReadFile(f.Name())
b, err := afero.ReadFile(fs, file.Name())
assert.NoError(err)
actual := string(b)

assert.Equalf(expected, actual, "expected output was %s but actual is %s", expected, actual)
}

func TestList(t *testing.T) {
fs := afero.NewMemMapFs()
assert := require.New(t)

user := backend.User{
Expand All @@ -115,19 +116,19 @@ func TestList(t *testing.T) {
},
}

f, err := ioutil.TempFile("", "")
file, err := afero.TempFile(fs, "", "")
assert.NoError(err)
defer os.Remove(f.Name())
defer fs.Remove(file.Name())

logrus.SetOutput(f)
logrus.SetOutput(file)
logrus.SetFormatter(&logrus.TextFormatter{
DisableTimestamp: true,
})

list(user, machines, logrus.StandardLogger(), &mockTranslator{})

const expected = "level=info msg=\"+-----------+---------+-----------+-----------+\\n| ID | NAME | IP | AGENTPORT |\\n+-----------+---------+-----------+-----------+\\n| nowhere42 | nowhere | localhost | 3002 |\\n+-----------+---------+-----------+-----------+\\nListCaption\\n\" user=foobar42\n"
b, err := ioutil.ReadFile(f.Name())
b, err := afero.ReadFile(fs, file.Name())
assert.NoError(err)
actual := string(b)

Expand Down
51 changes: 30 additions & 21 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,62 @@ package config

import (
"log"
"path/filepath"
"reflect"
"strings"

"github.com/pkg/errors"
"github.com/spf13/viper"
)

const configPath = "/etc/securegate/gate/"

// Configuration is the config used by the Secure Gate shell.
// Configuration is the config used by the Gate.
type Configuration struct {
SSHUser string `mapstructure:"ssh_user"`
BackendURI string `mapstructure:"backend_uri"`
AgentAuthToken string `mapstructure:"agent_authentication_token"`
SSHUser string `mapstructure:"ssh_user"`
Language string `mapstructure:"language"`
DBPath string `mapstructure:"db_path"`
}

// FromFile load the configuration from the given file.
func FromFile(filename string) (Configuration, error) {
// Debug prints the given configuration struct.
func Debug(cfg interface{}) {
log.Println("--------------------------------------------------------------")
v := reflect.ValueOf(cfg).Elem()
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
log.Printf("%s %s = %v\n", f.Type(), v.Type().Field(i).Name, f.Interface())
}
log.Println("--------------------------------------------------------------")
}

// FromFile load the configuration from the given file path.
func FromFile(path string) (Configuration, error) {
v := viper.New()
setDefaults(v)

// Get the filename without the extension
base := filepath.Base(path)
filename := strings.TrimSuffix(base, filepath.Ext(base))
v.SetConfigName(filename)
v.AddConfigPath(configPath)

// Get the directory where the config file is located
path = filepath.Dir(path)
v.AddConfigPath(path)

if err := v.ReadInConfig(); err != nil {
return Configuration{}, errors.Wrapf(err, "%s could not be loaded", filename)
return Configuration{}, errors.Wrapf(err, "%s could not be loaded", path)
}

var cfg Configuration
if err := v.UnmarshalExact(&cfg); err != nil {
return Configuration{}, errors.Wrapf(err, "%s could not be loaded", filename)
return Configuration{}, errors.Wrapf(err, "%s could not be loaded", path)
}

return cfg, nil
}

func setDefaults(v *viper.Viper) {
v.SetDefault("ssh_user", "secure")
v.SetDefault("language", "en")
v.SetDefault("db_path", "/var/lib/securegate/gate")
}

// Debug prints the given configuration struct.
func Debug(cfg interface{}) {
log.Println("--------------------------------------------------------------")
v := reflect.ValueOf(cfg).Elem()
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
log.Printf("%s %s = %v\n", f.Type(), v.Type().Field(i).Name, f.Interface())
}
log.Println("--------------------------------------------------------------")
v.SetDefault("db_path", "/var/lib/securegate/gate/securegate.db")
}
7 changes: 4 additions & 3 deletions pkg/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func (core *SecureGateCore) initSSHKeys(keysPath string) error {
return nil
}

// loadPublicSSHKey parse the public ssh key located keysPath and
// loadPublicSSHKey parse the public ssh key located in keysPath and
// set the user public key to the parsed key if no error occured.
func (core *SecureGateCore) loadPublicSSHKey(keysPath string) error {
key, err := ioutil.ReadFile(path.Join(keysPath, "id_rsa.pub"))
Expand Down Expand Up @@ -302,8 +302,6 @@ func (core *SecureGateCore) updateUser(ctx context.Context) error {
// updateAgents update agents authorized_keys file depending on permissions
// changes.
func (core *SecureGateCore) updateAgents(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*15)
defer cancel()
user, err := core.DB.GetUser(core.User().ID)
if err != nil {
return err
Expand Down Expand Up @@ -347,6 +345,9 @@ func (core *SecureGateCore) updateAgents(ctx context.Context) error {
}
}

ctx, cancel := context.WithTimeout(ctx, time.Second*15)
defer cancel()

// Agent running on accessible node must add our public key to authorized_keys
// if the user got rights to access the node.
for _, m := range insertions {
Expand Down
Loading

0 comments on commit 883d0f3

Please sign in to comment.