diff --git a/src/cfg/cfg.go b/src/cfg/cfg.go index 9e13dd2..4d7bc64 100644 --- a/src/cfg/cfg.go +++ b/src/cfg/cfg.go @@ -18,6 +18,8 @@ type AppSettings struct { Fail2BanSocketPath string FileCollectorPath string FileCollectorEnabled bool + BasicAuthUsername string + BasicAuthPassword string } func Parse() *AppSettings { @@ -28,6 +30,8 @@ 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(&appSettings.BasicAuthUsername, "web.basic-auth.username", "", "set username for basic auth") + flag.StringVar(&appSettings.BasicAuthPassword, "web.basic-auth.password", "", "set password for basic auth") flag.Parse() appSettings.validateFlags() diff --git a/src/exporter.go b/src/exporter.go index a62271c..843b861 100644 --- a/src/exporter.go +++ b/src/exporter.go @@ -48,6 +48,21 @@ func metricHandler(w http.ResponseWriter, r *http.Request, collector *textfile.C collector.WriteTextFileMetrics(w, r) } +func authMiddleware(handlerFunc http.HandlerFunc, appSettings *cfg.AppSettings) http.HandlerFunc { + authEnabled := len(appSettings.BasicAuthUsername) > 0 && len(appSettings.BasicAuthPassword) > 0 + if authEnabled { + return func(w http.ResponseWriter, r *http.Request) { + username, password, ok := r.BasicAuth() + if !ok || username != appSettings.BasicAuthUsername || password != appSettings.BasicAuthPassword { + w.WriteHeader(http.StatusUnauthorized) + return + } + handlerFunc.ServeHTTP(w, r) + } + } + return handlerFunc +} + func main() { appSettings := cfg.Parse() if appSettings.VersionMode { @@ -63,10 +78,13 @@ func main() { textFileCollector := textfile.NewCollector(appSettings) prometheus.MustRegister(textFileCollector) - http.HandleFunc("/", rootHtmlHandler) - http.HandleFunc(metricsPath, func(w http.ResponseWriter, r *http.Request) { - metricHandler(w, r, textFileCollector) - }) + http.HandleFunc("/", authMiddleware(rootHtmlHandler, appSettings)) + http.HandleFunc(metricsPath, authMiddleware( + func(w http.ResponseWriter, r *http.Request) { + metricHandler(w, r, textFileCollector) + }, + appSettings, + )) log.Printf("metrics available at '%s'", metricsPath) svrErr := make(chan error)