Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NET-10891: Add authorization middleware to sync catalog metrics endpoint #4275

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions control-plane/subcommand/sync-catalog/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/armon/go-metrics/prometheus"
mapset "github.com/deckarep/golang-set"
"github.com/hashicorp/consul-server-connection-manager/discovery"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/go-hclog"
"github.com/mitchellh/cli"
"github.com/prometheus/client_golang/prometheus/promhttp"
Expand Down Expand Up @@ -396,7 +397,7 @@ func (c *Command) Run(args []string) int {
// Start metrics handler
go func() {
mux := http.NewServeMux()
mux.Handle(c.flagMetricsPath, c.authorizeMiddleware()(promhttp.Handler()))
mux.Handle(c.flagMetricsPath, c.authorizeMiddleware(consulConfig)(promhttp.Handler()))
var handler http.Handler = mux

c.UI.Info(fmt.Sprintf("Listening on %q...", c.flagMetricsPort))
Expand Down Expand Up @@ -523,11 +524,37 @@ func (c *Command) recordMetrics() (*prometheus.PrometheusSink, error) {
return sink, nil
}

func (c *Command) validateToken(token string, consulConfig *consul.Config) bool {
if token == "" {
return false
}

// Create a new consul client.
consulClient, err := consul.NewClientFromConnMgr(consulConfig, c.connMgr)
if err != nil {
c.logger.Error("failed to create Consul API client", "error", err)
return false
}

tok, _, err := consulClient.ACL().TokenReadSelf(&api.QueryOptions{Token: token})
if err != nil || tok == nil {
c.logger.Error("failed to validate ACL token", "error", err)
return false
}

return true
}

// authorizeMiddleware validates the token and returns http handler.
func (c *Command) authorizeMiddleware() func(http.Handler) http.Handler {
func (c *Command) authorizeMiddleware(consulConfig *consul.Config) func(http.Handler) http.Handler {

return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TO-DO: Validate the token and proceed to the next handler
token := r.Header.Get("X-Consul-Token")
if !c.validateToken(token, consulConfig) {
http.Error(w, "invalid token", http.StatusInternalServerError)
return
}
next.ServeHTTP(w, r)
})
}
Expand Down
Loading