Skip to content

Commit

Permalink
use viper to read shared config (#54)
Browse files Browse the repository at this point in the history
* use viper to read shared config. still need to wire into actual cmds.
  • Loading branch information
bhamail authored Nov 3, 2020
1 parent 2041c38 commit 57bd6df
Show file tree
Hide file tree
Showing 13 changed files with 1,017 additions and 118 deletions.
84 changes: 37 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,39 +113,34 @@ Usage:
Available Commands:
chase chase is used for auditing projects with OSS Index
config Setup credentials to use when connecting to services
help Help about any command
iq iq is used for auditing your projects with Nexus IQ Server
Flags:
-h, --help help for ahab
-h, --help help for ahab
-t, --token string Specify your OSS Index API Token
-u, --username string Specify your OSS Index Username
Use "ahab [command] --help" for more information about a command.
```

#### OSS Index usage

```
$ ahab chase
______ __ __
/\ _ \ /\ \ /\ \
\ \ \L\ \ \ \ \___ __ \ \ \____
\ \ __ \ \ \ _ `\ /'__`\ \ \ '__`\
\ \ \/\ \ \ \ \ \ \ /\ \L\.\_ \ \ \L\ \
\ \_\ \_\ \ \_\ \_\\ \__/.\_\ \ \_,__/
\/_/\/_/ \/_/\/_/ \/__/\/_/ \/___/
_ _ _ _
/_) /_` _ _ _ _/_ _ _ (/ /_` _ . _ _ _/ _
/_) /_/ ._/ /_// //_|/ /_/ /_//_' (_X / / / /_'/ //_/ _\
_/ _/ /
Ahab version: development
$ ahab chase -h
chase is used for auditing projects with OSS Index
Usage:
ahab chase [flags]
Examples:
dpkg-query --show --showformat='${Package} ${Version}\n' | ./ahab chase
yum list installed | ./ahab chase
dnf list installed | ./ahab chase
apk info -vv | sort | ./ahab chase
Flags:
-v, -- count Set log level, higher is more verbose
Expand All @@ -158,9 +153,11 @@ Flags:
--os string Specify a value for the operating system type you want to scan (alpine, debian, fedora). Useful if autodetection fails and/or you want to explicitly set it. (DEPRECATED: use package-manager)
--output string Specify the output type you want (json, text, csv) (default "text")
--package-manager string Specify package manager type you want to scan (apk, dnf, dpkg or yum). Useful if autodetection fails and/or you want to explicitly set it.
--quiet Quiet removes the header from being printed
--token string Specify your OSS Index API Token
--user string Specify your OSS Index Username
--quiet Quiet removes the header from being printed (default true)
Global Flags:
-t, --token string Specify your OSS Index API Token
-u, --username string Specify your OSS Index Username
```

#### Exclude vulnerabilities
Expand Down Expand Up @@ -204,43 +201,36 @@ CVN-543 until=2018-02-12 #Waiting on release from third party. Should be out bef
#### Nexus IQ Server Usage

```
$ ahab iq
______ __ __
/\ _ \ /\ \ /\ \
\ \ \L\ \ \ \ \___ __ \ \ \____
\ \ __ \ \ \ _ `\ /'__`\ \ \ '__`\
\ \ \/\ \ \ \ \ \ \ /\ \L\.\_ \ \ \L\ \
\ \_\ \_\ \ \_\ \_\\ \__/.\_\ \ \_,__/
\/_/\/_/ \/_/\/_/ \/__/\/_/ \/___/
_ _ _ _
/_) /_` _ _ _ _/_ _ _ (/ /_` _ . _ _ _/ _
/_) /_/ ._/ /_// //_|/ /_/ /_//_' (_X / / / /_'/ //_/ _\
_/ _/ /
Ahab version: development
$ ahab iq -h
iq is used for auditing your projects with Nexus IQ Server
Usage:
ahab iq [flags]
Examples:
dpkg-query --show --showformat='${Package} ${Version}\n' | ./ahab iq --application testapp
yum list installed | ./ahab iq --application testapp
apk info -vv | sort | ./ahab iq --application testapp
dpkg-query --show --showformat='${Package} ${Version}\n' | ./ahab iq --iq-application testapp
yum list installed | ./ahab iq --iq-application testapp
dnf list installed | ./ahab iq --iq-application testapp
apk info -vv | sort | ./ahab iq --iq-application testapp
Flags:
-v, -- count Set log level, higher is more verbose
--clean-cache Flag to clean the database cache for OSS Index
-e, --exclude-vulnerability CveListFlag Comma separated list of CVEs to exclude (default [])
-x, --exclude-vulnerability-file string Path to a file containing newline separated CVEs to be excluded (default "./.ahab-ignore")
-h, --help help for chase
--loud Specify if you want non vulnerable packages included in your output
--no-color Specify if you want no color in your results
--os string Specify a value for the operating system type you want to scan (alpine, debian, fedora). Useful if autodetection fails and/or you want to explicitly set it. (DEPRECATED: use package-manager)
--output string Specify the output type you want (json, text, csv) (default "text")
--package-manager string Specify package manager type you want to scan (apk, dnf, dpkg or yum). Useful if autodetection fails and/or you want to explicitly set it.
--quiet Quiet removes the header from being printed
--token string Specify your OSS Index API Token
--user string Specify your OSS Index Username
-v, -- count Set log level, higher is more verbose
-h, --help help for iq
-a, --iq-application string Specify public application ID for request (required)
-x, --iq-server-url string Specify Nexus IQ Server URL (default "http://localhost:8070")
-s, --iq-stage string Specify stage for application (default "develop")
-k, --iq-token string Specify Nexus IQ Token/Password for request (default "admin123")
-l, --iq-username string Specify Nexus IQ Username for request (default "admin")
--max-retries int Specify maximum number of tries to poll Nexus IQ Server (default 300)
--os string Specify a value for the operating system type you want to scan (alpine, debian, fedora). Useful if autodetection fails and/or you want to explicitly set it. (DEPRECATED: use package-manager)
--package-manager string Specify package manager type you want to scan (apk, dnf, dpkg or yum). Useful if autodetection fails and/or you want to explicitly set it.
--quiet Quiet removes the header from being printed (default true)
Global Flags:
-t, --token string Specify your OSS Index API Token
-u, --username string Specify your OSS Index Username
```

## Why Ahab?
Expand Down
1 change: 1 addition & 0 deletions audit/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ func outputText(noColor bool, loud bool, projects []types.Coordinate) (int, stri
t.AppendSeparator()
t.AppendRow([]interface{}{"Vulnerable Dependencies", au.Bold(au.Red(strconv.Itoa(len(vulnerablePackages))))})
sb.WriteString(t.Render())
sb.WriteString("\n")

return len(vulnerablePackages), sb.String(), nil
}
Expand Down
76 changes: 62 additions & 14 deletions cmd/chase.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ package cmd
import (
"bufio"
"fmt"
"github.com/sonatype-nexus-community/go-sona-types/configuration"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"os"
"regexp"
"strings"
Expand All @@ -28,6 +31,7 @@ import (
"github.com/sirupsen/logrus"
"github.com/sonatype-nexus-community/ahab/audit"
"github.com/sonatype-nexus-community/ahab/buildversion"
"github.com/sonatype-nexus-community/ahab/internal/customerrors"
"github.com/sonatype-nexus-community/ahab/logger"
"github.com/sonatype-nexus-community/ahab/packages"
"github.com/sonatype-nexus-community/ahab/parse"
Expand Down Expand Up @@ -56,8 +60,10 @@ func (cve *CveListFlag) Set(value string) error {
func (cve *CveListFlag) Type() string { return "CveListFlag" }

var (
cfgFile string
packageManager string
cleanCache bool
ossIndexURL string
ossIndexUser string
ossIndexToken string
output string
Expand All @@ -78,11 +84,9 @@ func init() {
pf.StringVar(&packageManager, "os", "", "Specify a value for the operating system type you want to scan (alpine, debian, fedora). Useful if autodetection fails and/or you want to explicitly set it.")
pf.StringVar(&packageManager, "package-manager", "", "Specify package manager type you want to scan (apk, dnf, dpkg or yum). Useful if autodetection fails and/or you want to explicitly set it.")
pf.BoolVar(&cleanCache, "clean-cache", false, "Flag to clean the database cache for OSS Index")
pf.StringVar(&ossIndexUser, "user", "", "Specify your OSS Index Username")
pf.StringVar(&ossIndexToken, "token", "", "Specify your OSS Index API Token")
pf.StringVar(&output, "output", "text", "Specify the output type you want (json, text, csv)")
pf.BoolVar(&loud, "loud", false, "Specify if you want non vulnerable packages included in your output")
pf.BoolVar(&quiet, "quiet", false, "Quiet removes the header from being printed")
pf.BoolVar(&quiet, "quiet", true, "Quiet removes the header from being printed")
pf.BoolVar(&noColor, "no-color", false, "Specify if you want no color in your results")
pf.CountVarP(&verbose, "", "v", "Set log level, higher is more verbose")

Expand All @@ -101,8 +105,7 @@ var chaseCmd = &cobra.Command{
dnf list installed | ./ahab chase
apk info -vv | sort | ./ahab chase
`,
SilenceErrors: true,
SilenceUsage: true,
PreRun: func(cmd *cobra.Command, args []string) { bindViperRootCmd() },
RunE: func(cmd *cobra.Command, args []string) (err error) {
defer func() {
if r := recover(); r != nil {
Expand All @@ -111,8 +114,7 @@ var chaseCmd = &cobra.Command{
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
_ = cmd.Usage()
logger.PrintErrorAndLogLocation(err)
err = customerrors.ErrorShowLogPath{Err: err}
}
}()

Expand All @@ -131,10 +133,21 @@ var chaseCmd = &cobra.Command{
TTL: time.Now().Local().Add(time.Hour * 12),
Tool: "ahab-client",
Version: buildversion.BuildVersion,
Username: ossIndexUser,
Token: ossIndexToken,
OSSIndexURL: ossIndexURL,
Username: viper.GetString(configuration.ViperKeyUsername),
Token: viper.GetString(configuration.ViperKeyToken),
})

logLady.WithField("ossiServer", types.Options{
OSSIndexURL: ossi.Options.OSSIndexURL,
Username: cleanUserName(ossi.Options.Username),
Token: "***hidden***",
Tool: ossi.Options.Tool,
Version: ossi.Options.Version,
DBCacheName: ossi.Options.DBCacheName,
TTL: ossi.Options.TTL,
}).Debug("Created ossiIndex server")

if cleanCache {
err = ossi.NoCacheNoProblems()
if err != nil {
Expand Down Expand Up @@ -190,6 +203,32 @@ var chaseCmd = &cobra.Command{
},
}

const (
flagNameOssiUsername = "username"
flagNameOssiToken = "token"
)

func bindViperRootCmd() {
// need to defer bind call until command is run. see: https://github.com/spf13/viper/issues/233

// Bind viper to the flags passed in via the command line, so it will override config from file
if err := viper.BindPFlag(configuration.ViperKeyUsername, lookupPersistentFlagNotNil(flagNameOssiUsername, rootCmd)); err != nil {
panic(err)
}
if err := viper.BindPFlag(configuration.ViperKeyToken, lookupPersistentFlagNotNil(flagNameOssiToken, rootCmd)); err != nil {
panic(err)
}
}

func lookupPersistentFlagNotNil(flagName string, cmd *cobra.Command) *pflag.Flag {
// see: https://github.com/spf13/viper/pull/949
foundFlag := cmd.PersistentFlags().Lookup(flagName)
if foundFlag == nil {
panic(fmt.Errorf("persisent flag lookup for name: '%s' returned nil", flagName))
}
return foundFlag
}

func getLogger(level int) (*logrus.Logger, error) {
switch level {
case 1:
Expand Down Expand Up @@ -244,14 +283,23 @@ func parseStdInList(list []string, packageManager *string) (packages.IPackage, e
}
}

const MsgMissingStdIn = "nothing passed in to standard in"

func checkStdIn() (err error) {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
logLady.Info("StdIn is valid")
} else {
err = fmt.Errorf(MsgMissingStdIn)
logLady.Error(err)
}
return
}

func parseStdIn(packageManager *string) (packages.IPackage, error) {
fi, err := os.Stdin.Stat()
if err != nil {
if err := checkStdIn(); err != nil {
return nil, err
}
if (fi.Mode() & os.ModeNamedPipe) == 0 {
return nil, fmt.Errorf("Nothing passed in to standard in")
}

var list []string
scanner := bufio.NewScanner(os.Stdin)
Expand Down
Loading

0 comments on commit 57bd6df

Please sign in to comment.