feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f1ac462d1
commit
b7462c14fa
325 files changed
+19117
-1307
No files matched your search
+133
-4
@@ -61,9 +61,22 @@ type peerState struct {
|
||||
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
|
||||
}
|
||||
|
||||
const (
|
||||
extraTTL = 15 * time.Second
|
||||
extraMax = 12 // cached on-demand exports per peer
|
||||
)
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
type Hub struct {
|
||||
Peers []Peer
|
||||
@@ -78,6 +91,10 @@ type Hub struct {
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// NewHub creates a hub; Interval defaults to 15 seconds.
|
||||
@@ -88,7 +105,7 @@ func NewHub(peers []Peer, token string) *Hub {
|
||||
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{}}
|
||||
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}, extra: map[string]*extraExport{}}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -139,7 +156,7 @@ func (h *Hub) Refresh(ctx context.Context) {
|
||||
exports := map[string]store.PeerExport{}
|
||||
var lat time.Duration
|
||||
var ferr error
|
||||
for name := range store.Ranges {
|
||||
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 {
|
||||
@@ -172,6 +189,106 @@ func (h *Hub) Refresh(ctx context.Context) {
|
||||
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
|
||||
}
|
||||
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()
|
||||
return out
|
||||
}
|
||||
|
||||
// SummariesFor returns the summaries of online peers 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 {
|
||||
out = append(out, e.Summary)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TrafficFor returns the analytics of online peers for any 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 {
|
||||
if t, ok := e.Traffic[domain]; ok {
|
||||
t.Host = p.Name
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -248,6 +365,18 @@ func (h *Hub) Summaries(rangeName, only string) []store.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 {
|
||||
@@ -259,14 +388,14 @@ func (h *Hub) Has(name string) bool {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 30-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"]
|
||||
e, ok := st.exports["30d"]
|
||||
if !ok || !st.online {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -200,6 +200,9 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
|
||||
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 = ""
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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