MCPcopy Create free account
hub / github.com/danielmiessler/Fabric / apiKeyMiddleware

Function apiKeyMiddleware

internal/server/auth.go:125–164  ·  view source on GitHub ↗
(apiKey string, limiter *authFailureLimiter)

Source from the content-addressed store, hash-verified

123}
124
125func apiKeyMiddleware(apiKey string, limiter *authFailureLimiter) gin.HandlerFunc {
126 // Hash the configured key so the comparison avoids leaking its length through timing.
127 expectedKey := sha256.Sum256([]byte(apiKey))
128 return func(c *gin.Context) {
129 // Skip authentication for Swagger documentation endpoints
130 // This allows public access to API docs even when authentication is enabled
131 if strings.HasPrefix(c.Request.URL.Path, "/swagger/") {
132 c.Next()
133 return
134 }
135
136 client := c.ClientIP()
137 if wait := limiter.retryAfter(client); wait > 0 {
138 c.Header("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
139 c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Too many wrong API keys"})
140 return
141 }
142
143 headerApiKey := c.GetHeader(APIKeyHeader)
144
145 if headerApiKey == "" {
146 slog.Warn("API key missing", "client", c.ClientIP(), "path", c.Request.URL.Path)
147 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"})
148 return
149 }
150
151 headerKey := sha256.Sum256([]byte(headerApiKey))
152 if subtle.ConstantTimeCompare(headerKey[:], expectedKey[:]) != 1 {
153 // An operator can find repeated guesses in this log.
154 slog.Warn("API key wrong", "client", client, "path", c.Request.URL.Path)
155 if wait := limiter.fail(client); wait > 0 {
156 slog.Warn("too many wrong API keys: client locked out", "client", client, "for", wait)
157 }
158 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Wrong API Key"})
159 return
160 }
161
162 c.Next()
163 }
164}
165
166// auditChange writes a structured log event after a request that changes a
167// stored object or the configuration. The event has no body and no

Callers 2

limitedRouterFunction · 0.85
APIKeyMiddlewareFunction · 0.85

Calls 2

retryAfterMethod · 0.80
failMethod · 0.80

Tested by 1

limitedRouterFunction · 0.68