Files
urutau/internal/store/services.go
T
Lucas RayanandClaude Opus 5.5 2ebda1e4d7
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

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

511 lines
12 KiB
Go

package store
import (
"net/url"
"sort"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Per-service health: for every backend service, per hour, the request mix,
// the error classes (see core.ErrorClass), latency histograms, Apdex and the
// protocol/TLS mix; per day the top failing routes, broken links and so on.
const (
svcCap = 64
svcOther = "(other)"
svcRoutes = 200
svcCiphers = 50
svcLatN = latN + 1 // the existing bounds plus a 30 s bound
)
// Class slots of svcHour.Cls.
const (
ClsApp = iota
ClsProxy
ClsBlocked
ClsAttack
ClsBot
ClsClientBroken
ClsClientAuth
ClsClientOther
NumCls
)
// ClsNames names the Cls slots.
var ClsNames = [NumCls]string{"app", "proxy", "blocked", "attack", "bot", "client_broken", "client_auth", "client_other"}
// SvcBounds are the upper bounds (ms) of the latency histograms; the last
// bucket is everything above.
var SvcBounds = [svcLatN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000}
func svcBucket(ns int64) int {
ms := float64(ns) / 1e6
for i, b := range SvcBounds {
if ms <= b {
return i
}
}
return svcLatN - 1
}
type svcHour struct {
Hour int64
Req, Legit uint32
Cls [NumCls]uint32
S [5]uint32 // 2xx 3xx 4xx 5xx other
Dur, Org, Ov [svcLatN]uint32
ApSat, ApTol uint32 // Apdex satisfied / tolerating
ApN uint32
Retries uint32
Proto [4]uint32 // HTTP/1.x HTTP/2 HTTP/3 other
TLS [4]uint32 // 1.3 1.2 older none
BytesMax uint32
}
type svcDay struct {
Day int64
ErrRoutes map[string]uint32 // "class|METHOD path"
Broken404 map[string]uint32 // "path\x00referer path"
Methods map[string]uint32 // "METHOD|class"
Ciphers map[string]uint32
ProtoCls map[string]uint32 // "proto|class"
TLSCls map[string]uint32 // "tls|class"
Last404 map[string]int64 // broken link key -> last seen
}
type svcData struct {
Hours [hourSlots]svcHour
Days [anDays]svcDay
Doms map[string]uint32
Last int64
}
type svcState struct {
m map[string]*svcData
}
// ServiceKey names the service of an event: the Traefik service without the
// provider suffix, else the router, else the host.
func ServiceKey(ev core.Event) string {
k := ev.Service
if k == "" || strings.HasPrefix(k, "noop@") || strings.HasPrefix(k, "api@") {
k = ev.Router
}
if i := strings.IndexByte(k, '@'); i >= 0 {
k = k[:i]
}
if k == "" {
k = normDomain(ev.Domain)
}
return clipS(k, 64)
}
func isAPIPath(p string) bool {
return strings.HasPrefix(p, "/api") || strings.HasPrefix(p, "/v2/") || p == "/v2" || strings.HasPrefix(p, "/graphql") || strings.HasPrefix(p, "/trpc")
}
func urlPath(ref string) string {
u, err := url.Parse(ref)
if err != nil || u.Host == "" {
return ""
}
p := u.EscapedPath()
if p == "" {
p = "/"
}
// a Referer path can carry personal data or secrets (reset links, e-mail)
return clipS(normalizePath(p), 120)
}
func clsSlot(class, sub string) int {
switch class {
case core.ClassApp:
return ClsApp
case core.ClassProxy:
return ClsProxy
case core.ClassBlocked:
return ClsBlocked
case core.ClassAttack:
return ClsAttack
case core.ClassBot:
return ClsBot
case core.ClassClient:
switch sub {
case core.SubBrokenLink, core.SubExternalLink:
return ClsClientBroken
case core.SubAuth, core.SubAuthChallenge:
return ClsClientAuth
}
return ClsClientOther
}
return -1
}
func protoSlot(p string) int {
switch {
case strings.HasPrefix(p, "HTTP/1"):
return 0
case strings.HasPrefix(p, "HTTP/2"):
return 1
case strings.HasPrefix(p, "HTTP/3"):
return 2
}
return 3
}
func protoName(i int) string { return [...]string{"http1", "http2", "http3", "other"}[i] }
func tlsSlot(ev core.Event) int {
switch ev.TLSVer {
case "1.3":
return 0
case "1.2":
return 1
case "":
if ev.Scheme == "http" || ev.Scheme == "" {
return 3
}
}
return 2
}
// TLSName names the TLS slots.
func TLSName(i int) string { return [...]string{"tls13", "tls12", "tls_old", "none"}[i] }
// ObserveService records one Traefik request for the service health views. It
// takes every request (attacks too: the error classes need them) but only
// those that carry the origin fields feed the latency and protocol parts.
func (s *Store) ObserveService(ev core.Event) {
if ev.Source != "traefik" {
return
}
now := s.now()
if ev.Time.Before(now.Add(-s.cfg.Retention)) {
return
}
ts := ev.Time.Unix()
if max := now.Unix() + 300; ts > max {
ts = max
}
key := ServiceKey(ev)
dom := normDomain(ev.Domain)
s.mu.Lock()
defer s.mu.Unlock()
susp := false
if r := s.ips[ev.IP]; r != nil {
susp = r.BanSince > 0 || core.LevelOf(r.Score, r.Strong || attackKinds(r.Counts) >= 2, r.adminAt(now.Unix())) != core.LevelLow
}
if s.sv.m == nil {
s.sv.m = map[string]*svcData{}
}
d := s.sv.m[key]
if d == nil {
if len(s.sv.m) >= svcCap {
key = svcOther
d = s.sv.m[key]
}
if d == nil {
d = &svcData{}
s.sv.m[key] = d
}
}
d.Last = ts
bumpCap(&d.Doms, dom, 8)
h := ts / 3600
hs := &d.Hours[int(h%hourSlots)]
if hs.Hour != h {
*hs = svcHour{Hour: h}
}
day := ts / 86400
dd := &d.Days[int(day%anDays)]
if dd.Day != day {
*dd = svcDay{Day: day}
}
hs.Req++
switch c := ev.Status / 100; {
case c >= 2 && c <= 5:
hs.S[c-2]++
default:
hs.S[4]++
}
class, sub, _ := core.ErrorClassify(ev, susp)
slot := clsSlot(class, sub)
attackish := ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce || susp
if slot >= 0 {
hs.Cls[slot]++
}
if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && !(slot < 0 && attackish) {
hs.Legit++
}
if ev.Retries > 0 {
hs.Retries += uint32(ev.Retries)
}
if ev.DurationNS > 0 {
hs.Dur[svcBucket(ev.DurationNS)]++
}
if ev.OriginNS > 0 {
hs.Org[svcBucket(ev.OriginNS)]++
}
if ev.OverheadNS > 0 {
hs.Ov[svcBucket(ev.OverheadNS)]++
}
if ev.Bytes > 0 {
b := uint32(min64(ev.Bytes, 1<<32-1))
if b > hs.BytesMax {
hs.BytesMax = b
}
}
// Apdex over the requests that count for the service
if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && ev.DurationNS > 0 {
t := int64(500e6)
if isAPIPath(ev.Path) {
t = 1000e6
}
hs.ApN++
switch {
case ev.Status >= 500:
case ev.DurationNS <= t:
hs.ApSat++
case ev.DurationNS <= 4*t:
hs.ApTol++
}
}
if ev.Proto != "" {
hs.Proto[protoSlot(ev.Proto)]++
hs.TLS[tlsSlot(ev)]++
if ev.TLSCiph != "" {
bumpCap(&dd.Ciphers, ev.TLSCiph, svcCiphers)
}
}
cn := class
if cn == "" {
cn = "ok"
}
if ev.Method != "" {
bumpCap(&dd.Methods, strings.ToUpper(ev.Method)+"|"+cn, svcCiphers*2)
}
if ev.Proto != "" {
bumpCap(&dd.ProtoCls, protoName(protoSlot(ev.Proto))+"|"+cn, 40)
bumpCap(&dd.TLSCls, TLSName(tlsSlot(ev))+"|"+cn, 40)
}
if class == "" {
return
}
p := ev.Path
if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
np := normalizePath(p)
bumpCap(&dd.ErrRoutes, class+"|"+strings.ToUpper(ev.Method)+" "+clipS(np, 120), svcRoutes)
if class == core.ClassClient && ev.Status == 404 && (sub == core.SubBrokenLink || sub == core.SubExternalLink) {
rp := urlPath(ev.Referer)
if rp == "" {
rp = "-"
}
k := clipS(np, 120) + "\x00" + rp
if sub == core.SubExternalLink {
if u, err := url.Parse(ev.Referer); err == nil {
rp = u.Hostname()
}
k = clipS(np, 120) + "\x00" + "@" + rp
}
bumpCap(&dd.Broken404, k, svcRoutes)
if dd.Last404 == nil {
dd.Last404 = map[string]int64{}
}
if _, ok := dd.Broken404[k]; ok {
dd.Last404[k] = ts
}
if len(dd.Last404) > 2*svcRoutes {
for kk := range dd.Last404 {
if _, ok := dd.Broken404[kk]; !ok {
delete(dd.Last404, kk)
}
}
}
}
}
func min64(a, b int64) int64 {
if a < b {
return a
}
return b
}
// SvcView is one service over a window.
type SvcView struct {
Key, Alias string
Hours []SvcHourOut // hours in the window, ascending (only those with traffic)
Tot SvcHourOut // the sum
ErrRoutes map[string]uint32
Broken map[string]uint32
BrokenLast map[string]int64
Methods map[string]uint32
Ciphers map[string]uint32
ProtoCls map[string]uint32
TLSCls map[string]uint32
}
// SvcHourOut is an exported copy of an hour (or of a sum of hours).
type SvcHourOut struct {
Hour int64
Req, Legit uint32
Cls [NumCls]uint32
S [5]uint32
Dur, Org, Ov [svcLatN]uint32
ApSat, ApTol uint32
ApN uint32
Retries uint32
Proto [4]uint32
TLS [4]uint32
BytesMax uint32
}
func (o *SvcHourOut) add(h *svcHour) {
o.Req += h.Req
o.Legit += h.Legit
o.ApSat += h.ApSat
o.ApTol += h.ApTol
o.ApN += h.ApN
o.Retries += h.Retries
if h.BytesMax > o.BytesMax {
o.BytesMax = h.BytesMax
}
for i := range h.Cls {
o.Cls[i] += h.Cls[i]
}
for i := range h.S {
o.S[i] += h.S[i]
}
for i := range h.Dur {
o.Dur[i] += h.Dur[i]
o.Org[i] += h.Org[i]
o.Ov[i] += h.Ov[i]
}
for i := range h.Proto {
o.Proto[i] += h.Proto[i]
o.TLS[i] += h.TLS[i]
}
}
func mergeMap(dst *map[string]uint32, src map[string]uint32) {
if len(src) == 0 {
return
}
if *dst == nil {
*dst = make(map[string]uint32, len(src))
}
for k, v := range src {
(*dst)[k] += v
}
}
// Services returns every service with traffic in [from, to] (unix seconds),
// busiest first. svc filters by key or alias, host by served domain; both may be "".
func (s *Store) Services(from, to int64, svc, host string) []SvcView {
fh, lh := from/3600, to/3600
fd, ld := from/86400, to/86400
s.mu.RLock()
defer s.mu.RUnlock()
var out []SvcView
for key, d := range s.sv.m {
v := SvcView{Key: key, Alias: svcAlias(key, d)}
if svc != "" && svc != key && svc != v.Alias {
continue
}
if host != "" {
if _, ok := d.Doms[host]; !ok {
continue
}
}
for i := range d.Hours {
h := &d.Hours[i]
if h.Hour == 0 || h.Hour < fh || h.Hour > lh || h.Req == 0 {
continue
}
var o SvcHourOut
o.Hour = h.Hour
o.add(h)
v.Hours = append(v.Hours, o)
v.Tot.add(h)
}
if v.Tot.Req == 0 {
continue
}
sort.Slice(v.Hours, func(a, b int) bool { return v.Hours[a].Hour < v.Hours[b].Hour })
for i := range d.Days {
dd := &d.Days[i]
if dd.Day == 0 || dd.Day < fd || dd.Day > ld {
continue
}
mergeMap(&v.ErrRoutes, dd.ErrRoutes)
mergeMap(&v.Broken, dd.Broken404)
mergeMap(&v.Methods, dd.Methods)
mergeMap(&v.Ciphers, dd.Ciphers)
mergeMap(&v.ProtoCls, dd.ProtoCls)
mergeMap(&v.TLSCls, dd.TLSCls)
for k, t := range dd.Last404 {
if v.BrokenLast == nil {
v.BrokenLast = map[string]int64{}
}
if t > v.BrokenLast[k] {
v.BrokenLast[k] = t
}
}
}
out = append(out, v)
}
sort.Slice(out, func(a, b int) bool {
if out[a].Tot.Req != out[b].Tot.Req {
return out[a].Tot.Req > out[b].Tot.Req
}
return out[a].Key < out[b].Key
})
return out
}
// svcAlias is the most frequent domain of the service, or the key itself.
func svcAlias(key string, d *svcData) string {
best, n := "", uint32(0)
for dom, c := range d.Doms {
if c > n || c == n && dom < best {
best, n = dom, c
}
}
if best == "" || best == "-" {
return key
}
return best
}
// Quantile estimates the q-quantile (0..1) in milliseconds from a latency
// histogram laid out by SvcBounds (linear inside the bucket); 0 when empty.
func Quantile(h [svcLatN]uint32, q float64) float64 {
var tot float64
for _, c := range h {
tot += float64(c)
}
if tot == 0 {
return 0
}
target := q * tot
var acc float64
lo := 0.0
for i, c := range h {
up := SvcBounds[len(SvcBounds)-1] * 2
if i < len(SvcBounds) {
up = SvcBounds[i]
}
if acc+float64(c) >= target && c > 0 {
return lo + (up-lo)*(target-acc)/float64(c)
}
acc += float64(c)
lo = up
}
return lo
}