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>
672 lines
21 KiB
Go
672 lines
21 KiB
Go
package hub_test
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/app"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/probeagent"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
|
)
|
|
|
|
var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
|
|
|
|
func randTok() string {
|
|
b := make([]byte, 24)
|
|
rand.Read(b)
|
|
return hex.EncodeToString(b)
|
|
}
|
|
|
|
func cfgFor(dir string, mut func(*app.Config)) app.Config {
|
|
c := app.Config{Bind: "127.0.0.1:0", Name: "oracle", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), Ignore: app.DefaultIgnore,
|
|
MonitorUA: app.DefaultMonitorUA, TrustedProxy: app.DefaultTrustedProxy, Retention: 168 * time.Hour, TorAuto: "off",
|
|
EventsMax: "64MB", Enforce: "off", EnforceShare: "off", EnforceThreshold: 3, EnforceMaxPerMin: 60, Egress: "on", PeerBlocklist: "on"}
|
|
if mut != nil {
|
|
mut(&c)
|
|
}
|
|
return c
|
|
}
|
|
|
|
// hubProc is a hub on a fixed address that can be stopped and started again
|
|
// over the same data directory (a process restart).
|
|
type hubProc struct {
|
|
t *testing.T
|
|
cfg app.Config
|
|
tok string
|
|
addr string
|
|
cancel context.CancelFunc
|
|
hub *app.Hub
|
|
srv *http.Server
|
|
}
|
|
|
|
func newAddr(t *testing.T) string {
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
a := l.Addr().String()
|
|
l.Close()
|
|
return a
|
|
}
|
|
|
|
func (p *hubProc) start() {
|
|
p.t.Helper()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
p.cancel = cancel
|
|
h, err := app.NewHub(ctx, p.cfg, p.tok, quiet)
|
|
if err != nil {
|
|
p.t.Fatal(err)
|
|
}
|
|
p.hub = h
|
|
var ln net.Listener
|
|
for i := 0; i < 50; i++ {
|
|
if ln, err = net.Listen("tcp", p.addr); err == nil {
|
|
break
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
if err != nil {
|
|
p.t.Fatal(err)
|
|
}
|
|
p.srv = &http.Server{Handler: h.Handler}
|
|
go p.srv.Serve(ln)
|
|
}
|
|
|
|
func (p *hubProc) stop() {
|
|
p.srv.Close()
|
|
p.cancel()
|
|
p.hub.Wait()
|
|
}
|
|
|
|
func (p *hubProc) get(path string) (int, []byte) {
|
|
req, _ := http.NewRequest("GET", "http://"+p.addr+path, nil)
|
|
req.Header.Set("Authorization", "Bearer "+p.tok)
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
p.t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
b, _ := io.ReadAll(resp.Body)
|
|
return resp.StatusCode, b
|
|
}
|
|
|
|
func (p *hubProc) json(path string, v any) {
|
|
p.t.Helper()
|
|
code, b := p.get(path)
|
|
if code != 200 {
|
|
p.t.Fatalf("%s: %d %s", path, code, b)
|
|
}
|
|
if err := json.Unmarshal(b, v); err != nil {
|
|
p.t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func (p *hubProc) send(method, path string, body any) (int, []byte) {
|
|
b, _ := json.Marshal(body)
|
|
req, _ := http.NewRequest(method, "http://"+p.addr+path, bytes.NewReader(b))
|
|
req.Header.Set("Authorization", "Bearer "+p.tok)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
p.t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
out, _ := io.ReadAll(resp.Body)
|
|
return resp.StatusCode, out
|
|
}
|
|
|
|
func waitFor(t *testing.T, what string, d time.Duration, f func() bool) {
|
|
t.Helper()
|
|
end := time.Now().Add(d)
|
|
for time.Now().Before(end) {
|
|
if f() {
|
|
return
|
|
}
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
t.Fatalf("timeout: %s", what)
|
|
}
|
|
|
|
type probe struct {
|
|
name, dir, traefik, auth, f2b, egress, decisions, unban string
|
|
cancel context.CancelFunc
|
|
done chan error
|
|
}
|
|
|
|
func newProbe(t *testing.T, name string) *probe {
|
|
d := t.TempDir()
|
|
p := &probe{name: name, dir: d, traefik: filepath.Join(d, "access.log"), auth: filepath.Join(d, "auth.log"), f2b: filepath.Join(d, "f2b.log"),
|
|
egress: filepath.Join(d, "egress.log"), decisions: filepath.Join(d, "enf", "decisions.log"), unban: filepath.Join(d, "enf", "unban.log")}
|
|
os.MkdirAll(filepath.Join(d, "enf"), 0o755)
|
|
for _, f := range []string{p.traefik, p.auth, p.f2b, p.egress} {
|
|
os.WriteFile(f, nil, 0o644)
|
|
}
|
|
return p
|
|
}
|
|
|
|
func (p *probe) run(t *testing.T, hubURL, token string, spool int64) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
p.cancel, p.done = cancel, make(chan error, 1)
|
|
c := probeagent.Config{Hub: hubURL, Name: p.name, Token: token, StateDir: filepath.Join(p.dir, "state"), SpoolMax: spool,
|
|
Paths: map[string]string{wire.SrcTraefik: p.traefik, wire.SrcAuth: p.auth, wire.SrcFail2ban: p.f2b, wire.SrcEgress: p.egress},
|
|
DecisionsLog: p.decisions, UnbanLog: p.unban, Location: &wire.Location{Lat: -23.5, Lon: -46.6, Label: p.name}, Version: "test"}
|
|
go func() { p.done <- probeagent.Run(ctx, c, quiet) }()
|
|
t.Cleanup(p.stop)
|
|
}
|
|
|
|
func (p *probe) stop() {
|
|
if p.cancel != nil {
|
|
p.cancel()
|
|
select {
|
|
case <-p.done:
|
|
case <-time.After(5 * time.Second):
|
|
}
|
|
p.cancel = nil
|
|
}
|
|
}
|
|
|
|
func appendTo(t *testing.T, path, text string) {
|
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer f.Close()
|
|
f.WriteString(text)
|
|
}
|
|
|
|
func traefikLine(ip string, i int, status int, path string) string {
|
|
ua := "Mozilla/5.0"
|
|
if status == 404 { // an attack: path traversal from a scanner
|
|
ua, path = "nuclei", "/index.php?file=../../etc/passwd&x="
|
|
}
|
|
return fmt.Sprintf(`{"ClientHost":"%s","DownstreamStatus":%d,"RequestHost":"example.org","RequestMethod":"GET","RequestPath":"%s?n=%d","StartUTC":"%s","request_User-Agent":"%s"}`+"\n",
|
|
ip, status, path, i, time.Now().UTC().Format(time.RFC3339Nano), ua)
|
|
}
|
|
|
|
type summary struct {
|
|
Host string `json:"host"`
|
|
Totals struct {
|
|
Requests uint64 `json:"requests"`
|
|
} `json:"totals"`
|
|
Hosts []struct {
|
|
Name string `json:"name"`
|
|
Location *struct {
|
|
Label string `json:"label"`
|
|
} `json:"location"`
|
|
} `json:"hosts"`
|
|
}
|
|
|
|
func requests(t *testing.T, p *hubProc, host string) uint64 {
|
|
var s summary
|
|
p.json("/api/v1/summary?range=24h&host="+host, &s)
|
|
return s.Totals.Requests
|
|
}
|
|
|
|
type probesResp struct {
|
|
Probes []struct {
|
|
Name string `json:"name"`
|
|
Connected bool `json:"connected"`
|
|
Dropped uint64 `json:"dropped"`
|
|
Sources []wire.SourceStatus `json:"sources"`
|
|
Location *wire.Location `json:"location"`
|
|
LastLine int64 `json:"last_line"`
|
|
} `json:"probes"`
|
|
}
|
|
|
|
func TestTwoProbesEndToEnd(t *testing.T) {
|
|
dir := t.TempDir()
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "off" })}
|
|
hp.start()
|
|
defer func() { hp.stop() }()
|
|
url := "http://" + hp.addr
|
|
|
|
// create the probes through the admin API (token shown once)
|
|
tokens := map[string]string{}
|
|
for _, n := range []string{"oracle", "hostinger"} {
|
|
code, b := hp.send("POST", "/api/v1/probes", map[string]string{"name": n})
|
|
var o struct{ Name, Token string }
|
|
if code != 201 || json.Unmarshal(b, &o) != nil || !strings.HasPrefix(o.Token, "urp_") || len(o.Token) != 47 {
|
|
t.Fatalf("create %s: %d %s", n, code, b)
|
|
}
|
|
tokens[n] = o.Token
|
|
}
|
|
if code, _ := hp.send("POST", "/api/v1/probes", map[string]string{"name": "oracle"}); code != 409 {
|
|
t.Fatalf("duplicate probe: %d", code)
|
|
}
|
|
// probes.json holds hashes only
|
|
raw, err := os.ReadFile(filepath.Join(dir, "probes.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, tk := range tokens {
|
|
if strings.Contains(string(raw), tk) {
|
|
t.Fatal("probes.json contains a token")
|
|
}
|
|
}
|
|
if fi, _ := os.Stat(filepath.Join(dir, "probes.json")); fi.Mode().Perm() != 0o600 {
|
|
t.Fatalf("probes.json mode %v", fi.Mode())
|
|
}
|
|
|
|
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
|
|
po.run(t, url, tokens["oracle"], 0)
|
|
ph.run(t, url, tokens["hostinger"], 0)
|
|
waitFor(t, "both probes connected", 15*time.Second, func() bool {
|
|
var r probesResp
|
|
hp.json("/api/v1/probes", &r)
|
|
n := 0
|
|
for _, x := range r.Probes {
|
|
if x.Connected {
|
|
n++
|
|
}
|
|
}
|
|
return n == 2
|
|
})
|
|
|
|
// every source of both hosts
|
|
for i := 0; i < 20; i++ {
|
|
appendTo(t, po.traefik, traefikLine("45.94.31.7", i, 404, "/wp-login.php"))
|
|
}
|
|
for i := 0; i < 7; i++ {
|
|
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
|
|
}
|
|
appendTo(t, ph.auth, time.Now().UTC().Format("2006-01-02T15:04:05.000000+00:00")+" hostinger sshd[123]: Failed password for root from 45.94.31.11 port 22 ssh2\n")
|
|
appendTo(t, ph.f2b, time.Now().Format("2006-01-02 15:04:05,000")+" fail2ban.actions [1]: NOTICE [sshd] Ban 45.94.31.11\n")
|
|
appendTo(t, ph.egress, time.Now().UTC().Format("2006-01-02T15:04:05+00:00")+" hostinger kernel: URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.3.5 DST=93.184.216.34 PROTO=TCP SPT=40000 DPT=443 SYN\n")
|
|
waitFor(t, "events in the right node", 15*time.Second, func() bool {
|
|
return requests(t, hp, "oracle") >= 20 && requests(t, hp, "hostinger") >= 7
|
|
})
|
|
if got := requests(t, hp, "oracle"); got != 20 {
|
|
t.Fatalf("oracle requests %d", got)
|
|
}
|
|
if got := requests(t, hp, "hostinger"); got != 7 {
|
|
t.Fatalf("hostinger requests %d", got)
|
|
}
|
|
var s summary
|
|
hp.json("/api/v1/summary?range=24h&host=hostinger", &s)
|
|
if s.Host != "hostinger" {
|
|
t.Fatalf("host %q", s.Host)
|
|
}
|
|
// per-node data directories
|
|
if _, err := os.Stat(filepath.Join(dir, "probes", "hostinger")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// live: the events carry the location of their probe
|
|
waitFor(t, "live location", 10*time.Second, func() bool {
|
|
var r struct {
|
|
Events []struct {
|
|
Host string `json:"host"`
|
|
Dst *struct {
|
|
Label string `json:"label"`
|
|
} `json:"dst"`
|
|
} `json:"events"`
|
|
}
|
|
code, b := hp.get("/api/v1/live/recent?n=100")
|
|
if code != 200 || json.Unmarshal(b, &r) != nil {
|
|
// the payload may be a bare array
|
|
var arr []struct {
|
|
Host string `json:"host"`
|
|
Dst *struct {
|
|
Label string `json:"label"`
|
|
} `json:"dst"`
|
|
}
|
|
if json.Unmarshal(b, &arr) != nil {
|
|
return false
|
|
}
|
|
for _, e := range arr {
|
|
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
for _, e := range r.Events {
|
|
if e.Host == "hostinger" && e.Dst != nil && e.Dst.Label == "hostinger" {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
})
|
|
|
|
// enforce: the decision reaches decisions.log of the right probe only
|
|
waitFor(t, "decision on the probe of the attacked host", 20*time.Second, func() bool {
|
|
b, _ := os.ReadFile(ph.decisions)
|
|
return strings.Contains(string(b), "ip=45.94.31.9") || strings.Contains(string(b), "ip=45.94.31.7")
|
|
})
|
|
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "45.94.31.9") {
|
|
t.Fatal("a decision of hostinger leaked to the oracle probe")
|
|
}
|
|
// unban through the API for one host
|
|
if code, b := hp.send("POST", "/api/v1/enforce/unban", map[string]any{"ip": "203.0.113.50", "allow_s": 3600, "host": "hostinger"}); code != 200 {
|
|
t.Fatalf("unban: %d %s", code, b)
|
|
}
|
|
waitFor(t, "unban.log", 10*time.Second, func() bool {
|
|
b, _ := os.ReadFile(ph.unban)
|
|
return strings.Contains(string(b), "unban ip=203.0.113.50 allow=3600")
|
|
})
|
|
if _, err := os.Stat(po.unban); err == nil {
|
|
t.Fatal("the unban of one host reached the other probe")
|
|
}
|
|
|
|
// hub down: 1000 lines written meanwhile arrive exactly once after the restart
|
|
before := requests(t, hp, "oracle")
|
|
hp.stop()
|
|
var sb strings.Builder
|
|
for i := 0; i < 1000; i++ {
|
|
sb.WriteString(traefikLine(fmt.Sprintf("45.94.32.%d", i%200+1), 1000+i, 200, "/page"))
|
|
}
|
|
appendTo(t, po.traefik, sb.String())
|
|
time.Sleep(300 * time.Millisecond)
|
|
hp.start()
|
|
waitFor(t, "1000 lines after the restart", 30*time.Second, func() bool { return requests(t, hp, "oracle") >= before+1000 })
|
|
time.Sleep(500 * time.Millisecond)
|
|
if got := requests(t, hp, "oracle"); got != before+1000 {
|
|
t.Fatalf("after the restart: %d requests, want %d (no gap, no duplicate)", got, before+1000)
|
|
}
|
|
|
|
// revoke: 401 afterwards, data stays
|
|
po.stop()
|
|
if code, _ := hp.send("DELETE", "/api/v1/probes/oracle", nil); code != 200 {
|
|
t.Fatalf("revoke: %d", code)
|
|
}
|
|
req, _ := http.NewRequest("POST", url+wire.PathHello, strings.NewReader(`{"proto":1,"name":"oracle"}`))
|
|
req.Header.Set("Authorization", "Bearer "+tokens["oracle"])
|
|
req.Header.Set(wire.HeaderProbe, "oracle")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil || resp.StatusCode != 401 {
|
|
t.Fatalf("revoked token: %v %v", resp, err)
|
|
}
|
|
resp.Body.Close()
|
|
if got := requests(t, hp, "oracle"); got != before+1000 {
|
|
t.Fatalf("data lost after revoke: %d", got)
|
|
}
|
|
// the old peer routes are gone
|
|
for _, p := range []string{"/api/v1/peer/export", "/api/v1/peer/stream", "/api/v1/peer/decisions"} {
|
|
if code, _ := hp.get(p); code != 404 {
|
|
t.Errorf("%s: %d, want 404", p, code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEnforceShareReachesBothProbes(t *testing.T) {
|
|
dir := t.TempDir()
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Enforce = "on"; c.EnforceShare = "on" })}
|
|
hp.start()
|
|
defer hp.stop()
|
|
url := "http://" + hp.addr
|
|
po, ph := newProbe(t, "oracle"), newProbe(t, "hostinger")
|
|
for _, p := range []*probe{po, ph} {
|
|
tok, err := hp.hub.Mgr.Create(p.name)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p.run(t, url, tok, 0)
|
|
}
|
|
for i := 0; i < 30; i++ {
|
|
appendTo(t, ph.traefik, traefikLine("45.94.31.9", i, 404, "/wp-login.php"))
|
|
}
|
|
waitFor(t, "decision on the origin probe", 20*time.Second, func() bool {
|
|
b, _ := os.ReadFile(ph.decisions)
|
|
return strings.Contains(string(b), "ip=45.94.31.9")
|
|
})
|
|
// the sharing loop runs every 30 s: relay now through the engines
|
|
for _, n := range hp.hub.Mgr.Nodes() {
|
|
_ = n
|
|
}
|
|
// the relay runs every 30 s; the receiver applies its own policy, and an
|
|
// address its own probe never saw attacking is first held "peer_unconfirmed"
|
|
waitFor(t, "shared decision on the other probe", 60*time.Second, func() bool {
|
|
if b, _ := os.ReadFile(po.decisions); strings.Contains(string(b), "src=peer:hostinger") {
|
|
return true
|
|
}
|
|
return hp.hub.Primary.Enf.Report(0).Counts.Skipped["peer_unconfirmed"] > 0
|
|
})
|
|
}
|
|
|
|
func TestSpoolOverflowIsReportedAsDropped(t *testing.T) {
|
|
dir := t.TempDir()
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
|
// the hub is not up yet: create the registry offline and start the probe against a dead address
|
|
hp.start()
|
|
tok, _ := hp.hub.Mgr.Create("hostinger")
|
|
hp.stop()
|
|
p := newProbe(t, "hostinger")
|
|
p.run(t, "http://"+hp.addr, tok, 4096)
|
|
for round := 0; round < 12; round++ {
|
|
var sb strings.Builder
|
|
for i := 0; i < 100; i++ {
|
|
sb.WriteString(traefikLine("45.94.33.1", round*100+i, 200, "/spool"))
|
|
}
|
|
appendTo(t, p.traefik, sb.String())
|
|
time.Sleep(1200 * time.Millisecond)
|
|
}
|
|
hp.start()
|
|
defer hp.stop()
|
|
waitFor(t, "dropped reported", 30*time.Second, func() bool {
|
|
var r probesResp
|
|
hp.json("/api/v1/probes", &r)
|
|
for _, x := range r.Probes {
|
|
if x.Name == "hostinger" && x.Dropped > 0 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
})
|
|
}
|
|
|
|
func TestIngestLimitsAndDedup(t *testing.T) {
|
|
dir := t.TempDir()
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
|
hp.start()
|
|
defer hp.stop()
|
|
tok, _ := hp.hub.Mgr.Create("hostinger")
|
|
do := func(path string, body []byte, gz bool) int {
|
|
req, _ := http.NewRequest("POST", "http://"+hp.addr+path, bytes.NewReader(body))
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
req.Header.Set(wire.HeaderProbe, "hostinger")
|
|
if gz {
|
|
req.Header.Set("Content-Encoding", "gzip")
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
io.Copy(io.Discard, resp.Body)
|
|
return resp.StatusCode
|
|
}
|
|
push := func(b wire.Batch) (int, wire.PushResp) {
|
|
raw, _ := json.Marshal(b)
|
|
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathPush, bytes.NewReader(raw))
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
req.Header.Set(wire.HeaderProbe, "hostinger")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
var pr wire.PushResp
|
|
json.NewDecoder(resp.Body).Decode(&pr)
|
|
return resp.StatusCode, pr
|
|
}
|
|
line := func(i int, inode uint64, off int64) wire.Line {
|
|
return wire.Line{Src: wire.SrcTraefik, Text: strings.TrimSpace(traefikLine("45.94.34.1", i, 200, "/d")), End: wire.Pos{Inode: inode, Offset: off}}
|
|
}
|
|
if code, r := push(wire.Batch{Seq: 1, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200)}}); code != 200 || r.Accepted != 2 {
|
|
t.Fatalf("first: %d %+v", code, r)
|
|
}
|
|
// same positions again under a new seq: duplicates by offset
|
|
if code, r := push(wire.Batch{Seq: 2, Lines: []wire.Line{line(1, 7, 100), line(2, 7, 200), line(3, 7, 300)}}); code != 200 || r.Dup != 2 || r.Accepted != 1 {
|
|
t.Fatalf("dedup by offset: %d %+v", code, r)
|
|
}
|
|
// a new inode with a smaller offset is new data (rotation)
|
|
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(4, 8, 50)}}); code != 200 || r.Accepted != 1 {
|
|
t.Fatalf("new inode: %d %+v", code, r)
|
|
}
|
|
// the same seq again is acknowledged without applying
|
|
if code, r := push(wire.Batch{Seq: 3, Lines: []wire.Line{line(5, 8, 500)}}); code != 200 || r.Ack != 3 || r.Accepted != 0 {
|
|
t.Fatalf("idempotent seq: %d %+v", code, r)
|
|
}
|
|
// limits
|
|
big := make([]wire.Line, wire.MaxLines+1)
|
|
for i := range big {
|
|
big[i] = wire.Line{Src: wire.SrcTraefik, Text: "x", End: wire.Pos{Inode: 9, Offset: int64(i + 1)}}
|
|
}
|
|
if code, _ := push(wire.Batch{Seq: 10, Lines: big}); code != 400 {
|
|
t.Fatalf("too many lines: %d", code)
|
|
}
|
|
if code, _ := push(wire.Batch{Seq: 11, Lines: []wire.Line{{Src: "bogus", Text: "x"}}}); code != 400 {
|
|
t.Fatalf("invalid source: %d", code)
|
|
}
|
|
if code := do(wire.PathPush, bytes.Repeat([]byte("a"), wire.MaxBodyBytes+10), false); code != 413 {
|
|
t.Fatalf("raw body too big: %d", code)
|
|
}
|
|
var zb bytes.Buffer
|
|
zw := gzip.NewWriter(&zb)
|
|
zw.Write(bytes.Repeat([]byte(" "), wire.MaxInflated+10))
|
|
zw.Close()
|
|
if code := do(wire.PathPush, zb.Bytes(), true); code != 413 {
|
|
t.Fatalf("inflated body too big: %d", code)
|
|
}
|
|
// hello returns the committed offsets
|
|
hb, _ := json.Marshal(wire.Hello{Proto: wire.Proto, Name: "hostinger", Version: "t"})
|
|
req, _ := http.NewRequest("POST", "http://"+hp.addr+wire.PathHello, bytes.NewReader(hb))
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
req.Header.Set(wire.HeaderProbe, "hostinger")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var hr wire.HelloResp
|
|
json.NewDecoder(resp.Body).Decode(&hr)
|
|
resp.Body.Close()
|
|
if hr.Offsets[wire.SrcTraefik].Inode != 8 || hr.Offsets[wire.SrcTraefik].Offset != 50 {
|
|
t.Fatalf("hello offsets: %+v", hr.Offsets)
|
|
}
|
|
// incompatible protocol
|
|
hb, _ = json.Marshal(wire.Hello{Proto: 99, Name: "hostinger"})
|
|
if code := do(wire.PathHello, hb, false); code != 409 {
|
|
t.Fatalf("protocol: %d", code)
|
|
}
|
|
}
|
|
|
|
func TestOldPeerVariablesRefuseToStart(t *testing.T) {
|
|
t.Setenv("URUTAU_PEERS", "hostinger=https://x.example.org")
|
|
t.Setenv("URUTAU_TOKEN", randTok())
|
|
c := cfgFor(t.TempDir(), func(c *app.Config) { c.NoAuth = false })
|
|
err := app.Serve(c)
|
|
if err == nil || !strings.Contains(err.Error(), "URUTAU_PEERS") || !strings.Contains(err.Error(), "migration-2.0") {
|
|
t.Fatalf("Serve with URUTAU_PEERS: %v", err)
|
|
}
|
|
}
|
|
|
|
// copyTree copies a directory (fixtures are read-only inputs).
|
|
func copyTree(t *testing.T, from, to string) {
|
|
filepath.Walk(from, func(p string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rel, _ := filepath.Rel(from, p)
|
|
dst := filepath.Join(to, rel)
|
|
if info.IsDir() {
|
|
return os.MkdirAll(dst, 0o755)
|
|
}
|
|
b, err := os.ReadFile(p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(dst, b, 0o644)
|
|
})
|
|
}
|
|
|
|
var fixture = filepath.Join("..", "app", "testdata", "hostinger-1.6")
|
|
|
|
func TestPrimaryLoads16DataDirWithSameCounts(t *testing.T) {
|
|
if _, err := os.Stat(fixture); err != nil {
|
|
t.Skip("fixture of the 1.6 data directory missing")
|
|
}
|
|
dir := t.TempDir()
|
|
copyTree(t, fixture, dir)
|
|
want, err := app.CountDir(dir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, func(c *app.Config) { c.Name = "hostinger" })}
|
|
hp.start()
|
|
defer hp.stop()
|
|
var ips struct {
|
|
Total int `json:"total"`
|
|
}
|
|
hp.json("/api/v1/ips?range=30d&per=200", &ips)
|
|
if want.IPs == 0 || hp.hub.Primary.St.IPCount() != want.IPs {
|
|
t.Fatalf("IPs: node %d, directory %d", hp.hub.Primary.St.IPCount(), want.IPs)
|
|
}
|
|
var inc struct {
|
|
Total int `json:"total"`
|
|
}
|
|
hp.json("/api/v1/incidents?per_page=100", &inc)
|
|
if inc.Total != want.Incidents {
|
|
t.Fatalf("incidents: api %d, directory %d", inc.Total, want.Incidents)
|
|
}
|
|
}
|
|
|
|
func TestImportedHostIncidentWithComments(t *testing.T) {
|
|
if _, err := os.Stat(fixture); err != nil {
|
|
t.Skip("fixture of the 1.6 data directory missing")
|
|
}
|
|
dir := t.TempDir()
|
|
rep, err := app.Import(fixture, dir, "hostinger", app.ImportOptions{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
hp := &hubProc{t: t, tok: randTok(), addr: newAddr(t), cfg: cfgFor(dir, nil)}
|
|
hp.start()
|
|
defer hp.stop()
|
|
for _, path := range []string{"/api/v1/incidents/hostinger%2FINC-2", "/api/v1/incidents/hostinger/INC-2", "/api/v1/incidents/INC-2?host=hostinger"} {
|
|
var tk struct {
|
|
ID string `json:"id"`
|
|
Host string `json:"host"`
|
|
Comments []any `json:"comments"`
|
|
}
|
|
hp.json(path, &tk)
|
|
if tk.ID != "hostinger/INC-2" || tk.Host != "hostinger" || len(tk.Comments) != 2 {
|
|
t.Fatalf("%s: %+v", path, tk)
|
|
}
|
|
}
|
|
// the list qualifies the ids and counts the imported tickets
|
|
var list struct {
|
|
Total int `json:"total"`
|
|
Items []struct {
|
|
ID string `json:"id"`
|
|
} `json:"items"`
|
|
}
|
|
hp.json("/api/v1/incidents?host=hostinger", &list)
|
|
if list.Total != rep.Incidents || len(list.Items) == 0 || !strings.HasPrefix(list.Items[0].ID, "hostinger/INC-") {
|
|
t.Fatalf("list: %+v (imported %d)", list, rep.Incidents)
|
|
}
|
|
// and the node serves the imported IPs under its own host
|
|
var s summary
|
|
hp.json("/api/v1/summary?range=30d&host=hostinger", &s)
|
|
if s.Host != "hostinger" {
|
|
t.Fatalf("summary host %q", s.Host)
|
|
}
|
|
var mu sync.Mutex
|
|
mu.Lock()
|
|
mu.Unlock()
|
|
}
|