Skip to content

Commit

Permalink
chore(docs): Add CLI YAML def.
Browse files Browse the repository at this point in the history
Signed-off-by: sbailey <[email protected]>
  • Loading branch information
spbsoluble committed Mar 29, 2024
1 parent c55d95d commit f6ae138
Show file tree
Hide file tree
Showing 13 changed files with 1,635 additions and 228 deletions.
49 changes: 33 additions & 16 deletions cmd/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,33 @@ package cmd
import "fmt"

const (
ColorRed = "\033[31m"
ColorWhite = "\033[37m"
DefaultAPIPath = "KeyfactorAPI"
DefaultConfigFileName = "command_config.json"
FailedAuthMsg = "Login failed!"
SuccessfulAuthMsg = "Login successful!"
XKeyfactorRequestedWith = "APIClient"
XKeyfactorApiVersion = "1"
FlagGitRef = "git-ref"
FlagFromFile = "from-file"
DebugFuncEnter = "entered: %s"
DebugFuncExit = "exiting: %s"
DebugFuncCall = "calling: %s"
ErrMsgEmptyResponse = "empty response received from Keyfactor Command %s"
ColorRed = "\033[31m"
ColorWhite = "\033[37m"
DefaultAPIPath = "KeyfactorAPI"
DefaultConfigFileName = "command_config.json"
DefaultROTAuditStoresOutfilePath = "rot_audit_selected_stores.csv"
DefaultROTAuditAddCertsOutfilePath = "rot_audit_selected_certs_add.csv"
DefaultROTAuditRemoveCertsOutfilePath = "rot_audit_selected_certs_remove.csv"
FailedAuthMsg = "Login failed!"
SuccessfulAuthMsg = "Login successful!"
XKeyfactorRequestedWith = "APIClient"
XKeyfactorApiVersion = "1"
FlagGitRef = "git-ref"
FlagFromFile = "from-file"
DebugFuncEnter = "entered: %s"
DebugFuncExit = "exiting: %s"
DebugFuncCall = "calling: %s"
ErrMsgEmptyResponse = "empty response received from Keyfactor Command %s"
)

// CLI Menu Defaults
const (
DefaultMenuPageSizeSmall = 25
DefaultMenuPageSizeLarge = 100
)

var (
DefaultSourceTypeOptions = []string{"API", "File"}
)

var ProviderTypeChoices = []string{
Expand All @@ -40,6 +53,10 @@ var ErrKfcEmptyResponse = fmt.Errorf("empty response recieved from Keyfactor Com

// Error messages
var (
StoreTypeReadError = fmt.Errorf("error reading store type from configuration file")
InvalidInputError = fmt.Errorf("invalid input")
StoreTypeReadError = fmt.Errorf("error reading store type from configuration file")
InvalidInputError = fmt.Errorf("invalid input")
InvalidROTCertsInputErr = fmt.Errorf(
"at least one of `--add-certs` or `--remove-certs` is required to perform a" +
" root of trust audit",
)
)
27 changes: 21 additions & 6 deletions cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"

"github.com/Keyfactor/keyfactor-go-client-sdk/api/keyfactor"
"github.com/Keyfactor/keyfactor-go-client/v2/api"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"os"
"strconv"
)

var exportPath string
Expand Down Expand Up @@ -371,8 +372,10 @@ func getIssuedAlerts(kfClient *keyfactor.APIClient) []keyfactor.KeyfactorApiMode
func getDeniedAlerts(kfClient *keyfactor.APIClient) []keyfactor.KeyfactorApiModelsAlertsDeniedDeniedAlertCreationRequest {

alerts, _, reqErr := kfClient.DeniedAlertApi.DeniedAlertGetDeniedAlerts(
context.Background()).XKeyfactorRequestedWith(
XKeyfactorRequestedWith).XKeyfactorApiVersion(XKeyfactorApiVersion).Execute()
context.Background(),
).XKeyfactorRequestedWith(
XKeyfactorRequestedWith,
).XKeyfactorApiVersion(XKeyfactorApiVersion).Execute()
if reqErr != nil {
fmt.Printf("%s Error! Unable to get denied cert alerts %s%s\n", ColorRed, reqErr, ColorWhite)
}
Expand Down Expand Up @@ -575,7 +578,13 @@ func init() {
exportCmd.Flags().Lookup("collections").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fMetadata, "metadata", "m", false, "export metadata to JSON file")
exportCmd.Flags().Lookup("metadata").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fExpirationAlerts, "expiration-alerts", "e", false, "export expiration cert alerts to JSON file")
exportCmd.Flags().BoolVarP(
&fExpirationAlerts,
"expiration-alerts",
"e",
false,
"export expiration cert alerts to JSON file",
)
exportCmd.Flags().Lookup("expiration-alerts").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fIssuedAlerts, "issued-alerts", "i", false, "export issued cert alerts to JSON file")
exportCmd.Flags().Lookup("issued-alerts").NoOptDefVal = "true"
Expand All @@ -585,7 +594,13 @@ func init() {
exportCmd.Flags().Lookup("pending-alerts").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fNetworks, "networks", "n", false, "export SSL networks to JSON file")
exportCmd.Flags().Lookup("networks").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fWorkflowDefinitions, "workflow-definitions", "w", false, "export workflow definitions to JSON file")
exportCmd.Flags().BoolVarP(
&fWorkflowDefinitions,
"workflow-definitions",
"w",
false,
"export workflow definitions to JSON file",
)
exportCmd.Flags().Lookup("workflow-definitions").NoOptDefVal = "true"
exportCmd.Flags().BoolVarP(&fReports, "reports", "r", false, "export reports to JSON file")
exportCmd.Flags().Lookup("reports").NoOptDefVal = "true"
Expand Down
8 changes: 6 additions & 2 deletions cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ import (
"github.com/spf13/cobra"
)

func mergeErrsToString(errs *[]error) string {
func mergeErrsToString(errs *[]error, indent bool) string {
var errStr string
if errs == nil || len(*errs) == 0 {
return ""
}
for _, err := range *errs {
errStr += fmt.Sprintf("%s\n", err)
if indent {
errStr += fmt.Sprintf(" \t%s\r\n", err)
continue
}
errStr += fmt.Sprintf("%s\r\n", err)
}
return errStr
}
Expand Down
160 changes: 138 additions & 22 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ package cmd

import (
"fmt"
"io"
stdlog "log"
"os"
"os/signal"
"syscall"

"github.com/Keyfactor/keyfactor-go-client-sdk/api/keyfactor"
"github.com/Keyfactor/keyfactor-go-client/v2/api"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"golang.org/x/crypto/bcrypt"
"io"
stdlog "log"
"os"
)

var (
Expand All @@ -45,6 +48,19 @@ var (
outputFormat string
)

func setupSignalHandler() {
// Start a goroutine to listen for SIGINT signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)

go func() {
<-sigChan
// Handle SIGINT signal
fmt.Println("\nCtrl+C pressed. Exiting...")
os.Exit(1)
}()
}

func hashSecretValue(secretValue string) string {
log.Debug().Msg("Enter hashSecretValue()")
if logInsecure {
Expand All @@ -63,7 +79,15 @@ func hashSecretValue(secretValue string) string {
return string(hashedPassword)
}

func initClient(flagConfigFile string, flagProfile string, flagAuthProviderType string, flagAuthProviderProfile string, noPrompt bool, authConfig *api.AuthConfig, saveConfig bool) (*api.Client, error) {
func initClient(
flagConfigFile string,
flagProfile string,
flagAuthProviderType string,
flagAuthProviderProfile string,
noPrompt bool,
authConfig *api.AuthConfig,
saveConfig bool,
) (*api.Client, error) {
log.Debug().Msg("Enter initClient()")
var clientAuth api.AuthConfig
var commandConfig ConfigurationFile
Expand Down Expand Up @@ -163,9 +187,18 @@ func initClient(flagConfigFile string, flagProfile string, flagAuthProviderType
if !noPrompt {
// Auth user interactively
authConfigEntry := commandConfig.Servers[flagProfile]
commandConfig, _ = authInteractive(authConfigEntry.Hostname, authConfigEntry.Username, authConfigEntry.Password, authConfigEntry.Domain, authConfigEntry.APIPath, flagProfile, false, false, flagConfigFile)
commandConfig, _ = authInteractive(
authConfigEntry.Hostname,
authConfigEntry.Username,
authConfigEntry.Password,
authConfigEntry.Domain,
authConfigEntry.APIPath,
flagProfile,
false,
false,
flagConfigFile,
)
} else {
//log.Fatalf("[ERROR] auth config profile: %s", flagProfile)
log.Error().Str("flagProfile", flagProfile).Msg("invalid auth config profile")
return nil, fmt.Errorf("invalid auth config profile: %s", flagProfile)
}
Expand All @@ -191,14 +224,19 @@ func initClient(flagConfigFile string, flagProfile string, flagAuthProviderType
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.Info().Msg("Keyfactor Command client created")
return c, nil
}

func initGenClient(flagConfig string, flagProfile string, noPrompt bool, authConfig *api.AuthConfig, saveConfig bool) (*keyfactor.APIClient, error) {
func initGenClient(
flagConfig string,
flagProfile string,
noPrompt bool,
authConfig *api.AuthConfig,
saveConfig bool,
) (*keyfactor.APIClient, error) {
var commandConfig ConfigurationFile

if providerType != "" {
Expand Down Expand Up @@ -246,7 +284,17 @@ func initGenClient(flagConfig string, flagProfile string, noPrompt bool, authCon
if !noPrompt {
// Auth user interactively
authConfigEntry := commandConfig.Servers[flagProfile]
commandConfig, _ = authInteractive(authConfigEntry.Hostname, authConfigEntry.Username, authConfigEntry.Password, authConfigEntry.Domain, authConfigEntry.APIPath, flagProfile, false, false, flagConfig)
commandConfig, _ = authInteractive(
authConfigEntry.Hostname,
authConfigEntry.Username,
authConfigEntry.Password,
authConfigEntry.Domain,
authConfigEntry.APIPath,
flagProfile,
false,
false,
flagConfig,
)
} else {
//log.Fatalf("[ERROR] auth config profile: %s", flagProfile)
log.Error().Str("flagProfile", flagProfile).Msg("invalid auth config profile")
Expand Down Expand Up @@ -306,24 +354,92 @@ func init() {

defaultConfigPath := fmt.Sprintf("$HOME/.keyfactor/%s", DefaultConfigFileName)

RootCmd.PersistentFlags().StringVarP(&configFile, "config", "", "", fmt.Sprintf("Full path to config file in JSON format. (default is %s)", defaultConfigPath))
RootCmd.PersistentFlags().BoolVar(&noPrompt, "no-prompt", false, "Do not prompt for any user input and assume defaults or environmental variables are set.")
RootCmd.PersistentFlags().BoolVar(&expEnabled, "exp", false, "Enable expEnabled features. (USE AT YOUR OWN RISK, these features are not supported and may change or be removed at any time.)")
RootCmd.PersistentFlags().StringVarP(
&configFile,
"config",
"",
"",
fmt.Sprintf("Full path to config file in JSON format. (default is %s)", defaultConfigPath),
)
RootCmd.PersistentFlags().BoolVar(
&noPrompt,
"no-prompt",
false,
"Do not prompt for any user input and assume defaults or environmental variables are set.",
)
RootCmd.PersistentFlags().BoolVar(
&expEnabled,
"exp",
false,
"Enable expEnabled features. (USE AT YOUR OWN RISK, these features are not supported and may change or be removed at any time.)",
)
RootCmd.PersistentFlags().BoolVar(&debugFlag, "debug", false, "Enable debugFlag logging.")
RootCmd.PersistentFlags().BoolVar(&logInsecure, "log-insecure", false, "Log insecure API requests. (USE AT YOUR OWN RISK, this WILL log sensitive information to the console.)")
RootCmd.PersistentFlags().StringVarP(&profile, "profile", "", "", "Use a specific profile from your config file. If not specified the config named 'default' will be used if it exists.")
RootCmd.PersistentFlags().StringVar(&outputFormat, "format", "text", "How to format the CLI output. Currently only `text` is supported.")
RootCmd.PersistentFlags().BoolVar(
&logInsecure,
"log-insecure",
false,
"Log insecure API requests. (USE AT YOUR OWN RISK, this WILL log sensitive information to the console.)",
)
RootCmd.PersistentFlags().StringVarP(
&profile,
"profile",
"",
"",
"Use a specific profile from your config file. If not specified the config named 'default' will be used if it exists.",
)
RootCmd.PersistentFlags().StringVar(
&outputFormat,
"format",
"text",
"How to format the CLI output. Currently only `text` is supported.",
)

RootCmd.PersistentFlags().StringVar(&providerType, "auth-provider-type", "", "Provider type choices: (azid)")
// Validating the provider-type flag against the predefined choices
RootCmd.PersistentFlags().SetAnnotation("auth-provider-type", cobra.BashCompCustom, ProviderTypeChoices)
RootCmd.PersistentFlags().StringVarP(&providerProfile, "auth-provider-profile", "", "default", "The profile to use defined in the securely stored config. If not specified the config named 'default' will be used if it exists.")

RootCmd.PersistentFlags().StringVarP(&kfcUsername, "username", "", "", "Username to use for authenticating to Keyfactor Command.")
RootCmd.PersistentFlags().StringVarP(&kfcHostName, "hostname", "", "", "Hostname to use for authenticating to Keyfactor Command.")
RootCmd.PersistentFlags().StringVarP(&kfcPassword, "password", "", "", "Password to use for authenticating to Keyfactor Command. WARNING: Remember to delete your console history if providing kfcPassword here in plain text.")
RootCmd.PersistentFlags().StringVarP(&kfcDomain, "domain", "", "", "Domain to use for authenticating to Keyfactor Command.")
RootCmd.PersistentFlags().StringVarP(&kfcAPIPath, "api-path", "", "KeyfactorAPI", "API Path to use for authenticating to Keyfactor Command. (default is KeyfactorAPI)")
RootCmd.PersistentFlags().StringVarP(
&providerProfile,
"auth-provider-profile",
"",
"default",
"The profile to use defined in the securely stored config. If not specified the config named 'default' will be used if it exists.",
)

RootCmd.PersistentFlags().StringVarP(
&kfcUsername,
"username",
"",
"",
"Username to use for authenticating to Keyfactor Command.",
)
RootCmd.PersistentFlags().StringVarP(
&kfcHostName,
"hostname",
"",
"",
"Hostname to use for authenticating to Keyfactor Command.",
)
RootCmd.PersistentFlags().StringVarP(
&kfcPassword,
"password",
"",
"",
"Password to use for authenticating to Keyfactor Command. WARNING: Remember to delete your console history if providing kfcPassword here in plain text.",
)
RootCmd.PersistentFlags().StringVarP(
&kfcDomain,
"domain",
"",
"",
"Domain to use for authenticating to Keyfactor Command.",
)
RootCmd.PersistentFlags().StringVarP(
&kfcAPIPath,
"api-path",
"",
"KeyfactorAPI",
"API Path to use for authenticating to Keyfactor Command. (default is KeyfactorAPI)",
)

// Cobra also supports local flags, which will only run
// when this action is called directly.
Expand Down
Loading

0 comments on commit f6ae138

Please sign in to comment.