Files
urutau/internal/server/api_enforce.go
T
Lucas RayanandClaude Opus 5.5 8546d14cef
CI / Format and vet (pull_request) Failing after 53s
CI / Dependency audit (pull_request) Successful in 33s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m1s
CI / Docker images (build and smoke test) (pull_request) Failing after 47s
feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
Each server runs an ultralight probe (scratch image, ~7 MiB RSS) that
tails the logs, ships raw lines to the hub over HTTPS with an on-disk
spool, and applies enforce decisions locally. The hub keeps one node per
probe (primary node = the 1.x data dir, unchanged), does all analysis and
serves the UI. Peer federation is removed. 'urutau import' brings 1.x
data dirs in with hash and count verification. UI: probes page, host
qualified incidents, IPs never wrap, egress heatmap labels, live and
replay globes no longer auto-rotate, replay repeat, live traffic metrics.

BREAKING CHANGE: URUTAU_PEERS, URUTAU_PEER_* and /api/v1/peer/* are gone;
log path variables move from the hub to the probe. See docs/migration-2.0.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:14:50 -03:00

130 lines
4.3 KiB
Go

package server
import (
"encoding/json"
"errors"
"net/http"
"net/netip"
"strings"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
)
// enforceEngine is the optional second firewall (nil when --enforce is off).
var enforceEngine atomic.Pointer[enforce.Engine]
// SetEnforce installs the engine the enforce endpoints talk to.
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
func init() {
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
now := s.opt.Now()
from := now.Add(-rg.Dur).Unix()
if rg.From > 0 {
from = rg.From
}
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
"allows": []enforce.Allow{}, "unban_log_writable": false, "coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
if e := s.enforceFor(r.URL.Query().Get("host")); e != nil {
rep := e.Report(from)
share := "off"
if e.Share() {
share = "on"
}
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
if e.HasSink() { // the probe writes the files: queueing is always possible
out["log_writable"], out["unban_log_writable"] = true, true
} else {
out["log_writable"] = enforce.Writable(e.LogPath())
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
}
out["allows"] = e.Allows()
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
}
writeJSON(w, http.StatusOK, out)
}
})
registerUserRoute("POST /api/v1/enforce/unban", func(s *Server) http.HandlerFunc { return s.enforceUnban })
registerUserRoute("DELETE /api/v1/enforce/allow", func(s *Server) http.HandlerFunc { return s.enforceEndAllow })
}
const maxUnbanBody = 1 << 10
func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
var in struct {
IP string `json:"ip"`
AllowS int `json:"allow_s"`
Host string `json:"host"`
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUnbanBody))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil || dec.More() {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
return
}
a, err := netip.ParseAddr(strings.TrimSpace(in.IP))
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow || len(in.Host) > 64 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip, host or allow_s"})
return
}
var engines []*enforce.Engine
if in.Host == "all" {
hosts := []string{s.primaryName()}
if s.opt.Nodes != nil {
hosts = s.opt.Nodes.Hosts()
}
for _, h := range hosts {
if e := s.enforceFor(h); e != nil {
engines = append(engines, e)
}
}
} else if e := s.enforceFor(in.Host); e != nil {
engines = append(engines, e)
}
if len(engines) == 0 {
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
return
}
done := 0
for _, e := range engines {
switch err := e.Unban(a, in.AllowS, "local"); {
case errors.Is(err, enforce.ErrNoUnbanLog):
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
return
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
return
}
done++
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS, "hosts": done})
}
func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
e := s.enforceFor(r.URL.Query().Get("host"))
a, err := netip.ParseAddr(r.URL.Query().Get("ip"))
if e == nil || err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
return
}
if !e.EndAllow(a) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "no allowance for this address"})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}