diff --git a/internal/wire/wire.go b/internal/wire/wire.go new file mode 100644 index 0000000..f49596b --- /dev/null +++ b/internal/wire/wire.go @@ -0,0 +1,201 @@ +// Package wire is the probe↔hub protocol of Urutau 2. +package wire + +import ( + "errors" + "net/netip" + "net/url" + "regexp" + "strings" +) + +const ( + Proto = 1 + PathHello = "/api/v1/probe/hello" + PathPush = "/api/v1/probe/push" + PathCommands = "/api/v1/probe/commands" + HeaderProbe = "X-Urutau-Probe" + MaxBodyBytes = 2 << 20 + MaxInflated = 8 << 20 + MaxLines = 5000 + MaxLine = 64 * 1024 + MaxFileBytes = 1 << 20 // containers.map / resolv.conf + MaxCmdLine = 512 + MaxWaitSec = 25 + HeartbeatSec = 15 + OfflineSec = 45 +) + +// Source names (fixed set; the hub rejects others). +const ( + SrcTraefik = "traefik" + SrcAuth = "auth" + SrcFail2ban = "fail2ban" + SrcProbe = "probe" + SrcEgress = "egress" +) + +// File names carried whole. +const ( + FileContainers = "containers.map" + FileResolv = "resolv.conf" +) + +var Sources = []string{SrcTraefik, SrcAuth, SrcFail2ban, SrcProbe, SrcEgress} + +func ValidSource(s string) bool { + for _, x := range Sources { + if x == s { + return true + } + } + return false +} + +var nameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`) + +// ValidName is the probe/host name rule (also the data-dir subdirectory). +func ValidName(s string) bool { return nameRE.MatchString(s) } + +// Pos mirrors tail.Pos / store.Offset. +type Pos struct { + Inode uint64 `json:"inode"` + Offset int64 `json:"offset"` + FP uint64 `json:"fp,omitempty"` + FPLen int `json:"fplen,omitempty"` +} + +type Location struct { + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Label string `json:"label,omitempty"` +} + +type Hello struct { + Proto int `json:"proto"` + Name string `json:"name"` + Version string `json:"version"` + Hostname string `json:"hostname,omitempty"` + Sources []string `json:"sources"` // configured (enabled) sources + Location *Location `json:"location,omitempty"` // URUTAU_LOCATION of the probe; hub config wins + LastSeq uint64 `json:"last_seq"` + LastCmd uint64 `json:"last_cmd"` +} + +type HelloResp struct { + Proto int `json:"proto"` + HubVer string `json:"hub_version"` + Offsets map[string]Pos `json:"offsets"` // hub-committed position per source + AckSeq uint64 `json:"ack_seq"` // last batch applied + FlushMS int `json:"flush_ms"` // suggested batch interval (default 1000) +} + +// Line is one raw log line. End is the position right after the line +// (newline included) in file Inode; the hub dedups on it. +type Line struct { + Src string `json:"s"` + Text string `json:"t"` // invalid UTF-8 is replaced by U+FFFD + End Pos `json:"e"` +} + +// File is a whole small file, sent on change. +type File struct { + Name string `json:"name"` + Data string `json:"data"` +} + +type SourceStatus struct { + Src string `json:"src"` + State string `json:"state"` // following|waiting|error + Error string `json:"error,omitempty"` // "permission denied"|"read error", never a path + Lines uint64 `json:"lines"` + Oversize uint64 `json:"oversize"` + LastLine int64 `json:"last_line"` // unix seconds +} + +type Status struct { + UptimeSec int64 `json:"uptime"` + RSSBytes uint64 `json:"rss"` + SpoolBytes int64 `json:"spool_bytes"` + SpoolFiles int `json:"spool_files"` + Dropped uint64 `json:"dropped"` // lines discarded by the spool cap (cumulative) + CmdErrors uint64 `json:"cmd_errors"` + Sources []SourceStatus `json:"sources"` +} + +type Batch struct { + Seq uint64 `json:"seq"` // 0 = heartbeat only (never acked/stored) + Sent int64 `json:"sent"` // unix ms, for lag + Lines []Line `json:"lines,omitempty"` + Files []File `json:"files,omitempty"` + Status *Status `json:"status,omitempty"` +} + +type PushResp struct { + Ack uint64 `json:"ack"` + Accepted int `json:"accepted"` + Dup int `json:"dup"` + PendCmd uint64 `json:"pend_cmd"` // highest queued command seq (hint) +} + +const ( + CmdDecision = "decision" // append to decisions.log + CmdUnban = "unban" // append to unban.log +) + +type Cmd struct { + Seq uint64 `json:"seq"` + Kind string `json:"kind"` + Line string `json:"line"` // full line incl. trailing "\n" +} + +type CmdResp struct { + Cmds []Cmd `json:"cmds"` + Dropped uint64 `json:"dropped,omitempty"` +} + +var ( + decRE = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ urutau decision=ban ip=([0-9a-fA-F:.]+) reason=[a-z0-9_-]{1,32} score=\d{1,3} ttl=\d{1,9} host=[A-Za-z0-9._-]{1,64} src=(local|peer:[A-Za-z0-9._-]{1,64})\n$`) + unbanRE = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ urutau unban ip=([0-9a-fA-F:.]+) allow=\d{1,9}\n$`) +) + +// ValidCmdLine is the probe-side guard: only lines enforce.FormatLine / +// enforce.UnbanLine can produce are ever written to the host files. +func ValidCmdLine(kind, line string) bool { + if len(line) > MaxCmdLine { + return false + } + var m []string + switch kind { + case CmdDecision: + m = decRE.FindStringSubmatch(line) + case CmdUnban: + m = unbanRE.FindStringSubmatch(line) + } + if m == nil { + return false + } + _, err := netip.ParseAddr(m[1]) + return err == nil +} + +// CheckHubURL accepts https, or http only for loopback/private hosts. +func CheckHubURL(raw string) (*url.URL, error) { + u, err := url.Parse(strings.TrimRight(raw, "/")) + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" { + return nil, errors.New("invalid hub URL") + } + switch u.Scheme { + case "https": + return u, nil + case "http": + h := u.Hostname() + if a, err := netip.ParseAddr(h); err == nil && (a.IsLoopback() || a.IsPrivate()) { + return u, nil + } + if h == "localhost" || !strings.Contains(h, ".") { // docker service name + return u, nil + } + } + return nil, errors.New("hub URL must be https (http only for local/private hosts)") +}