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 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=&wait=. 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)) }