Files
urutau/internal/egress/workload.go
T
Lucas RayanandClaude Opus 5.5 8546d14cef
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
feat!: Urutau 2.0.0, ultralight probes and a single analysis hub
Each server runs an ultralight probe (scratch image, ~7 MiB RSS) that
tails the logs, ships raw lines to the hub over HTTPS with an on-disk
spool, and applies enforce decisions locally. The hub keeps one node per
probe (primary node = the 1.x data dir, unchanged), does all analysis and
serves the UI. Peer federation is removed. 'urutau import' brings 1.x
data dirs in with hash and count verification. UI: probes page, host
qualified incidents, IPs never wrap, egress heatmap labels, live and
replay globes no longer auto-rotate, replay repeat, live traffic metrics.

BREAKING CHANGE: URUTAU_PEERS, URUTAU_PEER_* and /api/v1/peer/* are gone;
log path variables move from the hub to the probe. See docs/migration-2.0.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:14:50 -03:00

176 lines
4.8 KiB
Go

package egress
import (
"bufio"
"fmt"
"io"
"net/netip"
"os"
"regexp"
"strings"
)
// Roles of a workload.
const (
RoleDefault = "default"
RoleScanner = "scanner"
RoleMail = "mail"
RoleResolver = "resolver"
)
func validRole(r string) bool {
return r == RoleDefault || r == RoleScanner || r == RoleMail || r == RoleResolver
}
type matcher struct {
prefix netip.Prefix // valid when name == "" and !host
name string // container name: exact base name, or a prefix when pfx
pfx bool
host bool // the host's own output ("host")
}
type workloadDef struct {
name, role string
m []matcher
}
// ParseWorkloads parses "name=ITEM,ITEM:role;name2=...". An ITEM is a CIDR, an
// IP, "host" (the host's own output, so it can take a role such as mail),
// "name:<container name>" (exact base name, without the -<digits> suffix) or
// "name:<prefix>*" (explicit prefix); the role (scanner, mail, resolver,
// default) follows the last colon.
func ParseWorkloads(s string) ([]workloadDef, error) {
var out []workloadDef
for _, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, rest, ok := strings.Cut(part, "=")
name, rest = strings.TrimSpace(name), strings.TrimSpace(rest)
if !ok || name == "" || rest == "" {
return nil, fmt.Errorf("workload %q: expected name=items[:role]", part)
}
role := RoleDefault
if i := strings.LastIndex(rest, ":"); i >= 0 && validRole(rest[i+1:]) {
role, rest = rest[i+1:], rest[:i]
}
w := workloadDef{name: name, role: role}
for _, it := range strings.Split(rest, ",") {
it = strings.TrimSpace(it)
switch {
case it == "":
case it == "host":
w.m = append(w.m, matcher{host: true})
case strings.HasPrefix(it, "name:"):
p := strings.TrimPrefix(it, "name:")
pfx := strings.HasSuffix(p, "*")
p = strings.TrimSuffix(p, "*")
if !nameRe.MatchString(p) {
return nil, fmt.Errorf("workload %q: bad container name %q", name, p)
}
w.m = append(w.m, matcher{name: p, pfx: pfx})
default:
pf, err := netip.ParsePrefix(it)
if err != nil {
a, err2 := netip.ParseAddr(it)
if err2 != nil {
return nil, fmt.Errorf("workload %q: bad address %q", name, it)
}
pf = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
}
w.m = append(w.m, matcher{prefix: pf.Masked()})
}
}
if len(w.m) == 0 {
return nil, fmt.Errorf("workload %q: no addresses", name)
}
out = append(out, w)
}
return out, nil
}
var nameRe = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`)
var tsSuffix = regexp.MustCompile(`-\d{9,}$`)
var digitSuffix = regexp.MustCompile(`-\d+$`)
// ContainerBase strips the "-<timestamp>" suffix of a container name.
func ContainerBase(n string) string { return tsSuffix.ReplaceAllString(n, "") }
const maxMapLines = 10000
// LoadContainers reads a containers.map file ("<ip> <name>" per line; invalid
// lines are skipped, at most 10k lines).
func LoadContainers(path string) (map[netip.Addr]string, error) {
fh, err := os.Open(path)
if err != nil {
return nil, err
}
defer fh.Close()
return parseContainers(fh)
}
// parseContainers reads the containers.map format from r.
func parseContainers(r io.Reader) (map[netip.Addr]string, error) {
m := map[netip.Addr]string{}
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 0, 4096), 4096)
for n := 0; sc.Scan() && n < maxMapLines; n++ {
f := strings.Fields(sc.Text())
if len(f) != 2 || !nameRe.MatchString(f[1]) {
continue
}
a, err := netip.ParseAddr(f[0])
if err != nil {
continue
}
m[a.Unmap()] = f[1]
}
return m, sc.Err()
}
// resolve names the workload of an event: host output is "host"; a container
// address matches the configured workloads (CIDR or container name from the
// current map); otherwise it is named after its mapped container (without the
// timestamp suffix) or "container <ip>".
func (e *Engine) resolve(ev Event) (name, role string) {
if ev.Host {
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
return w.name, w.role
}
}
}
return "host", RoleDefault
}
cname := e.containers[ev.Src]
for _, w := range e.wls {
for _, m := range w.m {
if m.host {
continue
}
if m.name != "" {
if cname != "" && m.matchName(cname) {
return w.name, w.role
}
} else if m.prefix.Contains(ev.Src) {
return w.name, w.role
}
}
}
if cname != "" {
return ContainerBase(cname), RoleDefault
}
return "container " + ev.Src.String(), RoleDefault
}
// matchName compares a container name: the exact base name (the full name or
// without a -<digits> suffix), or a prefix when the item ended in "*".
func (m matcher) matchName(cname string) bool {
if m.pfx {
return strings.HasPrefix(cname, m.name)
}
return cname == m.name || digitSuffix.ReplaceAllString(cname, "") == m.name
}