feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
CI / Format and vet (pull_request) Failing after 53s
CI / Dependency audit (pull_request) Successful in 33s
CI / Tests (Linux, race detector) (pull_request) Successful in 2m1s
CI / Docker images (build and smoke test) (pull_request) Failing after 47s

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:
Lucas RayanandClaude Opus 5.5 committed 2026-11-15 22:14:50 -03:00
1 parent 23a7a5963a
commit 8546d14cef
130 files changed
+9396 -3311

No files matched your search

+191
View File
@@ -0,0 +1,191 @@
package hub
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// MaxQueue is the most commands kept per node; the oldest are dropped.
const MaxQueue = 10000
// CmdQueue is the persisted command queue of one node (commands.json).
type CmdQueue struct {
mu sync.Mutex
path string
next uint64
dropped uint64
cmds []wire.Cmd
dirty bool
notify chan struct{} // closed and replaced on every enqueue
stop chan struct{}
done chan struct{}
}
type queueFile struct {
Next uint64 `json:"next"`
Dropped uint64 `json:"dropped"`
Cmds []wire.Cmd `json:"cmds"`
}
// OpenQueue loads path (missing: empty) and starts the debounced writer; call
// Close to flush. An empty path keeps the queue in memory only.
func OpenQueue(path string) (*CmdQueue, error) {
q := &CmdQueue{path: path, next: 1, notify: make(chan struct{}), stop: make(chan struct{}), done: make(chan struct{})}
if path != "" {
if b, err := os.ReadFile(path); err == nil {
var f queueFile
if err := json.Unmarshal(b, &f); err != nil {
_ = os.Rename(path, path+".corrupt")
} else {
q.next, q.dropped, q.cmds = max(f.Next, 1), f.Dropped, f.Cmds
for _, c := range q.cmds {
q.next = max(q.next, c.Seq+1)
}
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
go q.writer()
return q, nil
}
func (q *CmdQueue) writer() {
defer close(q.done)
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-q.stop:
q.flush()
return
case <-t.C:
q.flush()
}
}
}
func (q *CmdQueue) flush() {
if q.path == "" {
return
}
q.mu.Lock()
if !q.dirty {
q.mu.Unlock()
return
}
b, err := json.Marshal(queueFile{Next: q.next, Dropped: q.dropped, Cmds: q.cmds})
q.dirty = false
q.mu.Unlock()
if err != nil {
return
}
_ = os.MkdirAll(filepath.Dir(q.path), 0o700)
tmp := q.path + ".tmp"
if os.WriteFile(tmp, b, 0o600) == nil {
_ = os.Rename(tmp, q.path)
}
}
// Close flushes the queue and stops the writer.
func (q *CmdQueue) Close() {
select {
case <-q.stop:
default:
close(q.stop)
}
<-q.done
}
// Enqueue appends a command; it matches the signature of enforce.Config.Sink.
func (q *CmdQueue) Enqueue(kind, line string) error {
if !wire.ValidCmdLine(kind, line) {
return errors.New("invalid command line")
}
q.mu.Lock()
q.cmds = append(q.cmds, wire.Cmd{Seq: q.next, Kind: kind, Line: line})
q.next++
if len(q.cmds) > MaxQueue {
n := len(q.cmds) - MaxQueue
q.dropped += uint64(n)
q.cmds = append([]wire.Cmd(nil), q.cmds[n:]...)
}
q.dirty = true
old := q.notify
q.notify = make(chan struct{})
q.mu.Unlock()
close(old)
return nil
}
// Last is the highest queued sequence (0 when nothing was ever queued).
func (q *CmdQueue) Last() uint64 {
q.mu.Lock()
defer q.mu.Unlock()
return q.next - 1
}
// Pending counts the queued commands after seq.
func (q *CmdQueue) Pending(after uint64) int {
q.mu.Lock()
defer q.mu.Unlock()
n := 0
for _, c := range q.cmds {
if c.Seq > after {
n++
}
}
return n
}
// Dropped counts the commands discarded by the size cap.
func (q *CmdQueue) Dropped() uint64 {
q.mu.Lock()
defer q.mu.Unlock()
return q.dropped
}
func (q *CmdQueue) after(seq uint64) ([]wire.Cmd, chan struct{}, uint64) {
q.mu.Lock()
defer q.mu.Unlock()
// the probe persisted everything up to seq: forget it
i := 0
for i < len(q.cmds) && q.cmds[i].Seq <= seq {
i++
}
if i > 0 {
q.cmds = append([]wire.Cmd(nil), q.cmds[i:]...)
q.dirty = true
}
out := q.cmds
if len(out) > 500 {
out = out[:500]
}
return append([]wire.Cmd(nil), out...), q.notify, q.dropped
}
// Wait returns the commands after seq at once, or holds up to wait for one.
func (q *CmdQueue) Wait(ctx context.Context, seq uint64, wait time.Duration) wire.CmdResp {
cmds, ch, dropped := q.after(seq)
if len(cmds) == 0 && wait > 0 {
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-ch:
cmds, _, dropped = q.after(seq)
case <-t.C:
case <-ctx.Done():
}
}
if cmds == nil {
cmds = []wire.Cmd{}
}
return wire.CmdResp{Cmds: cmds, Dropped: dropped}
}
+254
View File
@@ -0,0 +1,254 @@
package hub
import (
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Authenticate checks Authorization: Bearer <token> and X-Urutau-Probe for a
// registered, non-revoked probe and returns its name.
func (m *Manager) Authenticate(r *http.Request) (string, bool) {
name := r.Header.Get(wire.HeaderProbe)
a := r.Header.Get("Authorization")
if !strings.HasPrefix(a, "Bearer ") {
m.Reg.Verify(name, "") // same work as a real check
return "", false
}
if !m.Reg.Verify(name, strings.TrimSpace(a[7:])) {
return "", false
}
return name, true
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"error": msg})
}
// node returns the ready node of an authenticated probe or answers 503.
func (m *Manager) node(w http.ResponseWriter, name string) Node {
n, err := m.Ensure(name)
if err != nil {
w.Header().Set("Retry-After", "5")
fail(w, http.StatusServiceUnavailable, "node unavailable")
return nil
}
if !n.Ready() {
w.Header().Set("Retry-After", "5")
fail(w, http.StatusServiceUnavailable, "node loading")
return nil
}
return n
}
// Hello: POST /api/v1/probe/hello.
func (m *Manager) Hello(w http.ResponseWriter, r *http.Request, name string) {
var h wire.Hello
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&h); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON")
return
}
if h.Proto != wire.Proto {
fail(w, http.StatusConflict, "incompatible protocol version")
return
}
if h.Name != "" && h.Name != name {
fail(w, http.StatusBadRequest, "name does not match the token")
return
}
for _, s := range h.Sources {
if !wire.ValidSource(s) {
fail(w, http.StatusBadRequest, "unknown source")
return
}
}
n := m.node(w, name)
if n == nil {
return
}
if h.Location != nil && (h.Location.Lat < -90 || h.Location.Lat > 90 || h.Location.Lon < -180 || h.Location.Lon > 180) {
h.Location = nil
}
h.Version = clip(h.Version, 32)
h.Hostname = clip(h.Hostname, 64)
c := m.conn(name)
c.mu.Lock()
c.lastSeen, c.version, c.hostname = m.Now().Unix(), h.Version, h.Hostname
if h.LastSeq < c.ack {
c.ack = h.LastSeq // a probe that lost its state restarts its numbering
}
ack := c.ack
c.mu.Unlock()
n.Hello(h)
if rec, _ := m.Reg.Get(name); rec.Location != nil {
n.SetLocation(rec.Location)
} else if h.Location != nil {
n.SetLocation(h.Location)
}
writeJSON(w, 200, wire.HelloResp{Proto: wire.Proto, HubVer: m.Version, Offsets: n.Offsets(), AckSeq: ack, FlushMS: 1000})
}
func clip(s string, n int) string {
if len(s) > n {
s = s[:n]
}
return strings.ToValidUTF8(s, "")
}
// Push: POST /api/v1/probe/push.
func (m *Manager) Push(w http.ResponseWriter, r *http.Request, name string) {
c := m.conn(name)
if !c.busy.CompareAndSwap(false, true) {
w.Header().Set("Retry-After", "1")
fail(w, http.StatusTooManyRequests, "one push at a time")
return
}
defer c.busy.Store(false)
if m.infl.Add(1) > 16 {
m.infl.Add(-1)
w.Header().Set("Retry-After", "2")
fail(w, http.StatusServiceUnavailable, "ingest busy")
return
}
defer m.infl.Add(-1)
n := m.node(w, name)
if n == nil {
return
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, wire.MaxBodyBytes))
if err != nil {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
fail(w, http.StatusRequestEntityTooLarge, "body too large")
} else {
fail(w, http.StatusBadRequest, "unreadable body")
}
return
}
if ce := strings.ToLower(r.Header.Get("Content-Encoding")); ce == "gzip" {
zr, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
fail(w, http.StatusBadRequest, "invalid gzip")
return
}
raw, err = io.ReadAll(io.LimitReader(zr, wire.MaxInflated+1))
if err != nil {
fail(w, http.StatusBadRequest, "invalid gzip")
return
}
if len(raw) > wire.MaxInflated {
fail(w, http.StatusRequestEntityTooLarge, "body too large")
return
}
} else if ce != "" && ce != "identity" {
fail(w, http.StatusBadRequest, "unsupported encoding")
return
}
var b wire.Batch
if err := json.Unmarshal(raw, &b); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON")
return
}
if len(b.Lines) > wire.MaxLines {
fail(w, http.StatusBadRequest, "too many lines")
return
}
for i := range b.Lines {
l := &b.Lines[i]
if !wire.ValidSource(l.Src) || len(l.Text) > wire.MaxLine {
fail(w, http.StatusBadRequest, "invalid line")
return
}
if l.End.Offset < 0 {
fail(w, http.StatusBadRequest, "invalid line")
return
}
if !utf8.ValidString(l.Text) {
l.Text = strings.ToValidUTF8(l.Text, "�")
}
}
for _, f := range b.Files {
if (f.Name != wire.FileContainers && f.Name != wire.FileResolv) || len(f.Data) > wire.MaxFileBytes {
fail(w, http.StatusBadRequest, "invalid file")
return
}
}
now := m.Now()
c.mu.Lock()
c.lastSeen = now.Unix()
if b.Sent > 0 {
c.lagMS = max(0, now.UnixMilli()-b.Sent)
}
if b.Status != nil {
c.status = *b.Status
for _, s := range b.Status.Sources {
if s.LastLine > c.lastLine {
c.lastLine = s.LastLine
}
}
}
dup := false
if b.Seq != 0 && b.Seq <= c.ack {
dup = true
}
ack := c.ack
c.mu.Unlock()
if b.Status != nil {
n.SetStatus(*b.Status, true)
}
resp := wire.PushResp{Ack: ack}
if q := n.Queue(); q != nil {
resp.PendCmd = q.Last()
}
switch {
case b.Seq == 0: // heartbeat: status only
case dup:
resp.Dup = len(b.Lines)
default:
resp.Accepted, resp.Dup = n.Apply(b)
c.mu.Lock()
c.ack = b.Seq
resp.Ack = b.Seq
c.mu.Unlock()
}
writeJSON(w, 200, resp)
}
// Commands: GET /api/v1/probe/commands?after=<seq>&wait=<s>.
func (m *Manager) Commands(w http.ResponseWriter, r *http.Request, name string) {
n := m.node(w, name)
if n == nil {
return
}
after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64)
wait, _ := strconv.Atoi(r.URL.Query().Get("wait"))
wait = max(0, min(wait, wire.MaxWaitSec))
c := m.conn(name)
c.mu.Lock()
c.lastSeen = m.Now().Unix()
c.mu.Unlock()
q := n.Queue()
if q == nil {
writeJSON(w, 200, wire.CmdResp{Cmds: []wire.Cmd{}})
return
}
// the write timeout of the server must outlive the long poll
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(time.Duration(wait+10) * time.Second))
writeJSON(w, 200, q.Wait(r.Context(), after, time.Duration(wait)*time.Second))
}
+671
View File
@@ -0,0 +1,671 @@
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()
}
+305
View File
@@ -0,0 +1,305 @@
package hub
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// Node is one probe's data seen from the ingest layer (implemented by the app).
type Node interface {
Name() string
// Ready is false while the node still loads its snapshot.
Ready() bool
// Offsets are the hub-committed positions, keyed by wire source name.
Offsets() map[string]wire.Pos
// Apply commits a batch under the node's commit mutex.
Apply(b wire.Batch) (accepted, dup int)
// Hello tells the node what the probe announced (sources, location).
Hello(h wire.Hello)
// Queue is the command queue of the node.
Queue() *CmdQueue
// SetStatus hands over the last status the probe reported.
SetStatus(st wire.Status, connected bool)
// SetLocation changes the location events of this node point to.
SetLocation(l *wire.Location)
}
// Factory builds the node of a probe.
type Factory func(name string, primary bool, rec Probe) (Node, error)
// Update is the body of PUT /api/v1/probes/{name}.
type Update struct {
Location *wire.Location `json:"location"`
Egress Egress `json:"egress"`
}
// ProbeInfo is one row of GET /api/v1/probes.
type ProbeInfo struct {
Name string `json:"name"`
Primary bool `json:"primary"`
Registered bool `json:"registered"`
Revoked bool `json:"revoked"`
Created int64 `json:"created,omitempty"`
Connected bool `json:"connected"`
LastSeen int64 `json:"last_seen"`
LastLine int64 `json:"last_line"`
LagMS int64 `json:"lag_ms"`
Version string `json:"version,omitempty"`
Hostname string `json:"hostname,omitempty"`
Dropped uint64 `json:"dropped"`
Spool int64 `json:"spool"`
SpoolFiles int `json:"spool_files"`
CmdPending int `json:"cmd_pending"`
CmdDropped uint64 `json:"cmd_dropped"`
CmdErrors uint64 `json:"cmd_errors"`
Uptime int64 `json:"uptime"`
RSS uint64 `json:"rss"`
Sources []wire.SourceStatus `json:"sources"`
Location *wire.Location `json:"location,omitempty"`
Egress Egress `json:"egress"`
}
type conn struct {
mu sync.Mutex
lastSeen int64
lastLine int64
lagMS int64
version string
hostname string
status wire.Status
ack uint64
busy atomic.Bool
}
// Manager owns the registry and the nodes.
type Manager struct {
Dir string // data directory (primary node lives in its root)
Primary string
Version string
Reg *Registry
Make Factory
Log *slog.Logger
Now func() time.Time
mu sync.Mutex
nodes map[string]Node
conns map[string]*conn
infl atomic.Int32
}
// NewManager opens probes.json in dir and returns a manager; call Load to
// create the nodes.
func NewManager(dir, primary, version string, mk Factory, log *slog.Logger) (*Manager, error) {
reg, err := OpenRegistry(filepath.Join(dir, "probes.json"))
if err != nil {
return nil, err
}
if log == nil {
log = slog.Default()
}
return &Manager{Dir: dir, Primary: primary, Version: version, Reg: reg, Make: mk, Log: log, Now: time.Now,
nodes: map[string]Node{}, conns: map[string]*conn{}}, nil
}
// Load creates the primary node, one node per registered probe and one per
// directory in probes/ (imported data), so every data set is served at once.
func (m *Manager) Load() error {
names := map[string]bool{m.Primary: true}
for _, p := range m.Reg.List() {
names[p.Name] = true
}
if ents, err := os.ReadDir(filepath.Join(m.Dir, "probes")); err == nil {
for _, e := range ents {
if e.IsDir() && wire.ValidName(e.Name()) {
names[e.Name()] = true
}
}
}
list := make([]string, 0, len(names))
for n := range names {
list = append(list, n)
}
sort.Strings(list)
for _, n := range list {
if _, err := m.Ensure(n); err != nil {
return fmt.Errorf("node %s: %w", n, err)
}
}
return nil
}
// Ensure returns the node of name, creating it on first use.
func (m *Manager) Ensure(name string) (Node, error) {
m.mu.Lock()
defer m.mu.Unlock()
if n, ok := m.nodes[name]; ok {
return n, nil
}
if !wire.ValidName(name) {
return nil, ErrName
}
rec, _ := m.Reg.Get(name)
n, err := m.Make(name, name == m.Primary, rec)
if err != nil {
return nil, err
}
m.nodes[name] = n
if m.conns[name] == nil {
m.conns[name] = &conn{}
}
return n, nil
}
// Get returns an existing node.
func (m *Manager) Get(name string) Node {
m.mu.Lock()
defer m.mu.Unlock()
return m.nodes[name]
}
// Nodes lists the nodes sorted by name, the primary first.
func (m *Manager) Nodes() []Node {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]Node, 0, len(m.nodes))
for _, n := range m.nodes {
out = append(out, n)
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i].Name(), out[j].Name()
if (a == m.Primary) != (b == m.Primary) {
return a == m.Primary
}
return a < b
})
return out
}
func (m *Manager) conn(name string) *conn {
m.mu.Lock()
defer m.mu.Unlock()
c := m.conns[name]
if c == nil {
c = &conn{}
m.conns[name] = c
}
return c
}
// Connected reports whether the probe pushed within OfflineSec.
func (m *Manager) Connected(name string) bool {
c := m.conn(name)
c.mu.Lock()
defer c.mu.Unlock()
return c.lastSeen > 0 && m.Now().Unix()-c.lastSeen <= wire.OfflineSec
}
// Info describes one probe.
func (m *Manager) Info(name string) (ProbeInfo, bool) {
n := m.Get(name)
rec, reg := m.Reg.Get(name)
if n == nil && !reg {
return ProbeInfo{}, false
}
c := m.conn(name)
c.mu.Lock()
st := c.status
in := ProbeInfo{Name: name, Primary: name == m.Primary, Registered: reg, Revoked: rec.Revoked, Created: rec.Created,
LastSeen: c.lastSeen, LastLine: c.lastLine, LagMS: c.lagMS, Version: c.version, Hostname: c.hostname,
Dropped: st.Dropped, Spool: st.SpoolBytes, SpoolFiles: st.SpoolFiles, CmdErrors: st.CmdErrors,
Uptime: st.UptimeSec, RSS: st.RSSBytes, Sources: append([]wire.SourceStatus{}, st.Sources...), Location: rec.Location, Egress: rec.Egress}
c.mu.Unlock()
in.Connected = m.Connected(name)
if n != nil {
if q := n.Queue(); q != nil {
in.CmdPending, in.CmdDropped = q.Pending(0), q.Dropped()
}
}
return in, true
}
// List describes every probe (registered ones and nodes without a record, such
// as the primary or imported data).
func (m *Manager) List() []ProbeInfo {
names := map[string]bool{}
for _, n := range m.Nodes() {
names[n.Name()] = true
}
for _, p := range m.Reg.List() {
names[p.Name] = true
}
var out []ProbeInfo
for n := range names {
if in, ok := m.Info(n); ok {
out = append(out, in)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Primary != out[j].Primary {
return out[i].Primary
}
return out[i].Name < out[j].Name
})
return out
}
// Create registers a probe, returning its token (shown once).
func (m *Manager) Create(name string) (string, error) {
tok, err := m.Reg.Create(name)
if err != nil {
return "", err
}
if _, err := m.Ensure(name); err != nil {
return "", err
}
return tok, nil
}
// Revoke disables the token of a probe and drops its connection state; the
// data stays.
func (m *Manager) Revoke(name string) error {
if err := m.Reg.Revoke(name); err != nil {
return err
}
c := m.conn(name)
c.mu.Lock()
c.lastSeen = 0
c.mu.Unlock()
return nil
}
// UpdateProbe stores the location and egress configuration and applies the location now.
func (m *Manager) UpdateProbe(name string, u Update) error {
if u.Location != nil {
if l := u.Location; l.Lat < -90 || l.Lat > 90 || l.Lon < -180 || l.Lon > 180 || len(l.Label) > 80 {
return fmt.Errorf("invalid location")
}
}
if err := m.Reg.Update(name, u.Location, u.Egress); err != nil {
return err
}
if n := m.Get(name); n != nil {
n.SetLocation(u.Location)
if r, ok := n.(interface{ ResetEgress(Egress) }); ok {
r.ResetEgress(u.Egress)
}
}
return nil
}
// Close flushes the command queues.
func (m *Manager) Close() {
for _, n := range m.Nodes() {
if q := n.Queue(); q != nil {
q.Close()
}
}
}
+214
View File
@@ -0,0 +1,214 @@
// Package hub is the server side of the probe protocol: the registry of
// probes (probes.json), the per-node command queue and the ingest handlers.
package hub
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// TokenPrefix starts every probe token.
const TokenPrefix = "urp_"
// Egress is the per-probe configuration of the egress analysis.
type Egress struct {
Workloads string `json:"workloads,omitempty"`
Resolvers string `json:"resolvers,omitempty"`
Allow string `json:"allow,omitempty"`
}
// Probe is one entry of probes.json. The token is never stored, only its hash.
type Probe struct {
Name string `json:"name"`
TokenSHA256 string `json:"token_sha256"`
Created int64 `json:"created"`
Revoked bool `json:"revoked"`
Location *wire.Location `json:"location,omitempty"`
Egress Egress `json:"egress"`
}
// Errors of the registry.
var (
ErrExists = errors.New("probe already exists")
ErrNotFound = errors.New("probe not found")
ErrName = errors.New("invalid probe name (a-z, 0-9 and -, at most 32 characters)")
)
// Registry is probes.json.
type Registry struct {
mu sync.Mutex
path string
probes map[string]*Probe
}
type regFile struct {
Probes []*Probe `json:"probes"`
}
// OpenRegistry loads path (a missing file is an empty registry).
func OpenRegistry(path string) (*Registry, error) {
r := &Registry{path: path, probes: map[string]*Probe{}}
b, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return r, nil
}
if err != nil {
return nil, err
}
var f regFile
if err := json.Unmarshal(b, &f); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
for _, p := range f.Probes {
if p != nil && wire.ValidName(p.Name) {
r.probes[p.Name] = p
}
}
return r, nil
}
// save writes the file atomically with mode 0600; the caller holds mu.
func (r *Registry) save() error {
list := make([]*Probe, 0, len(r.probes))
for _, p := range r.probes {
list = append(list, p)
}
sort.Slice(list, func(i, j int) bool { return list[i].Name < list[j].Name })
b, err := json.MarshalIndent(regFile{Probes: list}, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(r.path), 0o700); err != nil {
return err
}
tmp := r.path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
if err := os.Chmod(tmp, 0o600); err != nil {
return err
}
return os.Rename(tmp, r.path)
}
// HashToken is the hex sha256 of a token.
func HashToken(tok string) string {
h := sha256.Sum256([]byte(tok))
return hex.EncodeToString(h[:])
}
// NewToken returns a fresh token: "urp_" + 43 base64url characters.
func NewToken() (string, error) {
var b [32]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return TokenPrefix + base64.RawURLEncoding.EncodeToString(b[:]), nil
}
// Create registers a probe and returns its token, shown only once. Creating a
// probe that was revoked replaces its token and makes it active again.
func (r *Registry) Create(name string) (string, error) {
if !wire.ValidName(name) || name == "all" {
return "", ErrName
}
tok, err := NewToken()
if err != nil {
return "", err
}
r.mu.Lock()
defer r.mu.Unlock()
if p, ok := r.probes[name]; ok && !p.Revoked {
return "", ErrExists
}
p := r.probes[name]
if p == nil {
p = &Probe{Name: name, Created: time.Now().Unix()}
r.probes[name] = p
}
p.TokenSHA256, p.Revoked = HashToken(tok), false
if err := r.save(); err != nil {
delete(r.probes, name)
return "", err
}
return tok, nil
}
// Revoke disables the token of a probe; its data stays.
func (r *Registry) Revoke(name string) error {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return ErrNotFound
}
p.Revoked = true
return r.save()
}
// Update replaces the location and the egress configuration of a probe.
func (r *Registry) Update(name string, loc *wire.Location, eg Egress) error {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return ErrNotFound
}
p.Location, p.Egress = loc, eg
return r.save()
}
// Verify checks a token in constant time; revoked and unknown probes fail.
func (r *Registry) Verify(name, token string) bool {
r.mu.Lock()
p := r.probes[name]
var want string
revoked := true
if p != nil {
want, revoked = p.TokenSHA256, p.Revoked
}
r.mu.Unlock()
if want == "" {
want = strings.Repeat("0", 64)
}
got := HashToken(token)
ok := subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
return ok && !revoked
}
// Get returns a copy of the entry.
func (r *Registry) Get(name string) (Probe, bool) {
r.mu.Lock()
defer r.mu.Unlock()
p, ok := r.probes[name]
if !ok {
return Probe{}, false
}
return *p, true
}
// List returns every entry sorted by name.
func (r *Registry) List() []Probe {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]Probe, 0, len(r.probes))
for _, p := range r.probes {
out = append(out, *p)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
+59
View File
@@ -0,0 +1,59 @@
package hub
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestRegistryHashOnlyAndRevoke(t *testing.T) {
p := filepath.Join(t.TempDir(), "probes.json")
r, err := OpenRegistry(p)
if err != nil {
t.Fatal(err)
}
tok, err := r.Create("hostinger")
if err != nil || !strings.HasPrefix(tok, "urp_") || len(tok) != 47 {
t.Fatalf("%q %v", tok, err)
}
if b, _ := os.ReadFile(p); strings.Contains(string(b), tok) {
t.Fatal("token stored")
}
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
t.Fatal(fi.Mode())
}
if !r.Verify("hostinger", tok) || r.Verify("hostinger", tok+"x") || r.Verify("other", tok) {
t.Fatal("verify")
}
if _, err := r.Create("hostinger"); err != ErrExists {
t.Fatal(err)
}
if _, err := r.Create("All"); err != ErrName {
t.Fatal(err)
}
r.Revoke("hostinger")
if r.Verify("hostinger", tok) {
t.Fatal("revoked token accepted")
}
}
func TestQueuePersistsAndPrunes(t *testing.T) {
p := filepath.Join(t.TempDir(), "commands.json")
q, _ := OpenQueue(p)
line := "2026-11-15T10:00:00Z urutau unban ip=203.0.113.9 allow=60\n"
for i := 0; i < 3; i++ {
if err := q.Enqueue("unban", line); err != nil {
t.Fatal(err)
}
}
if q.Enqueue("unban", "rm -rf /\n") == nil {
t.Fatal("invalid line queued")
}
q.Close()
q2, _ := OpenQueue(p)
defer q2.Close()
if q2.Last() != 3 || q2.Pending(1) != 2 {
t.Fatalf("%d %d", q2.Last(), q2.Pending(1))
}
}