Use the RealIP middleware also behind a reverse proxy (#2858)

* Use the RealIP middleware only behind a reverse proxy

* Fix proxy ip source in tests

* Fix test for PR#2087

The PR did not update the test after changing the behavior, but the test still
passed because another condition was preventing the user from being created in
the test.

* Use RealIP even without a trusted reverse proxy

* Use own type for context key

* Fix casing to follow go's conventions

* Do not apply RealIP middleware twice

* Fix IP source in logs

The most interesting data point in the log message is the proxy's IP, but
having the client IP too can help identify integration issues.
This commit is contained in:
crazygolem
2024-04-26 02:43:58 +02:00
committed by GitHub
parent 8f9ed1b994
commit 18143fa5a1
5 changed files with 71 additions and 30 deletions
+29 -6
View File
@@ -1,6 +1,7 @@
package server
import (
"context"
"errors"
"fmt"
"io/fs"
@@ -158,13 +159,35 @@ func clientUniqueIDMiddleware(next http.Handler) http.Handler {
})
}
// realIPMiddleware wraps the middleware.RealIP middleware function, bypassing it if the
// ReverseProxyWhitelist configuration option is set.
func realIPMiddleware(h http.Handler) http.Handler {
if conf.Server.ReverseProxyWhitelist == "" {
return middleware.RealIP(h)
// realIPMiddleware applies middleware.RealIP, and additionally saves the request's original RemoteAddr to the request's
// context if navidrome is behind a trusted reverse proxy.
func realIPMiddleware(next http.Handler) http.Handler {
if conf.Server.ReverseProxyWhitelist != "" {
return chi.Chain(
reqToCtx(request.ReverseProxyIp, func(r *http.Request) any { return r.RemoteAddr }),
middleware.RealIP,
).Handler(next)
}
// The middleware is applied without a trusted reverse proxy to support other use-cases such as multiple clients
// behind a caching proxy. In this case, navidrome only uses the request's RemoteAddr for logging, so the security
// impact of reading the headers from untrusted sources is limited.
return middleware.RealIP(next)
}
// reqToCtx creates a middleware that updates the request's context with a value computed from the request. A given key
// can only be set once.
func reqToCtx(key any, fn func(req *http.Request) any) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Context().Value(key) == nil {
ctx := context.WithValue(r.Context(), key, fn(r))
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
return h
}
// serverAddressMiddleware is a middleware function that modifies the request object