From c1dd76788d1fcc428ae38e34600b8d78df2de20d Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Thu, 13 Dec 2018 12:15:05 +0000 Subject: [PATCH] httplib: make http serving with auth generate INFO messages on auth fail 2018/12/13 12:13:44 INFO : /: 127.0.0.1:39696: Basic auth challenge sent 2018/12/13 12:13:54 INFO : /: 127.0.0.1:40050: Unauthorized request from ncw Fixes #2834 --- cmd/serve/httplib/httplib.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/cmd/serve/httplib/httplib.go b/cmd/serve/httplib/httplib.go index f39a1d901..49d55c640 100644 --- a/cmd/serve/httplib/httplib.go +++ b/cmd/serve/httplib/httplib.go @@ -4,11 +4,13 @@ package httplib import ( "crypto/tls" "crypto/x509" + "encoding/base64" "fmt" "io/ioutil" "log" "net" "net/http" + "strings" "time" auth "github.com/abbot/go-http-auth" @@ -143,7 +145,28 @@ func NewServer(handler http.Handler, opt *Options) *Server { secretProvider = s.singleUserProvider } authenticator := auth.NewBasicAuthenticator(s.Opt.Realm, secretProvider) - handler = auth.JustCheck(authenticator, handler.ServeHTTP) + oldHandler := handler + handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if username := authenticator.CheckAuth(r); username == "" { + authHeader := r.Header.Get(authenticator.Headers.V().Authorization) + if authHeader != "" { + s := strings.SplitN(authHeader, " ", 2) + var userName = "UNKNOWN" + if len(s) == 2 && s[0] == "Basic" { + b, err := base64.StdEncoding.DecodeString(s[1]) + if err == nil { + userName = strings.SplitN(string(b), ":", 2)[0] + } + } + fs.Infof(r.URL.Path, "%s: Unauthorized request from %s", r.RemoteAddr, userName) + } else { + fs.Infof(r.URL.Path, "%s: Basic auth challenge sent", r.RemoteAddr) + } + authenticator.RequireAuth(w, r) + } else { + oldHandler.ServeHTTP(w, r) + } + }) s.usingAuth = true }