Files
urutau/internal/fed/fed.go
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
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 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Always-on Go service (stdlib only) that follows the Traefik JSON access
log, the sshd log and the fail2ban log of a host, classifies attacks,
scores sources, keeps bounded aggregates with snapshots, and serves an
embedded dashboard with live updates, offline geolocation (DB-IP Lite),
privacy-friendly traffic analytics, an exportable blocklist and
token-authenticated federation between instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:13:34 -03:00

290 lines
7.0 KiB
Go

// Package fed lets one instance aggregate the summaries of other instances.
package fed
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/netip"
"net/url"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// maxBody caps what a hub accepts from one peer response.
const maxBody = 8 << 20
// Peer is a remote Urutau instance.
type Peer struct {
Name, URL string
// Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_<NAME>).
Token string
}
// ParsePeer parses "name=https://url".
func ParsePeer(s string) (Peer, error) {
name, u, ok := strings.Cut(s, "=")
name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/")
if !ok || name == "" || u == "" {
return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s)
}
pu, err := url.Parse(u)
if err != nil || pu.Host == "" || pu.User != nil {
return Peer{}, fmt.Errorf("peer %q: invalid URL", s)
}
switch {
case pu.Scheme == "https":
case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()):
default:
return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s)
}
return Peer{Name: name, URL: u}, nil
}
func isLoopbackHost(h string) bool {
if h == "localhost" {
return true
}
a, err := netip.ParseAddr(h)
return err == nil && a.IsLoopback()
}
type peerState struct {
online bool
lastOK int64
err string
latency int64
version string
exports map[string]store.PeerExport
}
// Hub polls peers and serves their latest summaries.
type Hub struct {
Peers []Peer
Token string
Interval time.Duration
client *http.Client
mu sync.RWMutex
state map[string]*peerState
}
// NewHub creates a hub; Interval defaults to 15 seconds.
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{}}
for _, p := range peers {
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}}
}
return h
}
func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil)
if err != nil {
return 0, err
}
tok := h.Token
if p.Token != "" {
tok = p.Token
}
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
req.Header.Set("Accept", "application/json")
t := time.Now()
resp, err := h.client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
if err != nil {
return 0, err
}
if len(body) > maxBody {
return 0, fmt.Errorf("response larger than %d bytes", maxBody)
}
if err := json.Unmarshal(body, out); err != nil {
return 0, err
}
return time.Since(t), nil
}
// Refresh fetches every peer once, concurrently. Failures only mark the peer offline.
func (h *Hub) Refresh(ctx context.Context) {
var wg sync.WaitGroup
for _, p := range h.Peers {
wg.Add(1)
go func(p Peer) {
defer wg.Done()
exports := map[string]store.PeerExport{}
var lat time.Duration
var ferr error
for name := range store.Ranges {
var e store.PeerExport
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
if err == nil {
err = e.Sanitize(name)
}
if err != nil {
ferr = err
break
}
lat = d
e.Summary = rename(e.Summary, p.Name)
exports[name] = e
}
h.mu.Lock()
st := h.state[p.Name]
if ferr != nil {
st.online, st.err = false, ferr.Error()
if len(st.err) > 160 {
st.err = st.err[:160]
}
} else {
st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports
for _, e := range exports {
st.version = e.Summary.Version
}
}
h.mu.Unlock()
}(p)
}
wg.Wait()
}
// rename forces the configured peer name on every row of a remote summary.
func rename(s store.Summary, name string) store.Summary {
s.Host = name
for i := range s.Hosts {
s.Hosts[i].Name, s.Hosts[i].Self = name, false
}
for i := range s.IPs {
s.IPs[i].Hosts = []string{name}
}
for i := range s.Recent {
s.Recent[i].Host = name
}
for i := range s.Sources {
s.Sources[i].Host = name
}
return s
}
// Run refreshes until ctx is done.
func (h *Hub) Run(ctx context.Context) {
if len(h.Peers) == 0 {
return
}
h.Refresh(ctx)
t := time.NewTicker(h.Interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
h.Refresh(ctx)
}
}
}
// Hosts lists the status of every peer (online or not).
func (h *Hub) Hosts() []store.HostInfo {
h.mu.RLock()
defer h.mu.RUnlock()
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}
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
}
out = append(out, hi)
}
return out
}
// Summaries returns the summaries of online peers for a range. When only is
// not empty just that peer is returned.
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.Summary
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
st := h.state[p.Name]
if e, ok := st.exports[rangeName]; ok && st.online {
out = append(out, e.Summary)
}
}
return out
}
// Has reports whether name is a configured peer.
func (h *Hub) Has(name string) bool {
for _, p := range h.Peers {
if p.Name == name {
return true
}
}
return false
}
// IPDetail looks an address up in the cached exports of the online peers (the
// 7-day summary, which carries the full row). No request is made to the peer.
func (h *Hub) IPDetail(ip string) []store.IPSummary {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.IPSummary
for _, p := range h.Peers {
st := h.state[p.Name]
e, ok := st.exports["7d"]
if !ok || !st.online {
continue
}
for _, x := range e.Summary.IPs {
if x.IP == ip {
out = append(out, x)
break
}
}
}
return out
}
// Traffic returns the cached analytics of online peers (or only one) for a
// domain ("all" or a name), from the same export.
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
h.mu.RLock()
defer h.mu.RUnlock()
var out []store.TrafficData
for _, p := range h.Peers {
if only != "" && only != p.Name {
continue
}
st := h.state[p.Name]
if e, ok := st.exports[rangeName]; ok && st.online {
if t, ok := e.Traffic[domain]; ok {
t.Host = p.Name
out = append(out, t)
}
}
}
return out
}