restic / rest-server

Rest Server is a high performance HTTP server that implements restic's REST backend API.
BSD 2-Clause "Simplified" License
922 stars 138 forks source link

Support X-Forwarded-For in logging when behind a proxy #233

Open systemmonkey42 opened 1 year ago

systemmonkey42 commented 1 year ago

Hi,

By default, the logging in rest-server will always log the IP address of the connection, which in many cases will be the nearest proxy.

Adding support for the X-Forwarded-For headers will allow the logging to display the correct external IP.

Currently 'gorilla/handlers' is used for logging. 'gorilla/handlers' fully supports decoding the X-Forwarded-For headers if you add the proxyHeaders middleware before the logging middleware.

I'm currently using the following patch (against master) to implemented the additional middleware:

diff --git mux.go mux.go
index 77fcdb4..294708e 100644
--- mux.go
+++ mux.go
@@ -21,6 +21,10 @@ func (s *Server) debugHandler(next http.Handler) http.Handler {
        })
 }

+func (s *Server) proxyHandler(next http.Handler) http.Handler {
+   return handlers.ProxyHeaders(next)
+}
+
 func (s *Server) logHandler(next http.Handler) http.Handler {
    var accessLog io.Writer

@@ -104,6 +108,9 @@ func NewHandler(server *Server) (http.Handler, error) {
    if server.Debug {
        handler = server.debugHandler(handler)
    }
+
+   handler = server.proxyHandler(handler)
+
    if server.Log != "" {
        handler = server.logHandler(handler)
    }

As a result, my logs now show the correct external IP, instead of the IP address of my proxy.

Any thoughts?

MichaelEischer commented 1 year ago

Sounds useful. Interpreting the X-Forwarded-For should be opt-in (via a CLI option) as not everyone uses a proxy in front of rest-server.

Are you willing to open a PR for that?