feat: 1.1.0 interface, geography drill-down and live attack map
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 19s
CI / Tests (Linux, race detector) (push) Successful in 35s
CI / Dependency audit (push) Successful in 16s
Release / ci (push) Successful in 35s
Release / Build image (arm64) (push) Successful in 51s
Release / Build image (amd64) (push) Successful in 1m11s
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 19s
CI / Tests (Linux, race detector) (push) Successful in 35s
CI / Dependency audit (push) Successful in 16s
Release / ci (push) Successful in 35s
Release / Build image (arm64) (push) Successful in 51s
Release / Build image (amd64) (push) Successful in 1m11s
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Skipped
A new console interface (side rail, seven pages, opening sentence and active slice on every page, IP drawer, light and dark design tokens); a Geography page that drills from the world to a country's regions and cities; a Live page drawing attacks as arcs on a flat map or a globe. Backend: GET /api/v1/geo, GET /api/v1/live/recent, host/src/dst on live events, --location, a strict static file pattern, and live federation through GET /api/v1/peer/stream (peer token only, bounded and sanitized relay on the hub). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff143ec4a2
commit
f4b295f582
37 files changed
+5312
-1000
No files matched your search
+13
-1
@@ -61,6 +61,7 @@ type peerState struct {
|
||||
latency int64
|
||||
version string
|
||||
exports map[string]store.PeerExport
|
||||
live bool
|
||||
}
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
@@ -69,6 +70,10 @@ type Hub struct {
|
||||
Token string
|
||||
Interval time.Duration
|
||||
client *http.Client
|
||||
stream *http.Client // long-lived SSE: no overall timeout, no redirects
|
||||
|
||||
lmu sync.Mutex
|
||||
live liveState
|
||||
|
||||
mu sync.RWMutex
|
||||
state map[string]*peerState
|
||||
@@ -78,6 +83,9 @@ type Hub struct {
|
||||
func NewHub(peers []Peer, token string) *Hub {
|
||||
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
|
||||
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.ResponseHeaderTimeout = 10 * time.Second
|
||||
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
for _, p := range peers {
|
||||
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}}
|
||||
}
|
||||
@@ -186,6 +194,7 @@ func (h *Hub) Run(ctx context.Context) {
|
||||
if len(h.Peers) == 0 {
|
||||
return
|
||||
}
|
||||
h.Stream(ctx)
|
||||
h.Refresh(ctx)
|
||||
t := time.NewTicker(h.Interval)
|
||||
defer t.Stop()
|
||||
@@ -206,11 +215,14 @@ func (h *Hub) Hosts() []store.HostInfo {
|
||||
out := make([]store.HostInfo, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version}
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
|
||||
if e, ok := st.exports["24h"]; ok && st.online {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
if len(s.Hosts) > 0 {
|
||||
hi.Location = s.Hosts[0].Location
|
||||
}
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxLiveLine = 16 << 10 // longest SSE line accepted from a peer
|
||||
maxLiveRate = 50 // events per second accepted from one peer
|
||||
liveBuffer = 500 // events kept for /api/v1/live/recent
|
||||
liveIdle = 70 * time.Second
|
||||
liveBackoff0 = time.Second
|
||||
liveBackoffTo = 60 * time.Second
|
||||
)
|
||||
|
||||
type liveState struct {
|
||||
recent []store.LiveEvent // ring of the newest peer events
|
||||
head int
|
||||
subs map[chan store.LiveEvent]struct{}
|
||||
}
|
||||
|
||||
// Subscribe returns the live events relayed from peers; call stop when done.
|
||||
func (h *Hub) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
ch := make(chan store.LiveEvent, 64)
|
||||
h.lmu.Lock()
|
||||
if h.live.subs == nil {
|
||||
h.live.subs = map[chan store.LiveEvent]struct{}{}
|
||||
}
|
||||
h.live.subs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.subs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Recent returns the newest relayed peer events, newest first.
|
||||
func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
total := len(h.live.recent)
|
||||
out := make([]store.LiveEvent, 0, min(n, total))
|
||||
for i := 0; i < total && len(out) < n; i++ {
|
||||
idx := ((h.live.head-1-i)%total + total) % total
|
||||
out = append(out, h.live.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Hub) publish(e store.LiveEvent) {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
if len(h.live.recent) < liveBuffer {
|
||||
h.live.recent = append(h.live.recent, e)
|
||||
} else {
|
||||
h.live.recent[h.live.head] = e
|
||||
h.live.head = (h.live.head + 1) % liveBuffer
|
||||
}
|
||||
for ch := range h.live.subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default: // slow client: drop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) setLive(name string, v bool) {
|
||||
h.mu.Lock()
|
||||
h.state[name].live = v
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// peerLocation is the location the peer reported in its last export.
|
||||
func (h *Hub) peerLocation(name string) *store.Location {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for _, e := range h.state[name].exports {
|
||||
if len(e.Summary.Hosts) > 0 && e.Summary.Hosts[0].Location != nil {
|
||||
l := *e.Summary.Hosts[0].Location
|
||||
return &l
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stream keeps one live subscription per peer until ctx is done, reconnecting
|
||||
// with an exponential backoff (1 s up to 60 s).
|
||||
func (h *Hub) Stream(ctx context.Context) {
|
||||
for _, p := range h.Peers {
|
||||
go h.streamPeer(ctx, p)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) streamPeer(ctx context.Context, p Peer) {
|
||||
back := liveBackoff0
|
||||
for ctx.Err() == nil {
|
||||
start := time.Now()
|
||||
h.consume(ctx, p)
|
||||
h.setLive(p.Name, false)
|
||||
if time.Since(start) > 2*liveBackoffTo {
|
||||
back = liveBackoff0 // it had been healthy for a while
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(back):
|
||||
}
|
||||
if back *= 2; back > liveBackoffTo {
|
||||
back = liveBackoffTo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errLive = errors.New("live stream refused")
|
||||
|
||||
func (h *Hub) consume(ctx context.Context, p Peer) error {
|
||||
rctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
resp, err := h.stream.Do(req) // no redirects; https is enforced by ParsePeer
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||
return errLive
|
||||
}
|
||||
idle := time.AfterFunc(liveIdle, cancel) // the peer pings every 20 s
|
||||
defer idle.Stop()
|
||||
h.setLive(p.Name, true)
|
||||
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
|
||||
var evName string
|
||||
var tokens = float64(maxLiveRate)
|
||||
last := time.Now()
|
||||
for {
|
||||
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
idle.Reset(liveIdle)
|
||||
line = bytes.TrimRight(line, "\r\n")
|
||||
switch {
|
||||
case bytes.HasPrefix(line, []byte("event:")):
|
||||
evName = strings.TrimSpace(string(line[6:]))
|
||||
case bytes.HasPrefix(line, []byte("data:")) && evName == "ev":
|
||||
now := time.Now()
|
||||
tokens += now.Sub(last).Seconds() * maxLiveRate
|
||||
if tokens > maxLiveRate {
|
||||
tokens = maxLiveRate
|
||||
}
|
||||
last = now
|
||||
if tokens < 1 {
|
||||
continue // over the budget: discard
|
||||
}
|
||||
tokens--
|
||||
var e store.LiveEvent
|
||||
if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) {
|
||||
continue
|
||||
}
|
||||
e.Host = p.Name
|
||||
if e.Dst == nil {
|
||||
e.Dst = h.peerLocation(p.Name)
|
||||
}
|
||||
h.publish(e)
|
||||
case len(line) == 0:
|
||||
evName = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"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/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func fakeStream(t *testing.T, conns *atomic.Int32, body func(w http.ResponseWriter)) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/peer/stream" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer tok" {
|
||||
http.Error(w, "no", 401)
|
||||
return
|
||||
}
|
||||
conns.Add(1)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(200)
|
||||
body(w)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
}
|
||||
|
||||
func ev(data string) string { return "event: ev\ndata: " + data + "\n\n" }
|
||||
|
||||
func TestLiveRelaySanitizesAndDrops(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
big := ev(`{"ip":"1.2.3.4","cat":"scanner","path":"` + strings.Repeat("a", 20000) + `"}`)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, ": connected\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"not-an-ip","cat":"scanner"}`))
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"ok"}`)) // not malicious
|
||||
fmt.Fprint(w, ev(`{"ip":"5.5.5.5","cat":"<script>"}`)) // unknown category
|
||||
fmt.Fprint(w, ev(`{"ip":"6.6.6.6","cat":"exploit","host":"evil","path":"/a\u0001b`+strings.Repeat("x", 500)+`","cc":"brasil","status":99999,"src":{"lat":500,"lon":1},"dst":{"lat":10,"lon":20,"label":"`+strings.Repeat("L", 200)+`"},"extra":"x"}`))
|
||||
fmt.Fprint(w, "event: other\ndata: {\"ip\":\"7.7.7.7\",\"cat\":\"exploit\"}\n\n")
|
||||
fmt.Fprint(w, ev(`{"ip":"8.8.8.8","cat":"scanner","src":{"lat":-8,"lon":-34,"cc":"BR","city":"Recife"}}`))
|
||||
fmt.Fprint(w, big) // over 16 KB: the stream is cut
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ch, stop := h.Subscribe()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
h.Stream(ctx)
|
||||
|
||||
var got []store.LiveEvent
|
||||
for len(got) < 2 {
|
||||
select {
|
||||
case e := <-ch:
|
||||
got = append(got, e)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("only %d events: %+v", len(got), got)
|
||||
}
|
||||
}
|
||||
a, b := got[0], got[1]
|
||||
if a.IP != "6.6.6.6" || a.Host != "edge" || a.Cat != "exploit" || a.CC != "" || a.Status != 0 || a.Src != nil {
|
||||
t.Fatalf("sanitized event %+v", a)
|
||||
}
|
||||
if strings.ContainsRune(a.Path, 1) || len(a.Path) > 240 || a.Dst == nil || len(a.Dst.Label) != 64 {
|
||||
t.Fatalf("strings %q dst %+v", a.Path, a.Dst)
|
||||
}
|
||||
if b.IP != "8.8.8.8" || b.Src == nil || b.Src.City != "Recife" || b.Host != "edge" {
|
||||
t.Fatalf("second %+v", b)
|
||||
}
|
||||
if r := h.Recent(10); len(r) != 2 || r[0].IP != "8.8.8.8" {
|
||||
t.Fatalf("recent %+v", r)
|
||||
}
|
||||
// the oversize line ended the stream: no event from it, and the hub reconnects
|
||||
deadline := time.After(5 * time.Second)
|
||||
for conns.Load() < 2 {
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatalf("no reconnection (%d)", conns.Load())
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.IP == "1.2.3.4" {
|
||||
t.Fatal("oversize line must not become an event")
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveRateLimitAndFlag(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 400; i++ {
|
||||
fmt.Fprint(w, ev(fmt.Sprintf(`{"ip":"9.9.%d.%d","cat":"scanner"}`, i/250, i%250+1)))
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if n := len(h.Recent(500)); n < 40 || n > 120 {
|
||||
t.Fatalf("a burst of 400 must be cut to about 50 (got %d)", n)
|
||||
}
|
||||
if hs := h.Hosts(); len(hs) != 1 || hs[0].Live {
|
||||
// Live also needs the peer to be online (polled); here it never was
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveWithRealPeerServer(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote", Version: "t", Location: &store.Location{Lat: -8, Lon: -35, Label: "Recife"}})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
h.Refresh(ctx)
|
||||
h.Stream(ctx)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
if len(h.Recent(5)) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
r := h.Recent(5)
|
||||
if len(r) == 0 || r[0].Host != "edge" || r[0].IP != "5.5.5.5" || r[0].Dst == nil || r[0].Dst.Label != "Recife" {
|
||||
t.Fatalf("relayed %+v", r)
|
||||
}
|
||||
hs := h.Hosts()
|
||||
if !hs[0].Live || !hs[0].Online || hs[0].Location == nil || hs[0].Location.Label != "Recife" {
|
||||
t.Fatalf("hosts %+v", hs)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user