MetricsAuth returns a middleware that controls access to the /metrics endpoint. Behavior based on secure mode and token configuration: - Secure mode OFF, no token: open access (no auth required) - Secure mode OFF, token set: require bearer token - Secure mode ON, token set: require bearer token - S
(secure bool, token string)
| 78 | // This uses the standard Authorization header that Prometheus natively supports via |
| 79 | // its scrape_configs authorization block. |
| 80 | func MetricsAuth(secure bool, token string) gin.HandlerFunc { |
| 81 | return func(c *gin.Context) { |
| 82 | if secure && token == "" { |
| 83 | c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ |
| 84 | "error": "Metrics endpoint unavailable: metrics_bearer_token must be configured when secure mode is enabled", |
| 85 | }) |
| 86 | return |
| 87 | } |
| 88 | |
| 89 | if token == "" { |
| 90 | c.Next() |
| 91 | return |
| 92 | } |
| 93 | |
| 94 | auth := c.GetHeader("Authorization") |
| 95 | if auth == "" { |
| 96 | c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization required for metrics endpoint"}) |
| 97 | return |
| 98 | } |
| 99 | |
| 100 | const prefix = "Bearer " |
| 101 | if !strings.HasPrefix(auth, prefix) { |
| 102 | c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header must use Bearer scheme"}) |
| 103 | return |
| 104 | } |
| 105 | |
| 106 | provided := auth[len(prefix):] |
| 107 | if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 { |
| 108 | c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid bearer token"}) |
| 109 | return |
| 110 | } |
| 111 | |
| 112 | c.Next() |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // MetricsAuthHandler wraps an http.Handler with bearer token authentication. |
| 117 | // This is the non-Gin equivalent of MetricsAuth, used for the worker monitoring server |