zoraxy-waf/middleware.go

55 lines
1.5 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"zoraxy-waf/zoraxy_plugin"
)
var breaker = newCircuitBreaker()
// handleInspect is the static capture ingress handler.
// Zoraxy proxies matching requests here. The plugin decides:
// - Return 280 (CAPTURED) → block the request
// - Return 284 (UNHANDLED) → forward as normal
func handleInspect(w http.ResponseWriter, r *http.Request) {
cfg := getConfig()
if !cfg.Enabled {
// WAF disabled — pass through.
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
return
}
state := breaker.State()
if state == StateOpen {
// Fail-open: Wallarm is down, let traffic through.
log.Printf("WAF: breaker OPEN — fail-open, passing %s %s", r.Method, r.URL.Path)
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
return
}
resp, err := inspect(r)
if err != nil {
log.Printf("WAF: inspection error: %v", err)
breaker.RecordFailure()
// Fail-open on error.
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
return
}
breaker.RecordSuccess()
if resp.Verdict == "block" {
log.Printf("WAF: BLOCKED %s %s — reason: %s", r.Method, r.URL.Path, resp.Reason)
// Return the Zoraxy control code for "captured" (blocked).
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_CAPTURED))
fmt.Fprintf(w, `<html><body><h1>403 Forbidden</h1><p>Request blocked by WAF.</p></body></html>`)
return
}
// Allowed — let Zoraxy forward normally.
w.WriteHeader(int(zoraxy_plugin.ControlStatusCode_UNHANDLED))
}