feat: add support for basic auth (#16)

Add new CLI parameters to enable protecting the API endpoints with basic
auth authentication.
Wrap the server endpoints in a new auth middleware that protects it using
the provided basic auth credentials (if set).
Store the provided basic auth credentials as hashed values to prevent them
from being accidentally leaked.
Add unit tests to ensure the new functionality works as expected.
This commit is contained in:
Hector
2022-01-14 21:36:49 +00:00
parent 013e8f30c9
commit 6f76a03118
9 changed files with 251 additions and 10 deletions

View File

@ -18,9 +18,13 @@ type AppSettings struct {
Fail2BanSocketPath string
FileCollectorPath string
FileCollectorEnabled bool
BasicAuthProvider *hashedBasicAuth
}
func Parse() *AppSettings {
var rawBasicAuthUsername string
var rawBasicAuthPassword string
appSettings := &AppSettings{}
flag.BoolVar(&appSettings.VersionMode, "version", false, "show version info and exit")
flag.StringVar(&appSettings.MetricsAddress, "web.listen-address", "0.0.0.0", "address to use for the metrics server")
@ -28,12 +32,19 @@ func Parse() *AppSettings {
flag.StringVar(&appSettings.Fail2BanSocketPath, "socket", "", "path to the fail2ban server socket")
flag.BoolVar(&appSettings.FileCollectorEnabled, "collector.textfile", false, "enable the textfile collector")
flag.StringVar(&appSettings.FileCollectorPath, "collector.textfile.directory", "", "directory to read text files with metrics from")
flag.StringVar(&rawBasicAuthUsername, "web.basic-auth.username", "", "username to use to protect endpoints with basic auth")
flag.StringVar(&rawBasicAuthPassword, "web.basic-auth.password", "", "password to use to protect endpoints with basic auth")
flag.Parse()
appSettings.setBasicAuthValues(rawBasicAuthUsername, rawBasicAuthPassword)
appSettings.validateFlags()
return appSettings
}
func (settings *AppSettings) setBasicAuthValues(rawUsername, rawPassword string) {
settings.BasicAuthProvider = newHashedBasicAuth(rawUsername, rawPassword)
}
func (settings *AppSettings) validateFlags() {
var flagsValid = true
if !settings.VersionMode {
@ -50,6 +61,10 @@ func (settings *AppSettings) validateFlags() {
fmt.Printf("file collector directory path must not be empty if collector enabled\n")
flagsValid = false
}
if (len(settings.BasicAuthProvider.username) > 0) != (len(settings.BasicAuthProvider.password) > 0) {
fmt.Printf("to enable basic auth both the username and the password must be provided")
flagsValid = false
}
}
if !flagsValid {
flag.Usage()