try to improve

This commit is contained in:
Adrien PONSIN 2025-04-17 17:56:39 +02:00
parent 7bc9fa242e
commit 17aa156fa5
No known key found for this signature in database
GPG Key ID: 7B4D4A32C05C475E

View File

@ -15,6 +15,7 @@ import (
"net/netip" "net/netip"
"net/url" "net/url"
"regexp" "regexp"
"slices"
"strings" "strings"
"time" "time"
) )
@ -149,8 +150,7 @@ func Serve(group *errgroup.Group) *cli.Command {
func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 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") log.Debug().Str("remote_addr", r.RemoteAddr).Str("method", r.Method).Str("path", r.URL.Path).Msg("incoming request")
mr, ok := containerMethodRegex["*"] if mr, ok := containerMethodRegex["*"]; ok {
if ok {
if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK { if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK {
http.Error(w, http.StatusText(code), code) http.Error(w, http.StatusText(code), code)
return return
@ -158,10 +158,18 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ph.rp.ServeHTTP(w, r) ph.rp.ServeHTTP(w, r)
return return
} }
var ( host, _, _ := net.SplitHostPort(r.RemoteAddr)
containerName string for containerName, mr := range containerMethodRegex {
host, _, _ = net.SplitHostPort(r.RemoteAddr) 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 { for containerName, mr = range containerMethodRegex {
resolvedIPs, err := net.LookupIP(containerName) resolvedIPs, err := net.LookupIP(containerName)
if err != nil { if err != nil {
@ -178,9 +186,22 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
} }
*/
logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones") logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) 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) { func logDeniedRequest(r *http.Request, statusCode int, message string) {