rest.CORS refuses "*" together with credentials since go-pkgz/rest#52, so the bump and the option have to land together: the option does not exist in v1.22.0 and the panic fires at construction, inside routes(), which makes it a startup failure rather than a request-time one. The wildcard stays. The comment widget is embedded on arbitrary third-party sites, so the set of origins is not knowable, which is why the escape hatch was asked for upstream instead of accepting the panic. What it costs is unchanged and now written next to the call: any site a signed-in user visits can read authenticated responses, so state-changing requests have to keep being protected by something other than the origin, X-XSRF-Token today. The example module is tidied in the same commit, as it reaches go-pkgz/rest through the replace directive and its indirect graph would otherwise keep the old pin and fail the readonly module check in CI. The bump also carries testify to v1.12.0, which drops go-spew and go-difflib from the module graph.
43 lines
1.4 KiB
Go
43 lines
1.4 KiB
Go
package rest
|
|
|
|
import (
|
|
"expvar"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// Metrics responds to GET /metrics with list of expvar, limited to the given source ips.
|
|
// Called without any ip it rejects every request, as an endpoint nobody can reach is the safe
|
|
// default for one that publishes expvar; use MetricsAllowAll to serve it to everyone on purpose.
|
|
func Metrics(onlyIps ...string) func(http.Handler) http.Handler {
|
|
return metricsHandler(false, onlyIps)
|
|
}
|
|
|
|
// MetricsAllowAll responds to GET /metrics with list of expvar for any source, without any ip check.
|
|
// expvar exposes cmdline, which usually carries the flag values the process was started with, so
|
|
// only use this where something else already keeps the endpoint private.
|
|
func MetricsAllowAll() func(http.Handler) http.Handler {
|
|
return metricsHandler(true, nil)
|
|
}
|
|
|
|
func metricsHandler(allowAll bool, onlyIps []string) func(http.Handler) http.Handler {
|
|
return func(h http.Handler) http.Handler {
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == "GET" && strings.HasSuffix(strings.ToLower(r.URL.Path), "/metrics") {
|
|
if !allowAll {
|
|
if matched, ip, err := matchSourceIP(r, onlyIps); !matched || err != nil {
|
|
_ = EncodeJSON(w, http.StatusForbidden, JSON{"error": fmt.Sprintf("ip %s rejected", ip)})
|
|
return
|
|
}
|
|
}
|
|
expvar.Handler().ServeHTTP(w, r)
|
|
return
|
|
}
|
|
h.ServeHTTP(w, r)
|
|
}
|
|
|
|
return http.HandlerFunc(fn)
|
|
}
|
|
}
|