55 "log/slog"
66 "net"
77 "net/http"
8- "strings"
98)
109
1110// handleHTTPRequest checks if the request is allowed and sends it to the proxy.
@@ -34,7 +33,7 @@ func handleHTTPRequest(w http.ResponseWriter, r *http.Request) {
3433 return
3534 }
3635
37- // finally log and proxy the request
36+ // finally, log and proxy the request
3837 slog .Debug ("allowed request" , "method" , r .Method , "URL" , r .URL , "client" , r .RemoteAddr )
3938 socketProxy .ServeHTTP (w , r ) // proxy the request
4039}
@@ -53,31 +52,35 @@ func isAllowedClient(remoteAddr string) (bool, error) {
5352 return false , errors .New ("invalid IP format" )
5453 }
5554
56- _ , allowedIPNet , err := net .ParseCIDR (cfg .AllowFrom )
57- if err == nil {
58- // AllowFrom is a valid CIDR, so check if IP address is in allowed network
59- return allowedIPNet .Contains (clientIP ), nil
60- }
55+ for _ , allowFromItem := range cfg .AllowFrom {
56+
57+ // first try to handle as an CIDR
58+ _ , allowedIPNet , err := net .ParseCIDR (allowFromItem )
59+ if err == nil {
60+ // AllowFrom is a valid CIDR, so check if IP address is in allowed network
61+ return allowedIPNet .Contains (clientIP ), nil
62+ }
6163
62- // AllowFrom is not a valid CIDR, so try to resolve it via DNS
63- // split over comma to support multiple hostnames
64- allowFromList := strings .Split (cfg .AllowFrom , "," )
65- for _ , allowFrom := range allowFromList {
66- ips , err := net .LookupIP (allowFrom )
64+ // AllowFrom is not a valid CIDR, so try to resolve it via DNS
65+ // We intentionally do not cache the DNS lookups.
66+ // In our use case, the resolver should be a local service, and we don't want to cause DNS caching errors.
67+ ips , err := net .LookupIP (allowFromItem )
6768 if err != nil {
68- slog .Warn ("error looking up allowed client hostname" , "hostname" , allowFrom , "error" , err .Error ())
69+ slog .Warn ("error looking up allowed client hostname" , "hostname" , allowFromItem , "error" , err .Error ())
6970 }
7071 for _ , ip := range ips {
71- // Check if IP address is one of the resolved IPs
72+ // Check if the IP address is one of the resolved IPs
7273 if ip .Equal (clientIP ) {
7374 return true , nil
7475 }
7576 }
7677 }
78+
79+ // If we get here, the IP address is not allowed
7780 return false , nil
7881}
7982
80- // sendHTTPError sends a HTTP error with the given status code.
83+ // sendHTTPError sends an HTTP error with the given status code.
8184func sendHTTPError (w http.ResponseWriter , status int ) {
8285 http .Error (w , http .StatusText (status ), status )
8386}
0 commit comments