1
0
Fork 0
mirror of https://github.com/gocsaf/csaf.git synced 2025-12-22 18:15:42 +01:00

Load config from TOML file

This commit is contained in:
Sascha L. Teichmann 2023-07-20 01:33:58 +02:00
parent 12ad7706e3
commit bfcf98464f
2 changed files with 106 additions and 37 deletions

View file

@ -11,28 +11,109 @@ package main
import ( import (
"crypto/tls" "crypto/tls"
"errors" "errors"
"fmt"
"log"
"net/http" "net/http"
"os"
"github.com/BurntSushi/toml"
"github.com/csaf-poc/csaf_distribution/v2/util"
"github.com/jessevdk/go-flags"
"github.com/mitchellh/go-homedir"
) )
type config struct { type config struct {
Output string `short:"o" long:"output" description:"File name of the generated report" value-name:"REPORT-FILE"` Output string `short:"o" long:"output" description:"File name of the generated report" value-name:"REPORT-FILE" toml:"output"`
Format string `short:"f" long:"format" choice:"json" choice:"html" description:"Format of report" default:"json"` Format string `short:"f" long:"format" choice:"json" choice:"html" description:"Format of report" default:"json" toml:"format"`
Insecure bool `long:"insecure" description:"Do not check TLS certificates from provider"` Insecure bool `long:"insecure" description:"Do not check TLS certificates from provider" toml:"insecure"`
ClientCert *string `long:"client-cert" description:"TLS client certificate file (PEM encoded data)" value-name:"CERT-FILE"` ClientCert *string `long:"client-cert" description:"TLS client certificate file (PEM encoded data)" value-name:"CERT-FILE" toml:"client_cert"`
ClientKey *string `long:"client-key" description:"TLS client private key file (PEM encoded data)" value-name:"KEY-FILE"` ClientKey *string `long:"client-key" description:"TLS client private key file (PEM encoded data)" value-name:"KEY-FILE" toml:"client_key"`
Version bool `long:"version" description:"Display version of the binary"` Version bool `long:"version" description:"Display version of the binary" toml:"-"`
Verbose bool `long:"verbose" short:"v" description:"Verbose output"` Verbose bool `long:"verbose" short:"v" description:"Verbose output" toml:"verbose"`
Rate *float64 `long:"rate" short:"r" description:"The average upper limit of https operations per second (defaults to unlimited)"` Rate *float64 `long:"rate" short:"r" description:"The average upper limit of https operations per second (defaults to unlimited)" toml:"rate"`
Years *uint `long:"years" short:"y" description:"Number of years to look back from now" value-name:"YEARS"` Years *uint `long:"years" short:"y" description:"Number of years to look back from now" value-name:"YEARS" toml:"years"`
ExtraHeader http.Header `long:"header" short:"H" description:"One or more extra HTTP header fields"` ExtraHeader http.Header `long:"header" short:"H" description:"One or more extra HTTP header fields" toml:"header"`
RemoteValidator string `long:"validator" description:"URL to validate documents remotely" value-name:"URL"` RemoteValidator string `long:"validator" description:"URL to validate documents remotely" value-name:"URL" toml:"validator"`
RemoteValidatorCache string `long:"validatorcache" description:"FILE to cache remote validations" value-name:"FILE"` RemoteValidatorCache string `long:"validatorcache" description:"FILE to cache remote validations" value-name:"FILE" toml:"validator_cache"`
RemoteValidatorPresets []string `long:"validatorpreset" description:"One or more presets to validate remotely" default:"mandatory"` RemoteValidatorPresets []string `long:"validatorpreset" description:"One or more presets to validate remotely" default:"mandatory" toml:"validator_preset"`
Config *string `short:"c" long:"config" description:"Path to config TOML file" value-name:"TOML-FILE" toml:"-"`
clientCerts []tls.Certificate clientCerts []tls.Certificate
} }
// parseArgsConfig parse the command arguments and loads configuration
// from a configuration file.
func parseArgsConfig() ([]string, *config, error) {
cfg := &config{
RemoteValidatorPresets: []string{"mandatory"},
}
parser := flags.NewParser(cfg, flags.Default)
parser.Usage = "[OPTIONS] domain..."
args, err := parser.Parse()
if err != nil {
return nil, nil, err
}
if cfg.Version {
fmt.Println(util.SemVersion)
os.Exit(0)
}
if cfg.Config != nil {
path, err := homedir.Expand(*cfg.Config)
if err != nil {
return nil, nil, err
}
if err := cfg.load(path); err != nil {
return nil, nil, err
}
} else if path := findConfigFile(); path != "" {
if err := cfg.load(path); err != nil {
return nil, nil, err
}
}
return args, cfg, nil
}
// configPaths are the potential file locations of the the config file.
var configPaths = []string{
"~/.config/csaf/checker.toml",
"~/.csaf_checker.toml",
"csaf_checker.toml",
}
// findConfigFile looks for a file in the pre-defined paths in "configPaths".
// The returned value will be the name of file if found, otherwise an empty string.
func findConfigFile() string {
for _, f := range configPaths {
name, err := homedir.Expand(f)
if err != nil {
log.Printf("warn: %v\n", err)
continue
}
if _, err := os.Stat(name); err == nil {
return name
}
}
return ""
}
// load loads a configuration from file.
func (cfg *config) load(path string) error {
md, err := toml.DecodeFile(path, &cfg)
if err != nil {
return err
}
if undecoded := md.Undecoded(); len(undecoded) != 0 {
return fmt.Errorf("could not parse %q from %q", undecoded, path)
}
return nil
}
// protectedAccess returns true if we have client certificates or // protectedAccess returns true if we have client certificates or
// extra http headers configured. // extra http headers configured.
// This may be a wrong assumption, because the certs are not checked // This may be a wrong assumption, because the certs are not checked
@ -41,6 +122,7 @@ func (cfg *config) protectedAccess() bool {
return len(cfg.clientCerts) > 0 || len(cfg.ExtraHeader) > 0 return len(cfg.clientCerts) > 0 || len(cfg.ExtraHeader) > 0
} }
// prepare prepares internal state of a loaded configuration.
func (cfg *config) prepare() error { func (cfg *config) prepare() error {
// Load client certs. // Load client certs.
switch hasCert, hasKey := cfg.ClientCert != nil, cfg.ClientKey != nil; { switch hasCert, hasKey := cfg.ClientCert != nil, cfg.ClientKey != nil; {
@ -57,3 +139,13 @@ func (cfg *config) prepare() error {
} }
return nil return nil
} }
// errCheck checks if err is not nil and terminates the program if so.
func errCheck(err error) {
if err != nil {
if flags.WroteHelp(err) {
os.Exit(0)
}
log.Fatalf("error: %v\n", err)
}
}

View file

@ -13,28 +13,15 @@ import (
"bufio" "bufio"
_ "embed" // Used for embedding. _ "embed" // Used for embedding.
"encoding/json" "encoding/json"
"fmt"
"html/template" "html/template"
"io" "io"
"log" "log"
"os" "os"
"github.com/csaf-poc/csaf_distribution/v2/util"
"github.com/jessevdk/go-flags"
) )
//go:embed tmpl/report.html //go:embed tmpl/report.html
var reportHTML string var reportHTML string
func errCheck(err error) {
if err != nil {
if flags.WroteHelp(err) {
os.Exit(0)
}
log.Fatalf("error: %v\n", err)
}
}
// writeJSON writes the JSON encoding of the given report to the given stream. // writeJSON writes the JSON encoding of the given report to the given stream.
// It returns nil, otherwise an error. // It returns nil, otherwise an error.
func writeJSON(report *Report, w io.WriteCloser) error { func writeJSON(report *Report, w io.WriteCloser) error {
@ -113,17 +100,7 @@ func run(cfg *config, domains []string) (*Report, error) {
} }
func main() { func main() {
cfg := new(config) domains, cfg, err := parseArgsConfig()
parser := flags.NewParser(cfg, flags.Default)
parser.Usage = "[OPTIONS] domain..."
domains, err := parser.Parse()
errCheck(err)
if cfg.Version {
fmt.Println(util.SemVersion)
return
}
errCheck(cfg.prepare()) errCheck(cfg.prepare())