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
@@ -1,46 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get fetches a peer path with the peer token and decodes the JSON answer.
|
||||
func (h *Hub) Get(ctx context.Context, p Peer, path string, out any) error {
|
||||
_, err := h.get(ctx, p, path, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// PostJSON sends v as JSON to a peer path with the peer token.
|
||||
func (h *Hub) PostJSON(ctx context.Context, p Peer, path string, v any) error {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.URL+path, bytes.NewReader(b))
|
||||
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("Content-Type", "application/json")
|
||||
resp, err := h.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// EgressFor asks the online peers (or one) for their egress analysis of the
|
||||
// window [from, to] (unix seconds). The raw answers are untrusted: the caller
|
||||
// decodes and sanitizes them.
|
||||
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
|
||||
out := map[string]json.RawMessage{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st != nil && st.online
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
var raw json.RawMessage
|
||||
if _, err := h.get(ctx, p, fmt.Sprintf("/api/v1/peer/egress?from=%d&to=%d", from, to), &raw); err != nil {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
out[p.Name] = raw
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package fed
|
||||
|
||||
import "time"
|
||||
|
||||
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
|
||||
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
|
||||
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
|
||||
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
|
||||
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
|
||||
}
|
||||
|
||||
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
|
||||
func (h *Hub) WaitStream() { h.swg.Wait() }
|
||||
+178
-343
@@ -1,287 +1,139 @@
|
||||
// Package fed lets one instance aggregate the summaries of other instances.
|
||||
// Package fed aggregates the nodes of the hub: one node per probe, each with
|
||||
// its own store, served in process through the Backend interface.
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sort"
|
||||
"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
|
||||
// Backend is one probe node seen from the aggregation layer.
|
||||
type Backend interface {
|
||||
Name() string
|
||||
Export(rg store.Range) store.PeerExport
|
||||
Study(q store.PeriodQuery) store.PeerStudy
|
||||
Egress(from, to int64) json.RawMessage
|
||||
Subscribe() (<-chan store.LiveEvent, func())
|
||||
SubscribeVisits() (<-chan store.VisitMsg, func())
|
||||
// Online reports whether the probe is connected. The data of an offline
|
||||
// node is still served (it lives in the hub).
|
||||
Online() bool
|
||||
Location() *store.Location
|
||||
}
|
||||
|
||||
// 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
|
||||
extra map[string]*extraExport // on-demand windows
|
||||
studies map[string]*studyCached
|
||||
live bool
|
||||
}
|
||||
|
||||
// extraExport is an export of a window outside the background set.
|
||||
type extraExport struct {
|
||||
at time.Time
|
||||
e store.PeerExport
|
||||
// HostStatus is implemented by backends that know more than Online (version,
|
||||
// last contact, lag); Hosts uses it when present.
|
||||
type HostStatus interface {
|
||||
HostInfo() store.HostInfo
|
||||
}
|
||||
|
||||
const (
|
||||
extraTTL = 15 * time.Second
|
||||
extraMax = 12 // cached on-demand exports per peer
|
||||
exportTTL = 5 * time.Second
|
||||
studyTTL = 30 * time.Second
|
||||
cacheMax = 24
|
||||
liveBuf = 500
|
||||
)
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
type cached[T any] struct {
|
||||
at time.Time
|
||||
v T
|
||||
}
|
||||
|
||||
// Hub merges the backends supplied by Provider.
|
||||
type Hub struct {
|
||||
Peers []Peer
|
||||
Token string
|
||||
Interval time.Duration
|
||||
client *http.Client
|
||||
stream *http.Client // long-lived SSE: no overall timeout, no redirects
|
||||
Provider func() []Backend
|
||||
|
||||
swg sync.WaitGroup // live stream goroutines
|
||||
lmu sync.Mutex
|
||||
live liveState
|
||||
mu sync.Mutex
|
||||
exports map[string]cached[store.PeerExport]
|
||||
studies map[string]cached[store.PeerStudy]
|
||||
|
||||
mu sync.RWMutex
|
||||
state map[string]*peerState
|
||||
|
||||
// OnLive, when set, sees every sanitized peer event before it is published
|
||||
// (it assigns the local id and registers it in the event log).
|
||||
OnLive func(*store.LiveEvent)
|
||||
lmu sync.Mutex
|
||||
recent []store.LiveEvent
|
||||
head int
|
||||
subs map[chan store.LiveEvent]struct{}
|
||||
vsubs map[chan store.VisitMsg]struct{}
|
||||
attach map[string]func() // backend name -> stop
|
||||
}
|
||||
|
||||
// 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{}}
|
||||
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{}, extra: map[string]*extraExport{}}
|
||||
}
|
||||
return h
|
||||
// NewHub creates a hub over the backends returned by provider (called on every use).
|
||||
func NewHub(provider func() []Backend) *Hub {
|
||||
return &Hub{Provider: provider, exports: map[string]cached[store.PeerExport]{}, studies: map[string]cached[store.PeerStudy]{},
|
||||
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
|
||||
}
|
||||
|
||||
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
|
||||
func (h *Hub) backends(only string) []Backend {
|
||||
if h == nil || h.Provider == nil {
|
||||
return nil
|
||||
}
|
||||
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.BackgroundRanges {
|
||||
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()
|
||||
}
|
||||
|
||||
// fetchRange asks a peer for the export of a window and sanitizes it.
|
||||
func (h *Hub) fetchRange(ctx context.Context, p Peer, rg store.Range) (store.PeerExport, error) {
|
||||
var e store.PeerExport
|
||||
path := "/api/v1/peer/export?range=" + url.QueryEscape(rg.Name)
|
||||
if rg.Custom() {
|
||||
path = fmt.Sprintf("/api/v1/peer/export?from=%d&to=%d", rg.From, rg.To)
|
||||
}
|
||||
if _, err := h.get(ctx, p, path, &e); err != nil {
|
||||
return e, err
|
||||
}
|
||||
if err := e.SanitizeRange(rg); err != nil {
|
||||
return e, err
|
||||
}
|
||||
e.Summary = rename(e.Summary, p.Name)
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// exportsFor returns the exports of the online peers (or one) for a window:
|
||||
// the cached background ones, or an on-demand fetch cached for 15 s.
|
||||
func (h *Hub) exportsFor(ctx context.Context, rg store.Range, only string) map[string]store.PeerExport {
|
||||
out := map[string]store.PeerExport{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
all := h.Provider()
|
||||
out := make([]Backend, 0, len(all))
|
||||
for _, b := range all {
|
||||
if only == "" || only == b.Name() {
|
||||
out = append(out, b)
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st.online
|
||||
var cached *store.PeerExport
|
||||
if !rg.Custom() {
|
||||
if e, ok := st.exports[rg.Name]; ok {
|
||||
cached = &e
|
||||
}
|
||||
}
|
||||
if cached == nil {
|
||||
if x := st.extra[rg.Key()]; x != nil && time.Since(x.at) < extraTTL {
|
||||
e := x.e
|
||||
cached = &e
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
if cached != nil {
|
||||
out[p.Name] = *cached
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
e, err := h.fetchRange(ctx, p, rg)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if len(st.extra) >= extraMax {
|
||||
st.extra = map[string]*extraExport{}
|
||||
}
|
||||
st.extra[rg.Key()] = &extraExport{at: time.Now(), e: e}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[p.Name] = e
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
||||
return out
|
||||
}
|
||||
|
||||
// SummariesFor returns the summaries of online peers for any window.
|
||||
// PeerNames lists the names of the nodes (nil-safe).
|
||||
func (h *Hub) PeerNames() []string {
|
||||
var out []string
|
||||
for _, b := range h.backends("") {
|
||||
out = append(out, b.Name())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Has reports whether name is a node served by this hub.
|
||||
func (h *Hub) Has(name string) bool { return len(h.backends(name)) > 0 }
|
||||
|
||||
func (h *Hub) export(b Backend, rg store.Range) (store.PeerExport, bool) {
|
||||
key := b.Name() + "|" + rg.Key()
|
||||
h.mu.Lock()
|
||||
if c, ok := h.exports[key]; ok && time.Since(c.at) < exportTTL {
|
||||
h.mu.Unlock()
|
||||
return c.v, true
|
||||
}
|
||||
h.mu.Unlock()
|
||||
e := b.Export(rg)
|
||||
if err := e.SanitizeRange(rg); err != nil {
|
||||
return e, false
|
||||
}
|
||||
e.Summary = rename(e.Summary, b.Name())
|
||||
h.mu.Lock()
|
||||
if len(h.exports) >= cacheMax {
|
||||
h.exports = map[string]cached[store.PeerExport]{}
|
||||
}
|
||||
h.exports[key] = cached[store.PeerExport]{time.Now(), e}
|
||||
h.mu.Unlock()
|
||||
return e, true
|
||||
}
|
||||
|
||||
// SummariesFor returns the summaries of the nodes (or one) for any window.
|
||||
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
|
||||
m := h.exportsFor(ctx, rg, only)
|
||||
var out []store.Summary
|
||||
for _, p := range h.Peers {
|
||||
if e, ok := m[p.Name]; ok {
|
||||
for _, b := range h.backends(only) {
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
out = append(out, e.Summary)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TrafficFor returns the analytics of online peers for any window and domain.
|
||||
// TrafficFor returns the analytics of the nodes (or one) for a window and domain.
|
||||
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
|
||||
m := h.exportsFor(ctx, rg, only)
|
||||
var out []store.TrafficData
|
||||
for _, p := range h.Peers {
|
||||
if e, ok := m[p.Name]; ok {
|
||||
for _, b := range h.backends(only) {
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
if t, ok := e.Traffic[domain]; ok {
|
||||
t.Host = p.Name
|
||||
t.Host = b.Name()
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
@@ -289,7 +141,17 @@ func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only strin
|
||||
return out
|
||||
}
|
||||
|
||||
// rename forces the configured peer name on every row of a remote summary.
|
||||
// Summaries is SummariesFor for a named range.
|
||||
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
|
||||
return h.SummariesFor(context.Background(), store.ParseRange(rangeName), only)
|
||||
}
|
||||
|
||||
// Traffic is TrafficFor for a named range.
|
||||
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
|
||||
return h.TrafficFor(context.Background(), store.ParseRange(rangeName), domain, only)
|
||||
}
|
||||
|
||||
// rename forces the node name on every row of a summary.
|
||||
func rename(s store.Summary, name string) store.Summary {
|
||||
s.Host = name
|
||||
for i := range s.Hosts {
|
||||
@@ -307,96 +169,13 @@ func rename(s store.Summary, name string) store.Summary {
|
||||
return s
|
||||
}
|
||||
|
||||
// Run refreshes until ctx is done.
|
||||
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()
|
||||
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, 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)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// Peers lists the configured peer names (nil-safe).
|
||||
func (h *Hub) PeerNames() []string {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
out = append(out, p.Name)
|
||||
}
|
||||
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
|
||||
// 30-day summary, which carries the full row). No request is made to the peer.
|
||||
// IPDetail looks an address up in the 30-day export of every node.
|
||||
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["30d"]
|
||||
if !ok || !st.online {
|
||||
rg := store.ParseRange("30d")
|
||||
for _, b := range h.backends("") {
|
||||
e, ok := h.export(b, rg)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, x := range e.Summary.IPs {
|
||||
@@ -409,22 +188,78 @@ func (h *Hub) IPDetail(ip string) []store.IPSummary {
|
||||
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 {
|
||||
// Hosts lists the status of every node (online or not).
|
||||
func (h *Hub) Hosts() []store.HostInfo {
|
||||
rg := store.ParseRange("24h")
|
||||
var out []store.HostInfo
|
||||
for _, b := range h.backends("") {
|
||||
hi := store.HostInfo{Name: b.Name(), Online: b.Online(), Live: b.Online(), Location: b.Location()}
|
||||
if hs, ok := b.(HostStatus); ok {
|
||||
hi = hs.HostInfo()
|
||||
hi.Name = b.Name()
|
||||
}
|
||||
if e, ok := h.export(b, rg); ok {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
if hi.Location == nil && len(s.Hosts) > 0 {
|
||||
hi.Location = s.Hosts[0].Location
|
||||
}
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func studyKey(q store.PeriodQuery) string {
|
||||
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
|
||||
}
|
||||
|
||||
// StudiesFor returns the period and metrics study of every node (or one).
|
||||
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
|
||||
out := map[string]store.PeerStudy{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, b := range h.backends(only) {
|
||||
key := b.Name() + "|" + studyKey(q)
|
||||
h.mu.Lock()
|
||||
c, hit := h.studies[key]
|
||||
h.mu.Unlock()
|
||||
if hit && time.Since(c.at) < studyTTL {
|
||||
out[b.Name()] = c.v
|
||||
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)
|
||||
wg.Add(1)
|
||||
go func(b Backend) {
|
||||
defer wg.Done()
|
||||
pq := q
|
||||
pq.Host = b.Name()
|
||||
s := b.Study(pq)
|
||||
if !s.Sanitize(b.Name()) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
if len(h.studies) >= cacheMax {
|
||||
h.studies = map[string]cached[store.PeerStudy]{}
|
||||
}
|
||||
h.studies[key] = cached[store.PeerStudy]{time.Now(), s}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[b.Name()] = s
|
||||
mu.Unlock()
|
||||
}(b)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
|
||||
// EgressFor returns the egress report of every node (or one) for [from, to];
|
||||
// nodes without egress analysis are left out.
|
||||
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
|
||||
out := map[string]json.RawMessage{}
|
||||
for _, b := range h.backends(only) {
|
||||
if raw := b.Egress(from, to); len(raw) > 0 {
|
||||
out[b.Name()] = raw
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
+32
-150
@@ -1,168 +1,50 @@
|
||||
package fed_test
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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 TestPeerPollingMergeAndOffline(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote-self-name", Version: "t"})
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
|
||||
p, err := fed.ParsePeer("hostinger=" + srv.URL + "/")
|
||||
if err != nil || p.Name != "hostinger" {
|
||||
t.Fatal(p, err)
|
||||
}
|
||||
for _, bad := range []string{"nourl", "=http://x", "a=ftp://x", "a=", "a=http://example.org", "a=http://10.0.0.5:8790", "a=https://user:pw@example.org"} {
|
||||
if _, err := fed.ParsePeer(bad); err == nil {
|
||||
t.Errorf("%q must be rejected", bad)
|
||||
}
|
||||
}
|
||||
|
||||
good := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
good.Refresh(context.Background())
|
||||
sums := good.Summaries("24h", "")
|
||||
if len(sums) != 1 || sums[0].Host != "hostinger" || sums[0].IPs[0].Hosts[0] != "hostinger" || sums[0].IPs[0].IP != "5.5.5.5" {
|
||||
t.Fatalf("summaries %+v", sums)
|
||||
}
|
||||
if h := good.Hosts(); !h[0].Online || h[0].Name != "hostinger" {
|
||||
t.Fatalf("hosts %+v", h)
|
||||
}
|
||||
if d := good.IPDetail("5.5.5.5"); len(d) != 1 || d[0].Hosts[0] != "hostinger" {
|
||||
t.Fatalf("ip detail from the cached export: %v", d)
|
||||
}
|
||||
if tr := good.Traffic("24h", "all", ""); len(tr) != 1 || tr[0].Requests != 1 || tr[0].Host != "hostinger" {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
if tr := good.Traffic("24h", "a.example", "hostinger"); len(tr) != 1 || tr[0].Requests != 1 {
|
||||
t.Fatalf("per-domain traffic %+v", tr)
|
||||
}
|
||||
|
||||
bad := fed.NewHub([]fed.Peer{p}, "wrong")
|
||||
bad.Refresh(context.Background())
|
||||
if h := bad.Hosts(); h[0].Online || h[0].Error == "" || len(bad.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("wrong token must mark the peer offline: %+v", h)
|
||||
}
|
||||
|
||||
srv.Close()
|
||||
good.Refresh(context.Background())
|
||||
if h := good.Hosts(); h[0].Online || len(good.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("closed peer must be offline: %+v", h)
|
||||
}
|
||||
type fake struct {
|
||||
name string
|
||||
online bool
|
||||
}
|
||||
|
||||
func TestHubOnlyAsksForTheExportAndRefusesHostileResponses(t *testing.T) {
|
||||
var paths []string
|
||||
var huge atomic.Bool
|
||||
var redirects atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
redirects.Add(1)
|
||||
w.Write([]byte("{}"))
|
||||
}))
|
||||
defer target.Close()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path)
|
||||
switch {
|
||||
case r.URL.Query().Get("redirect") == "1":
|
||||
case huge.Load():
|
||||
w.Write([]byte(`{"v":1,"pad":"` + strings.Repeat("x", 9<<20) + `"}`))
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, target.URL+"/x", http.StatusFound)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
p := fed.Peer{Name: "evil", URL: srv.URL}
|
||||
func (f fake) Name() string { return f.name }
|
||||
func (f fake) Export(rg store.Range) store.PeerExport {
|
||||
return store.PeerExport{V: store.ExportVersion, Summary: store.Summary{Host: f.name, Hosts: []store.HostInfo{{Name: f.name, Self: true}}}, Traffic: map[string]store.TrafficData{}}
|
||||
}
|
||||
func (f fake) Study(q store.PeriodQuery) store.PeerStudy { return store.PeerStudy{} }
|
||||
func (f fake) Egress(a, b int64) json.RawMessage { return json.RawMessage(`{"findings":[]}`) }
|
||||
func (f fake) Subscribe() (<-chan store.LiveEvent, func()) {
|
||||
return make(chan store.LiveEvent), func() {}
|
||||
}
|
||||
func (f fake) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
return make(chan store.VisitMsg), func() {}
|
||||
}
|
||||
func (f fake) Online() bool { return f.online }
|
||||
func (f fake) Location() *store.Location { return nil }
|
||||
|
||||
h := fed.NewHub([]fed.Peer{p}, "t")
|
||||
h.Refresh(context.Background())
|
||||
if redirects.Load() != 0 {
|
||||
t.Fatal("redirects must not be followed")
|
||||
func TestHubServesBackendsEvenOffline(t *testing.T) {
|
||||
h := NewHub(func() []Backend { return []Backend{fake{"b", false}, fake{"a", true}} })
|
||||
if got := h.PeerNames(); len(got) != 2 || got[0] != "a" || !h.Has("b") || h.Has("c") {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if st := h.Hosts()[0]; st.Online {
|
||||
t.Fatalf("a redirect is a failure: %+v", st)
|
||||
rg := store.ParseRange("24h")
|
||||
if s := h.SummariesFor(context.Background(), rg, ""); len(s) != 2 || s[0].Host != "a" || s[0].Hosts[0].Self {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
huge.Store(true)
|
||||
h.Refresh(context.Background())
|
||||
if st := h.Hosts()[0]; st.Online || !strings.Contains(st.Error, "larger") {
|
||||
t.Fatalf("an oversized response must be refused: %+v", st)
|
||||
if s := h.SummariesFor(context.Background(), rg, "b"); len(s) != 1 {
|
||||
t.Fatalf("only: %+v", s)
|
||||
}
|
||||
for _, path := range paths {
|
||||
if path != "/api/v1/peer/export" {
|
||||
t.Fatalf("the hub asked for %s", path)
|
||||
}
|
||||
hosts := h.Hosts()
|
||||
if len(hosts) != 2 || hosts[0].Online != true || hosts[1].Online != false {
|
||||
t.Fatalf("%+v", hosts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubBoundsAnInflatedPeer(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
var e store.PeerExport
|
||||
e.V = 1
|
||||
e.Summary.Version = strings.Repeat("v", 5000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "1.2.3." + "4", Score: 1, Samples: make([]string, 40), Hosts: make([]string, 40)})
|
||||
}
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "not an ip", Score: 1e9})
|
||||
e.Summary.Timeline.Series = map[string][]uint32{"exploit": make([]uint32, 100000), "evil": make([]uint32, 10)}
|
||||
for i := 0; i < 200; i++ {
|
||||
e.Summary.TopPaths = append(e.Summary.TopPaths, store.Count{Key: strings.Repeat("p", 9000), N: 1})
|
||||
}
|
||||
e.Traffic = map[string]store.TrafficData{}
|
||||
for i := 0; i < 60; i++ {
|
||||
e.Traffic[strings.Repeat("d", i+1)] = store.TrafficData{Timeline: struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Req []uint32 `json:"req"`
|
||||
Pages []uint32 `json:"pages"`
|
||||
}{Req: make([]uint32, 5000)}}
|
||||
}
|
||||
json.NewEncoder(w).Encode(e)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
h := fed.NewHub([]fed.Peer{{Name: "p", URL: srv.URL}}, "t")
|
||||
h.Refresh(context.Background())
|
||||
sums := h.Summaries("1h", "")
|
||||
if len(sums) != 1 {
|
||||
t.Fatalf("hosts %+v", h.Hosts())
|
||||
}
|
||||
s := sums[0]
|
||||
if len(s.IPs) != 500 || len(s.Version) > 32 || len(s.TopPaths) > 50 || len(s.TopPaths[0].Key) > 300 {
|
||||
t.Fatalf("caps not applied: ips=%d version=%d paths=%d", len(s.IPs), len(s.Version), len(s.TopPaths))
|
||||
}
|
||||
for _, x := range s.IPs {
|
||||
if x.IP == "not an ip" || len(x.Samples) > 6 || len(x.Hosts) > 4 {
|
||||
t.Fatalf("bad row survived: %+v", x)
|
||||
}
|
||||
}
|
||||
if len(s.Timeline.Series["exploit"]) != 60 || s.Timeline.Series["evil"] != nil || len(s.Timeline.Series["ok"]) != 60 {
|
||||
t.Fatal("the timeline grid is fixed by the range")
|
||||
}
|
||||
kept := 0
|
||||
for i := 1; i <= 60; i++ {
|
||||
for _, got := range h.Traffic("1h", strings.Repeat("d", i), "") {
|
||||
kept++
|
||||
if len(got.Timeline.Req) != 60 {
|
||||
t.Fatalf("traffic grid must be fixed: %d", len(got.Timeline.Req))
|
||||
}
|
||||
}
|
||||
}
|
||||
if kept > 27 {
|
||||
t.Fatalf("too many domains accepted from a peer: %d", kept)
|
||||
if m := h.EgressFor(context.Background(), 0, 1, ""); len(m) != 2 {
|
||||
t.Fatalf("%v", m)
|
||||
}
|
||||
}
|
||||
+54
-175
@@ -1,52 +1,21 @@
|
||||
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.
|
||||
// SubscribeVisits returns the legitimate visits of the nodes.
|
||||
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.vsubs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.vsubs, ch)
|
||||
delete(h.vsubs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -54,7 +23,7 @@ func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) {
|
||||
func (h *Hub) publishVisit(m store.VisitMsg) {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
for ch := range h.live.vsubs {
|
||||
for ch := range h.vsubs {
|
||||
select {
|
||||
case ch <- m:
|
||||
default:
|
||||
@@ -62,31 +31,28 @@ func (h *Hub) publishVisit(m store.VisitMsg) {
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe returns the live events relayed from peers; call stop when done.
|
||||
// Subscribe returns the live events of the nodes; 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.subs[ch] = struct{}{}
|
||||
h.lmu.Unlock()
|
||||
return ch, func() {
|
||||
h.lmu.Lock()
|
||||
delete(h.live.subs, ch)
|
||||
delete(h.subs, ch)
|
||||
h.lmu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Recent returns the newest relayed peer events, newest first.
|
||||
// Recent returns the newest live events of the nodes, newest first.
|
||||
func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
h.lmu.Lock()
|
||||
defer h.lmu.Unlock()
|
||||
total := len(h.live.recent)
|
||||
total := len(h.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])
|
||||
idx := ((h.head-1-i)%total + total) % total
|
||||
out = append(out, h.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -94,13 +60,13 @@ func (h *Hub) Recent(n int) []store.LiveEvent {
|
||||
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)
|
||||
if len(h.recent) < liveBuf {
|
||||
h.recent = append(h.recent, e)
|
||||
} else {
|
||||
h.live.recent[h.live.head] = e
|
||||
h.live.head = (h.live.head + 1) % liveBuffer
|
||||
h.recent[h.head] = e
|
||||
h.head = (h.head + 1) % liveBuf
|
||||
}
|
||||
for ch := range h.live.subs {
|
||||
for ch := range h.subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default: // slow client: drop
|
||||
@@ -108,143 +74,56 @@ func (h *Hub) publish(e store.LiveEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
// Run keeps the live relay of every node (also those created later) until ctx is done.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
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
|
||||
t := time.NewTicker(time.Second)
|
||||
defer t.Stop()
|
||||
defer func() {
|
||||
h.lmu.Lock()
|
||||
for _, stop := range h.attach {
|
||||
stop()
|
||||
}
|
||||
h.lmu.Unlock()
|
||||
}()
|
||||
for {
|
||||
h.sync(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(back):
|
||||
}
|
||||
if back *= 2; back > liveBackoffTo {
|
||||
back = liveBackoffTo
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// sync starts the relay of the backends that appeared since the last call.
|
||||
func (h *Hub) sync(ctx context.Context) {
|
||||
for _, b := range h.backends("") {
|
||||
h.lmu.Lock()
|
||||
_, ok := h.attach[b.Name()]
|
||||
h.lmu.Unlock()
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
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)
|
||||
}
|
||||
ev, stopEv := b.Subscribe()
|
||||
vis, stopVis := b.SubscribeVisits()
|
||||
cctx, cancel := context.WithCancel(ctx)
|
||||
h.lmu.Lock()
|
||||
h.attach[b.Name()] = func() { cancel(); stopEv(); stopVis() }
|
||||
h.lmu.Unlock()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-cctx.Done():
|
||||
return
|
||||
case e := <-ev:
|
||||
h.publish(e)
|
||||
case v := <-vis:
|
||||
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 = ""
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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 func() { cancel(); h.WaitStream() }()
|
||||
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 func() { cancel(); h.WaitStream() }()
|
||||
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 func() { cancel(); h.WaitStream() }()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveByteFloodDropsConnection(t *testing.T) {
|
||||
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
|
||||
start := time.Now()
|
||||
var conns atomic.Int32
|
||||
pad := strings.Repeat("a", 1000)
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
|
||||
fmt.Fprintf(w, ": %s\n", pad)
|
||||
}
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
// the flood ends the connection (window check), then the hub reconnects after the backoff
|
||||
for conns.Load() < 2 {
|
||||
if time.Since(start) > 2500*time.Millisecond {
|
||||
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n")
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n")
|
||||
fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n")
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
ch, stop := h.SubscribeVisits()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
var got []store.VisitMsg
|
||||
for len(got) < 2 {
|
||||
select {
|
||||
case m := <-ch:
|
||||
got = append(got, m)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("timeout, got %+v", got)
|
||||
}
|
||||
}
|
||||
for _, m := range got {
|
||||
b, _ := json.Marshal(m)
|
||||
if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" {
|
||||
t.Fatalf("relayed %s", b)
|
||||
}
|
||||
}
|
||||
if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 {
|
||||
t.Fatalf("%+v recent=%d", got, len(h.Recent(10)))
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
studyTTL = 30 * time.Second
|
||||
studyMax = 8 // cached studies per peer
|
||||
)
|
||||
|
||||
type studyCached struct {
|
||||
at time.Time
|
||||
s store.PeerStudy
|
||||
}
|
||||
|
||||
func studyKey(q store.PeriodQuery) string {
|
||||
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
|
||||
}
|
||||
|
||||
// StudiesFor asks the online peers (or one) for their period and metrics
|
||||
// study of a window, on demand, cached for 30 s. The answers are sanitized
|
||||
// and carry the configured peer name.
|
||||
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
|
||||
out := map[string]store.PeerStudy{}
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
key := studyKey(q)
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
h.mu.RLock()
|
||||
st := h.state[p.Name]
|
||||
online := st.online
|
||||
var hit *store.PeerStudy
|
||||
if c := st.studies[key]; c != nil && time.Since(c.at) < studyTTL {
|
||||
s := c.s
|
||||
hit = &s
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
if !online {
|
||||
continue
|
||||
}
|
||||
if hit != nil {
|
||||
out[p.Name] = *hit
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
v := url.Values{}
|
||||
v.Set("from", fmt.Sprint(q.From))
|
||||
v.Set("to", fmt.Sprint(q.To))
|
||||
for k, x := range map[string]string{"ip": q.IP, "cat": q.Cat, "fam": q.Fam} {
|
||||
if x != "" {
|
||||
v.Set(k, x)
|
||||
}
|
||||
}
|
||||
if q.Gap > 0 {
|
||||
v.Set("gap", fmt.Sprint(q.Gap))
|
||||
}
|
||||
var s store.PeerStudy
|
||||
if _, err := h.get(ctx, p, "/api/v1/peer/period?"+v.Encode(), &s); err != nil || !s.Sanitize(p.Name) {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if st.studies == nil || len(st.studies) >= studyMax {
|
||||
st.studies = map[string]*studyCached{}
|
||||
}
|
||||
st.studies[key] = &studyCached{time.Now(), s}
|
||||
h.mu.Unlock()
|
||||
mu.Lock()
|
||||
out[p.Name] = s
|
||||
mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"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/evlog"
|
||||
"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 TestHubOnDemandRangesRatesAndOldPeers(t *testing.T) {
|
||||
peerTok := "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
ps := store.New(store.Config{Name: "remote", Version: "t", Retention: 720 * time.Hour})
|
||||
for i := 0; i < 4; i++ {
|
||||
ps.Ingest(core.Event{Time: time.Now().Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
}
|
||||
ps.Ingest(core.Event{Time: time.Now().Add(-10 * 24 * time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Path: "/y", Method: "GET"})
|
||||
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
var calls []string
|
||||
inner := server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: ps})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls = append(calls, r.URL.RawQuery)
|
||||
inner.ServeHTTP(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("hostinger=" + srv.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, peerTok)
|
||||
hub.Refresh(context.Background())
|
||||
if len(calls) != len(store.BackgroundRanges) {
|
||||
t.Fatalf("background fetches: %v", calls)
|
||||
}
|
||||
// a window outside the background set is fetched on demand, then cached
|
||||
rg := store.Ranges["15d"]
|
||||
n := len(calls)
|
||||
sums := hub.SummariesFor(context.Background(), rg, "")
|
||||
if len(sums) != 1 || sums[0].Range.Name != "15d" || sums[0].Totals.Counts["scanner"] != 1 || sums[0].Rates.Last1h != 4 {
|
||||
t.Fatalf("15d %+v", sums)
|
||||
}
|
||||
hub.SummariesFor(context.Background(), rg, "")
|
||||
if len(calls) != n+1 {
|
||||
t.Fatalf("on-demand windows must be cached: %v", calls[n:])
|
||||
}
|
||||
// a custom window goes as from/to
|
||||
now := time.Now().Unix()
|
||||
local := store.New(store.Config{Name: "hub", Retention: 720 * time.Hour})
|
||||
cr, err := local.ResolveRange("", fmt.Sprint(now-3*3600), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs := hub.SummariesFor(context.Background(), cr, "")
|
||||
if len(cs) != 1 || cs[0].Totals.Counts["exploit"] != 4 || !strings.Contains(calls[len(calls)-1], "from=") {
|
||||
t.Fatalf("custom %+v calls %v", cs, calls[len(calls)-1])
|
||||
}
|
||||
if tr := hub.TrafficFor(context.Background(), cr, "all", ""); len(tr) != 1 || tr[0].Requests != 1 {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
if got := hub.IPDetail("6.6.6.6"); len(got) != 1 {
|
||||
t.Fatal("the 30 day export must carry the 10 day old address")
|
||||
}
|
||||
m := store.Merge("all", []store.Summary{local.Summary("24h"), sums[0]})
|
||||
if m.Rates.Last1h != 4 {
|
||||
t.Fatalf("merged rates %+v", m.Rates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldPeerStringRangeStillParses(t *testing.T) {
|
||||
var s store.Summary
|
||||
if err := json.Unmarshal([]byte(`{"range":"24h","host":"x"}`), &s); err != nil || s.Range.Name != "24h" {
|
||||
t.Fatalf("legacy range: %v %+v", err, s.Range)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(`{"range":{"name":"7d","from":1,"to":2,"clipped":true}}`), &s); err != nil || !s.Range.Clipped {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerEventsAreRegisteredWithHostAndLocalID(t *testing.T) {
|
||||
var conns atomic.Int32
|
||||
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
|
||||
fmt.Fprint(w, ev(`{"id":999999,"ip":"6.6.6.6","cat":"exploit","host":"evil","ua":"sqlmap","fam":"vcs","tech":["T1190"],"flags":"SZ!"}`))
|
||||
})
|
||||
defer srv.Close()
|
||||
p, _ := fed.ParsePeer("edge=" + srv.URL)
|
||||
h := fed.NewHub([]fed.Peer{p}, "tok")
|
||||
local := store.New(store.Config{Name: "hub"})
|
||||
l, _ := evlog.Open(evlog.Options{Dir: t.TempDir() + "/events"})
|
||||
local.SetEventLog(l)
|
||||
h.OnLive = local.RecordPeerEvent
|
||||
ch, stop := h.Subscribe()
|
||||
defer stop()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer func() { cancel(); h.WaitStream() }()
|
||||
h.Stream(ctx)
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.Host != "edge" || e.ID == 0 || e.ID == 999999 || e.Flags != "S" {
|
||||
t.Fatalf("relayed %+v", e)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("no event")
|
||||
}
|
||||
pg, _ := local.QueryEvents(store.EventsQuery{From: time.Now().Unix() - 3600, To: time.Now().Unix() + 10, Host: "edge"})
|
||||
if len(pg.Events) != 1 || !strings.Contains(string(pg.Events[0]), `"host":"edge"`) {
|
||||
t.Fatalf("registry %v", pg.Events)
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"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 logged(t *testing.T, name string) *store.Store {
|
||||
s := store.New(store.Config{Name: name, Version: "t", Retention: 720 * time.Hour})
|
||||
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.SetEventLog(l)
|
||||
return s
|
||||
}
|
||||
|
||||
func TestHubMergesPeriodAndMetrics(t *testing.T) {
|
||||
const userTok, peerTok = "main-token-0123456789-abcdefghijklmnopqrs", "peer-secret-0123456789-abcdefghijklmnopqr"
|
||||
peer := logged(t, "hostinger")
|
||||
hubSt := logged(t, "oracle")
|
||||
now := time.Now()
|
||||
for i := 0; i < 4; i++ {
|
||||
peer.Ingest(core.Event{Time: now.Add(-time.Duration(i) * time.Minute), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, Domain: "p.example"})
|
||||
}
|
||||
hubSt.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "6.6.6.6", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/wp-login.php", Status: 404, Domain: "h.example"})
|
||||
// a copy of the peer's event relayed live to the hub must not be counted twice
|
||||
le := store.LiveEvent{FeedEvent: store.FeedEvent{T: now.Unix() - 30, IP: "5.5.5.5", Cat: "exploit", Source: "traefik", Host: "hostinger"}}
|
||||
hubSt.RecordPeerEvent(&le)
|
||||
|
||||
var peerCalls []string
|
||||
pinner := server.New(server.Options{Token: "other-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{peerTok}, Version: "t", Store: peer})
|
||||
psrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
peerCalls = append(peerCalls, r.URL.Path)
|
||||
pinner.ServeHTTP(w, r)
|
||||
}))
|
||||
defer psrv.Close()
|
||||
p, _ := fed.ParsePeer("hostinger=" + psrv.URL)
|
||||
hub := fed.NewHub([]fed.Peer{p}, peerTok)
|
||||
hub.Refresh(context.Background())
|
||||
h := server.New(server.Options{Token: userTok, Version: "t", Store: hubSt, Hub: hub})
|
||||
get := func(path string) map[string]any {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.Header.Set("Authorization", "Bearer "+userTok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
var m map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &m)
|
||||
return m
|
||||
}
|
||||
pd := get("/api/v1/period?range=24h")
|
||||
if pd["sessions_n"].(float64) != 2 || pd["events"].(float64) != 5 {
|
||||
t.Fatalf("merged period: sessions %v events %v (relayed copies must not double count)", pd["sessions_n"], pd["events"])
|
||||
}
|
||||
hosts := map[string]bool{}
|
||||
for _, s := range pd["sessions"].([]any) {
|
||||
hosts[s.(map[string]any)["hosts"].([]any)[0].(string)] = true
|
||||
}
|
||||
if !hosts["oracle"] || !hosts["hostinger"] {
|
||||
t.Fatalf("sessions must carry their host: %v", hosts)
|
||||
}
|
||||
if only := get("/api/v1/period?range=24h&host=hostinger"); only["sessions_n"].(float64) != 1 {
|
||||
t.Fatalf("one peer: %v", only["sessions_n"])
|
||||
}
|
||||
if loc := get("/api/v1/period?range=24h&host=oracle"); loc["sessions_n"].(float64) != 1 {
|
||||
t.Fatalf("local only: %v", loc["sessions_n"])
|
||||
}
|
||||
mt := get("/api/v1/metrics?range=24h")
|
||||
if v := mt["attacks_per_hour_24h"].(map[string]any)["value"].(float64); v < 0.2 || v > 0.3 { // 5 events / 24 h, rounded to 0.1
|
||||
t.Fatalf("merged attacks per hour: %v", v)
|
||||
}
|
||||
n := len(peerCalls)
|
||||
get("/api/v1/period?range=24h")
|
||||
for _, c := range peerCalls[n:] {
|
||||
if c == "/api/v1/peer/period" {
|
||||
t.Fatal("studies are cached for 30 s")
|
||||
}
|
||||
}
|
||||
// the peer route: only the peer token, never the user token
|
||||
for tok, want := range map[string]int{peerTok: 200, "other-token-0123456789-abcdefghijklmnopqrs": 401, "bad": 401} {
|
||||
r := httptest.NewRequest("GET", "/api/v1/peer/period?from=1&to=2", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w := httptest.NewRecorder()
|
||||
pinner.ServeHTTP(w, r)
|
||||
if tok == peerTok {
|
||||
r = httptest.NewRequest("GET", "/api/v1/peer/period?from="+itoa(now.Unix()-3600)+"&to="+itoa(now.Unix()), nil)
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
r.RemoteAddr = "198.51.100.1:1"
|
||||
w = httptest.NewRecorder()
|
||||
pinner.ServeHTTP(w, r)
|
||||
}
|
||||
if w.Code != want {
|
||||
t.Errorf("peer route with %q: %d, want %d", tok[:3], w.Code, want)
|
||||
}
|
||||
}
|
||||
// a hub that is offline for the peer still answers (local + relayed)
|
||||
psrv.Close()
|
||||
hub.Refresh(context.Background())
|
||||
if pd := get("/api/v1/period?range=24h"); pd["sessions_n"].(float64) < 1 {
|
||||
t.Fatal("must answer without the peer")
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int64) string { b, _ := json.Marshal(n); return string(b) }
|
||||
Reference in new issue
Block a user