Files
urutau/internal/fed/live.go
T
Lucas RayanandClaude Opus 5.5 2ebda1e4d7
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

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

251 lines
6.2 KiB
Go

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
liveBackoffTo = 60 * time.Second
)
// Variables so tests can shrink them.
var (
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
liveByteWindow = 10 * time.Second
liveBackoff0 = time.Second
)
type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept
}
// SubscribeVisits returns the legitimate visits relayed from peers.
func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
ch := make(chan store.VisitMsg, 64)
h.lmu.Lock()
if h.live.vsubs == nil {
h.live.vsubs = map[chan store.VisitMsg]struct{}{}
}
h.live.vsubs[ch] = struct{}{}
h.lmu.Unlock()
return ch, func() {
h.lmu.Lock()
delete(h.live.vsubs, ch)
h.lmu.Unlock()
}
}
func (h *Hub) publishVisit(m store.VisitMsg) {
h.lmu.Lock()
defer h.lmu.Unlock()
for ch := range h.live.vsubs {
select {
case ch <- m:
default:
}
}
}
// 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 {
h.swg.Add(1)
go func() { defer h.swg.Done(); 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?visits=1", 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)
winStart, winBytes := time.Now(), 0
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)
winBytes += len(line)
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
return errLive // a window's worth of budget burned already: flooding
}
if el := time.Since(winStart); el >= liveByteWindow {
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
return errLive // flooding: drop the connection, the backoff applies
}
winStart, winBytes = time.Now(), 0
}
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" || evName == "visit"):
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--
if evName == "visit" {
var v store.VisitMsg
if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) {
v.Host = p.Name
if v.Kind == "visit" && v.Dst == nil {
v.Dst = h.peerLocation(p.Name)
}
h.publishVisit(v)
}
continue
}
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)
}
if h.OnLive != nil {
h.OnLive(&e)
}
h.publish(e)
case len(line) == 0:
evName = ""
}
}
}