package server import ( "context" "encoding/csv" "encoding/json" "errors" "net/http" "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 }) } 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 || egressEngine.Load() == nil { return } now := s.opt.Store.Now().Unix() cctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "") s.syncIncidents(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) { if s.opt.Incidents == 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}) } s.opt.Incidents.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 } keys := make([]string, len(rep.Findings)) for i, f := range rep.Findings { keys[i] = s.findingKey(f) } refs := s.opt.Incidents.Lookup(keys) out := rep.Findings[:0:0] n := 0 for i, f := range rep.Findings { if ref, ok := refs[keys[i]]; ok { f.TicketID, f.TicketStatus, f.Suppressed = ref.ID, ref.Status, ref.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 } func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } q, ok := s.incidentQuery(w, r) if !ok { return } writeJSON(w, 200, s.opt.Incidents.List(q)) } func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) { if !s.incidentsOn(w) { return } t, err := s.opt.Incidents.Get(r.PathValue("id")) if err != nil { incidentErr(w, err) return } writeJSON(w, 200, t) } 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) t, err := s.opt.Incidents.Create(in) if err != nil { incidentErr(w, err) return } writeJSON(w, http.StatusCreated, t) } 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) t, err := s.opt.Incidents.Update(r.PathValue("id"), p) if err != nil { incidentErr(w, err) return } writeJSON(w, 200, t) } 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 } t, err := s.opt.Incidents.AddComment(r.PathValue("id"), in.Text, in.Author, s.via(r)) if err != nil { incidentErr(w, err) return } writeJSON(w, http.StatusCreated, t) } // 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"}) for _, t := range s.opt.Incidents.All(q) { 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() }