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>
This commit is contained in:
1 parent
23a7a5963a
commit
8546d14cef
130 files changed
+9396
-3311
No files matched your search
@@ -94,23 +94,3 @@ func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers
|
||||
}
|
||||
return rep, peerOn
|
||||
}
|
||||
|
||||
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
|
||||
// only by the peer token (and --peer-allow). It must be registered next to
|
||||
// the other peer routes.
|
||||
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
eng := egressEngine.Load()
|
||||
if eng == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
|
||||
return
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from, to := rg.Bounds(s.opt.Store.Now().Unix())
|
||||
writeJSON(w, 200, eng.Report(from, to))
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"testing"
|
||||
@@ -70,30 +67,4 @@ func TestEgressAPI(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
|
||||
t.Fatalf("peer token must not open the user route")
|
||||
}
|
||||
|
||||
// peer endpoint (registered by the daemon next to the other peer routes)
|
||||
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
call := func(tok string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
|
||||
r.RemoteAddr = "198.51.100.1:1234"
|
||||
if tok != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
m.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
if w := call(""); w.Code != 401 {
|
||||
t.Fatalf("peer no token: %d", w.Code)
|
||||
}
|
||||
if w := call(userTok); w.Code != 401 {
|
||||
t.Fatalf("user token on peer route: %d", w.Code)
|
||||
}
|
||||
w := call("peer-secret")
|
||||
var rep egress.Report
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
|
||||
t.Fatalf("peer: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
+41
-105
@@ -3,13 +3,10 @@ package server
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
)
|
||||
@@ -20,16 +17,6 @@ var enforceEngine atomic.Pointer[enforce.Engine]
|
||||
// SetEnforce installs the engine the enforce endpoints talk to.
|
||||
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
|
||||
|
||||
// peerRoute is a route opened by the federation token, contributed by its own file.
|
||||
type peerRoute struct {
|
||||
pattern string
|
||||
handler func(*Server) http.HandlerFunc
|
||||
}
|
||||
|
||||
var peerRoutes []peerRoute
|
||||
|
||||
const maxDecisionBody = 64 << 10
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -44,15 +31,19 @@ func init() {
|
||||
}
|
||||
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 := enforceEngine.Load(); e != nil {
|
||||
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()
|
||||
out["log_writable"] = enforce.Writable(e.LogPath())
|
||||
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
|
||||
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
|
||||
}
|
||||
@@ -61,80 +52,6 @@ func init() {
|
||||
})
|
||||
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 })
|
||||
peerRoutes = append(peerRoutes,
|
||||
peerRoute{"POST /api/v1/peer/unban", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Unbans []enforce.UnbanWire `json:"unbans"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDecisionBody)).Decode(&in); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]int{"accepted": e.AcceptPeerUnban(r.URL.Query().Get("from"), in.Unbans)})
|
||||
}
|
||||
}},
|
||||
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
|
||||
since = min
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
|
||||
}
|
||||
}},
|
||||
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
e := enforceEngine.Load()
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
if e == nil || !e.Share() {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
|
||||
if err != nil {
|
||||
var mb *http.MaxBytesError
|
||||
if errors.As(err, &mb) {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
|
||||
} else {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
|
||||
}
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Decisions []enforce.Wire `json:"decisions"`
|
||||
}
|
||||
if json.Unmarshal(body, &in) != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
if len(in.Decisions) > enforce.MaxWire {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
|
||||
return
|
||||
}
|
||||
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
|
||||
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
|
||||
}
|
||||
}},
|
||||
)
|
||||
}
|
||||
|
||||
const maxUnbanBody = 1 << 10
|
||||
@@ -144,14 +61,10 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
e := enforceEngine.Load()
|
||||
if e == nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
|
||||
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()
|
||||
@@ -160,18 +73,41 @@ func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
a, err := netip.ParseAddr(strings.TrimSpace(in.IP))
|
||||
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip or allow_s"})
|
||||
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
|
||||
}
|
||||
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"})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
|
||||
default:
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS})
|
||||
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) {
|
||||
@@ -179,7 +115,7 @@ func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
e := enforceEngine.Load()
|
||||
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"})
|
||||
|
||||
@@ -24,7 +24,7 @@ func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string
|
||||
st.SetIngestHook(e.Observe)
|
||||
SetEnforce(e)
|
||||
t.Cleanup(func() { SetEnforce(nil) })
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
|
||||
return New(Options{Token: userTok, Version: "t", Store: st}), e, log
|
||||
}
|
||||
|
||||
func TestEnforceAPI(t *testing.T) {
|
||||
@@ -66,9 +66,6 @@ func TestEnforceAPI(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
|
||||
t.Fatalf("bad range %d", w.Code)
|
||||
}
|
||||
@@ -96,69 +93,6 @@ func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
|
||||
return w
|
||||
}
|
||||
|
||||
func TestPeerDecisionsEndpoints(t *testing.T) {
|
||||
h, e, log := enforceRig(t, true)
|
||||
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
|
||||
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
|
||||
p := "/api/v1/peer/decisions?from=hostinger"
|
||||
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
|
||||
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("token %q: %d", tok, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
|
||||
t.Fatalf("GET token %q: %d", tok, w.Code)
|
||||
}
|
||||
}
|
||||
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
|
||||
t.Fatalf("big body: %d", w.Code)
|
||||
}
|
||||
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
|
||||
t.Fatalf("bad json: %d", w.Code)
|
||||
}
|
||||
var many strings.Builder
|
||||
many.WriteString(`{"decisions":[`)
|
||||
for i := 0; i < 501; i++ {
|
||||
if i > 0 {
|
||||
many.WriteString(",")
|
||||
}
|
||||
many.WriteString(`{"ip":"1.1.1.1"}`)
|
||||
}
|
||||
many.WriteString(`]}`)
|
||||
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
|
||||
t.Fatalf("501 items: %d", w.Code)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
|
||||
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
w := post(h, p, peerTok, good)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
|
||||
t.Fatalf("log %q", b)
|
||||
}
|
||||
// GET returns local decisions only
|
||||
if len(e.LocalSince(0)) != 0 {
|
||||
t.Fatal("peer decision leaked into the local list")
|
||||
}
|
||||
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
|
||||
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
|
||||
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerDecisionsShareOff(t *testing.T) {
|
||||
h, _, _ := enforceRig(t, false)
|
||||
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
|
||||
t.Fatalf("share off: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnforceFromStoreHook(t *testing.T) {
|
||||
log := filepath.Join(t.TempDir(), "d.log")
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -25,6 +26,10 @@ func init() {
|
||||
registerUserRoute("POST /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentCreate })
|
||||
registerUserRoute("PATCH /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
|
||||
registerUserRoute("POST /api/v1/incidents/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
|
||||
// host/INC-n written as two path segments
|
||||
registerUserRoute("GET /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet })
|
||||
registerUserRoute("PATCH /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
|
||||
registerUserRoute("POST /api/v1/incidents/{host}/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
|
||||
}
|
||||
|
||||
var incidentServer atomic.Pointer[Server]
|
||||
@@ -55,14 +60,31 @@ func StartIncidentSync(ctx context.Context, wg *sync.WaitGroup) {
|
||||
}
|
||||
|
||||
func (s *Server) syncNow(ctx context.Context) {
|
||||
if s.opt.Incidents == nil || egressEngine.Load() == nil {
|
||||
if s.opt.Incidents == nil {
|
||||
return
|
||||
}
|
||||
now := s.opt.Store.Now().Unix()
|
||||
if s.opt.Nodes != nil { // one store per node, fed by that node's own egress
|
||||
for _, h := range s.opt.Nodes.Hosts() {
|
||||
eng, st := s.opt.Nodes.Egress(h), s.opt.Nodes.Incidents(h)
|
||||
if eng == nil || st == nil {
|
||||
continue
|
||||
}
|
||||
rep := eng.Report(now-24*3600, now)
|
||||
for i := range rep.Findings {
|
||||
rep.Findings[i].Host = h
|
||||
}
|
||||
s.syncInto(st, rep)
|
||||
}
|
||||
return
|
||||
}
|
||||
if egressEngine.Load() == nil {
|
||||
return
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "")
|
||||
s.syncIncidents(rep)
|
||||
s.syncInto(s.opt.Incidents, rep)
|
||||
}
|
||||
|
||||
func (s *Server) findingHost(f egress.Finding) string {
|
||||
@@ -76,8 +98,10 @@ func (s *Server) findingKey(f egress.Finding) string {
|
||||
return incidents.Key(s.findingHost(f), f.Kind, f.Workload, f.Dst, f.DPort, f.Proto)
|
||||
}
|
||||
|
||||
func (s *Server) syncIncidents(rep egress.Report) {
|
||||
if s.opt.Incidents == nil {
|
||||
func (s *Server) syncIncidents(rep egress.Report) { s.syncInto(s.opt.Incidents, rep) }
|
||||
|
||||
func (s *Server) syncInto(st *incidents.Store, rep egress.Report) {
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
fs := make([]incidents.Finding, 0, len(rep.Findings))
|
||||
@@ -85,7 +109,7 @@ func (s *Server) syncIncidents(rep egress.Report) {
|
||||
fs = append(fs, incidents.Finding{Host: s.findingHost(f), Kind: f.Kind, Severity: f.Severity, Workload: f.Workload, Dst: f.Dst,
|
||||
Proto: f.Proto, Detail: f.Detail, DPort: f.DPort, First: f.First, Last: f.Last, Count: f.Count})
|
||||
}
|
||||
s.opt.Incidents.Sync(fs)
|
||||
st.Sync(fs)
|
||||
}
|
||||
|
||||
// annotateFindings fills ticket_id/ticket_status/suppressed and, unless show
|
||||
@@ -95,16 +119,35 @@ func (s *Server) annotateFindings(rep *egress.Report, show bool) int {
|
||||
if s.opt.Incidents == nil || len(rep.Findings) == 0 {
|
||||
return 0
|
||||
}
|
||||
keys := make([]string, len(rep.Findings))
|
||||
refs := make([]incidents.Ref, len(rep.Findings))
|
||||
has := make([]bool, len(rep.Findings))
|
||||
byStore := map[string][]int{}
|
||||
for i, f := range rep.Findings {
|
||||
keys[i] = s.findingKey(f)
|
||||
h := s.findingHost(f)
|
||||
byStore[h] = append(byStore[h], i)
|
||||
}
|
||||
for h, idx := range byStore {
|
||||
st := s.incStore(h)
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
keys := make([]string, len(idx))
|
||||
for j, i := range idx {
|
||||
keys[j] = s.findingKey(rep.Findings[i])
|
||||
}
|
||||
m := st.Lookup(keys)
|
||||
for j, i := range idx {
|
||||
if ref, ok := m[keys[j]]; ok {
|
||||
ref.ID = h + "/" + ref.ID
|
||||
refs[i], has[i] = ref, true
|
||||
}
|
||||
}
|
||||
}
|
||||
refs := s.opt.Incidents.Lookup(keys)
|
||||
out := rep.Findings[:0:0]
|
||||
n := 0
|
||||
for i, f := range rep.Findings {
|
||||
if ref, ok := refs[keys[i]]; ok {
|
||||
f.TicketID, f.TicketStatus, f.Suppressed = ref.ID, ref.Status, ref.Suppress
|
||||
if has[i] {
|
||||
f.TicketID, f.TicketStatus, f.Suppressed = refs[i].ID, refs[i].Status, refs[i].Suppress
|
||||
}
|
||||
if f.Suppressed {
|
||||
n++
|
||||
@@ -191,6 +234,54 @@ func (s *Server) incidentQuery(w http.ResponseWriter, r *http.Request) (incident
|
||||
return q, true
|
||||
}
|
||||
|
||||
// qSummary and qTicket carry the id qualified by the node ("hostinger/INC-2")
|
||||
// and the node as host.
|
||||
type qSummary struct {
|
||||
incidents.Summary
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type qTicket struct {
|
||||
incidents.Ticket
|
||||
ID string `json:"id"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
type qPage struct {
|
||||
Items []qSummary `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Store incidents.Stats `json:"store"`
|
||||
Hosts []string `json:"hosts"`
|
||||
}
|
||||
|
||||
// splitID reads "INC-n" with an optional host (path segment, "host/INC-n"
|
||||
// in one segment, or ?host=); without host the primary node is meant.
|
||||
func (s *Server) splitID(r *http.Request) (host, id string) {
|
||||
id = r.PathValue("id")
|
||||
host = r.PathValue("host")
|
||||
if h, rest, ok := strings.Cut(id, "/"); ok {
|
||||
host, id = h, rest
|
||||
}
|
||||
if host == "" {
|
||||
host = r.URL.Query().Get("host")
|
||||
}
|
||||
if host == "" {
|
||||
host = s.primaryName()
|
||||
}
|
||||
return host, id
|
||||
}
|
||||
|
||||
// storeFor answers 404 itself when the node has no ticket store.
|
||||
func (s *Server) storeFor(w http.ResponseWriter, host string) *incidents.Store {
|
||||
if st := s.incStore(host); st != nil {
|
||||
return st
|
||||
}
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
@@ -199,19 +290,93 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.opt.Incidents.List(q))
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
if s.incStore(q.Host) == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
}
|
||||
q.Host = ""
|
||||
if len(hosts) == 1 {
|
||||
pg := s.incStore(hosts[0]).List(q)
|
||||
out := qPage{Items: make([]qSummary, 0, len(pg.Items)), Total: pg.Total, Counts: pg.Counts, Store: pg.Store, Hosts: s.incHosts()}
|
||||
for _, it := range pg.Items {
|
||||
out.Items = append(out.Items, qSummary{Summary: it, ID: hosts[0] + "/" + it.ID, Host: hosts[0]})
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
return
|
||||
}
|
||||
// several nodes: merge, sort and page here
|
||||
all := []qSummary{}
|
||||
out := qPage{Counts: map[string]int{}, Hosts: s.incHosts()}
|
||||
page, per := q.Page, q.PerPage
|
||||
for _, h := range hosts {
|
||||
st := s.incStore(h)
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
pg := st.List(incidents.Query{Status: q.Status, Severity: q.Severity, Q: q.Q, Sort: q.Sort, Page: 1, PerPage: 1})
|
||||
for k, v := range pg.Counts {
|
||||
out.Counts[k] += v
|
||||
}
|
||||
out.Store.Size += pg.Store.Size
|
||||
out.Store.Max += pg.Store.Max
|
||||
out.Store.Untracked += pg.Store.Untracked
|
||||
for _, it := range st.All(q) {
|
||||
all = append(all, qSummary{Summary: it, ID: h + "/" + it.ID, Host: h})
|
||||
}
|
||||
}
|
||||
sortSummaries(all, q.Sort)
|
||||
if per <= 0 {
|
||||
per = 50
|
||||
}
|
||||
per = min(per, 200)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
lo := min((page-1)*per, len(all))
|
||||
hi := min(lo+per, len(all))
|
||||
out.Total, out.Items = len(all), all[lo:hi]
|
||||
if out.Items == nil {
|
||||
out.Items = []qSummary{}
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
func sortSummaries(l []qSummary, mode string) {
|
||||
sort.SliceStable(l, func(i, j int) bool {
|
||||
a, b := l[i], l[j]
|
||||
switch mode {
|
||||
case "severity":
|
||||
if ra, rb := incidents.SevRank(a.Severity), incidents.SevRank(b.Severity); ra != rb {
|
||||
return ra > rb
|
||||
}
|
||||
case "last_seen":
|
||||
if a.LastSeen != b.LastSeen {
|
||||
return a.LastSeen > b.LastSeen
|
||||
}
|
||||
}
|
||||
return a.UpdatedAt > b.UpdatedAt
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.Get(r.PathValue("id"))
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.Get(id)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -223,12 +388,16 @@ func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
in.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Create(in)
|
||||
host := s.primaryName()
|
||||
if in.Host != "" && s.incStore(in.Host) != nil {
|
||||
host = in.Host
|
||||
}
|
||||
t, err := s.incStore(host).Create(in)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -240,12 +409,17 @@ func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Update(r.PathValue("id"), p)
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.Update(id, p)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -259,12 +433,17 @@ func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
|
||||
if !incidentBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.AddComment(r.PathValue("id"), in.Text, in.Author, s.via(r))
|
||||
host, id := s.splitID(r)
|
||||
st := s.storeFor(w, host)
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
t, err := st.AddComment(id, in.Text, in.Author, s.via(r))
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host})
|
||||
}
|
||||
|
||||
// csvCell neutralises spreadsheet formulas.
|
||||
@@ -301,7 +480,20 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
|
||||
for _, t := range s.opt.Incidents.All(q) {
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
}
|
||||
q.Host = ""
|
||||
var rows []qSummary
|
||||
for _, h := range hosts {
|
||||
if st := s.incStore(h); st != nil {
|
||||
for _, t := range st.All(q) {
|
||||
rows = append(rows, qSummary{Summary: t, ID: h + "/" + t.ID, Host: h})
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, t := range rows {
|
||||
row := []string{t.ID, t.Status, t.Severity, t.Host, t.Kind, t.Workload, t.Dst, strconv.Itoa(int(t.DPort)), t.Proto, t.Title,
|
||||
strconv.FormatInt(t.FirstSeen, 10), strconv.FormatInt(t.LastSeen, 10), strconv.Itoa(t.Count), t.Assignee, strings.Join(t.Tags, ","), t.Verdict,
|
||||
strconv.FormatBool(t.Suppress), strconv.FormatInt(t.CreatedAt, 10), strconv.FormatInt(t.UpdatedAt, 10)}
|
||||
|
||||
@@ -23,7 +23,7 @@ func incRig(t *testing.T) http.Handler {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st, Incidents: inc})
|
||||
return New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc})
|
||||
}
|
||||
|
||||
func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
@@ -50,11 +50,11 @@ func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
f = m
|
||||
}
|
||||
}
|
||||
if f == nil || f["ticket_id"] != "INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
if f == nil || f["ticket_id"] != "oracle/INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
t.Fatalf("annotated: %v", d)
|
||||
}
|
||||
// suppression needs false_positive/benign
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"oracle/INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
t.Fatalf("list: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"suppress":true}`, auth); w.Code != 409 {
|
||||
@@ -99,9 +99,6 @@ func TestIncidentsAPI(t *testing.T) {
|
||||
if w := req(h, p[0], p[1], `{}`, nil); w.Code != 401 {
|
||||
t.Errorf("%v no auth: %d", p, w.Code)
|
||||
}
|
||||
if w := req(h, p[0], p[1], `{}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Errorf("%v peer token: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
for _, p := range paths[2:5] {
|
||||
@@ -115,7 +112,7 @@ func TestIncidentsAPI(t *testing.T) {
|
||||
}
|
||||
var tk map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &tk)
|
||||
if tk["id"] != "INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
if tk["id"] != "oracle/INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
t.Fatalf("ticket: %v", tk)
|
||||
}
|
||||
bad := []struct{ m, p, b string }{
|
||||
|
||||
@@ -22,7 +22,7 @@ func unbanRig(t *testing.T) (http.Handler, *enforce.Engine, string) {
|
||||
Host: "oracle", Threshold: 3, Share: true})
|
||||
SetEnforce(e)
|
||||
t.Cleanup(func() { SetEnforce(nil) })
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
|
||||
return New(Options{Token: userTok, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
|
||||
}
|
||||
|
||||
func req(h http.Handler, method, path, body string, hdr map[string]string) *httptest.ResponseRecorder {
|
||||
@@ -42,9 +42,6 @@ func TestUnbanRoute(t *testing.T) {
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7","allow_s":60}`, nil); w.Code != 401 {
|
||||
t.Fatalf("no auth: %d", w.Code)
|
||||
}
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Fatalf("peer token: %d", w.Code)
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, cross); w.Code != 403 {
|
||||
t.Fatalf("cross-site: %d", w.Code)
|
||||
@@ -96,24 +93,3 @@ func TestUnbanRoute(t *testing.T) {
|
||||
t.Fatal("DELETE wrote to the host file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerUnbanRoute(t *testing.T) {
|
||||
h, e, file := unbanRig(t)
|
||||
peer := map[string]string{"Authorization": "Bearer " + peerTok}
|
||||
if w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, map[string]string{"Authorization": "Bearer " + userTok}); w.Code == 200 {
|
||||
t.Fatalf("user token accepted on peer route")
|
||||
}
|
||||
w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, peer)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if len(e.Allows()) != 1 {
|
||||
t.Fatal("peer allow not applied")
|
||||
}
|
||||
if b, _ := os.ReadFile(file); !strings.Contains(string(b), "ip=203.0.113.7 allow=3600") {
|
||||
t.Fatalf("file: %q", b)
|
||||
}
|
||||
if len(e.UnbansSince(0)) != 0 {
|
||||
t.Fatal("peer unban must not be echoed back")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// fakeBackend is an in-process node serving a fixed export.
|
||||
type fakeBackend struct {
|
||||
name string
|
||||
exp store.PeerExport
|
||||
}
|
||||
|
||||
func (f fakeBackend) Name() string { return f.name }
|
||||
func (f fakeBackend) Export(store.Range) store.PeerExport { return f.exp }
|
||||
func (f fakeBackend) Study(q store.PeriodQuery) store.PeerStudy {
|
||||
return store.PeerStudy{}
|
||||
}
|
||||
func (f fakeBackend) Egress(from, to int64) json.RawMessage { return nil }
|
||||
func (f fakeBackend) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
return make(chan store.LiveEvent), func() {}
|
||||
}
|
||||
func (f fakeBackend) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
return make(chan store.VisitMsg), func() {}
|
||||
}
|
||||
func (f fakeBackend) Online() bool { return true }
|
||||
func (f fakeBackend) Location() *store.Location { return nil }
|
||||
@@ -1,15 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -50,12 +47,9 @@ func TestBlocklistRevalidatesPeerRowsAndAdmins(t *testing.T) {
|
||||
{IP: "2606:4700:0:7::/64", Score: 80, Strong: true},
|
||||
{IP: "5.6.7.8", Score: 99, Strong: false},
|
||||
}
|
||||
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(exp) }))
|
||||
defer peer.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "p", URL: peer.URL}}, ptok)
|
||||
hub.Refresh(context.Background())
|
||||
hub := fed.NewHub(func() []fed.Backend { return []fed.Backend{fakeBackend{name: "p", exp: exp}} })
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")})
|
||||
h := New(Options{Token: utok, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")})
|
||||
code, body := bearerGet(h, "/api/v1/blocklist.txt")
|
||||
if code != 200 {
|
||||
t.Fatal(code)
|
||||
@@ -185,59 +179,3 @@ func TestClientIPVectors(t *testing.T) {
|
||||
t.Fatal("a peer outside the trusted list is the client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHubAndStoreUnderLoad(t *testing.T) {
|
||||
pst := store.New(store.Config{Name: "peer", Version: "t"})
|
||||
ph := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: pst})
|
||||
ps := httptest.NewServer(ph)
|
||||
defer ps.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "peer", URL: ps.URL}}, ptok)
|
||||
hub.Interval = 20 * time.Millisecond
|
||||
st := store.New(store.Config{Name: "me", Version: "t", MaxIPs: 3000})
|
||||
srv := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub}))
|
||||
defer srv.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go hub.Run(ctx)
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
now := time.Now()
|
||||
for _, s := range []*store.Store{st, pst} {
|
||||
wg.Add(1)
|
||||
go func(s *store.Store) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.Ingest(core.Event{Time: now, IP: fmt.Sprintf("9.%d.%d.%d", i>>16&255, i>>8&255, i&255), Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET", Domain: "d"})
|
||||
s.Traffic(core.Event{Time: now, IP: "3.3.3.3", Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200})
|
||||
}
|
||||
}(s)
|
||||
}
|
||||
paths := []string{"/api/v1/summary", "/api/v1/summary?host=peer", "/api/v1/ips?per=200&sort=events", "/api/v1/traffic?domain=d", "/api/v1/blocklist.json", "/api/v1/ip/9.0.0.1"}
|
||||
for g := 0; g < 6; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
req, _ := http.NewRequest("GET", srv.URL+paths[(g+i)%len(paths)], nil)
|
||||
req.Header.Set("Authorization", "Bearer "+utok)
|
||||
if r, err := http.DefaultClient.Do(req); err == nil {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -332,33 +332,6 @@ func (s *Server) metricsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// peerPeriod: GET /api/v1/peer/period, the study a hub merges; opened only by
|
||||
// the peer token (and --peer-allow). At most two run at once.
|
||||
func (s *Server) peerPeriod(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case s.study <- struct{}{}:
|
||||
defer func() { <-s.study }()
|
||||
default:
|
||||
w.Header().Set("Retry-After", "5")
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
|
||||
return
|
||||
}
|
||||
eq, ok := s.eventFilter(w, r, 24*time.Hour)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
pq := store.PeriodQuery{From: eq.From, To: eq.To, Host: s.opt.Store.Name(), IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
|
||||
if v := r.URL.Query().Get("gap"); v != "" {
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 30 && n <= 86400 {
|
||||
pq.Gap = n
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, s.opt.Store.StudyFor(pq))
|
||||
}
|
||||
|
||||
// listed reproduces the blocklist rule for one row.
|
||||
func (s *Server) listed(x store.IPSummary) bool {
|
||||
if x.Score < 50 || !x.Strong || x.Admin {
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
@@ -49,7 +44,7 @@ func geoSetup(t *testing.T) (http.Handler, map[string]string) {
|
||||
ing("200.3.3.3", core.BruteForce, 1, false)
|
||||
ing("9.9.9.9", core.SSHFail, 3, false)
|
||||
ing("8.8.8.8", core.Exploit, 1, false) // unknown geo: skipped
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st})
|
||||
h := New(Options{Token: utok, Version: "t", Store: st})
|
||||
return h, map[string]string{"Authorization": "Bearer " + utok}
|
||||
}
|
||||
|
||||
@@ -124,9 +119,6 @@ func TestGeoAggregation(t *testing.T) {
|
||||
if w := do(h, "GET", "/api/v1/geo?host=nope", cloneHdr(u), nil); w.Code != 404 {
|
||||
t.Fatalf("unknown host: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/geo", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
@@ -179,127 +171,3 @@ func TestStaticAssetsWhitelist(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStreamIsPeerOnly(t *testing.T) {
|
||||
old := sseHeartbeat
|
||||
sseHeartbeat = 50 * time.Millisecond
|
||||
defer func() { sseHeartbeat = old }()
|
||||
h, _ := geoSetup(t)
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + utok}, nil); w.Code != 401 {
|
||||
t.Fatalf("user token: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/stream", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("anonymous: %d", w.Code)
|
||||
}
|
||||
for _, p := range []string{"/api/v1/events/stream"} {
|
||||
if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("peer token on %s: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
h2 := New(Options{Token: utok, PeerAllow: mustPrefixes("203.0.113.0/24"), PeerTokens: []string{ptok}, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h2, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 403 {
|
||||
t.Fatalf("--peer-allow: %d", w.Code)
|
||||
}
|
||||
h3 := New(Options{Token: utok, Version: "t", Store: store.New(store.Config{Name: "x"})})
|
||||
if w := do(h3, "GET", "/api/v1/peer/stream", map[string]string{"Authorization": "Bearer " + ptok}, nil); w.Code != 404 {
|
||||
t.Fatalf("federation off: %d", w.Code)
|
||||
}
|
||||
|
||||
st := store.New(store.Config{Name: "edge", Version: "t", Location: &store.Location{Lat: 3, Lon: 4, Label: "Edge"}})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
|
||||
defer ts.Close()
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+ptok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatal(err, resp)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik"}) // not malicious, not sent
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp"})
|
||||
}()
|
||||
sc := bufio.NewScanner(resp.Body)
|
||||
deadline := time.After(5 * time.Second)
|
||||
got := make(chan string, 1)
|
||||
go func() {
|
||||
for sc.Scan() {
|
||||
if strings.HasPrefix(sc.Text(), "data: ") {
|
||||
got <- sc.Text()[6:]
|
||||
return
|
||||
}
|
||||
}
|
||||
got <- ""
|
||||
}()
|
||||
select {
|
||||
case d := <-got:
|
||||
var e map[string]any
|
||||
if json.Unmarshal([]byte(d), &e) != nil || e["ip"] != "200.1.1.9" || e["cat"] != "scanner" || e["dst"].(map[string]any)["label"] != "Edge" || e["src"].(map[string]any)["cc"] != "BR" {
|
||||
t.Fatalf("peer event %s", d)
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatal("no event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
|
||||
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
strongHits := func(st *store.Store, ip string) {
|
||||
for i := 0; i < 8; i++ {
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
}
|
||||
}
|
||||
remote := store.New(store.Config{Name: "remote"})
|
||||
strongHits(remote, "45.94.31.7") // only the peer saw it
|
||||
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
|
||||
defer rs.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + rs.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, ptk)
|
||||
hub.Refresh(context.Background())
|
||||
for _, off := range []bool{false, true} {
|
||||
st := store.New(store.Config{Name: "o"})
|
||||
strongHits(st, "45.94.31.5")
|
||||
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
|
||||
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
|
||||
b := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
|
||||
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
|
||||
}
|
||||
if has := strings.Contains(b, "45.94.31.7"); has == off {
|
||||
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStreamVisitsOnlyOnRequestAndNoIP(t *testing.T) {
|
||||
const ptok = "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
for _, q := range []string{"", "?visits=1"} {
|
||||
st := store.New(store.Config{Name: "edge", Version: "t"})
|
||||
st.SetEnricher(fakeGeo{})
|
||||
ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st}))
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream"+q, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+ptok)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
t.Fatal(err, resp)
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
st.Traffic(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, UA: "Mozilla/5.0 x",
|
||||
E: core.Enrich{Device: "desktop"}})
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
resp.Body.Close()
|
||||
}()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
got := strings.Contains(string(body), "event: visit")
|
||||
if got != (q != "") {
|
||||
t.Fatalf("query %q: visit event present=%v\n%s", q, got, body)
|
||||
}
|
||||
if strings.Contains(string(body), "200.1.1.9") || strings.Contains(string(body), `"ip"`) || strings.Contains(string(body), "Mozilla") {
|
||||
t.Fatalf("address in stream: %s", body)
|
||||
}
|
||||
ts.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
||||
)
|
||||
|
||||
// ProbeAPI is the hub side of the probe protocol and of probe management
|
||||
// (implemented by *hub.Manager).
|
||||
type ProbeAPI interface {
|
||||
Authenticate(r *http.Request) (string, bool)
|
||||
Hello(w http.ResponseWriter, r *http.Request, name string)
|
||||
Push(w http.ResponseWriter, r *http.Request, name string)
|
||||
Commands(w http.ResponseWriter, r *http.Request, name string)
|
||||
List() []hub.ProbeInfo
|
||||
Info(name string) (hub.ProbeInfo, bool)
|
||||
Create(name string) (string, error)
|
||||
Revoke(name string) error
|
||||
UpdateProbe(name string, u hub.Update) error
|
||||
}
|
||||
|
||||
// NodeSet gives access to the per-probe engines and ticket stores. Hosts lists
|
||||
// every node, the primary first.
|
||||
type NodeSet interface {
|
||||
Hosts() []string
|
||||
Enforce(host string) *enforce.Engine
|
||||
Egress(host string) *egress.Engine
|
||||
Incidents(host string) *incidents.Store
|
||||
}
|
||||
|
||||
// probeIngest wraps an ingest handler with the probe token check and the same
|
||||
// attempt limiter as the user API. Errors carry no detail.
|
||||
func (s *Server) probeIngest(h func(w http.ResponseWriter, r *http.Request, name string)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
if wait := s.lim.blocked(ip); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"})
|
||||
return
|
||||
}
|
||||
name, ok := s.opt.Probes.Authenticate(r)
|
||||
if !ok {
|
||||
s.lim.failure(ip)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
h(w, r, name)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) probeRoutes(m *http.ServeMux) {
|
||||
if s.opt.Probes == nil {
|
||||
return
|
||||
}
|
||||
p := s.opt.Probes
|
||||
m.HandleFunc("POST "+wire.PathHello, s.probeIngest(p.Hello))
|
||||
m.HandleFunc("POST "+wire.PathPush, s.probeIngest(p.Push))
|
||||
m.HandleFunc("GET "+wire.PathCommands, s.probeIngest(p.Commands))
|
||||
m.HandleFunc("GET /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"probes": p.List()})
|
||||
}))
|
||||
m.HandleFunc("POST /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if !s.adminBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
tok, err := p.Create(in.Name)
|
||||
switch {
|
||||
case errors.Is(err, hub.ErrName):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
case errors.Is(err, hub.ErrExists):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
|
||||
default:
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"name": in.Name, "token": tok})
|
||||
}
|
||||
}))
|
||||
m.HandleFunc("DELETE /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return
|
||||
}
|
||||
switch err := p.Revoke(r.PathValue("name")); {
|
||||
case errors.Is(err, hub.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
|
||||
default:
|
||||
writeJSON(w, 200, map[string]bool{"ok": true})
|
||||
}
|
||||
}))
|
||||
m.HandleFunc("PUT /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in hub.Update
|
||||
if !s.adminBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
switch err := p.UpdateProbe(name, in); {
|
||||
case errors.Is(err, hub.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
default:
|
||||
info, _ := p.Info(name)
|
||||
writeJSON(w, 200, info)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func (s *Server) adminBody(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if !sameOrigin(r) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return false
|
||||
}
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil || dec.More() {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---- per-host lookups (fall back to the package level engines, i.e. the primary) ----
|
||||
|
||||
func (s *Server) primaryName() string { return s.opt.Store.Name() }
|
||||
|
||||
// enforceFor returns the engine of a host ("" or the primary: the primary's).
|
||||
func (s *Server) enforceFor(host string) *enforce.Engine {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return enforceEngine.Load()
|
||||
}
|
||||
return s.opt.Nodes.Enforce(host)
|
||||
}
|
||||
|
||||
func (s *Server) incStore(host string) *incidents.Store {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return s.opt.Incidents
|
||||
}
|
||||
return s.opt.Nodes.Incidents(host)
|
||||
}
|
||||
|
||||
// incHosts lists the hosts that have a ticket store, the primary first.
|
||||
func (s *Server) incHosts() []string {
|
||||
if s.opt.Nodes == nil {
|
||||
if s.opt.Incidents != nil {
|
||||
return []string{s.primaryName()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return s.opt.Nodes.Hosts()
|
||||
}
|
||||
+7
-157
@@ -15,7 +15,6 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -31,9 +30,6 @@ var webFS embed.FS
|
||||
// maxSSE bounds the simultaneous live streams.
|
||||
const maxSSE = 20
|
||||
|
||||
// maxPeerSSE bounds the simultaneous hub subscriptions to /api/v1/peer/stream.
|
||||
const maxPeerSSE = 10
|
||||
|
||||
// sseHeartbeat is how often a live stream pings and revalidates its session.
|
||||
var sseHeartbeat = 20 * time.Second
|
||||
|
||||
@@ -51,16 +47,12 @@ func HTTPServer(h http.Handler, base context.Context) *http.Server {
|
||||
// Options configure the handler.
|
||||
type Options struct {
|
||||
Token string
|
||||
// PeerTokens are the federation tokens accepted by /api/v1/peer/export.
|
||||
PeerTokens []string
|
||||
// Ignore lists networks that must never appear in the blocklist (ignore + trusted).
|
||||
Ignore []netip.Prefix
|
||||
// AllowHosts: with NoAuth, only requests whose Host is one of these are served
|
||||
// (anti DNS rebinding).
|
||||
AllowHosts []string
|
||||
// PeerAllow, when not empty, restricts /api/v1/peer/export to these source
|
||||
// networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
PeerAllow []netip.Prefix
|
||||
// TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
TrustedProxy []netip.Prefix
|
||||
NoAuth bool
|
||||
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
|
||||
@@ -68,6 +60,10 @@ type Options struct {
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
// Probes serves the probe ingest and the admin routes (nil: not a hub).
|
||||
Probes ProbeAPI
|
||||
// Nodes gives per-host access to the engines and tickets of every probe.
|
||||
Nodes NodeSet
|
||||
// Incidents is the ticket store (nil: incident management off).
|
||||
Incidents *incidents.Store
|
||||
Now func() time.Time
|
||||
@@ -76,14 +72,12 @@ type Options struct {
|
||||
// Server is the HTTP handler.
|
||||
type Server struct {
|
||||
sse atomic.Int32
|
||||
exp exportCache
|
||||
opt Options
|
||||
ses *sessions
|
||||
lim *limiter
|
||||
mux *http.ServeMux
|
||||
assets fs.FS
|
||||
geo geoCache
|
||||
psse atomic.Int32
|
||||
study chan struct{}
|
||||
user chan struct{} // user-side studies (period, metrics) running at once
|
||||
}
|
||||
@@ -102,10 +96,6 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("POST /logout", s.logout)
|
||||
m.HandleFunc("GET /{$}", s.index)
|
||||
m.HandleFunc("GET /{file}", s.asset)
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
|
||||
m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod)
|
||||
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
|
||||
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
|
||||
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
@@ -123,9 +113,7 @@ func New(opt Options) http.Handler {
|
||||
for _, r := range userRoutes {
|
||||
m.HandleFunc(r.pattern, s.api(r.handler(s)))
|
||||
}
|
||||
for _, r := range peerRoutes { // peer-token routes of api_<name>.go files
|
||||
m.HandleFunc(r.pattern, r.handler(s))
|
||||
}
|
||||
s.probeRoutes(m)
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
@@ -168,7 +156,7 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// authKind returns "session" or "bearer" for a valid user credential (cookie or
|
||||
// URUTAU_TOKEN), "peer" for the federation token, "" otherwise.
|
||||
// URUTAU_TOKEN), "" otherwise.
|
||||
func (s *Server) authKind(r *http.Request) string {
|
||||
if s.opt.NoAuth {
|
||||
return "session"
|
||||
@@ -178,9 +166,6 @@ func (s *Server) authKind(r *http.Request) string {
|
||||
if tokenEqual(tok, s.opt.Token) {
|
||||
return "bearer"
|
||||
}
|
||||
if s.peerTokenOK(tok) {
|
||||
return "peer"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) {
|
||||
@@ -189,25 +174,12 @@ func (s *Server) authKind(r *http.Request) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) peerTokenOK(tok string) bool {
|
||||
ok := false
|
||||
for _, t := range s.opt.PeerTokens { // no early exit: constant work per token
|
||||
if tokenEqual(tok, t) {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer
|
||||
// token is refused with 403 (it is a valid credential, for another route).
|
||||
func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
switch s.authKind(r) {
|
||||
case "session", "bearer":
|
||||
case "peer":
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"})
|
||||
return
|
||||
default:
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
wait := s.lim.blocked(ip)
|
||||
@@ -246,37 +218,6 @@ func (s *Server) slowFail(ip string, d time.Duration) {
|
||||
}
|
||||
}
|
||||
|
||||
type exportCache struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
v map[string][]byte
|
||||
}
|
||||
|
||||
// peerGate admits only the federation token (and --peer-allow sources); it
|
||||
// answers the request itself and returns false when it refuses.
|
||||
func (s *Server) peerGate(w http.ResponseWriter, r *http.Request) bool {
|
||||
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
|
||||
return false
|
||||
}
|
||||
if len(s.opt.PeerAllow) > 0 {
|
||||
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
|
||||
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
s.lim.failure(clientIP(r, s.opt.TrustedProxy))
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// rangeOf resolves the range parameters of a request (range, from, to); it
|
||||
// answers 400 itself and returns false on garbage.
|
||||
func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, bool) {
|
||||
@@ -289,31 +230,6 @@ func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, b
|
||||
return rg, true
|
||||
}
|
||||
|
||||
// peerExport: GET /api/v1/peer/export, opened by the peer token.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
rg, ok := s.rangeOf(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
key := rg.Key()
|
||||
s.exp.mu.Lock()
|
||||
if s.exp.v == nil || len(s.exp.v) >= 24 {
|
||||
s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{}
|
||||
}
|
||||
b, ok := s.exp.v[key]
|
||||
if !ok || time.Since(s.exp.at[key]) > 5*time.Second {
|
||||
b, _ = json.Marshal(s.opt.Store.ExportFor(rg))
|
||||
s.exp.v[key], s.exp.at[key] = b, time.Now()
|
||||
}
|
||||
s.exp.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range ps {
|
||||
@@ -691,72 +607,6 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// peerStream: GET /api/v1/peer/stream, SSE of this instance's own malicious
|
||||
// events for a hub. Opened only by the peer token, like the export.
|
||||
func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.peerGate(w, r) {
|
||||
return
|
||||
}
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", 500)
|
||||
return
|
||||
}
|
||||
if s.psse.Add(1) > maxPeerSSE {
|
||||
s.psse.Add(-1)
|
||||
w.Header().Set("Retry-After", "10")
|
||||
http.Error(w, "too many peer streams", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer s.psse.Add(-1)
|
||||
_ = http.NewResponseController(w).SetWriteDeadline(time.Time{})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
var visCh <-chan store.VisitMsg // only with ?visits=1; carries no address
|
||||
if r.URL.Query().Get("visits") == "1" {
|
||||
c, stopV := s.opt.Store.SubscribeVisits()
|
||||
defer stopV()
|
||||
visCh = c
|
||||
}
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case v := <-visCh:
|
||||
b, _ := json.Marshal(v)
|
||||
if _, err := fmt.Fprintf(w, "event: visit\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case <-tick.C:
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
return
|
||||
}
|
||||
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if !core.Category(e.Cat).IsMalicious() {
|
||||
continue
|
||||
}
|
||||
b, _ := json.Marshal(s.opt.Store.Live(e))
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// liveRecent: GET /api/v1/live/recent?limit=200 (max 500), newest first, local and peers.
|
||||
func (s *Server) liveRecent(w http.ResponseWriter, r *http.Request) {
|
||||
n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
func setup(t *testing.T) (http.Handler, *store.Store) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/<img src=x onerror=alert(1)>"})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st})
|
||||
return h, st
|
||||
}
|
||||
|
||||
@@ -240,7 +240,7 @@ func mustPrefixes(l string) []netip.Prefix {
|
||||
func federated(t *testing.T, mod func(*Options)) http.Handler {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
o := Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st,
|
||||
o := Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st,
|
||||
TrustedProxy: mustPrefixes("172.16.0.0/12")}
|
||||
if mod != nil {
|
||||
mod(&o)
|
||||
@@ -248,66 +248,6 @@ func federated(t *testing.T, mod func(*Options)) http.Handler {
|
||||
return New(o)
|
||||
}
|
||||
|
||||
func TestPeerTokenOnlyOpensExport(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json", "/api/v1/geo", "/api/v1/live/recent"} {
|
||||
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
|
||||
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", p, nil, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("no credential on %s: %d (want 401)", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("export without credential: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", user, nil); w.Code != 401 {
|
||||
t.Fatalf("the user token must not open the export: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/v1/peer/export?range=7d", peer, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"v":1`) || !strings.Contains(w.Body.String(), "45.94.31.4") || !strings.Contains(w.Body.String(), `"traffic"`) {
|
||||
t.Fatalf("export %d %.200s", w.Code, w.Body)
|
||||
}
|
||||
// without a peer token configured the route does not exist
|
||||
h2 := federated(t, func(o *Options) { o.PeerTokens = nil })
|
||||
if w := do(h2, "GET", "/api/v1/peer/export", peer, nil); w.Code != 404 {
|
||||
t.Fatalf("federation disabled: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAllowAndRealClientIP(t *testing.T) {
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
h := federated(t, func(o *Options) { o.PeerAllow = mustPrefixes("203.0.113.0/24") })
|
||||
with := func(remote, xff string) *httptest.ResponseRecorder {
|
||||
hd := map[string]string{"Authorization": peer["Authorization"], "X-Remote": remote}
|
||||
if xff != "" {
|
||||
hd["X-Forwarded-For"] = xff
|
||||
}
|
||||
return do(h, "GET", "/api/v1/peer/export", hd, nil)
|
||||
}
|
||||
if w := with("198.51.100.9:1", ""); w.Code != 403 {
|
||||
t.Fatalf("outside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("203.0.113.8:1", ""); w.Code != 200 {
|
||||
t.Fatalf("inside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("198.51.100.9:1", "203.0.113.8"); w.Code != 403 {
|
||||
t.Fatalf("forged XFF from an untrusted source must not pass: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8"); w.Code != 200 {
|
||||
t.Fatalf("XFF from the trusted proxy is the real client: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("real client outside the list behind the proxy: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8, 198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("the proxy appended the real client on the right: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRateLimitUsesRealClientBehindProxy(t *testing.T) {
|
||||
loginBlockedDelay = 0
|
||||
h := federated(t, nil)
|
||||
|
||||
@@ -33,7 +33,7 @@ func setupLog(t *testing.T) (http.Handler, *store.Store, map[string]string) {
|
||||
}
|
||||
st.Ingest(core.Event{Time: now.Add(-3 * time.Hour), IP: "45.94.31.9", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/wp-login.php", Status: 404})
|
||||
st.Ingest(core.Event{Time: now.Add(-time.Minute), IP: "45.94.31.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
|
||||
h := New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "test", Store: st})
|
||||
h := New(Options{Token: userTok, Version: "test", Store: st})
|
||||
return h, st, map[string]string{"Authorization": "Bearer " + userTok}
|
||||
}
|
||||
|
||||
@@ -131,11 +131,7 @@ func TestEventsAPI(t *testing.T) {
|
||||
t.Fatal("gap")
|
||||
}
|
||||
// the peer token opens none of the new routes
|
||||
peer := map[string]string{"Authorization": "Bearer " + peerTok}
|
||||
for _, p := range []string{"events", "events/sessions", "period", "period/events", "metrics", "ip/45.94.31.4", "ip/45.94.31.4/stix"} {
|
||||
if w := do(h, "GET", "/api/v1/"+p, cloneHdr(peer), nil); w.Code != 403 {
|
||||
t.Errorf("%s with the peer token: %d", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/"+p, nil, nil); w.Code != 401 {
|
||||
t.Errorf("%s without auth: %d", p, w.Code)
|
||||
}
|
||||
|
||||
+77
-12
@@ -997,13 +997,13 @@
|
||||
return fetch(path, o).then(function (r) {
|
||||
if (r.status === 401) { location.href = '/login'; throw mkErr('unauthorized', 401); }
|
||||
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
|
||||
return r.json();
|
||||
return r.text().then(function (txt) { try { return txt ? JSON.parse(txt) : {}; } catch (e) { return {}; } });
|
||||
});
|
||||
}
|
||||
|
||||
// Unban dialog: native <dialog> (focus trap, Esc), a radio group for how long the address stays protected, confirm.
|
||||
var UNBAN_CHOICES = [['0', 'unban.keep.none'], ['3600', 'unban.keep.1h'], ['86400', 'unban.keep.24h'], ['604800', 'unban.keep.7d']];
|
||||
function unbanDialog(ip, onDone) {
|
||||
function unbanDialog(ip, onDone, opts) {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg', 'aria-labelledby': 'unban-h', 'aria-describedby': 'unban-p' });
|
||||
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
|
||||
@@ -1018,6 +1018,19 @@
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('unban.cancel'));
|
||||
dlg.appendChild(el('h2', { id: 'unban-h' }, t('unban.title', { ip: ip })));
|
||||
dlg.appendChild(el('p', { id: 'unban-p' }, t('unban.explain')));
|
||||
// each probe enforces its own bans: the operator picks where to lift it (or every host)
|
||||
var hostSel = el('select', { id: 'unban-host' });
|
||||
var hostRow = el('div', { class: 'unban-host', hidden: true }, el('label', { for: 'unban-host' }, t('pr.unban.host')), hostSel);
|
||||
var wantHost = (opts && opts.host) || (state.host !== 'all' ? state.host : 'all');
|
||||
getSummary(ctx()).then(function (s) {
|
||||
var hs = (s.hosts || []).map(function (x) { return x.name; });
|
||||
if (hs.length < 2) return;
|
||||
hostSel.appendChild(el('option', { value: 'all' }, t('host.all')));
|
||||
hs.forEach(function (n) { hostSel.appendChild(el('option', { value: n }, n)); });
|
||||
hostSel.value = hs.indexOf(wantHost) >= 0 ? wantHost : 'all';
|
||||
hostRow.hidden = false;
|
||||
}).catch(function () { /* single host */ });
|
||||
dlg.appendChild(hostRow);
|
||||
dlg.appendChild(fs);
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
@@ -1030,7 +1043,7 @@
|
||||
ok.addEventListener('click', function () {
|
||||
var sel = dlg.querySelector('input[name="unban-keep"]:checked');
|
||||
ok.disabled = true;
|
||||
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0 }).then(function () {
|
||||
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0, host: hostRow.hidden ? (wantHost !== 'all' ? wantHost : undefined) : hostSel.value }).then(function () {
|
||||
close();
|
||||
toast(t('unban.done', { ip: ip }));
|
||||
if (onDone) onDone();
|
||||
@@ -1204,19 +1217,33 @@
|
||||
var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
|
||||
if (!mx) return empty(t('charts.empty'));
|
||||
var fmt = o.format || nf, wrap = h('div', 'vz vz-heat');
|
||||
var meas = document.createElement('canvas').getContext('2d');
|
||||
function textW(x) { meas.font = '11px ' + (cssVar('--font-sans') || 'sans-serif'); return meas.measureText(String(x)).width; }
|
||||
function fit(x, max) { // ellipsis only beyond max
|
||||
x = String(x); if (textW(x) <= max) return x;
|
||||
var lo = 0, hi = x.length; while (lo < hi) { var m = (lo + hi + 1) >> 1; if (textW(x.slice(0, m) + '\u2026') <= max) lo = m; else hi = m - 1; }
|
||||
return x.slice(0, lo) + '\u2026';
|
||||
}
|
||||
function draw(Wpx) {
|
||||
clear(wrap);
|
||||
var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22;
|
||||
var ny = matrix.length, nx = matrix[0].length, W = Math.max(240, Wpx), stacked = W < 480;
|
||||
var widest = 0; yl.forEach(function (x) { widest = Math.max(widest, textW(x)); });
|
||||
// wide: label column sized to the longest name (40% cap); narrow: the label sits above its own strip
|
||||
var LW = stacked ? 0 : Math.max(56, Math.min(Math.ceil(widest) + 14, Math.floor(W * .4)));
|
||||
var cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), lab = stacked ? 15 : 0, rowH = ch + lab, H = ny * rowH + 22;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw);
|
||||
matrix.forEach(function (row, y) {
|
||||
var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt);
|
||||
var y0 = y * rowH;
|
||||
var yt = stacked ? svgEl('text', { x: 2, y: y0 + 11, 'text-anchor': 'start', 'class': 'axis' }) : svgEl('text', { x: LW - 6, y: y0 + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' });
|
||||
yt.textContent = fit(yl[y], stacked ? W - 4 : LW - 10);
|
||||
var yti = svgEl('title', {}); yti.textContent = String(yl[y]); yt.appendChild(yti); svg.appendChild(yt);
|
||||
row.forEach(function (v, x) {
|
||||
var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0;
|
||||
var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
|
||||
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
|
||||
var r = svgEl('rect', { x: LW + x * cw + 1, y: y0 + lab + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
|
||||
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' \u00b7 ' + xl[x] + ' \u00b7 ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
|
||||
});
|
||||
});
|
||||
for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
|
||||
for (var x = 0; x < nx; x += step) { var first = x === 0 && stacked, xt = svgEl('text', { x: first ? 2 : LW + x * cw + cw / 2, y: ny * rowH + 15, 'text-anchor': first ? 'start' : 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
|
||||
wrap.appendChild(svg);
|
||||
}
|
||||
var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); })));
|
||||
@@ -1704,8 +1731,9 @@
|
||||
build: function (root) {
|
||||
var v = {}, g = grid12();
|
||||
v.lead = sp(12, h('div'));
|
||||
v.probes = window.Urutau && window.Urutau.probesPanel ? window.Urutau.probesPanel() : null;
|
||||
v.hostsBox = h('div', 'hosts');
|
||||
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox);
|
||||
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.probe' }, v.hostsBox);
|
||||
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
|
||||
v.tbody = h('tbody');
|
||||
v.srcEmpty = h('div');
|
||||
@@ -1713,11 +1741,11 @@
|
||||
v.geoBox = h('div');
|
||||
v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox);
|
||||
v.bl = blocklistPanel();
|
||||
g.appendChild(v.lead); g.appendChild(sp(12, v.hosts)); g.appendChild(sp(12, v.sources)); g.appendChild(sp(6, v.geo)); g.appendChild(sp(6, v.bl.node)); root.appendChild(g);
|
||||
g.appendChild(v.lead); if (v.probes) g.appendChild(sp(12, v.probes.node)); g.appendChild(sp(12, v.hosts)); g.appendChild(sp(12, v.sources)); g.appendChild(sp(6, v.geo)); g.appendChild(sp(6, v.bl.node)); root.appendChild(g);
|
||||
v.bl.sync();
|
||||
return v;
|
||||
},
|
||||
load: function (c, v) { v.bl.sync(); return getSummary(c); },
|
||||
load: function (c, v) { v.bl.sync(); if (v.probes) v.probes.reload(); return getSummary(c); },
|
||||
render: function (v, s) {
|
||||
var srcs = s.sources || [], hosts = s.hosts || [];
|
||||
var following = srcs.filter(function (r) { return r.state === 'following'; }).length;
|
||||
@@ -1751,11 +1779,47 @@
|
||||
dl.appendChild(h('dt', null, t('src.geo.attrib'))); dl.appendChild(h('dd', null, s.attribution || t('src.geo.none')));
|
||||
v.geoBox.appendChild(dl);
|
||||
},
|
||||
dispose: function (v) { v.bl.dispose(); }
|
||||
dispose: function (v) { v.bl.dispose(); if (v.probes) v.probes.dispose(); }
|
||||
});
|
||||
|
||||
[pOverview, pThreats, pTraffic, pIPs, pSources].forEach(function (p) { pages[p.id] = p; });
|
||||
|
||||
// ---------------------------------------------------------------- IPs never wrap
|
||||
// Any element whose whole text is an IP (v4/v6, optional :port or /prefix) gets .ipv (see style.css): one line, mono, tabular.
|
||||
// Done centrally so every table, card, feed and drawer behaves the same, whichever script drew it.
|
||||
var IP4_RE = /^\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?(?:\/\d{1,2})?$/;
|
||||
var IP6_RE = /^\[?[0-9A-Fa-f:]*:[0-9A-Fa-f:.]*\]?(?::\d{1,5})?(?:\/\d{1,3})?$/;
|
||||
function looksIP(x) { return x.length >= 7 && x.length <= 64 && (IP4_RE.test(x) || ((x.indexOf('::') >= 0 || x.split(':').length > 3) && IP6_RE.test(x))); }
|
||||
var IP_SKIP = { SCRIPT: 1, STYLE: 1, TEXTAREA: 1, OPTION: 1, TITLE: 1, INPUT: 1 };
|
||||
function tagIPs(root) {
|
||||
if (!root) return;
|
||||
var w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n, hits = [];
|
||||
while ((n = w.nextNode())) {
|
||||
var p = n.parentNode, v = n.nodeValue;
|
||||
if (!p || p.nodeType !== 1 || IP_SKIP[p.tagName] || !v || v.length > 70 || (p.classList && p.classList.contains('ipv'))) continue;
|
||||
var x = v.trim();
|
||||
if (looksIP(x)) hits.push([n, p, x]);
|
||||
}
|
||||
hits.forEach(function (hh) {
|
||||
var n = hh[0], p = hh[1], x = hh[2], target = p;
|
||||
if (p.childNodes.length > 1 || p.tagName === 'TD' || p.tagName === 'TH') { // mixed content: wrap only the address
|
||||
target = document.createElement('span'); p.replaceChild(target, n); target.appendChild(n);
|
||||
}
|
||||
target.classList.add('ipv');
|
||||
if (x.length > 24) target.classList.add('ipv-long');
|
||||
if (!target.hasAttribute('title')) target.setAttribute('title', x);
|
||||
});
|
||||
}
|
||||
var ipQueued = false;
|
||||
function watchIPs() {
|
||||
new MutationObserver(function () {
|
||||
if (ipQueued) return;
|
||||
ipQueued = true;
|
||||
requestAnimationFrame(function () { ipQueued = false; tagIPs(document.body); });
|
||||
}).observe(document.body, { childList: true, subtree: true, characterData: true });
|
||||
tagIPs(document.body);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- url (the source of truth)
|
||||
function parseHash() {
|
||||
var raw = location.hash.replace(/^#\/?/, ''), q = '', i = raw.indexOf('?');
|
||||
@@ -2147,6 +2211,7 @@
|
||||
});
|
||||
window.addEventListener('hashchange', route);
|
||||
window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage);
|
||||
watchIPs();
|
||||
connectLive();
|
||||
// the host must be validated before a page asks for data with a stale one
|
||||
shellSummary().catch(function (e) {
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.',
|
||||
'df.en.how.title': 'How to turn it on',
|
||||
'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.',
|
||||
'df.en.share': 'Sharing with peers',
|
||||
'df.en.share': 'Sharing between hosts',
|
||||
'df.en.share.on': 'on: bans are shared with other servers',
|
||||
'df.en.share.off': 'off: bans stay on this server',
|
||||
'df.en.threshold': 'Blocks from score {n}',
|
||||
@@ -105,12 +105,12 @@
|
||||
'df.en.allows.err': 'Could not end the release.',
|
||||
'df.en.allows.unwritable': 'The unban file is not writable, so unbanning will fail.',
|
||||
'df.en.src.local': 'this server',
|
||||
'df.en.src.peer': 'peer {n}',
|
||||
'df.en.src.peer': 'from {n}',
|
||||
'df.en.skip.trusted': 'Trusted address (your own list)',
|
||||
'df.en.skip.private': 'Private network (not on the internet)',
|
||||
'df.en.skip.crawler': 'Verified search engine',
|
||||
'df.en.skip.legit_visitor': 'Looks like a legitimate visitor',
|
||||
'df.en.skip.peer': 'Peer server (yours)',
|
||||
'df.en.skip.peer': 'Another of your servers',
|
||||
'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time',
|
||||
'df.en.reason.exploit-flood': 'Repeated exploit attempts',
|
||||
'df.en.reason.web-bruteforce': 'Password guessing on a website',
|
||||
@@ -174,7 +174,7 @@
|
||||
'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.',
|
||||
'df.en.how.title': 'Como ligar',
|
||||
'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.',
|
||||
'df.en.share': 'Compartilhamento com parceiros',
|
||||
'df.en.share': 'Compartilhamento entre hosts',
|
||||
'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores',
|
||||
'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor',
|
||||
'df.en.threshold': 'Bloqueia a partir da pontuação {n}',
|
||||
@@ -222,12 +222,12 @@
|
||||
'df.en.allows.err': 'Não foi possível encerrar a liberação.',
|
||||
'df.en.allows.unwritable': 'O arquivo de desban não é gravável, então desbanir vai falhar.',
|
||||
'df.en.src.local': 'este servidor',
|
||||
'df.en.src.peer': 'parceiro {n}',
|
||||
'df.en.src.peer': 'vindo de {n}',
|
||||
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
|
||||
'df.en.skip.private': 'Rede privada (fora da internet)',
|
||||
'df.en.skip.crawler': 'Buscador verificado',
|
||||
'df.en.skip.legit_visitor': 'Parece um visitante legítimo',
|
||||
'df.en.skip.peer': 'Servidor parceiro (seu)',
|
||||
'df.en.skip.peer': 'Outro servidor seu',
|
||||
'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo',
|
||||
'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração',
|
||||
'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site',
|
||||
|
||||
@@ -453,7 +453,7 @@
|
||||
function heat(st) {
|
||||
if (!U.charts || !U.charts.heatmap || !st.wls.length) return null;
|
||||
var rows = [], labels = [], step = st.tl.step || 3600;
|
||||
st.wls.forEach(function (w) { var s = seriesOf(st, w); if (s.length) { rows.push(s.slice(-24)); labels.push(w.name.length > 8 ? w.name.slice(0, 7) + '…' : w.name); } });
|
||||
st.wls.forEach(function (w) { var s = seriesOf(st, w); if (s.length) { rows.push(s.slice(-24)); labels.push(String(w.name)); } });
|
||||
if (!rows.length) return null;
|
||||
var n = rows[0].length, start = (st.tl.start || 0) + (st.tlLen - n) * step, xl = [];
|
||||
for (var i = 0; i < n; i++) xl.push(('0' + new Date((start + i * step) * 1000).getHours()).slice(-2) + 'h');
|
||||
|
||||
+12
-12
@@ -232,11 +232,11 @@ window.URUTAU_I18N = {
|
||||
'blocklist.failed': 'Could not copy the list.',
|
||||
'blocklist.count.one': '{n} IP would be listed (selected range).',
|
||||
'blocklist.count.other': '{n} IPs would be listed (selected range).',
|
||||
'hosts.title': 'Hosts and peers',
|
||||
'hosts.hint': 'This instance and the peers it federates with.',
|
||||
'hosts.title': 'Hosts',
|
||||
'hosts.hint': 'Every host that sends data to this hub.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'this instance',
|
||||
'host.self': 'hub host',
|
||||
'host.requests': 'Requests',
|
||||
'host.malicious': 'Malicious',
|
||||
'host.hostile': 'Hostile IPs',
|
||||
@@ -444,9 +444,9 @@ window.URUTAU_I18N = {
|
||||
'help.term.exposure.do': 'Remove or protect the resource and rotate any secret in it.',
|
||||
'help.term.blocklist': 'The list of hostile IPs ready to import into a firewall. Only addresses with strong evidence are included.',
|
||||
'help.term.blocklist.do': 'Export it as text or JSON and load it into your firewall or fail2ban.',
|
||||
'help.term.peer': 'Another Urutau instance that shares its data with this one.',
|
||||
'help.term.peer.do': 'If a peer is offline, its numbers are missing from the totals.',
|
||||
'help.term.hub': 'The instance that gathers the data of its peers into one view.',
|
||||
'help.term.probe': 'A small agent that runs next to the logs of a server and sends them to this hub.',
|
||||
'help.term.probe.do': 'If a probe is offline, its numbers are missing from the totals. Check the machine and its network.',
|
||||
'help.term.hub': 'The server that gathers the data of all probes into one view.',
|
||||
'help.term.hub.do': 'Open the hub to see all servers together.',
|
||||
'help.term.client_type': 'The kind of client behind each request: desktop, mobile, tablet, bot, tool or unknown, from its user agent.',
|
||||
'help.term.client_type.do': 'A large share of tools or unknown clients is worth checking.',
|
||||
@@ -747,11 +747,11 @@ window.URUTAU_I18N = {
|
||||
'blocklist.failed': 'Não foi possível copiar a lista.',
|
||||
'blocklist.count.one': '{n} IP seria listado (período selecionado).',
|
||||
'blocklist.count.other': '{n} IPs seriam listados (período selecionado).',
|
||||
'hosts.title': 'Hosts e pares',
|
||||
'hosts.hint': 'Esta instância e os pares com os quais ela se federa.',
|
||||
'hosts.title': 'Hosts',
|
||||
'hosts.hint': 'Todos os hosts que enviam dados a este hub.',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.self': 'esta instância',
|
||||
'host.self': 'host do hub',
|
||||
'host.requests': 'Requisições',
|
||||
'host.malicious': 'Maliciosos',
|
||||
'host.hostile': 'IPs hostis',
|
||||
@@ -959,9 +959,9 @@ window.URUTAU_I18N = {
|
||||
'help.term.exposure.do': 'Remova ou proteja o recurso e troque qualquer segredo contido nele.',
|
||||
'help.term.blocklist': 'A lista de IPs hostis pronta para importar em um firewall. Só entram endereços com evidência forte.',
|
||||
'help.term.blocklist.do': 'Exporte em texto ou JSON e carregue no firewall ou no fail2ban.',
|
||||
'help.term.peer': 'Outra instância do Urutau que compartilha seus dados com esta.',
|
||||
'help.term.peer.do': 'Se um par está offline, os números dele faltam nos totais.',
|
||||
'help.term.hub': 'A instância que reúne os dados dos pares em uma só visão.',
|
||||
'help.term.probe': 'Um agente pequeno que roda ao lado dos logs de um servidor e os envia a este hub.',
|
||||
'help.term.probe.do': 'Se uma sonda está offline, os números dela faltam nos totais. Confira a máquina e a rede dela.',
|
||||
'help.term.hub': 'O servidor que reúne os dados de todas as sondas em uma só visão.',
|
||||
'help.term.hub.do': 'Abra o hub para ver todos os servidores juntos.',
|
||||
'help.term.client_type': 'O tipo de cliente por trás de cada requisição: computador, celular, tablet, robô, ferramenta ou desconhecido, pelo user-agent.',
|
||||
'help.term.client_type.do': 'Uma parcela grande de ferramentas ou desconhecidos merece verificação.',
|
||||
|
||||
@@ -16,6 +16,14 @@
|
||||
var PER_PAGE = 25;
|
||||
var AUTHOR_KEY = 'urutau.author';
|
||||
|
||||
// Ticket ids are per host (each probe keeps its own INC-n sequence): shown and linked as host/INC-n.
|
||||
function splitId(it) {
|
||||
var id = String(it.id || ''), host = it.host ? String(it.host) : '', i = id.lastIndexOf('/');
|
||||
if (i > 0) { host = id.slice(0, i); id = id.slice(i + 1); }
|
||||
return { host: host, num: id, full: host ? host + '/' + id : id };
|
||||
}
|
||||
function idSegs(it) { var q = splitId(it); return q.host ? [q.host, q.num] : [q.num]; }
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerPage) return false;
|
||||
@@ -305,9 +313,9 @@
|
||||
el('span', { class: 'inc-mrow' }, el('strong', { class: 'inc-title', title: String(it.title || it.id) }, head),
|
||||
(it.tags && it.tags.length) ? el('span', { class: 'inc-rtags' }, tagChips(it.tags.slice(0, 1))) : null),
|
||||
auto ? el('span', { class: 'inc-sub mono', title: String(it.workload) }, String(it.workload)) : null);
|
||||
return el('a', { class: 'inc-row', href: U.href('incidents', [String(it.id)]), title: full },
|
||||
return el('a', { class: 'inc-row', href: U.href('incidents', idSegs(it)), title: full },
|
||||
dot(it.severity),
|
||||
el('span', { class: 'inc-id mono' }, String(it.id)),
|
||||
el('span', { class: 'inc-id mono', title: splitId(it).full }, splitId(it).full),
|
||||
titleLine,
|
||||
el('span', { class: 'inc-st' }, statusBadge(it.status)),
|
||||
el('span', { class: 'inc-who' }, it.assignee ? String(it.assignee) : '—'),
|
||||
@@ -401,7 +409,7 @@
|
||||
U.apiSend('POST', '/api/v1/incidents', { title: ttl, detail: detail.value.trim(), severity: sev.value, host: hostIn.value.trim(), tags: parseTags(tg.value), author: authorName() }).then(function (r) {
|
||||
close();
|
||||
pollBadge();
|
||||
if (r && r.id) location.hash = U.href('incidents', [String(r.id)]); else if (view && view.update) view.update();
|
||||
if (r && r.id) location.hash = U.href('incidents', idSegs(r.host || !hostIn.value.trim() ? r : { id: r.id, host: hostIn.value.trim() })); else if (view && view.update) view.update();
|
||||
}, function () {
|
||||
ok.disabled = false;
|
||||
err.textContent = t('inc.err.create');
|
||||
@@ -414,14 +422,14 @@
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ one ticket
|
||||
function detailView(host, id) {
|
||||
function detailView(host, id, idHost) {
|
||||
var seq = 0, on = true, tk = null, busy = false;
|
||||
var box = el('div', { class: 'inc-detail' });
|
||||
host.appendChild(el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back')));
|
||||
host.appendChild(box);
|
||||
var errBox = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || ''); }
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || '') + (idHost ? '?host=' + encodeURIComponent(idHost) : ''); }
|
||||
function send(method, suffix, body, errKey, okKey) {
|
||||
if (busy) return;
|
||||
busy = true; box.classList.add('busy');
|
||||
@@ -480,7 +488,7 @@
|
||||
quick(t('inc.quick.fp'), 'false_positive', 'fp'), quick(t('inc.quick.tp'), 'true_positive', 'tp'), quick(t('inc.quick.resolve'), 'resolved', 'ok'));
|
||||
var meta = el('span', { class: 'inc-hint inc-metaline' }, t('inc.meta', { a: x.created_at ? U.fmt.ago(x.created_at) : '-', b: x.updated_at ? U.fmt.ago(x.updated_at) : '-', n: nf(x.count) }));
|
||||
return el('header', { class: 'inc-head' },
|
||||
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, String(x.id)), title, q),
|
||||
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, splitId(x).full), title, q),
|
||||
el('div', { class: 'inc-h2' }, sevBadge(x.severity), statusBadge(x.status), x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null, tagChips(x.tags), meta));
|
||||
}
|
||||
|
||||
@@ -709,8 +717,10 @@
|
||||
if (view) { view.destroy(); view = null; }
|
||||
clear(root);
|
||||
var seg = ctx && ctx.params && ctx.params.segments ? ctx.params.segments : [];
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '';
|
||||
view = id ? detailView(root, id) : listView(root);
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '', idHost = '';
|
||||
if (seg[1]) { idHost = id.slice(0, 64); id = String(seg[1]).slice(0, 64); }
|
||||
else if (id.indexOf('/') > 0) { idHost = id.slice(0, id.lastIndexOf('/')); id = id.slice(id.lastIndexOf('/') + 1); }
|
||||
view = id ? detailView(root, id, idHost) : listView(root);
|
||||
}
|
||||
|
||||
U.registerPage({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* Urutau - INTEGRITY page ("Is the data complete?"): volume ingested per host and
|
||||
hour (holes show as empty cells), state of every source and peer, share of
|
||||
hour (holes show as empty cells), state of every source and probe, share of
|
||||
malformed lines, event log and geolocation base. Log data is hostile: every
|
||||
dynamic string goes through textContent (the shell's el/h helpers). */
|
||||
(function () {
|
||||
@@ -18,7 +18,7 @@
|
||||
'ig.lead.okBody': 'No gaps of {n} hours or more, every source answers and few lines were rejected.',
|
||||
'ig.lead.bad.one': '{n} hole in the data',
|
||||
'ig.lead.bad.other': '{n} holes in the data',
|
||||
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline peers or sources in error. Check the panels below.',
|
||||
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline probes or sources in error. Check the panels below.',
|
||||
'ig.lead.loading': 'Checking the data...',
|
||||
'ig.stat.hosts': 'Hosts reporting',
|
||||
'ig.stat.gaps': 'Gaps found',
|
||||
@@ -46,13 +46,13 @@
|
||||
'ig.state.error': 'error',
|
||||
'ig.state.degraded': 'degraded',
|
||||
'ig.state.disabled': 'disabled',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'No peers configured.',
|
||||
'ig.peers.online': 'online',
|
||||
'ig.peers.title': 'Probes',
|
||||
'ig.peers.none': 'No probes created.',
|
||||
'ig.peers.online': 'connected',
|
||||
'ig.peers.offline': 'offline',
|
||||
'ig.peers.live': 'live',
|
||||
'ig.peers.sync': 'synced {t}',
|
||||
'ig.peers.never': 'never synced',
|
||||
'ig.peers.sync': 'last seen {t}',
|
||||
'ig.peers.never': 'never seen',
|
||||
'ig.log.title': 'Event log and geolocation',
|
||||
'ig.log.off': 'The event log is off: periods, sessions and replay have no data.',
|
||||
'ig.log.days': 'Days kept',
|
||||
@@ -71,7 +71,7 @@
|
||||
'ig.lead.okBody': 'Nenhum buraco de {n} horas ou mais, todas as fontes respondem e poucas linhas foram rejeitadas.',
|
||||
'ig.lead.bad.one': '{n} buraco nos dados',
|
||||
'ig.lead.bad.other': '{n} buracos nos dados',
|
||||
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, peers fora do ar ou fontes com erro. Veja os painéis abaixo.',
|
||||
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, sondas fora do ar ou fontes com erro. Veja os painéis abaixo.',
|
||||
'ig.lead.loading': 'Conferindo os dados...',
|
||||
'ig.stat.hosts': 'Hosts reportando',
|
||||
'ig.stat.gaps': 'Buracos encontrados',
|
||||
@@ -99,13 +99,13 @@
|
||||
'ig.state.error': 'erro',
|
||||
'ig.state.degraded': 'degradada',
|
||||
'ig.state.disabled': 'desativada',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'Nenhum peer configurado.',
|
||||
'ig.peers.online': 'no ar',
|
||||
'ig.peers.offline': 'fora do ar',
|
||||
'ig.peers.title': 'Sondas',
|
||||
'ig.peers.none': 'Nenhuma sonda criada.',
|
||||
'ig.peers.online': 'conectada',
|
||||
'ig.peers.offline': 'offline',
|
||||
'ig.peers.live': 'ao vivo',
|
||||
'ig.peers.sync': 'sincronizado {t}',
|
||||
'ig.peers.never': 'nunca sincronizou',
|
||||
'ig.peers.sync': 'vista {t}',
|
||||
'ig.peers.never': 'nunca vista',
|
||||
'ig.log.title': 'Registro de eventos e geolocalização',
|
||||
'ig.log.off': 'O registro de eventos está desligado: períodos, sessões e replay ficam sem dados.',
|
||||
'ig.log.days': 'Dias guardados',
|
||||
@@ -169,14 +169,14 @@
|
||||
function paint() {
|
||||
if (!data) return;
|
||||
clear(box);
|
||||
var hosts = data.hosts || [], peers = data.peers || [];
|
||||
var hosts = data.hosts || [], peers = data.probes || data.peers || [];
|
||||
var gaps = 0, lines = 0, bad = 0, errors = 0, onlineN = 0;
|
||||
hosts.forEach(function (x) {
|
||||
gaps += (x.gaps || []).length;
|
||||
if (x.online) onlineN++;
|
||||
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error' || s.state === 'degraded') errors++; });
|
||||
});
|
||||
var offline = peers.filter(function (p) { return !p.online; }).length;
|
||||
var offline = peers.filter(function (p) { return !(p.online || p.connected); }).length;
|
||||
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
|
||||
var holes = gaps + offline + errors;
|
||||
var ok = holes === 0 && rate < 0.01;
|
||||
@@ -222,9 +222,9 @@
|
||||
else {
|
||||
var pl = h('ul', 'ig-list');
|
||||
peers.forEach(function (p) {
|
||||
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t(p.online ? 'ig.peers.online' : 'ig.peers.offline'), p.online ? 'ok' : 'danger'),
|
||||
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t((p.online || p.connected) ? 'ig.peers.online' : 'ig.peers.offline'), (p.online || p.connected) ? 'ok' : 'danger'),
|
||||
p.live ? ' ' : null, p.live ? U.ui.badge(t('ig.peers.live'), 'neutral') : null, ' ',
|
||||
h('span', 'ig-muted', p.last_sync ? t('ig.peers.sync', { t: U.fmt.ago(p.last_sync) }) : t('ig.peers.never'))));
|
||||
h('span', 'ig-muted', (p.last_seen || p.last_sync) ? t('ig.peers.sync', { t: U.fmt.ago(p.last_seen || p.last_sync) }) : t('ig.peers.never'))));
|
||||
});
|
||||
pp.body.appendChild(pl);
|
||||
}
|
||||
|
||||
@@ -170,9 +170,8 @@ button.lv-row[aria-pressed="false"] .lv-row-l { text-decoration: line-through; }
|
||||
.lv-vis-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--lv-muted); flex: none; }
|
||||
.lv-vis[aria-pressed="true"] { border-color: var(--accent); }
|
||||
.lv-vis[aria-pressed="true"] .lv-vis-dot { background: var(--lv-muted); border-color: var(--lv-muted); }
|
||||
.lv-devs, .lv-m-visit { display: none; }
|
||||
.lv-devs { display: none; }
|
||||
.lv-vis-on .lv-devs { display: flex; }
|
||||
.lv-vis-on .lv-m-visit { display: flex; }
|
||||
.lv-k-visit { --k: var(--ink-muted, #9db3bd); }
|
||||
.lv-ev-visit .lv-vtxt { grid-column: span 1; color: var(--lv-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
|
||||
|
||||
+39
-15
@@ -843,8 +843,6 @@
|
||||
if (Math.abs(this.vlon) > 0.05 || Math.abs(this.vlat) > 0.05) {
|
||||
this.lon0 += this.vlon * dt; this.lat0 = clamp(this.lat0 + this.vlat * dt, -75, 75);
|
||||
var f = Math.pow(0.04, dt); this.vlon *= f; this.vlat *= f;
|
||||
} else if (!this.reduced && this.T > this.idleAt) {
|
||||
this.lon0 += 4.5 * dt;
|
||||
}
|
||||
}
|
||||
if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle
|
||||
@@ -875,9 +873,11 @@
|
||||
'live.visits': 'Legitimate traffic',
|
||||
'live.visit': 'visit',
|
||||
'live.legend.visits': 'visits',
|
||||
'live.m.vis': 'Visits, 15 min',
|
||||
'live.m.pages': 'Pages, 15 min',
|
||||
'live.m.vis': 'Visitors, 1 h',
|
||||
'live.m.pages': 'Pages viewed, 1 h',
|
||||
'live.unit.pages': 'distinct pages',
|
||||
'live.sub.vis': '{n} requests',
|
||||
'live.sub.top': 'top: {x}',
|
||||
'live.devices': 'Devices',
|
||||
'live.vis.empty': 'anonymous',
|
||||
'live.mode': 'View',
|
||||
@@ -924,9 +924,11 @@
|
||||
'live.visits': 'Tráfego legítimo',
|
||||
'live.visit': 'visita',
|
||||
'live.legend.visits': 'visitas',
|
||||
'live.m.vis': 'Visitas, 15 min',
|
||||
'live.m.pages': 'Páginas, 15 min',
|
||||
'live.m.vis': 'Visitantes, 1 h',
|
||||
'live.m.pages': 'Páginas vistas, 1 h',
|
||||
'live.unit.pages': 'páginas distintas',
|
||||
'live.sub.vis': '{n} requisições',
|
||||
'live.sub.top': 'mais: {x}',
|
||||
'live.vis.empty': 'anônima',
|
||||
'live.devices': 'Dispositivos',
|
||||
'live.mode': 'Visualização',
|
||||
@@ -1010,7 +1012,8 @@
|
||||
if (window.matchMedia) { var mqw = matchMedia('(min-width: 1200px)'); if (mqw.addEventListener) this.listen(mqw, 'change', function () { self.placeRec(); self.map._map.resize(); }); }
|
||||
this.timers.push(setInterval(function () { self.tick(); }, 1000));
|
||||
this.timers.push(setInterval(function () { self.loadSummary(); self.loadMetrics(); }, 60000));
|
||||
this.loadSummary(); this.loadMetrics(); this.loadRecent();
|
||||
this.timers.push(setInterval(function () { self.loadTraffic(); }, 30000));
|
||||
this.loadSummary(); this.loadMetrics(); this.loadRecent(); this.loadTraffic();
|
||||
this.tick(true);
|
||||
}
|
||||
var P = Live.prototype;
|
||||
@@ -1336,7 +1339,7 @@
|
||||
|
||||
P.onVisibility = function () {
|
||||
this.hidden = document.hidden;
|
||||
if (!this.hidden) { this.loadSummary(); this.loadMetrics(); this.tick(true); }
|
||||
if (!this.hidden) { this.loadSummary(); this.loadMetrics(); this.loadTraffic(); this.tick(true); }
|
||||
};
|
||||
|
||||
P.addMore = function (n) {
|
||||
@@ -1596,14 +1599,35 @@
|
||||
for (var k in this.bk) if (+k < min - 1500) delete this.bk[k];
|
||||
};
|
||||
|
||||
// legitimate traffic: totals of the last hour from /api/v1/traffic (the server has no 15 min range),
|
||||
// refreshed every 30 s whether or not the "Legitimate traffic" toggle is on (it only controls the drawing)
|
||||
P.loadTraffic = function () {
|
||||
var self = this;
|
||||
if (!this.U.api || this.hidden) return;
|
||||
var h = this.ctx && this.ctx.host, q = { range: '1h' };
|
||||
if (h && h !== 'all') q.host = h;
|
||||
var key = q.host || 'all', p;
|
||||
try { p = this.U.api('/api/v1/traffic', q); } catch (x) { return; }
|
||||
if (!p || !p.then) return;
|
||||
p.then(function (d) {
|
||||
if (!self.alive || !d || typeof d !== 'object') return;
|
||||
var top = function (l) { return Array.isArray(l) && l[0] && l[0].key ? l[0] : null; };
|
||||
self.traf = { key: key, visitors: isNum(d.visitors) ? d.visitors : null, pages: isNum(d.pages) ? d.pages : null, requests: isNum(d.requests) ? d.requests : null, dom: top(d.domains), cc: top(d.countries) };
|
||||
self.minute = -1; self.tick(true);
|
||||
}).catch(function () { /* traffic unavailable */ });
|
||||
};
|
||||
P.visitMetrics = function (min, fmtN) {
|
||||
var vn = 0, pg = 0, vi, mm = this.mM, self = this;
|
||||
for (vi = min - 14; vi <= min; vi++) if (this.vbk[vi]) vn += this.vbk[vi].n;
|
||||
this.pathLast.forEach(function (last) { if (last >= min - 14) pg++; });
|
||||
mm.vis.val.textContent = fmtN(vn); this.setSub(mm.vis, this.t('live.legend.visits'), '');
|
||||
mm.pages.val.textContent = fmtN(pg); this.setSub(mm.pages, this.t('live.unit.pages'), '');
|
||||
this.pathLast.forEach(function (last, p) { if (last < min - 30) self.pathLast.delete(p); });
|
||||
var mm = this.mM, d = this.traf, h = this.ctx && this.ctx.host;
|
||||
if (!d || d.key !== (h && h !== 'all' ? h : 'all')) { mm.vis.val.textContent = '-'; mm.pages.val.textContent = '-'; return; }
|
||||
mm.vis.val.textContent = d.visitors === null ? '-' : fmtN(d.visitors);
|
||||
this.setSub(mm.vis, d.requests === null ? this.t('live.legend.visits') : this.t('live.sub.vis', { n: fmtN(d.requests) }), '');
|
||||
mm.pages.val.textContent = d.pages === null ? '-' : fmtN(d.pages);
|
||||
var x = d.dom ? str(d.dom.key, 40) : '';
|
||||
if (d.cc && d.cc.key) x = (x ? x + ' · ' : '') + cc2(d.cc.key);
|
||||
this.setSub(mm.pages, x ? this.t('live.sub.top', { x: x }) : this.t('live.unit.pages'), '');
|
||||
var pl = this.pathLast;
|
||||
for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk];
|
||||
pl.forEach(function (last, p) { if (last < min - 30) pl.delete(p); });
|
||||
};
|
||||
|
||||
P.regionName = function (cc) {
|
||||
@@ -1621,7 +1645,7 @@
|
||||
var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String;
|
||||
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
|
||||
if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); }
|
||||
if (this.visitsOn) this.visitMetrics(min, fmtN);
|
||||
this.visitMetrics(min, fmtN);
|
||||
// category and server counts, origins: the 15 minute window (partial minute included)
|
||||
var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c;
|
||||
CATS.forEach(function (k) {
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
{
|
||||
"name": "incidents",
|
||||
"css": true
|
||||
},
|
||||
{
|
||||
"name": "probes",
|
||||
"css": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Probes panel (Sources page) and its dialogs. */
|
||||
.pr-name { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||
.pr-name strong { overflow-wrap: normal; word-break: normal; white-space: nowrap; }
|
||||
.pr-table td:first-child { min-width: 7rem; }
|
||||
.pr-sum { margin: 0 0 10px; color: var(--ink-muted); }
|
||||
.pr-sum.bad { color: var(--danger); font-weight: 600; }
|
||||
@media (max-width: 760px) { .pr-name strong { white-space: normal; overflow-wrap: anywhere; } }
|
||||
.pr-muted { color: var(--ink-muted); font-size: .8125rem; }
|
||||
.pr-srcs { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.pr-acts { display: inline-flex; gap: 6px; flex-wrap: wrap; }
|
||||
.btn.pr-sm { padding: 3px 10px; font-size: .8125rem; min-height: 30px; }
|
||||
.btn.pr-danger { color: var(--danger); }
|
||||
.btn.pr-danger:hover:not(:disabled) { border-color: var(--danger); background: var(--danger-soft); }
|
||||
.pr-warnv { color: var(--warn); font-weight: 600; }
|
||||
.pr-revoked td { opacity: .6; }
|
||||
.pr-table td, .pr-table th { vertical-align: top; }
|
||||
.pr-body { display: grid; gap: var(--s-3, 12px); }
|
||||
.panel-b > .lead { margin-bottom: 12px; }
|
||||
|
||||
.pr-dlg { width: min(34rem, calc(100vw - 32px)); box-sizing: border-box; }
|
||||
.pr-dlg.wide { width: min(44rem, calc(100vw - 32px)); }
|
||||
.pr-dlg input[type="text"], .pr-dlg input[type="number"], .pr-dlg textarea { width: 100%; box-sizing: border-box; }
|
||||
.pr-dlg textarea { padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink); font-size: .8125rem; resize: vertical; }
|
||||
.pr-field { display: grid; gap: 4px; margin: 10px 0; min-width: 0; }
|
||||
.pr-field label, .pr-lbl { font-weight: 600; display: block; margin: 10px 0 4px; }
|
||||
.pr-field label { margin: 0; }
|
||||
.pr-fh { color: var(--ink-muted); }
|
||||
.pr-warn { margin: 0 0 8px; padding: 8px 10px; border: 1px solid color-mix(in srgb, var(--warn) 55%, transparent); background: var(--warn-soft); color: var(--ink); border-radius: var(--radius-sm); }
|
||||
.pr-row { display: flex; gap: 8px; align-items: center; }
|
||||
.pr-row .pr-tok { flex: 1; min-width: 0; }
|
||||
.pr-end { justify-content: flex-end; margin-top: 8px; }
|
||||
.pr-snip { white-space: pre; overflow: auto; margin-top: 6px; }
|
||||
.pr-note { min-height: 1.25em; margin: 8px 0 0; color: var(--ink-muted); }
|
||||
.pr-fs { border: 0; padding: 0; margin: 12px 0 0; min-width: 0; }
|
||||
.pr-fs legend { padding: 0; font-weight: 700; }
|
||||
.pr-grid { display: grid; grid-template-columns: 1fr 1fr 1.4fr; gap: 10px; }
|
||||
.unban-host { display: grid; gap: 4px; margin: 12px 0; }
|
||||
.unban-host label { font-weight: 600; }
|
||||
@media (max-width: 560px) {
|
||||
.pr-grid { grid-template-columns: 1fr; gap: 0; }
|
||||
.pr-row { flex-direction: column; align-items: stretch; }
|
||||
.pr-dlg { padding: 12px; }
|
||||
}
|
||||
.pr-dlg, .pr-dlg.wide { max-width: calc(100vw - 32px); }
|
||||
@@ -0,0 +1,430 @@
|
||||
/* Urutau - PROBES panel of the Sources page: the probes that ship logs to this hub (status, last line, lag, version,
|
||||
dropped lines, spool, source states), create (token shown once + compose snippet), edit location/egress, revoke.
|
||||
Data: GET/POST /api/v1/probes, PUT/DELETE /api/v1/probes/{name}. Names, versions and errors come from remote
|
||||
machines: dynamic text goes through textContent only. Exposes Urutau.probesPanel(); app.js mounts it. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
var SRC_STATES = ['following', 'waiting', 'error'];
|
||||
var PROBE_IMAGE = 'git.lucasrguerra.dev.br/ciberfauna/urutau-probe:latest';
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerI18n || !U.ui) return false;
|
||||
var el = U.el, t = U.t, nf = U.fmt.num;
|
||||
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'pr.title': 'Probes',
|
||||
'pr.hint': 'Machines that read their logs locally and send them to this hub.',
|
||||
'pr.help': 'A probe is a small agent that runs next to the logs. It sends lines to the hub and keeps a local queue (spool) while the hub is unreachable, so nothing is lost.',
|
||||
'pr.empty': 'No probe created yet.',
|
||||
'pr.empty.sub': 'Create one, copy its token once and start the probe on the machine that owns the logs.',
|
||||
'pr.new': 'New probe',
|
||||
'pr.col.probe': 'Probe', 'pr.col.status': 'Status', 'pr.col.lastLine': 'Last line', 'pr.col.lag': 'Delay',
|
||||
'pr.col.version': 'Version', 'pr.col.dropped': 'Dropped', 'pr.col.spool': 'Queue', 'pr.col.sources': 'Sources', 'pr.col.actions': 'Actions',
|
||||
'pr.st.connected': 'connected', 'pr.st.offline': 'offline', 'pr.st.revoked': 'revoked',
|
||||
'pr.src.following': 'following', 'pr.src.waiting': 'waiting', 'pr.src.error': 'error',
|
||||
'pr.src.none': 'no source reported',
|
||||
'pr.edit': 'Edit', 'pr.revoke': 'Revoke',
|
||||
'pr.lead.none': 'No probes',
|
||||
'pr.lead.all.one': 'The probe is connected',
|
||||
'pr.lead.all.other': 'All {n} probes are connected',
|
||||
'pr.lead.some': 'Probes connected: {a} of {n}',
|
||||
'pr.lead.body': 'Dropped lines: {d}. Queued on the probes: {q}.',
|
||||
'pr.err.load': 'Could not load the probes.',
|
||||
'pr.new.title': 'New probe',
|
||||
'pr.new.hint': 'The name identifies the machine in the dashboard. Letters, digits, dot, dash and underscore.',
|
||||
'pr.new.name': 'Probe name',
|
||||
'pr.new.create': 'Create probe',
|
||||
'pr.new.invalid': 'Use 1 to 64 letters, digits, dot, dash or underscore, starting with a letter or digit.',
|
||||
'pr.new.exists': 'A probe with this name already exists.',
|
||||
'pr.new.err': 'Could not create the probe. Try again.',
|
||||
'pr.tok.title': 'Probe "{name}" created',
|
||||
'pr.tok.warn': 'This token is shown only once. Copy it now: it cannot be recovered, only replaced by creating another probe.',
|
||||
'pr.tok.label': 'Token',
|
||||
'pr.tok.copy': 'Copy token',
|
||||
'pr.tok.copied': 'Token copied',
|
||||
'pr.tok.snippet': 'docker-compose.yml for the probe machine',
|
||||
'pr.tok.snippet.hint': 'The token is already filled in. Adjust the log paths if yours differ.',
|
||||
'pr.tok.copySnippet': 'Copy compose',
|
||||
'pr.tok.copiedSnippet': 'Compose copied',
|
||||
'pr.tok.copyFail': 'Could not copy. Select the text and copy it by hand.',
|
||||
'pr.tok.done': 'I saved the token',
|
||||
'pr.edit.title': 'Edit probe "{name}"',
|
||||
'pr.edit.loc': 'Location on the map',
|
||||
'pr.edit.lat': 'Latitude', 'pr.edit.lon': 'Longitude', 'pr.edit.label': 'Label',
|
||||
'pr.edit.egress': 'Outbound traffic (egress)',
|
||||
'pr.edit.workloads': 'Workloads', 'pr.edit.workloads.hint': 'name=ITEM,ITEM:role;name2=...',
|
||||
'pr.edit.resolvers': 'Allowed DNS resolvers', 'pr.edit.resolvers.hint': 'comma separated; empty uses the usual ones',
|
||||
'pr.edit.allow': 'Allowed destinations', 'pr.edit.allow.hint': 'comma separated',
|
||||
'pr.edit.save': 'Save',
|
||||
'pr.edit.badLoc': 'Latitude must be between -90 and 90 and longitude between -180 and 180.',
|
||||
'pr.edit.err': 'Could not save. Try again.',
|
||||
'pr.edit.done': 'Probe "{name}" updated',
|
||||
'pr.rev.title': 'Revoke probe "{name}"?',
|
||||
'pr.rev.body': 'The probe stops being accepted right away and its token no longer works. Data already received stays on the hub.',
|
||||
'pr.rev.confirm': 'Revoke',
|
||||
'pr.rev.done': 'Probe "{name}" revoked',
|
||||
'pr.rev.err': 'Could not revoke. Try again.',
|
||||
'pr.cancel': 'Cancel', 'pr.close': 'Close',
|
||||
'pr.age': '{t} ago',
|
||||
'pr.unban.host': 'Unban on'
|
||||
},
|
||||
'pt-BR': {
|
||||
'pr.title': 'Sondas',
|
||||
'pr.hint': 'Máquinas que leem os próprios logs e os enviam para este hub.',
|
||||
'pr.help': 'Uma sonda é um agente pequeno que roda ao lado dos logs. Ela envia as linhas ao hub e guarda uma fila local (spool) enquanto o hub está fora do ar, então nada se perde.',
|
||||
'pr.empty': 'Nenhuma sonda criada ainda.',
|
||||
'pr.empty.sub': 'Crie uma, copie o token uma única vez e inicie a sonda na máquina que tem os logs.',
|
||||
'pr.new': 'Nova sonda',
|
||||
'pr.col.probe': 'Sonda', 'pr.col.status': 'Status', 'pr.col.lastLine': 'Última linha', 'pr.col.lag': 'Atraso',
|
||||
'pr.col.version': 'Versão', 'pr.col.dropped': 'Descartadas', 'pr.col.spool': 'Fila', 'pr.col.sources': 'Fontes', 'pr.col.actions': 'Ações',
|
||||
'pr.st.connected': 'conectada', 'pr.st.offline': 'offline', 'pr.st.revoked': 'revogada',
|
||||
'pr.src.following': 'acompanhando', 'pr.src.waiting': 'aguardando', 'pr.src.error': 'erro',
|
||||
'pr.src.none': 'nenhuma fonte informada',
|
||||
'pr.edit': 'Editar', 'pr.revoke': 'Revogar',
|
||||
'pr.lead.none': 'Nenhuma sonda',
|
||||
'pr.lead.all.one': 'A sonda está conectada',
|
||||
'pr.lead.all.other': 'Todas as {n} sondas estão conectadas',
|
||||
'pr.lead.some': 'Sondas conectadas: {a} de {n}',
|
||||
'pr.lead.body': 'Linhas descartadas: {d}. Na fila das sondas: {q}.',
|
||||
'pr.err.load': 'Não foi possível carregar as sondas.',
|
||||
'pr.new.title': 'Nova sonda',
|
||||
'pr.new.hint': 'O nome identifica a máquina no painel. Letras, dígitos, ponto, hífen e sublinhado.',
|
||||
'pr.new.name': 'Nome da sonda',
|
||||
'pr.new.create': 'Criar sonda',
|
||||
'pr.new.invalid': 'Use de 1 a 64 letras, dígitos, ponto, hífen ou sublinhado, começando por letra ou dígito.',
|
||||
'pr.new.exists': 'Já existe uma sonda com este nome.',
|
||||
'pr.new.err': 'Não foi possível criar a sonda. Tente de novo.',
|
||||
'pr.tok.title': 'Sonda "{name}" criada',
|
||||
'pr.tok.warn': 'Este token aparece uma única vez. Copie agora: ele não pode ser recuperado, só substituído criando outra sonda.',
|
||||
'pr.tok.label': 'Token',
|
||||
'pr.tok.copy': 'Copiar token',
|
||||
'pr.tok.copied': 'Token copiado',
|
||||
'pr.tok.snippet': 'docker-compose.yml da máquina da sonda',
|
||||
'pr.tok.snippet.hint': 'O token já está preenchido. Ajuste os caminhos dos logs se os seus forem diferentes.',
|
||||
'pr.tok.copySnippet': 'Copiar compose',
|
||||
'pr.tok.copiedSnippet': 'Compose copiado',
|
||||
'pr.tok.copyFail': 'Não foi possível copiar. Selecione o texto e copie à mão.',
|
||||
'pr.tok.done': 'Guardei o token',
|
||||
'pr.edit.title': 'Editar sonda "{name}"',
|
||||
'pr.edit.loc': 'Localização no mapa',
|
||||
'pr.edit.lat': 'Latitude', 'pr.edit.lon': 'Longitude', 'pr.edit.label': 'Rótulo',
|
||||
'pr.edit.egress': 'Tráfego de saída (egress)',
|
||||
'pr.edit.workloads': 'Workloads', 'pr.edit.workloads.hint': 'nome=ITEM,ITEM:papel;nome2=...',
|
||||
'pr.edit.resolvers': 'Resolvedores DNS permitidos', 'pr.edit.resolvers.hint': 'separados por vírgula; vazio usa os usuais',
|
||||
'pr.edit.allow': 'Destinos permitidos', 'pr.edit.allow.hint': 'separados por vírgula',
|
||||
'pr.edit.save': 'Salvar',
|
||||
'pr.edit.badLoc': 'A latitude deve ficar entre -90 e 90 e a longitude entre -180 e 180.',
|
||||
'pr.edit.err': 'Não foi possível salvar. Tente de novo.',
|
||||
'pr.edit.done': 'Sonda "{name}" atualizada',
|
||||
'pr.rev.title': 'Revogar a sonda "{name}"?',
|
||||
'pr.rev.body': 'A sonda deixa de ser aceita na hora e o token dela para de funcionar. Os dados já recebidos continuam no hub.',
|
||||
'pr.rev.confirm': 'Revogar',
|
||||
'pr.rev.done': 'Sonda "{name}" revogada',
|
||||
'pr.rev.err': 'Não foi possível revogar. Tente de novo.',
|
||||
'pr.cancel': 'Cancelar', 'pr.close': 'Fechar',
|
||||
'pr.age': 'há {t}',
|
||||
'pr.unban.host': 'Desbanir em'
|
||||
}
|
||||
});
|
||||
|
||||
// ---- helpers
|
||||
function pick(o, a, b) { return o[a] !== undefined && o[a] !== null ? o[a] : o[b]; }
|
||||
// ProbeInfo tolerant of snake_case or Go field names
|
||||
function norm(p) {
|
||||
var loc = pick(p, 'location', 'Location') || null;
|
||||
var sec = function (v) { if (typeof v === 'string') { var d = Date.parse(v); return isFinite(d) ? d / 1000 : 0; } v = Number(v) || 0; return v > 1e12 ? v / 1000 : v; };
|
||||
return {
|
||||
name: String(pick(p, 'name', 'Name') || ''),
|
||||
connected: !!pick(p, 'connected', 'Connected'),
|
||||
revoked: !!pick(p, 'revoked', 'Revoked'),
|
||||
lastSeen: sec(pick(p, 'last_seen', 'LastSeen')),
|
||||
lastLine: sec(pick(p, 'last_line', 'LastLine')),
|
||||
lagMs: Number(pick(p, 'lag_ms', 'LagMS')) || 0,
|
||||
version: String(pick(p, 'version', 'Version') || ''),
|
||||
dropped: Number(pick(p, 'dropped', 'Dropped')) || 0,
|
||||
spool: Number(pick(p, 'spool', 'Spool')) || 0,
|
||||
sources: pick(p, 'sources', 'Sources') || [],
|
||||
location: loc,
|
||||
egress: pick(p, 'egress', 'Egress') || {}
|
||||
};
|
||||
}
|
||||
function fmtLag(ms) {
|
||||
if (!ms || ms < 0) return '0 ms';
|
||||
if (ms < 1000) return Math.round(ms) + ' ms';
|
||||
var s = ms / 1000;
|
||||
if (s < 60) return (s < 10 ? s.toFixed(1) : Math.round(s)) + ' s';
|
||||
if (s < 3600) return Math.round(s / 60) + ' min';
|
||||
return Math.round(s / 3600) + ' h';
|
||||
}
|
||||
function listText(v) { return Array.isArray(v) ? v.join(', ') : (v === undefined || v === null ? '' : String(v)); }
|
||||
function shape(orig, text) {
|
||||
// keep the type the hub sent: arrays stay arrays, strings stay strings
|
||||
if (Array.isArray(orig)) return text.split(/[,\n]+/).map(function (x) { return x.trim(); }).filter(Boolean);
|
||||
return text.trim();
|
||||
}
|
||||
function copy(text) {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
|
||||
return new Promise(function (ok, no) {
|
||||
var ta = el('textarea', { style: { position: 'fixed', opacity: '0' } }); ta.value = text; document.body.appendChild(ta); ta.select();
|
||||
var good = false; try { good = document.execCommand('copy'); } catch (e) { /* none */ }
|
||||
document.body.removeChild(ta); good ? ok() : no(new Error('copy'));
|
||||
});
|
||||
}
|
||||
|
||||
// ---- dialogs (native <dialog>, same look as the unban dialog)
|
||||
function dialog(title, labelId, wide) {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg pr-dlg' + (wide ? ' wide' : ''), 'aria-labelledby': labelId });
|
||||
dlg.appendChild(el('h2', { id: labelId }, title));
|
||||
dlg.addEventListener('close', function () {
|
||||
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
|
||||
if (prev && prev.focus && document.contains(prev)) prev.focus();
|
||||
});
|
||||
dlg.open_ = function () { document.body.appendChild(dlg); if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', ''); };
|
||||
return dlg;
|
||||
}
|
||||
function field(label, input, hint, id) {
|
||||
input.id = id;
|
||||
return el('div', { class: 'pr-field' }, el('label', { for: id }, label), input, hint ? el('small', { class: 'pr-fh' }, hint) : null);
|
||||
}
|
||||
function errBox() { return el('p', { class: 'unban-err', role: 'alert', hidden: true }); }
|
||||
function showErr(box, key) { box.textContent = t(key); box.hidden = false; }
|
||||
|
||||
function composeSnippet(name, token) {
|
||||
var hub = location.origin;
|
||||
return [
|
||||
'services:',
|
||||
' urutau-probe:',
|
||||
' image: ' + PROBE_IMAGE,
|
||||
' command: ["probe"]',
|
||||
' restart: unless-stopped',
|
||||
' group_add: ["4"]',
|
||||
' environment:',
|
||||
' URUTAU_HUB: "' + hub + '"',
|
||||
' URUTAU_PROBE_NAME: "' + name + '"',
|
||||
' URUTAU_PROBE_TOKEN: "' + token + '"',
|
||||
' URUTAU_STATE_DIR: /state',
|
||||
' URUTAU_TRAEFIK_LOG: /logs/traefik/access.log',
|
||||
' URUTAU_AUTH_LOG: /logs/host/auth.log',
|
||||
' URUTAU_FAIL2BAN_LOG: /logs/host/fail2ban.log',
|
||||
' URUTAU_PROBE_LOG: /logs/urutau/probe.log',
|
||||
' URUTAU_EGRESS_LOG: /logs/urutau/egress.log',
|
||||
' URUTAU_ENFORCE_LOG: /logs/enforce/decisions.log',
|
||||
' URUTAU_ENFORCE_UNBAN_LOG: /logs/enforce/unban.log',
|
||||
' volumes:',
|
||||
' - /var/log:/logs/host:ro',
|
||||
' - /data/coolify/proxy/logs:/logs/traefik:ro',
|
||||
' - /var/log/urutau:/logs/urutau:ro',
|
||||
' - /etc/resolv.conf:/etc/resolv.conf:ro',
|
||||
' - /var/log/urutau-enforce:/logs/enforce',
|
||||
' - urutau-probe-state:/state',
|
||||
'volumes:',
|
||||
' urutau-probe-state:',
|
||||
''
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function tokenDialog(name, token, done) {
|
||||
var dlg = dialog(t('pr.tok.title', { name: name }), 'pr-tok-h', true);
|
||||
var msg = el('p', { class: 'pr-note', role: 'status' });
|
||||
var tokIn = el('input', { type: 'text', readonly: true, class: 'mono pr-tok', value: token, 'aria-label': t('pr.tok.label') });
|
||||
tokIn.addEventListener('focus', function () { tokIn.select(); });
|
||||
var cpTok = el('button', { type: 'button', class: 'btn' }, t('pr.tok.copy'));
|
||||
var snip = composeSnippet(name, token);
|
||||
var pre = el('textarea', { class: 'mono pr-snip', readonly: true, rows: '14', spellcheck: 'false', 'aria-label': t('pr.tok.snippet') });
|
||||
pre.value = snip;
|
||||
var cpSnip = el('button', { type: 'button', class: 'btn' }, t('pr.tok.copySnippet'));
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.tok.done'));
|
||||
function doCopy(text, okKey) { copy(text).then(function () { msg.textContent = t(okKey); }, function () { msg.textContent = t('pr.tok.copyFail'); }); }
|
||||
cpTok.addEventListener('click', function () { doCopy(token, 'pr.tok.copied'); });
|
||||
cpSnip.addEventListener('click', function () { doCopy(snip, 'pr.tok.copiedSnippet'); });
|
||||
dlg.appendChild(el('p', { class: 'pr-warn' }, t('pr.tok.warn')));
|
||||
dlg.appendChild(el('label', { for: 'pr-tok', class: 'pr-lbl' }, t('pr.tok.label')));
|
||||
tokIn.id = 'pr-tok';
|
||||
dlg.appendChild(el('div', { class: 'pr-row' }, tokIn, cpTok));
|
||||
dlg.appendChild(el('p', { class: 'pr-lbl' }, t('pr.tok.snippet')));
|
||||
dlg.appendChild(el('small', { class: 'pr-fh' }, t('pr.tok.snippet.hint')));
|
||||
dlg.appendChild(pre);
|
||||
dlg.appendChild(el('div', { class: 'pr-row pr-end' }, cpSnip));
|
||||
dlg.appendChild(msg);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, ok));
|
||||
dlg.addEventListener('cancel', function (e) { e.preventDefault(); }); // Esc must not lose the only copy by accident
|
||||
ok.addEventListener('click', function () { dlg.close(); if (done) done(); });
|
||||
dlg.open_(); tokIn.focus(); tokIn.select();
|
||||
}
|
||||
|
||||
function newDialog(done) {
|
||||
var dlg = dialog(t('pr.new.title'), 'pr-new-h');
|
||||
var name = el('input', { type: 'text', autocomplete: 'off', maxlength: '64', spellcheck: 'false', class: 'mono' });
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.new.create'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(field(t('pr.new.name'), name, t('pr.new.hint'), 'pr-new-name'));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
function go() {
|
||||
var n = name.value.trim();
|
||||
if (!NAME_RE.test(n)) { showErr(err, 'pr.new.invalid'); name.focus(); return; }
|
||||
ok.disabled = true; err.hidden = true;
|
||||
U.apiSend('POST', '/api/v1/probes', { name: n }).then(function (r) {
|
||||
var token = r && (r.token || r.Token);
|
||||
dlg.close();
|
||||
if (!token) { showErr(err, 'pr.new.err'); return; }
|
||||
tokenDialog(n, String(token), done);
|
||||
if (done) done(true);
|
||||
}, function (e) {
|
||||
ok.disabled = false; showErr(err, e && e.status === 409 ? 'pr.new.exists' : 'pr.new.err');
|
||||
});
|
||||
}
|
||||
ok.addEventListener('click', go);
|
||||
name.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); go(); } });
|
||||
dlg.open_(); name.focus();
|
||||
}
|
||||
|
||||
function editDialog(p, done) {
|
||||
var dlg = dialog(t('pr.edit.title', { name: p.name }), 'pr-ed-h', true);
|
||||
var loc = p.location || {};
|
||||
var num = function (v) { return el('input', { type: 'number', step: 'any', inputmode: 'decimal', value: v === undefined || v === null ? '' : String(v) }); };
|
||||
var lat = num(loc.lat), lon = num(loc.lon);
|
||||
var label = el('input', { type: 'text', maxlength: '64', value: loc.label || '' });
|
||||
var eg = p.egress || {};
|
||||
var wl = el('textarea', { rows: '3', spellcheck: 'false', class: 'mono' }); wl.value = listText(eg.workloads !== undefined ? eg.workloads : eg.Workloads);
|
||||
var rs = el('textarea', { rows: '2', spellcheck: 'false', class: 'mono' }); rs.value = listText(eg.resolvers !== undefined ? eg.resolvers : eg.Resolvers);
|
||||
var al = el('textarea', { rows: '2', spellcheck: 'false', class: 'mono' }); al.value = listText(eg.allow !== undefined ? eg.allow : eg.Allow);
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('pr.edit.save'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(el('fieldset', { class: 'pr-fs' }, el('legend', null, t('pr.edit.loc')),
|
||||
el('div', { class: 'pr-grid' }, field(t('pr.edit.lat'), lat, '', 'pr-ed-lat'), field(t('pr.edit.lon'), lon, '', 'pr-ed-lon'), field(t('pr.edit.label'), label, '', 'pr-ed-label'))));
|
||||
dlg.appendChild(el('fieldset', { class: 'pr-fs' }, el('legend', null, t('pr.edit.egress')),
|
||||
field(t('pr.edit.workloads'), wl, t('pr.edit.workloads.hint'), 'pr-ed-wl'),
|
||||
field(t('pr.edit.resolvers'), rs, t('pr.edit.resolvers.hint'), 'pr-ed-rs'),
|
||||
field(t('pr.edit.allow'), al, t('pr.edit.allow.hint'), 'pr-ed-al')));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
ok.addEventListener('click', function () {
|
||||
var body = { egress: { workloads: shape(eg.workloads, wl.value), resolvers: shape(eg.resolvers, rs.value), allow: shape(eg.allow, al.value) }, location: null };
|
||||
if (lat.value.trim() !== '' || lon.value.trim() !== '' || label.value.trim() !== '') {
|
||||
var la = parseFloat(lat.value), lo = parseFloat(lon.value);
|
||||
if (!isFinite(la) || !isFinite(lo) || la < -90 || la > 90 || lo < -180 || lo > 180) { showErr(err, 'pr.edit.badLoc'); return; }
|
||||
body.location = { lat: la, lon: lo };
|
||||
if (label.value.trim()) body.location.label = label.value.trim();
|
||||
}
|
||||
ok.disabled = true; err.hidden = true;
|
||||
U.apiSend('PUT', '/api/v1/probes/' + encodeURIComponent(p.name), body).then(function () {
|
||||
dlg.close(); U.toast(t('pr.edit.done', { name: p.name })); if (done) done();
|
||||
}, function () { ok.disabled = false; showErr(err, 'pr.edit.err'); });
|
||||
});
|
||||
dlg.open_(); lat.focus();
|
||||
}
|
||||
|
||||
function revokeDialog(p, done) {
|
||||
var dlg = dialog(t('pr.rev.title', { name: p.name }), 'pr-rev-h');
|
||||
var err = errBox();
|
||||
var ok = el('button', { type: 'button', class: 'btn pr-danger' }, t('pr.rev.confirm'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('pr.cancel'));
|
||||
dlg.appendChild(el('p', null, t('pr.rev.body')));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
cancel.addEventListener('click', function () { dlg.close(); });
|
||||
ok.addEventListener('click', function () {
|
||||
ok.disabled = true;
|
||||
U.apiSend('DELETE', '/api/v1/probes/' + encodeURIComponent(p.name)).then(function () {
|
||||
dlg.close(); U.toast(t('pr.rev.done', { name: p.name })); if (done) done();
|
||||
}, function () { ok.disabled = false; showErr(err, 'pr.rev.err'); });
|
||||
});
|
||||
dlg.open_(); cancel.focus();
|
||||
}
|
||||
|
||||
// ---- the panel
|
||||
function sourceChips(p) {
|
||||
var box = el('span', { class: 'pr-srcs' });
|
||||
var srcs = Array.isArray(p.sources) ? p.sources : [];
|
||||
if (!srcs.length) { box.appendChild(el('span', { class: 'pr-muted' }, t('pr.src.none'))); return box; }
|
||||
srcs.forEach(function (s) {
|
||||
var st = SRC_STATES.indexOf(s.state) >= 0 ? s.state : 'error';
|
||||
var tone = st === 'following' ? 'ok' : st === 'waiting' ? 'warn' : 'danger';
|
||||
var chip = U.ui.badge(String(s.src || '?') + ' · ' + t('pr.src.' + st), tone);
|
||||
var tip = [String(s.src || ''), t('pr.src.' + st)];
|
||||
if (s.error) tip.push(String(s.error));
|
||||
if (s.lines) tip.push(nf(s.lines));
|
||||
chip.title = tip.join(' · ');
|
||||
box.appendChild(chip);
|
||||
});
|
||||
return box;
|
||||
}
|
||||
|
||||
return (U.probesPanel = function probesPanel() {
|
||||
var body = el('div', { class: 'pr-body' });
|
||||
var leadBox = el('div');
|
||||
var tbody = el('tbody');
|
||||
var thead = el('thead', null, el('tr', null, ['pr.col.probe', 'pr.col.status', 'pr.col.lastLine', 'pr.col.lag', 'pr.col.version', 'pr.col.dropped', 'pr.col.spool', 'pr.col.sources', 'pr.col.actions'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
|
||||
var tbl = el('div', { class: 'tbl-wrap' }, el('table', { class: 'stack tbl-cards pr-table' }, thead, tbody));
|
||||
var emptyBox = el('div');
|
||||
var errNode = el('p', { class: 'unban-err', role: 'alert', hidden: true }, t('pr.err.load'));
|
||||
var addBtn = el('button', { type: 'button', class: 'btn primary' }, t('pr.new'));
|
||||
var node = U.ui.panel({ title: t('pr.title'), hint: t('pr.hint'), actions: addBtn }, leadBox, errNode, tbl, emptyBox);
|
||||
var alive = true, seq = 0;
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
|
||||
function cell(tr, key, content, cls) {
|
||||
var td = el('td', { class: cls || '' }); td.setAttribute('data-label', t(key));
|
||||
td.appendChild(typeof content === 'string' ? document.createTextNode(content) : content); tr.appendChild(td);
|
||||
}
|
||||
function paint(list) {
|
||||
var ps = list.map(norm).filter(function (p) { return p.name; });
|
||||
clear(leadBox); clear(tbody); clear(emptyBox);
|
||||
var live = ps.filter(function (p) { return !p.revoked; });
|
||||
var conn = live.filter(function (p) { return p.connected; }).length;
|
||||
var dropped = 0, queue = 0;
|
||||
live.forEach(function (p) { dropped += p.dropped; queue += p.spool; });
|
||||
var title = !live.length ? t('pr.lead.none') : conn === live.length ? U.pl('pr.lead.all', live.length, { n: nf(live.length) }) : t('pr.lead.some', { a: nf(conn), n: nf(live.length) });
|
||||
leadBox.appendChild(el('p', { class: 'pr-sum' + (live.length && conn < live.length ? ' bad' : '') }, title + (live.length ? '. ' + t('pr.lead.body', { d: nf(dropped), q: U.fmt.bytes(queue) }) : '')));
|
||||
tbl.hidden = !ps.length;
|
||||
if (!ps.length) emptyBox.appendChild(U.ui.empty(t('pr.empty'), t('pr.empty.sub')));
|
||||
ps.forEach(function (p) {
|
||||
var tr = el('tr', { class: p.revoked ? 'pr-revoked' : '' });
|
||||
var nm = el('span', { class: 'pr-name' }, el('strong', null, p.name));
|
||||
if (p.location && (p.location.label || p.location.lat !== undefined)) nm.appendChild(el('small', { class: 'pr-muted' }, p.location.label ? String(p.location.label) : p.location.lat + ', ' + p.location.lon));
|
||||
cell(tr, 'pr.col.probe', nm);
|
||||
cell(tr, 'pr.col.status', p.revoked ? U.ui.badge(t('pr.st.revoked'), 'neutral') : p.connected ? U.ui.badge(t('pr.st.connected'), 'ok') : U.ui.badge(t('pr.st.offline'), 'danger'), 'nw');
|
||||
cell(tr, 'pr.col.lastLine', p.lastLine ? U.fmt.ago(p.lastLine) : (p.lastSeen && !p.connected ? U.fmt.ago(p.lastSeen) : t('never')), 'nw');
|
||||
cell(tr, 'pr.col.lag', p.connected ? fmtLag(p.lagMs) : '-', 'nw');
|
||||
cell(tr, 'pr.col.version', p.version || '-', 'nw');
|
||||
cell(tr, 'pr.col.dropped', el('span', { class: 'num' + (p.dropped ? ' pr-warnv' : '') }, nf(p.dropped)), 'nw');
|
||||
cell(tr, 'pr.col.spool', el('span', { class: 'num' }, U.fmt.bytes(p.spool)), 'nw');
|
||||
cell(tr, 'pr.col.sources', sourceChips(p));
|
||||
var acts = el('span', { class: 'pr-acts' });
|
||||
if (!p.revoked) {
|
||||
var ed = el('button', { type: 'button', class: 'btn pr-sm', 'aria-label': t('pr.edit') + ' ' + p.name }, t('pr.edit'));
|
||||
ed.addEventListener('click', function () { editDialog(p, reload); });
|
||||
var rv = el('button', { type: 'button', class: 'btn pr-sm pr-danger', 'aria-label': t('pr.revoke') + ' ' + p.name }, t('pr.revoke'));
|
||||
rv.addEventListener('click', function () { revokeDialog(p, reload); });
|
||||
acts.appendChild(ed); acts.appendChild(rv);
|
||||
}
|
||||
cell(tr, 'pr.col.actions', acts);
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
}
|
||||
function reload() {
|
||||
var my = ++seq;
|
||||
return U.api('/api/v1/probes').then(function (r) {
|
||||
if (!alive || my !== seq) return;
|
||||
errNode.hidden = true;
|
||||
paint(Array.isArray(r) ? r : (r && (r.probes || r.items)) || []);
|
||||
}, function () { if (alive && my === seq) errNode.hidden = false; });
|
||||
}
|
||||
addBtn.addEventListener('click', function () { newDialog(function () { reload(); }); });
|
||||
return { node: node, reload: reload, dispose: function () { alive = false; } };
|
||||
}) && true;
|
||||
}
|
||||
|
||||
function start() { if (!boot()) setTimeout(start, 50); }
|
||||
start();
|
||||
})();
|
||||
@@ -50,6 +50,7 @@
|
||||
'rp.only': 'Incidents only',
|
||||
'rp.select': 'Select segment',
|
||||
'rp.loopclear': 'Clear segment',
|
||||
'rp.repeat': 'Repeat',
|
||||
'rp.loop': 'Looping {a} to {b}',
|
||||
'rp.share': 'Copy link',
|
||||
'rp.copied': 'Link copied',
|
||||
@@ -145,6 +146,7 @@
|
||||
'rp.only': 'Só incidentes',
|
||||
'rp.select': 'Selecionar trecho',
|
||||
'rp.loopclear': 'Limpar trecho',
|
||||
'rp.repeat': 'Repetir',
|
||||
'rp.loop': 'Repetindo de {a} a {b}',
|
||||
'rp.share': 'Copiar link',
|
||||
'rp.copied': 'Link copiado',
|
||||
@@ -266,6 +268,7 @@
|
||||
next: ['M16.5 5H19v14h-2.5z|M5 5.5v13L14.5 12z', 1],
|
||||
stepb: ['M16 5.5v13L7 12z', 1],
|
||||
stepf: ['M8 5.5v13L17 12z', 1],
|
||||
repeat: ['M17 2l4 4-4 4|M3 11V9a3 3 0 0 1 3-3h15|M7 22l-4-4 4-4|M21 13v2a3 3 0 0 1-3 3H3', 0],
|
||||
restart: ['M4 4v6h6|M5.5 15a8 8 0 1 0 2-8L4 10', 0],
|
||||
share: ['M4 12v7h16v-7|M12 3v12|M8 7l4-4 4 4', 0],
|
||||
seg: ['M4 8v8|M20 8v8|M4 12h16', 0],
|
||||
@@ -307,7 +310,8 @@
|
||||
var from = 0, to = 0, tooBig = false, routeT = '', noReg = false, campStarted = false, campId = '', campIps = null;
|
||||
var F = { cat: '', fam: '', q: '', host: '' };
|
||||
var speed = 60, compress = false, only = false;
|
||||
var playing = false, ended = false;
|
||||
var playing = false, ended = false, repeat = false;
|
||||
try { repeat = localStorage.getItem('urutau.replay.repeat') === '1'; } catch (x) { /* storage blocked */ }
|
||||
var clock = 0;
|
||||
var buf = [], idx = 0, nextTok = null, loading = false, epoch = 0, startFrom = 0, firstBatch = true, landBefore = null;
|
||||
var failed = false, drained = false;
|
||||
@@ -676,7 +680,7 @@
|
||||
clockDirty = true; tlDirty = true;
|
||||
if (buf.length - idx < AHEAD && !drained && !loading) fetchMore();
|
||||
if (loop && clock > loop.b) { seek(loop.a); return; }
|
||||
if (clock >= to && idx >= buf.length && drained) { playing = false; ended = true; syncPlay(); }
|
||||
if (clock >= to && idx >= buf.length && drained) { playing = false; ended = true; syncPlay(); if (repeat) restart(); }
|
||||
trim();
|
||||
}
|
||||
function trim() {
|
||||
@@ -861,10 +865,15 @@
|
||||
ui.compB = toggle(t('rp.compress'), function () { compress = !compress; syncToggles(); writeHash(true); });
|
||||
ui.onlyB = toggle(t('rp.only'), function () { only = !only; syncToggles(); refilter(); });
|
||||
ui.selB = toggle(t('rp.select'), function () { selecting = !selecting; if (!selecting && loop) { loop = null; tlDirty = true; } syncToggles(); kick(); });
|
||||
ui.repB = btn('rp-rep rp-tog', 'repeat', t('rp.repeat'), function () {
|
||||
repeat = !repeat; syncToggles();
|
||||
try { localStorage.setItem('urutau.replay.repeat', repeat ? '1' : '0'); } catch (x) { /* storage blocked */ }
|
||||
if (repeat && ended) restart();
|
||||
});
|
||||
ui.shareB = btn('rp-share', 'share', t('rp.share'), function () { share(); });
|
||||
ui.detB = h('button', 'btn rp-det', t('rp.detail')); ui.detB.type = 'button';
|
||||
ui.detB.addEventListener('click', function () { openSheet(); });
|
||||
[ui.prevB, ui.stepbB, ui.playB, ui.stepfB, ui.nextB, ui.clock, ui.speedSeg, ui.speedSel, ui.compB, ui.onlyB, ui.selB, ui.shareB, ui.detB].forEach(function (n) { tr.appendChild(n); });
|
||||
[ui.prevB, ui.stepbB, ui.playB, ui.stepfB, ui.nextB, ui.clock, ui.speedSeg, ui.speedSel, ui.compB, ui.onlyB, ui.selB, ui.repB, ui.shareB, ui.detB].forEach(function (n) { tr.appendChild(n); });
|
||||
ui.loopNote = h('span', 'rp-loopnote'); tr.appendChild(ui.loopNote);
|
||||
|
||||
var tw = h('div', 'rp-tl');
|
||||
@@ -939,6 +948,7 @@
|
||||
function syncToggles() {
|
||||
ui.compB.setAttribute('aria-pressed', compress ? 'true' : 'false');
|
||||
ui.onlyB.setAttribute('aria-pressed', only ? 'true' : 'false');
|
||||
ui.repB.setAttribute('aria-pressed', repeat ? 'true' : 'false');
|
||||
ui.selB.setAttribute('aria-pressed', selecting ? 'true' : 'false');
|
||||
ui.selB.textContent = loop ? t('rp.loopclear') : t('rp.select');
|
||||
ui.loopNote.textContent = loop ? t('rp.loop', { a: clockStr(loop.a), b: clockStr(loop.b) }) : '';
|
||||
|
||||
@@ -690,3 +690,12 @@ html, body { overflow-x: clip; }
|
||||
table.mc td[colspan] { display: block; text-align: left; }
|
||||
}
|
||||
@media (max-width: 767px) { table.mc .mc-v { min-width: 0; overflow-wrap: anywhere; word-break: normal; } }
|
||||
|
||||
/* ---------------------------------------------------------------- IP addresses never wrap (class set by tagIPs() in app.js) */
|
||||
.ipv, td .ipv, table.mc td .ipv, table.mc .mc-v .ipv, td.nw .ipv {
|
||||
white-space: nowrap !important; overflow-wrap: normal !important; word-break: normal !important; hyphens: none;
|
||||
font-family: var(--font-mono); font-size: .875rem; font-variant-numeric: tabular-nums; letter-spacing: 0;
|
||||
max-width: 100%; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom;
|
||||
}
|
||||
.ipv.ipv-long { font-size: .75rem; }
|
||||
@media (max-width: 767px) { .ipv.ipv-long { font-size: .65rem; } }
|
||||
Reference in new issue
Block a user