From 6a1c6c596749d50fe67f44ecd77810f6e6870da1 Mon Sep 17 00:00:00 2001 From: Adrien PONSIN Date: Thu, 17 Apr 2025 15:07:57 +0200 Subject: [PATCH] fix refactoring --- command/serve.go | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/command/serve.go b/command/serve.go index 0607bfc..0670a64 100644 --- a/command/serve.go +++ b/command/serve.go @@ -151,10 +151,14 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Debug().Str("remote_addr", r.RemoteAddr).Str("method", r.Method).Str("path", r.URL.Path).Msg("incoming request") mr, ok := containerMethodRegex["*"] if ok { - ph.checkMethodAndRegex(w, r, mr) + if ph.checkMethodAndRegex(r, mr) { + ph.rp.ServeHTTP(w, r) + return + } } var ( containerName string + authorized bool host, _, _ = net.SplitHostPort(r.RemoteAddr) ) for containerName, mr = range containerMethodRegex { @@ -164,13 +168,19 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } for _, resolvedIP := range resolvedIPs { if resolvedIP.Equal(net.ParseIP(host)) { - ph.checkMethodAndRegex(w, r, mr) + if ph.checkMethodAndRegex(r, mr) { + authorized = true + break + } } } } - logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones") - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return + if !authorized { + logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones") + http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) + return + } + ph.rp.ServeHTTP(w, r) } func logDeniedRequest(r *http.Request, statusCode int, message string) { @@ -193,20 +203,23 @@ func logAuthorizedRequest(r *http.Request, containerName, message string) { l.Msg(message) } -func (ph *ProxyHandler) checkMethodAndRegex(w http.ResponseWriter, r *http.Request, mr methodRegex) { +func (ph *ProxyHandler) checkMethodAndRegex(r *http.Request, mr methodRegex) bool { req, ok := mr[r.Method] if !ok { logDeniedRequest(r, http.StatusMethodNotAllowed, "this HTTP method is not in the list of those authorized for this container") - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - return + return false + // http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + // return } if !req.MatchString(r.URL.Path) { logDeniedRequest(r, http.StatusForbidden, "this path does not match any regular expression for this HTTP method") - http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) - return + return false + // http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) + // return } logAuthorizedRequest(r, "", "incoming request matches a registered regular expression") - ph.rp.ServeHTTP(w, r) + return true + // ph.rp.ServeHTTP(w, r) } // action is executed when the ServeCmd command is called.