Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
Signed-off-by: Michele Meloni <[email protected]>

fix(pkg/client/tokenservice): file cache accepts the absolute file path of token file

Signed-off-by: Michele Meloni <[email protected]>

fix(pkg/client/tokenservice): immuclient accepts absolute token file path

Signed-off-by: Michele Meloni <[email protected]>

chore: tokenfile is stored on home state folder

Signed-off-by: Michele Meloni <[email protected]>

chore(cmd): fix login tests

Signed-off-by: Michele Meloni <[email protected]>

chore(cmd/immuadmin/command): add credentials env vars

Signed-off-by: Michele Meloni <[email protected]>

fix(pkg/client/tokenservice): fix token handling on windows

Signed-off-by: Michele Meloni <[email protected]>

chore(cmd/immuclient): value only is disabled by default

Signed-off-by: Jeronimo Irazabal <[email protected]>
  • Loading branch information
mmeloni authored and jeroiraz committed Mar 30, 2023
1 parent be85a0e commit becc1c5
Show file tree
Hide file tree
Showing 39 changed files with 200 additions and 159 deletions.
10 changes: 4 additions & 6 deletions cmd/helper/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ package helper

import (
"os"
"os/user"
"strings"

"github.com/adrg/xdg"
service "github.com/codenotary/immudb/cmd/immuclient/service/constants"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -37,11 +37,9 @@ func (c *Config) Init(name string) error {
if c.CfgFn != "" {
viper.SetConfigFile(c.CfgFn)
} else {
if user, err := user.Current(); err != nil {
return err
} else {
viper.AddConfigPath(user.HomeDir)
}

viper.AddConfigPath(xdg.Home)

viper.AddConfigPath("../src/configs")
viper.AddConfigPath(os.Getenv("GOPATH") + "/src/configs")
if path, _ := os.Executable(); path == service.ExecPath {
Expand Down
28 changes: 28 additions & 0 deletions cmd/helper/meta.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Copyright 2021 CodeNotary, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package helper

import (
"github.com/adrg/xdg"
"path/filepath"
)

var STATE_FOLDER string

func init() {
STATE_FOLDER = filepath.Join(xdg.StateHome, "immudb")
}
3 changes: 1 addition & 2 deletions cmd/immuadmin/command/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (

c "github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/pkg/auth"
"github.com/codenotary/immudb/pkg/client/homedir"
"github.com/codenotary/immudb/pkg/client/tokenservice"
"github.com/codenotary/immudb/pkg/fs"
"github.com/codenotary/immudb/pkg/immuos"
Expand Down Expand Up @@ -104,7 +103,7 @@ func (cl *commandlineBck) ConfigChain(post func(cmd *cobra.Command, args []strin
}
// here all command line options and services need to be configured by options retrieved from viper
cl.options = Options()
cl.ts = tokenservice.NewFileTokenService().WithHds(homedir.NewHomedirService()).WithTokenFileName(cl.options.TokenFileName)
cl.ts = tokenservice.NewFileTokenService().WithTokenFileAbsPath(cl.options.TokenFileName)
if post != nil {
return post(cmd, args)
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/immuadmin/command/backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func TestDumpToFile(t *testing.T) {
hds.FileExistsInUserHomeDirF = func(string) (bool, error) {
return true, nil
}
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
daemMock := defaultDaemonMock()
clb.Backupper = &backupper{
Expand Down Expand Up @@ -255,7 +255,7 @@ func TestBackup(t *testing.T) {
hds.FileExistsInUserHomeDirF = func(string) (bool, error) {
return true, nil
}
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
daemMock := defaultDaemonMock()
clb.Backupper = &backupper{
Expand Down Expand Up @@ -666,7 +666,7 @@ func TestRestore(t *testing.T) {
hds.FileExistsInUserHomeDirF = func(string) (bool, error) {
return true, nil
}
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
clb.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
daemMock := defaultDaemonMock()
bckpr := &backupper{
Expand Down
2 changes: 0 additions & 2 deletions cmd/immuadmin/command/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ func newCommand() *cobra.Command {
if err != nil {
c.QuitToStdErr(err)
}

cmd = cml.Register(cmd)
// register backup related commands
os := immuos.NewStandardOS()
Expand All @@ -57,6 +56,5 @@ func newCommand() *cobra.Command {

cmd.AddCommand(man.Generate(cmd, "immuadmin", "./cmd/docs/man/"+version.App))
cmd.AddCommand(version.VersionCmd())

return cmd
}
22 changes: 16 additions & 6 deletions cmd/immuadmin/command/commandline.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ package immuadmin
import (
"context"
"fmt"
"path/filepath"
"strings"

"github.com/codenotary/immudb/pkg/client/homedir"
"github.com/codenotary/immudb/pkg/client/tokenservice"
"github.com/spf13/viper"

c "github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/pkg/client"
Expand Down Expand Up @@ -65,7 +67,6 @@ func NewCommandLine() *commandline {
cl.config.Name = "immuadmin"
cl.passwordReader = c.DefaultPasswordReader
cl.context = context.Background()
//
return cl
}

Expand All @@ -74,9 +75,18 @@ func (cl *commandline) ConfigChain(post func(cmd *cobra.Command, args []string)
if err = cl.config.LoadConfig(cmd); err != nil {
return err
}
// here all command line options and services need to be configured by options retrieved from viper
cl.options = Options()
cl.ts = tokenservice.NewFileTokenService().WithHds(homedir.NewHomedirService()).WithTokenFileName(cl.options.TokenFileName)
// options now that config is loaded are availables
opt := Options()
tfAbsPath := opt.TokenFileName
if !viper.IsSet("tokenfile") {
tfAbsPath = filepath.Join(c.STATE_FOLDER, client.DefaultTokenFileName)
}
if !strings.HasSuffix(tfAbsPath, client.AdminTokenFileSuffix) {
tfAbsPath += client.AdminTokenFileSuffix
}
cl.options = opt.WithTokenFileName(tfAbsPath)
// token service is needed here because the one in cl.immuClient is not exposed
cl.ts = tokenservice.NewFileTokenService().WithTokenFileAbsPath(tfAbsPath)
if post != nil {
return post(cmd, args)
}
Expand Down Expand Up @@ -112,7 +122,7 @@ func (cl *commandline) connect(cmd *cobra.Command, args []string) (err error) {
if cl.immuClient, err = client.NewImmuClient(cl.options); err != nil {
cl.quit(err)
}
cl.immuClient.WithTokenService(tokenservice.NewFileTokenService().WithTokenFileName("token_admin"))
cl.immuClient.WithTokenService(cl.ts)
return

}
Expand Down
8 changes: 4 additions & 4 deletions cmd/immuadmin/command/commandline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func TestCommandline(t *testing.T) {
},
passwordReader: pwr,
context: context.Background(),
ts: tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile"),
ts: tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile"),
}
cmd := &cobra.Command{}
Expand Down Expand Up @@ -85,16 +85,16 @@ func TestCommandline(t *testing.T) {
hds.FileExistsInUserHomeDirF = func(pathToFile string) (bool, error) {
return false, errFileExists
}
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
require.NoError(t, cl.checkLoggedIn(cmd, nil))
hds.FileExistsInUserHomeDirF = prevFileExists
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
require.Equal(t, errPleaseLogin, cl.checkLoggedInAndConnect(cmd, nil))
hds.FileExistsInUserHomeDirF = func(pathToFile string) (bool, error) {
return true, nil
}
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileName("testTokenFile")
cl.ts = tokenservice.NewTokenService().WithHds(hds).WithTokenFileAbsPath("testTokenFile")
cl.newImmuClient = func(*client.Options) (client.ImmuClient, error) {
return nil, errNewImmuClient
}
Expand Down
36 changes: 22 additions & 14 deletions cmd/immuadmin/command/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,19 @@ package immuadmin

import (
"fmt"
"strings"

"github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/pkg/auth"
"github.com/codenotary/immudb/pkg/client"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"path/filepath"
)

func Options() *client.Options {
password, _ := auth.DecodeBase64Password(viper.GetString("password"))
tfAbsPath := viper.GetString("tokenfile")
port := viper.GetInt("immudb-port")
address := viper.GetString("immudb-address")
tokenFileName := viper.GetString("tokenfile")
if !strings.HasSuffix(tokenFileName, client.AdminTokenFileSuffix) {
tokenFileName += client.AdminTokenFileSuffix
}
mtls := viper.GetBool("mtls")
certificate := viper.GetString("certificate")
servername := viper.GetString("servername")
Expand All @@ -38,8 +37,10 @@ func Options() *client.Options {
options := client.DefaultOptions().
WithPort(port).
WithAddress(address).
WithUsername(viper.GetString("username")).
WithPassword(password).
WithAuth(true).
WithTokenFileName(tokenFileName).
WithTokenFileName(tfAbsPath).
WithMTLs(mtls)
if mtls {
// todo https://golang.org/src/crypto/x509/root_linux.go
Expand All @@ -55,14 +56,15 @@ func Options() *client.Options {
func (cl *commandline) configureFlags(cmd *cobra.Command) error {
cmd.PersistentFlags().IntP("immudb-port", "p", client.DefaultOptions().Port, "immudb port number")
cmd.PersistentFlags().StringP("immudb-address", "a", client.DefaultOptions().Address, "immudb host address")
cmd.PersistentFlags().String("username", "", "immudb username used to login")
cmd.PersistentFlags().String("password", "", "immudb password used to login; can be plain-text or base64 encoded (must be prefixed with 'enc:' if it is encoded)")
absPath := filepath.Join(helper.STATE_FOLDER, client.DefaultOptions().TokenFileName+client.AdminTokenFileSuffix)
cmd.PersistentFlags().String(
"tokenfile",
client.DefaultOptions().TokenFileName,
absPath,
fmt.Sprintf(
"authentication token file (default path is $HOME or binary location; the supplied "+
"value will be automatically suffixed with %s; default filename is %s%s)",
client.AdminTokenFileSuffix,
client.DefaultOptions().TokenFileName,
"authentication token file (the supplied "+
"value will be automatically suffixed with %s)",
client.AdminTokenFileSuffix))
cmd.PersistentFlags().StringVar(&cl.config.CfgFn, "config", "", "config file (default path is configs or $HOME; default filename is immuadmin.toml)")
cmd.PersistentFlags().BoolP("mtls", "m", client.DefaultOptions().MTLs, "enable mutual tls")
Expand All @@ -76,6 +78,12 @@ func (cl *commandline) configureFlags(cmd *cobra.Command) error {
if err := viper.BindPFlag("immudb-address", cmd.PersistentFlags().Lookup("immudb-address")); err != nil {
return err
}
if err := viper.BindPFlag("username", cmd.PersistentFlags().Lookup("username")); err != nil {
return err
}
if err := viper.BindPFlag("password", cmd.PersistentFlags().Lookup("password")); err != nil {
return err
}
if err := viper.BindPFlag("tokenfile", cmd.PersistentFlags().Lookup("tokenfile")); err != nil {
return err
}
Expand All @@ -96,12 +104,12 @@ func (cl *commandline) configureFlags(cmd *cobra.Command) error {
}
viper.SetDefault("immudb-port", client.DefaultOptions().Port)
viper.SetDefault("immudb-address", client.DefaultOptions().Address)
viper.SetDefault("tokenfile", client.DefaultOptions().TokenFileName+client.AdminTokenFileSuffix)
viper.SetDefault("password", "")
viper.SetDefault("username", "")
viper.SetDefault("mtls", client.DefaultOptions().MTLs)
viper.SetDefault("servername", client.DefaultMTLsOptions().Servername)
viper.SetDefault("certificate", client.DefaultMTLsOptions().Certificate)
viper.SetDefault("pkey", client.DefaultMTLsOptions().Pkey)
viper.SetDefault("clientcas", client.DefaultMTLsOptions().ClientCAs)

return nil
}
33 changes: 26 additions & 7 deletions cmd/immuadmin/command/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
c "github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/pkg/auth"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func (cl *commandline) login(cmd *cobra.Command) {
Expand All @@ -34,18 +35,33 @@ func (cl *commandline) login(cmd *cobra.Command) {
PersistentPostRun: cl.disconnect,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cl.context
userStr := args[0]
flagLogin := false
var userStr string
if len(args) == 0 && !viper.IsSet("username") {
return fmt.Errorf("username is required")
}
if len(args) > 0 {
userStr = args[0]
} else {
userStr = viper.GetString("username")
}
if userStr != auth.SysAdminUsername {
err := fmt.Errorf("Permission denied: user %s has no admin rights", userStr)
cl.quit(err)
return err
}

user := []byte(userStr)
pass, err := cl.passwordReader.Read("Password:")
if err != nil {
cl.quit(err)
return err

var pass []byte
if viper.IsSet("password") {
flagLogin = true
pass = []byte(viper.GetString("password"))
} else {
var err error
if pass, err = cl.passwordReader.Read("Password:"); err != nil {
cl.quit(err)
return err
}
}

responseWarning, err := cl.loginClient(ctx, user, pass)
Expand All @@ -55,6 +71,9 @@ func (cl *commandline) login(cmd *cobra.Command) {
}

c.PrintfColorW(cmd.OutOrStdout(), c.Green, "logged in\n")
if flagLogin {
return nil
}

if string(responseWarning) == auth.WarnDefaultAdminPassword {
c.PrintfColorW(cmd.OutOrStdout(), c.Yellow, "SECURITY WARNING: %s\n", responseWarning)
Expand All @@ -75,7 +94,7 @@ func (cl *commandline) login(cmd *cobra.Command) {

return nil
},
Args: cobra.ExactArgs(1),
Args: cobra.MinimumNArgs(0),
}
cmd.AddCommand(ccmd)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/immuadmin/command/login_errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func TestLoginLogoutErrors(t *testing.T) {
cl := &commandline{
immuClient: immuClientMock,
passwordReader: pwReaderMock,
ts: tokenservice.NewTokenService().WithHds(hdsMock).WithTokenFileName("tokenFileName"),
ts: tokenservice.NewTokenService().WithHds(hdsMock).WithTokenFileAbsPath("tokenFileName"),
}
rootCmd := &cobra.Command{}
Expand Down
Loading

0 comments on commit becc1c5

Please sign in to comment.