Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
chore(rot): Refactor rot

Signed-off-by: sbailey <[email protected]>
  • Loading branch information
spbsoluble committed Jul 11, 2024
1 parent 6c46549 commit 0129962
Show file tree
Hide file tree
Showing 13 changed files with 1,946 additions and 1,332 deletions.
2 changes: 1 addition & 1 deletion cmd/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ var containersDeleteCmd = &cobra.Command{

// Authenticate
//authConfig := createAuthConfigFromParams(kfcHostName, kfcUsername, kfcPassword, kfcDomain, kfcAPIPath)
//kfClient, _ := initClient(configFile, profile, providerType, providerProfile, noPrompt, authConfig, false)
//Client, _ := initClient(configFile, profile, providerType, providerProfile, noPrompt, authConfig, false)

// CLI Logic
return fmt.Errorf("delete store containers not implemented")
Expand Down
2 changes: 1 addition & 1 deletion cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ var exportCmd = &cobra.Command{
authConfig := createAuthConfigFromParams(kfcHostName, kfcUsername, kfcPassword, kfcDomain, kfcAPIPath)

if authConfig == nil {
log.Error().Msg("auth config is nil, invalid client configuration")
log.Error().Msg("auth config is nil, invalid Client configuration")
return fmt.Errorf(FailedAuthMsg)
}

Expand Down
342 changes: 272 additions & 70 deletions cmd/inventory.go

Large diffs are not rendered by default.

183 changes: 151 additions & 32 deletions cmd/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@ package cmd
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"syscall"

"github.com/Keyfactor/keyfactor-go-client-sdk/api/keyfactor"
"github.com/Keyfactor/keyfactor-go-client/v2/api"
"github.com/google/go-cmp/cmp"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"os"
"path"
"strings"
"syscall"
)

var loginCmd = &cobra.Command{
Expand Down Expand Up @@ -84,7 +85,11 @@ WARNING: The 'username'' and 'password' will be stored in the config file in pla
if noPrompt {
log.Info().Msg("Using environment variables for configuration data.")
// First try to auth with environment variables
authConfig, authEnvErr = authEnvVars(configFile, profile, true) // always save config file is login is called
authConfig, authEnvErr = authEnvVars(
configFile,
profile,
true,
) // always save config file is login is called
if authEnvErr != nil {
for _, err := range authEnvErr {
log.Error().Err(err)
Expand All @@ -94,7 +99,13 @@ WARNING: The 'username'' and 'password' will be stored in the config file in pla
if !validConfigFileEntry(authConfig, profile) {
// Attempt to auth with config file
log.Info().Msgf("Attempting to authenticate via config '%s' profile.", profile)
authConfig, authEnvErr = authConfigFile(configFile, profile, "", noPrompt, true) // always save config file is login is called
authConfig, authEnvErr = authConfigFile(
configFile,
profile,
"",
noPrompt,
true,
) // always save config file is login is called
if authEnvErr != nil {
// Print out the error messages
for _, err := range authEnvErr {
Expand Down Expand Up @@ -125,7 +136,17 @@ WARNING: The 'username'' and 'password' will be stored in the config file in pla
Str("domain", existingAuth.Domain).
Str("apiPath", existingAuth.APIPath).
Msg("call: authInteractive()")
authConfig, authErr = authInteractive(existingAuth.Hostname, existingAuth.Username, existingAuth.Password, existingAuth.Domain, existingAuth.APIPath, profile, !noPrompt, true, configFile)
authConfig, authErr = authInteractive(
existingAuth.Hostname,
existingAuth.Username,
existingAuth.Password,
existingAuth.Domain,
existingAuth.APIPath,
profile,
!noPrompt,
true,
configFile,
)
log.Debug().Msg("authInteractive() returned")
if authErr != nil {
log.Error().Err(authErr)
Expand All @@ -143,7 +164,13 @@ WARNING: The 'username'' and 'password' will be stored in the config file in pla
Str("profile", profile).
Bool("noPrompt", noPrompt).
Msg("call: authConfigFile()")
authConfig, authConfigFileErrs = authConfigFile(configFile, profile, "", noPrompt, true) // always save config file is login is called
authConfig, authConfigFileErrs = authConfigFile(
configFile,
profile,
"",
noPrompt,
true,
) // always save config file is login is called
log.Debug().Msg("authConfigFile() returned")
if authConfigFileErrs != nil {
// Print out the error messages
Expand All @@ -157,7 +184,17 @@ WARNING: The 'username'' and 'password' will be stored in the config file in pla
//Attempt to auth with user interactive login
log.Info().Msg("Attempting to authenticate via user interactive login.")
authEntry := authConfig.Servers[profile]
authConfig, authErr = authInteractive(authEntry.Hostname, authEntry.Username, authEntry.Password, authEntry.Domain, authEntry.APIPath, profile, false, true, configFile)
authConfig, authErr = authInteractive(
authEntry.Hostname,
authEntry.Username,
authEntry.Password,
authEntry.Domain,
authEntry.APIPath,
profile,
false,
true,
configFile,
)
if authErr != nil {
//log.Println(authErr)
log.Error().Err(authErr)
Expand Down Expand Up @@ -208,7 +245,10 @@ func validConfigFileEntry(configFile ConfigurationFile, profile string) bool {
if configFile.Servers[profile].Hostname == "" || configFile.Servers[profile].Username == "" || configFile.Servers[profile].Password == "" {
return false
}
if configFile.Servers[profile].Domain == "" && (!strings.Contains(configFile.Servers[profile].Username, "@") || !strings.Contains(configFile.Servers[profile].Username, "\\")) {
if configFile.Servers[profile].Domain == "" && (!strings.Contains(
configFile.Servers[profile].Username,
"@",
) || !strings.Contains(configFile.Servers[profile].Username, "\\")) {
return false
}
return true
Expand All @@ -223,7 +263,14 @@ func getDomainFromUsername(username string) string {
return ""
}

func createConfigFile(hostname string, username string, password string, domain string, apiPath string, profileName string) ConfigurationFile {
func createConfigFile(
hostname string,
username string,
password string,
domain string,
apiPath string,
profileName string,
) ConfigurationFile {
output := ConfigurationFile{
Servers: map[string]ConfigurationFileEntry{
profileName: {
Expand Down Expand Up @@ -329,7 +376,17 @@ func saveConfigFile(configFile ConfigurationFile, configPath string, profileName
return loadedConfig, nil
}

func authInteractive(hostname string, username string, password string, domain string, apiPath string, profileName string, forcePrompt bool, saveConfig bool, configPath string) (ConfigurationFile, error) {
func authInteractive(
hostname string,
username string,
password string,
domain string,
apiPath string,
profileName string,
forcePrompt bool,
saveConfig bool,
configPath string,
) (ConfigurationFile, error) {
if hostname == "" || forcePrompt {
hostname = promptForInteractiveParameter("Keyfactor Command kfcHostName", hostname)
}
Expand Down Expand Up @@ -397,7 +454,12 @@ func prepHomeDir() (string, error) {
return userHomeDir, hErr
}

func loadConfigFileData(profileName string, configPath string, noPrompt bool, configurationFile ConfigurationFile) (string, string, string, string, string) {
func loadConfigFileData(
profileName string,
configPath string,
noPrompt bool,
configurationFile ConfigurationFile,
) (string, string, string, string, string) {
log.Debug().Str("profileName", profileName).
Str("configPath", configPath).
Bool("noPrompt", noPrompt).
Expand Down Expand Up @@ -505,7 +567,10 @@ func authViaProvider() (*api.Client, error) {
log.Info().Str("providerType", providerType).Msg("attempting to auth via auth provider")
var providerConfig AuthProvider
if providerProfile == "" {
log.Info().Str("providerProfile", providerProfile).Msg("auth provider profile not set, defaulting to 'default'")
log.Info().Str(
"providerProfile",
providerProfile,
).Msg("auth provider profile not set, defaulting to 'default'")
providerProfile = "default"
}

Expand Down Expand Up @@ -586,10 +651,10 @@ func authViaProvider() (*api.Client, error) {
if err != nil {
//fmt.Printf("Error connecting to Keyfactor: %s\n", err)
outputError(err, true, "text")
//log.Fatalf("[ERROR] creating Keyfactor client: %s", err)
return nil, fmt.Errorf("unable to create Keyfactor Command client: %s", err)
//log.Fatalf("[ERROR] creating Keyfactor Client: %s", err)
return nil, fmt.Errorf("unable to create Keyfactor Command Client: %s", err)
}
log.Info().Msg("Keyfactor Command client created")
log.Info().Msg("Keyfactor Command Client created")
log.Debug().Str("flagAuthProvider", providerType).
Str("providerProfile", providerProfile).
Msg("returning from provider auth")
Expand All @@ -604,7 +669,10 @@ func authViaProviderGenClient() (*keyfactor.APIClient, error) {
log.Info().Str("providerType", providerType).Msg("attempting to auth via auth provider")
var providerConfig AuthProvider
if providerProfile == "" {
log.Info().Str("providerProfile", providerProfile).Msg("auth provider profile not set, defaulting to 'default'")
log.Info().Str(
"providerProfile",
providerProfile,
).Msg("auth provider profile not set, defaulting to 'default'")
providerProfile = "default"
}

Expand Down Expand Up @@ -683,7 +751,7 @@ func authViaProviderGenClient() (*keyfactor.APIClient, error) {
configuration := keyfactor.NewConfiguration(sdkClientConfig)
c := keyfactor.NewAPIClient(configuration)
log.Debug().Msg("complete: api.NewKeyfactorClient()")
log.Info().Msg("Keyfactor Command client created")
log.Info().Msg("Keyfactor Command Client created")
log.Debug().Str("flagAuthProvider", providerType).
Str("providerProfile", providerProfile).
Msg("returning from provider auth")
Expand All @@ -702,7 +770,11 @@ func authViaProviderParams(providerConfig *AuthProvider) (ConfigurationFile, err

// Check if auth provider is valid
if !validAuthProvider(pt) {
return ConfigurationFile{}, fmt.Errorf("invalid auth provider type '%s'. Valid auth providers are: %v", pt, ValidAuthProviders)
return ConfigurationFile{}, fmt.Errorf(
"invalid auth provider type '%s'. Valid auth providers are: %v",
pt,
ValidAuthProviders,
)
}

// Check if provider type matches requested provider type
Expand Down Expand Up @@ -734,7 +806,11 @@ func authViaProviderParams(providerConfig *AuthProvider) (ConfigurationFile, err
log.Error().Msg("invalid auth provider type")
break
}
return ConfigurationFile{}, fmt.Errorf("invalid auth provider type '%s'. Valid auth providers are: %v", pt, ValidAuthProviders)
return ConfigurationFile{}, fmt.Errorf(
"invalid auth provider type '%s'. Valid auth providers are: %v",
pt,
ValidAuthProviders,
)
}

func validAuthProvider(providerType string) bool {
Expand All @@ -752,7 +828,13 @@ func validAuthProvider(providerType string) bool {
return false
}

func authConfigFile(configPath string, profileName string, authProviderProfile string, noPrompt bool, saveConfig bool) (ConfigurationFile, []error) {
func authConfigFile(
configPath string,
profileName string,
authProviderProfile string,
noPrompt bool,
saveConfig bool,
) (ConfigurationFile, []error) {
var configurationFile ConfigurationFile
var (
hostName string
Expand Down Expand Up @@ -793,7 +875,12 @@ func authConfigFile(configPath string, profileName string, authProviderProfile s
}

log.Debug().Msg("calling loadConfigFileData()")
hostName, userName, password, domain, apiPath = loadConfigFileData(profileName, configPath, noPrompt, configurationFile)
hostName, userName, password, domain, apiPath = loadConfigFileData(
profileName,
configPath,
noPrompt,
configurationFile,
)
log.Debug().Msg("loadConfigFileData() returned")

log.Debug().Str("hostName", hostName).
Expand Down Expand Up @@ -832,7 +919,10 @@ func authConfigFile(configPath string, profileName string, authProviderProfile s

func authEnvProvider(authProvider *AuthProvider, configProfile string) (ConfigurationFile, []error) {
//log.Println(fmt.Sprintf("[INFO] authenticating with auth provider '%s' params from environment variables", authProvider.Type))
log.Info().Str("authProvider.Type", authProvider.Type).Msg("authenticating with auth provider params from environment variables")
log.Info().Str(
"authProvider.Type",
authProvider.Type,
).Msg("authenticating with auth provider params from environment variables")

if configProfile == "" {
log.Debug().Msg("configProfile is empty, setting to default")
Expand Down Expand Up @@ -918,7 +1008,12 @@ func authEnvProvider(authProvider *AuthProvider, configProfile string) (Configur
} else {
//log.Println(fmt.Sprintf("[DEBUG] profile '%s' not found in authProviderParams file", configProfile))
log.Debug().Str("configProfile", configProfile).Msg("profile not found in authProviderParams file")
return ConfigurationFile{}, []error{fmt.Errorf("profile '%s' not found in authProviderParams file", configProfile)}
return ConfigurationFile{}, []error{
fmt.Errorf(
"profile '%s' not found in authProviderParams file",
configProfile,
),
}
}
} else {
//check if provider params is an AuthProvider
Expand Down Expand Up @@ -956,7 +1051,10 @@ func authEnvProvider(authProvider *AuthProvider, configProfile string) (Configur
authProvider.Parameters = providerParams
}
//log.Println("[INFO] Attempting to fetch kfutil creds from auth provider ", authProvider)
log.Info().Str("authProvider", fmt.Sprintf("%+v", authProvider)).Msg("Attempting to fetch kfutil creds from auth provider")
log.Info().Str(
"authProvider",
fmt.Sprintf("%+v", authProvider),
).Msg("Attempting to fetch kfutil creds from auth provider")
configFile, authErr := authViaProviderParams(authProvider)
if authErr != nil {
//log.Println("[ERROR] Unable to authenticate via provider: ", authErr)
Expand Down Expand Up @@ -1011,16 +1109,28 @@ func authEnvVars(configPath string, profileName string, saveConfig bool) (Config

var outputErr []error
if !hostSet {
outputErr = append(outputErr, fmt.Errorf("KEYFACTOR_HOSTNAME environment variable not set. Please set the KEYFACTOR_HOSTNAME environment variable"))
outputErr = append(
outputErr,
fmt.Errorf("KEYFACTOR_HOSTNAME environment variable not set. Please set the KEYFACTOR_HOSTNAME environment variable"),
)
}
if !userSet {
outputErr = append(outputErr, fmt.Errorf("KEYFACTOR_USERNAME environment variable not set. Please set the KEYFACTOR_USERNAME environment variable"))
outputErr = append(
outputErr,
fmt.Errorf("KEYFACTOR_USERNAME environment variable not set. Please set the KEYFACTOR_USERNAME environment variable"),
)
}
if !passSet {
outputErr = append(outputErr, fmt.Errorf("KEYFACTOR_PASSWORD environment variable not set. Please set the KEYFACTOR_PASSWORD environment variable"))
outputErr = append(
outputErr,
fmt.Errorf("KEYFACTOR_PASSWORD environment variable not set. Please set the KEYFACTOR_PASSWORD environment variable"),
)
}
if !domainSet {
outputErr = append(outputErr, fmt.Errorf("KEYFACTOR_DOMAIN environment variable not set. Please set the KEYFACTOR_DOMAIN environment variable"))
outputErr = append(
outputErr,
fmt.Errorf("KEYFACTOR_DOMAIN environment variable not set. Please set the KEYFACTOR_DOMAIN environment variable"),
)
}
if !apiPathSet {
apiPath = DefaultAPIPath
Expand Down Expand Up @@ -1182,7 +1292,10 @@ func loadConfigurationFile(filePath string, silent bool) (ConfigurationFile, err
sjErr := json.Unmarshal(f, &singleEntry)
if sjErr != nil {
//log.Println(fmt.Sprintf("[DEBUG] config file '%s' is a not single entry, will attempt to parse as v1 config file", filePath))
log.Debug().Str("filePath", filePath).Msg("config file is not a single entry, will attempt to parse as v1 config file")
log.Debug().Str(
"filePath",
filePath,
).Msg("config file is not a single entry, will attempt to parse as v1 config file")
} else if (singleEntry != ConfigurationFileEntry{}) {
// if we successfully unmarshalled a single entry, add it to the map as the default entry
//log.Println(fmt.Sprintf("[DEBUG] config file '%s' is a single entry, adding to map", filePath))
Expand All @@ -1203,7 +1316,13 @@ func loadConfigurationFile(filePath string, silent bool) (ConfigurationFile, err
return data, nil
}

func createAuthConfigFromParams(hostname string, username string, password string, domain string, apiPath string) *api.AuthConfig {
func createAuthConfigFromParams(
hostname string,
username string,
password string,
domain string,
apiPath string,
) *api.AuthConfig {
output := api.AuthConfig{
Hostname: hostname,
Username: username,
Expand Down
Loading

0 comments on commit 0129962

Please sign in to comment.