From 17aa156fa5a44ca03da3c4f51b245c6c532d3a65 Mon Sep 17 00:00:00 2001 From: Adrien PONSIN Date: Thu, 17 Apr 2025 17:56:39 +0200 Subject: [PATCH] try to improve --- command/serve.go | 59 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/command/serve.go b/command/serve.go index f84fce3..8fa245e 100644 --- a/command/serve.go +++ b/command/serve.go @@ -15,6 +15,7 @@ import ( "net/netip" "net/url" "regexp" + "slices" "strings" "time" ) @@ -149,8 +150,7 @@ func Serve(group *errgroup.Group) *cli.Command { 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 { + if mr, ok := containerMethodRegex["*"]; ok { if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK { http.Error(w, http.StatusText(code), code) return @@ -158,29 +158,50 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ph.rp.ServeHTTP(w, r) return } - var ( - containerName string - host, _, _ = net.SplitHostPort(r.RemoteAddr) - ) - for containerName, mr = range containerMethodRegex { - resolvedIPs, err := net.LookupIP(containerName) - if err != nil { - continue - } - for _, resolvedIP := range resolvedIPs { - if resolvedIP.Equal(net.ParseIP(host)) { - if code := ph.checkMethodAndRegex(mr, r, containerName); code != http.StatusOK { - http.Error(w, http.StatusText(code), code) - return - } - ph.rp.ServeHTTP(w, r) + host, _, _ := net.SplitHostPort(r.RemoteAddr) + for containerName, mr := range containerMethodRegex { + if ph.isContainerAuthorized(containerName, host) { + if code := ph.checkMethodAndRegex(mr, r, containerName); code != http.StatusOK { + http.Error(w, http.StatusText(code), code) return } + ph.rp.ServeHTTP(w, r) + return } } + /* + for containerName, mr = range containerMethodRegex { + resolvedIPs, err := net.LookupIP(containerName) + if err != nil { + continue + } + for _, resolvedIP := range resolvedIPs { + if resolvedIP.Equal(net.ParseIP(host)) { + if code := ph.checkMethodAndRegex(mr, r, containerName); code != http.StatusOK { + http.Error(w, http.StatusText(code), code) + return + } + ph.rp.ServeHTTP(w, r) + return + } + } + } + */ logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return +} + +func (ph *ProxyHandler) isContainerAuthorized(containerName, host string) bool { + resolvedIPs, err := net.LookupIP(containerName) + if err != nil { + return false + } + for resolvedIP := range slices.Values(resolvedIPs) { + if resolvedIP.Equal(net.ParseIP(host)) { + return true + } + } + return false } func logDeniedRequest(r *http.Request, statusCode int, message string) {