Files
mc-proxy/internal/l7/policy.go
Kyle Isom feeadc582b Migrate module path from kyle/ to mc/ org
All import paths updated to git.wntrmute.dev/mc/. Bumps mcdsl to v1.2.0.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 02:05:59 -07:00

43 lines
1.1 KiB
Go

package l7
import (
"net/http"
"strings"
"git.wntrmute.dev/mc/mc-proxy/internal/metrics"
)
// PolicyRule defines an L7 blocking policy.
type PolicyRule struct {
Type string // "block_user_agent" or "require_header"
Value string
}
// PolicyMiddleware returns an http.Handler that evaluates L7 policies
// before delegating to next. Returns HTTP 403 if any policy blocks.
// If policies is empty, returns next unchanged.
func PolicyMiddleware(policies []PolicyRule, hostname string, next http.Handler) http.Handler {
if len(policies) == 0 {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, p := range policies {
switch p.Type {
case "block_user_agent":
if strings.Contains(r.UserAgent(), p.Value) {
metrics.L7PolicyBlocksTotal.WithLabelValues(hostname, "block_user_agent").Inc()
w.WriteHeader(http.StatusForbidden)
return
}
case "require_header":
if r.Header.Get(p.Value) == "" {
metrics.L7PolicyBlocksTotal.WithLabelValues(hostname, "require_header").Inc()
w.WriteHeader(http.StatusForbidden)
return
}
}
}
next.ServeHTTP(w, r)
})
}