package server import ( "context" "encoding/csv" "encoding/json" "errors" "net/http" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" ) const maxIncidentBody = 64 << 10 func init() { registerUserRoute("GET /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentList }) registerUserRoute("GET /api/v1/incidents/export.csv", func(s *Server) http.HandlerFunc { return s.incidentCSV }) registerUserRoute("GET /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet }) registerUserRoute("POST /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentCreate }) registerUserRoute("PATCH /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch }) registerUserRoute("POST /api/v1/incidents/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment }) // host/INC-n written as two path segments registerUserRoute("GET /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet }) registerUserRoute("PATCH /api/v1/incidents/{host}/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch }) registerUserRoute("POST /api/v1/incidents/{host}/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment }) } var incidentServer atomic.Pointer[Server] // StartIncidentSync runs the 60 s loop that feeds the incident store from the // merged egress report (same as GET /api/v1/egress, 24 h window). It does // nothing when incidents or egress are off. func StartIncidentSync(ctx context.Context, wg *sync.WaitGroup) { s := incidentServer.Load() if s == nil { return } wg.Add(1) go func() { defer wg.Done() t := time.NewTicker(60 * time.Second) defer t.Stop() for { s.syncNow(ctx) select { case <-ctx.Done(): s.opt.Incidents.Flush() return case <-t.C: } } }() } func (s *Server) syncNow(ctx context.Context) { if s.opt.Incidents == nil { return } now := s.opt.Store.Now().Unix() if s.opt.Nodes != nil { // one store per node, fed by that node's own egress for _, h := range s.opt.Nodes.Hosts() { eng, st := s.opt.Nodes.Egress(h), s.opt.Nodes.Incidents(h) if eng == nil || st == nil { continue } rep := eng.Report(now-24*3600, now) for i := range rep.Findings { rep.Findings[i].Host = h } s.syncInto(st, rep) } return } if egressEngine.Load() == nil { return } cctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "") s.syncInto(s.opt.Incidents, rep) } func (s *Server) findingHost(f egress.Finding) string { if f.Host != "" { return f.Host } return s.opt.Store.Name() } func (s *Server) findingKey(f egress.Finding) string { return incidents.Key(s.findingHost(f), f.Kind, f.Workload, f.Dst, f.DPort, f.Proto) } func (s *Server) syncIncidents(rep egress.Report) { s.syncInto(s.opt.Incidents, rep) } func (s *Server) syncInto(st *incidents.Store, rep egress.Report) { if st == nil { return } fs := make([]incidents.Finding, 0, len(rep.Findings)) for _, f := range rep.Findings { fs = append(fs, incidents.Finding{Host: s.findingHost(f), Kind: f.Kind, Severity: f.Severity, Workload: f.Workload, Dst: f.Dst, Proto: f.Proto, Detail: f.Detail, DPort: f.DPort, First: f.First, Last: f.Last, Count: f.Count}) } st.Sync(fs) } // annotateFindings fills ticket_id/ticket_status/suppressed and, unless show // is set, drops the findings whose ticket suppresses their exact key. It // returns how many were suppressed. func (s *Server) annotateFindings(rep *egress.Report, show bool) int { if s.opt.Incidents == nil || len(rep.Findings) == 0 { return 0 } refs := make([]incidents.Ref, len(rep.Findings)) has := make([]bool, len(rep.Findings)) byStore := map[string][]int{} for i, f := range rep.Findings { h := s.findingHost(f) byStore[h] = append(byStore[h], i) } for h, idx := range byStore { st := s.incStore(h) if st == nil { continue } keys := make([]string, len(idx)) for j, i := range idx { keys[j] = s.findingKey(rep.Findings[i]) } m := st.Lookup(keys) for j, i := range idx { if ref, ok := m[keys[j]]; ok { ref.ID = h + "/" + ref.ID refs[i], has[i] = ref, true } } } out := rep.Findings[:0:0] n := 0 for i, f := range rep.Findings { if has[i] { f.TicketID, f.TicketStatus, f.Suppressed = refs[i].ID, refs[i].Status, refs[i].Suppress } if f.Suppressed { n++ if !show { continue } } out = append(out, f) } rep.Findings = out return n } func (s *Server) incidentsOn(w http.ResponseWriter) bool { if s.opt.Incidents == nil { writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident management is not enabled"}) return false } return true } func incidentErr(w http.ResponseWriter, err error) { switch { case errors.Is(err, incidents.ErrNotFound): writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"}) case errors.Is(err, incidents.ErrConflict): writeJSON(w, http.StatusConflict, map[string]string{"error": strings.TrimPrefix(err.Error(), "conflict: ")}) case errors.Is(err, incidents.ErrInvalid): writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), "invalid: ")}) default: writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"}) } } // incidentBody checks the origin and decodes a strict JSON body (64 KiB max). func incidentBody(w http.ResponseWriter, r *http.Request, v any) bool { if !sameOrigin(r) { writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"}) return false } dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxIncidentBody)) dec.DisallowUnknownFields() if err := dec.Decode(v); err != nil || dec.More() { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"}) return false } return true } func csvList(v string) []string { var out []string for _, p := range strings.Split(v, ",") { if p = strings.TrimSpace(p); p != "" { out = append(out, p) } } return out } func (s *Server) incidentQuery(w http.ResponseWriter, r *http.Request) (incidents.Query, bool) { v := r.URL.Query() q := incidents.Query{Status: csvList(v.Get("status")), Severity: csvList(v.Get("severity")), Host: v.Get("host"), Q: v.Get("q"), Sort: v.Get("sort")} if len(q.Host) > 253 || len(q.Q) > 200 { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host or q"}) return q, false } for _, p := range []struct { name string dst *int }{{"page", &q.Page}, {"per_page", &q.PerPage}} { if x := v.Get(p.name); x != "" { n, err := strconv.Atoi(x) if err != nil || n < 1 || n > 100000 { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad " + p.name}) return q, false } *p.dst = n } } if err := q.Validate(); err != nil { incidentErr(w, err) return q, false } return q, true } // qSummary and qTicket carry the id qualified by the node ("hostinger/INC-2") // and the node as host. type qSummary struct { incidents.Summary ID string `json:"id"` Host string `json:"host"` } type qTicket struct { incidents.Ticket ID string `json:"id"` Host string `json:"host"` } type qPage struct { Items []qSummary `json:"items"` Total int `json:"total"` Counts map[string]int `json:"counts"` Store incidents.Stats `json:"store"` Hosts []string `json:"hosts"` } // splitID reads "INC-n" with an optional host (path segment, "host/INC-n" // in one segment, or ?host=); without host the primary node is meant. func (s *Server) splitID(r *http.Request) (host, id string) { id = r.PathValue("id") host = r.PathValue("host") if h, rest, ok := strings.Cut(id, "/"); ok { host, id = h, rest } if host == "" { host = r.URL.Query().Get("host") } if host == "" { host = s.primaryName() } return host, id } // storeFor answers 404 itself when the node has no ticket store. func (s *Server) storeFor(w http.ResponseWriter, host string) *incidents.Store { if st := s.incStore(host); st != nil { return st } writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"}) return nil } func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } q, ok := s.incidentQuery(w, r) if !ok { return } hosts := s.incSelect(q.Host) if hosts == nil { writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()}) return } q.Host = "" if len(hosts) == 1 { pg := s.incStore(hosts[0]).List(q) out := qPage{Items: make([]qSummary, 0, len(pg.Items)), Total: pg.Total, Counts: pg.Counts, Store: pg.Store, Hosts: s.incHosts()} for _, it := range pg.Items { out.Items = append(out.Items, qSummary{Summary: it, ID: hosts[0] + "/" + it.ID, Host: hosts[0]}) } writeJSON(w, 200, out) return } // several nodes: merge, sort and page here all := []qSummary{} out := qPage{Counts: map[string]int{}, Hosts: s.incHosts()} page, per := q.Page, q.PerPage for _, h := range hosts { st := s.incStore(h) if st == nil { continue } pg := st.List(incidents.Query{Status: q.Status, Severity: q.Severity, Q: q.Q, Sort: q.Sort, Page: 1, PerPage: 1}) for k, v := range pg.Counts { out.Counts[k] += v } out.Store.Size += pg.Store.Size out.Store.Max += pg.Store.Max out.Store.Untracked += pg.Store.Untracked for _, it := range st.All(q) { all = append(all, qSummary{Summary: it, ID: h + "/" + it.ID, Host: h}) } } sortSummaries(all, q.Sort) if per <= 0 { per = 50 } per = min(per, 200) if page < 1 { page = 1 } lo := min((page-1)*per, len(all)) hi := min(lo+per, len(all)) out.Total, out.Items = len(all), all[lo:hi] if out.Items == nil { out.Items = []qSummary{} } writeJSON(w, 200, out) } func sortSummaries(l []qSummary, mode string) { sort.SliceStable(l, func(i, j int) bool { a, b := l[i], l[j] switch mode { case "severity": if ra, rb := incidents.SevRank(a.Severity), incidents.SevRank(b.Severity); ra != rb { return ra > rb } case "last_seen": if a.LastSeen != b.LastSeen { return a.LastSeen > b.LastSeen } } return a.UpdatedAt > b.UpdatedAt }) } func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } host, id := s.splitID(r) st := s.storeFor(w, host) if st == nil { return } t, err := st.Get(id) if err != nil { incidentErr(w, err) return } writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host}) } func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } var in incidents.NewManual if !incidentBody(w, r, &in) { return } in.Via = s.via(r) host := s.primaryName() if in.Host != "" && s.incStore(in.Host) != nil { host = in.Host } t, err := s.incStore(host).Create(in) if err != nil { incidentErr(w, err) return } writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host}) } func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } var p incidents.Patch if !incidentBody(w, r, &p) { return } p.Via = s.via(r) host, id := s.splitID(r) st := s.storeFor(w, host) if st == nil { return } t, err := st.Update(id, p) if err != nil { incidentErr(w, err) return } writeJSON(w, 200, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host}) } func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } var in struct { Text string `json:"text"` Author string `json:"author"` } if !incidentBody(w, r, &in) { return } host, id := s.splitID(r) st := s.storeFor(w, host) if st == nil { return } t, err := st.AddComment(id, in.Text, in.Author, s.via(r)) if err != nil { incidentErr(w, err) return } writeJSON(w, http.StatusCreated, qTicket{Ticket: t, ID: host + "/" + t.ID, Host: host}) } // csvCell neutralises spreadsheet formulas. func csvCell(v string) string { if v == "" { return v } if v[0] == '\t' || v[0] == '\r' { return "'" + v } if t := strings.TrimLeft(v, " \t\r\n"); t != "" && strings.ContainsRune("=+-@", rune(t[0])) { return "'" + v } return v } // via names the credential that made a write, for the history. func (s *Server) via(r *http.Request) string { if s.authKind(r) == "bearer" { return "token" } return "session" } func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } q, ok := s.incidentQuery(w, r) if !ok { return } w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`) cw := csv.NewWriter(w) cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"}) hosts := s.incSelect(q.Host) q.Host = "" var rows []qSummary for _, h := range hosts { if st := s.incStore(h); st != nil { for _, t := range st.All(q) { rows = append(rows, qSummary{Summary: t, ID: h + "/" + t.ID, Host: h}) } } } for _, t := range rows { row := []string{t.ID, t.Status, t.Severity, t.Host, t.Kind, t.Workload, t.Dst, strconv.Itoa(int(t.DPort)), t.Proto, t.Title, strconv.FormatInt(t.FirstSeen, 10), strconv.FormatInt(t.LastSeen, 10), strconv.Itoa(t.Count), t.Assignee, strings.Join(t.Tags, ","), t.Verdict, strconv.FormatBool(t.Suppress), strconv.FormatInt(t.CreatedAt, 10), strconv.FormatInt(t.UpdatedAt, 10)} for i := range row { row[i] = csvCell(row[i]) } cw.Write(row) } cw.Flush() } // incSelect resolves the host filter of the ticket queries: "" or "all" is // every host with a store, otherwise the listed ones (comma list) that have // one. It returns nil when a selection names none. func (s *Server) incSelect(raw string) []string { if raw == "" || raw == "all" { return s.incHosts() } var out []string seen := map[string]bool{} for _, n := range strings.Split(raw, ",") { n = strings.TrimSpace(n) if n == "all" { return s.incHosts() } if n == "" || seen[n] || s.incStore(n) == nil { continue } seen[n] = true out = append(out, n) } return out }