Skip to content

Commit

Permalink
protect internal handler (#226)
Browse files Browse the repository at this point in the history
  • Loading branch information
realityone committed Mar 18, 2024
1 parent 55a3e1d commit 9f4b128
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
3 changes: 2 additions & 1 deletion proxy/debug/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path"
"strings"

rmux "github.com/go-kratos/gateway/router/mux"
"github.com/go-kratos/kratos/v2/log"
"github.com/gorilla/mux"
)
Expand Down Expand Up @@ -39,7 +40,7 @@ func Register(name string, debuggable Debuggable) {
func MashupWithDebugHandler(origin http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, _debugPrefix) {
globalService.ServeHTTP(w, req)
rmux.ProtectedHandler(globalService).ServeHTTP(w, req)
return
}
origin.ServeHTTP(w, req)
Expand Down
12 changes: 11 additions & 1 deletion router/mux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,23 @@ type muxRouter struct {
allCloser []io.Closer
}

func ProtectedHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Forwarded-For") != "" {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
})
}

// NewRouter new a mux router.
func NewRouter(notFoundHandler, methodNotAllowedHandler http.Handler) router.Router {
r := &muxRouter{
Router: mux.NewRouter().StrictSlash(EnableStrictSlash),
wg: &sync.WaitGroup{},
}
r.Router.Handle("/metrics", promhttp.Handler())
r.Router.Handle("/metrics", ProtectedHandler(promhttp.Handler()))
r.Router.NotFoundHandler = notFoundHandler
r.Router.MethodNotAllowedHandler = methodNotAllowedHandler
return r
Expand Down

0 comments on commit 9f4b128

Please sign in to comment.