MCPcopy Create free account
hub / github.com/devaccuracy/ledgerforge / MetricsAuthHandler

Function MetricsAuthHandler

api/middleware/middleware.go:120–154  ·  view source on GitHub ↗

MetricsAuthHandler wraps an http.Handler with bearer token authentication. This is the non-Gin equivalent of MetricsAuth, used for the worker monitoring server which uses a standard http.ServeMux instead of Gin. Same secure mode logic as MetricsAuth: blocks access when secure=true and token is empty

(secure bool, token string, next http.Handler)

Source from the content-addressed store, hash-verified

118// which uses a standard http.ServeMux instead of Gin.
119// Same secure mode logic as MetricsAuth: blocks access when secure=true and token is empty.
120func MetricsAuthHandler(secure bool, token string, next http.Handler) http.Handler {
121 if secure && token == "" {
122 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
123 w.Header().Set("Content-Type", "application/json")
124 w.WriteHeader(http.StatusForbidden)
125 _, _ = w.Write([]byte(`{"error":"Metrics endpoint unavailable: metrics_bearer_token must be configured when secure mode is enabled"}`))
126 })
127 }
128
129 if token == "" {
130 return next
131 }
132
133 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
134 auth := r.Header.Get("Authorization")
135 if auth == "" {
136 http.Error(w, `{"error":"Authorization required for metrics endpoint"}`, http.StatusUnauthorized)
137 return
138 }
139
140 const prefix = "Bearer "
141 if !strings.HasPrefix(auth, prefix) {
142 http.Error(w, `{"error":"Authorization header must use Bearer scheme"}`, http.StatusUnauthorized)
143 return
144 }
145
146 provided := auth[len(prefix):]
147 if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
148 http.Error(w, `{"error":"Invalid bearer token"}`, http.StatusUnauthorized)
149 return
150 }
151
152 next.ServeHTTP(w, r)
153 })
154}
155
156// SecurityHeaders sets security headers to the response.
157// It sets the following headers:

Callers 1

startMonitoringServerFunction · 0.92

Calls 3

SetMethod · 0.65
GetMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected