Release / Publish tags (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m14s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m13s
CI / Format and vet (push) Successful in 41s
CI / Tests (Linux, race detector) (push) Successful in 1m1s
CI / Dependency audit (push) Successful in 33s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1003 lines
27 KiB
Go
1003 lines
27 KiB
Go
// Package incidents keeps the tickets ("chamados") opened from egress findings
|
|
// or by hand: status, verdict, comments and a change history, persisted in
|
|
// <data-dir>/incidents.json. A ticket in false_positive or benign may suppress
|
|
// the findings with exactly its key.
|
|
package incidents
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Limits.
|
|
const (
|
|
MaxTickets = 5000
|
|
MaxComments = 200
|
|
MaxHistory = 500
|
|
MaxTags = 10
|
|
MaxTagLen = 32
|
|
MaxTitle = 200
|
|
MaxLong = 4000 // verdict, detail
|
|
MaxComment = 5000
|
|
MaxShort = 64 // author, assignee
|
|
MaxHost = 253
|
|
DefaultAuth = "operator"
|
|
Robot = "urutau"
|
|
)
|
|
|
|
var (
|
|
// ErrNotFound: no ticket with that id.
|
|
ErrNotFound = errors.New("incident not found")
|
|
// ErrInvalid wraps every validation failure (HTTP 400).
|
|
ErrInvalid = errors.New("invalid")
|
|
// ErrConflict: a refused suppression or a stale expected_updated_at (HTTP 409).
|
|
ErrConflict = errors.New("conflict")
|
|
)
|
|
|
|
func conflict(format string, a ...any) error {
|
|
return fmt.Errorf("%w: %s", ErrConflict, fmt.Sprintf(format, a...))
|
|
}
|
|
|
|
// Suppression and flood policy.
|
|
const (
|
|
SuppressTTL = 30 * 24 * time.Hour
|
|
SuppressMax = 90 * 24 * time.Hour
|
|
HostQuota = 300 // active (open/investigating) tickets per host before grouping
|
|
SaveDebounce = 30 * time.Second
|
|
floodTailKeep = 5
|
|
floodHead = "last grouped destinations:"
|
|
)
|
|
|
|
func invalid(format string, a ...any) error {
|
|
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, a...))
|
|
}
|
|
|
|
var (
|
|
statuses = []string{"open", "investigating", "true_positive", "false_positive", "benign", "resolved"}
|
|
severities = []string{"info", "low", "medium", "high", "critical"}
|
|
)
|
|
|
|
// Statuses lists the valid statuses.
|
|
func Statuses() []string { return append([]string(nil), statuses...) }
|
|
|
|
func inList(l []string, v string) bool {
|
|
for _, x := range l {
|
|
if x == v {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// SevRank orders severities (unknown = -1).
|
|
func SevRank(s string) int {
|
|
for i, x := range severities {
|
|
if x == s {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
func suppressible(status string) bool { return status == "false_positive" || status == "benign" }
|
|
func closed(status string) bool {
|
|
return status == "resolved" || status == "false_positive" || status == "benign"
|
|
}
|
|
|
|
// Comment is one note on a ticket.
|
|
type Comment struct {
|
|
ID int `json:"id"`
|
|
At int64 `json:"at"`
|
|
Author string `json:"author"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// Change is one history entry.
|
|
type Change struct {
|
|
At int64 `json:"at"`
|
|
Author string `json:"author"`
|
|
Field string `json:"field"`
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
}
|
|
|
|
type base struct {
|
|
ID string `json:"id"`
|
|
Key string `json:"key"`
|
|
Source string `json:"source"`
|
|
Host string `json:"host"`
|
|
Kind string `json:"kind"`
|
|
Severity string `json:"severity"`
|
|
MaxSeverity string `json:"max_severity"`
|
|
Workload string `json:"workload"`
|
|
Dst string `json:"dst"`
|
|
DPort uint16 `json:"dport"`
|
|
Proto string `json:"proto"`
|
|
Title string `json:"title"`
|
|
Detail string `json:"detail"`
|
|
FirstSeen int64 `json:"first_seen"`
|
|
LastSeen int64 `json:"last_seen"`
|
|
Count int `json:"count"`
|
|
Status string `json:"status"`
|
|
Verdict string `json:"verdict"`
|
|
Assignee string `json:"assignee"`
|
|
Tags []string `json:"tags"`
|
|
Suppress bool `json:"suppress"`
|
|
CreatedAt int64 `json:"created_at"`
|
|
UpdatedAt int64 `json:"updated_at"`
|
|
// SuppressedSev is the highest severity when the ticket was closed as FP/benign;
|
|
// a worse finding reopens it. SuppressUntil ends a suppression (unix s).
|
|
SuppressedSev string `json:"suppressed_sev"`
|
|
SuppressedAt int64 `json:"suppressed_at"`
|
|
SuppressUntil int64 `json:"suppress_until"`
|
|
SeverityManual bool `json:"severity_manual"`
|
|
}
|
|
|
|
// Ticket is a full incident.
|
|
type Ticket struct {
|
|
base
|
|
Comments []Comment `json:"comments"`
|
|
History []Change `json:"history"`
|
|
}
|
|
|
|
// Summary is a ticket without comments and history.
|
|
type Summary struct {
|
|
base
|
|
CommentCount int `json:"comment_count"`
|
|
}
|
|
|
|
// Finding is what Sync reads from an egress finding.
|
|
type Finding struct {
|
|
Host, Kind, Severity, Workload, Dst, Proto, Detail string
|
|
DPort uint16
|
|
First, Last int64
|
|
Count int
|
|
}
|
|
|
|
// Key identifies a finding: sha256 (hex) of host, kind, workload, dst, dport and
|
|
// proto, each with its length in front so no value can mimic a separator.
|
|
func Key(host, kind, workload, dst string, dport uint16, proto string) string {
|
|
h := sha256.New()
|
|
for _, f := range []string{host, kind, workload, dst, strconv.Itoa(int(dport)), proto} {
|
|
h.Write([]byte(strconv.Itoa(len(f)) + ":" + f))
|
|
}
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
}
|
|
|
|
func floodKey(host string) string { return Key(host, "flood", "", "", 0, "") }
|
|
|
|
// Key of the finding.
|
|
func (f Finding) Key() string { return Key(f.Host, f.Kind, f.Workload, f.Dst, f.DPort, f.Proto) }
|
|
|
|
// Ref is the light view of a ticket used to annotate findings.
|
|
type Ref struct {
|
|
ID string
|
|
Status string
|
|
Suppress bool
|
|
}
|
|
|
|
// Store is the persistent set of tickets.
|
|
type Store struct {
|
|
mu sync.Mutex
|
|
path string
|
|
log *slog.Logger
|
|
now func() time.Time
|
|
byID map[string]*Ticket
|
|
byKey map[string]*Ticket
|
|
next int
|
|
|
|
untracked int // findings dropped because the store was full
|
|
dirty bool // counters changed, not yet written
|
|
lastSave time.Time // of the last write
|
|
flooded map[string]bool // keys grouped into flood tickets (not persisted)
|
|
}
|
|
|
|
type disk struct {
|
|
Next int `json:"next"`
|
|
Tickets []*Ticket `json:"tickets"`
|
|
}
|
|
|
|
// Open loads path (created on the first write). A corrupt file is renamed to
|
|
// path+".corrupt-<time>" and the store starts empty; any other read error is returned.
|
|
func Open(path string, log *slog.Logger) (*Store, error) {
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
s := &Store{path: path, log: log, now: time.Now, byID: map[string]*Ticket{}, byKey: map[string]*Ticket{}, next: 1, flooded: map[string]bool{}}
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return s, nil
|
|
}
|
|
return nil, fmt.Errorf("incidents: cannot read %s: %w", path, err)
|
|
}
|
|
var d disk
|
|
if err := json.Unmarshal(b, &d); err != nil {
|
|
dst := path + ".corrupt-" + time.Now().UTC().Format("20060102T150405")
|
|
log.Error("incidents: corrupt store, starting empty", "path", path, "moved_to", dst, "err", err)
|
|
if rerr := os.Rename(path, dst); rerr != nil {
|
|
log.Error("incidents: cannot move the corrupt file", "err", rerr)
|
|
}
|
|
return s, nil
|
|
}
|
|
for _, t := range d.Tickets {
|
|
if t == nil || t.ID == "" {
|
|
continue
|
|
}
|
|
if t.Source == "egress" { // keys of older versions: recompute from the fields
|
|
t.Key = Key(t.Host, t.Kind, t.Workload, t.Dst, t.DPort, t.Proto)
|
|
}
|
|
s.byID[t.ID] = t
|
|
s.byKey[t.Key] = t
|
|
if n := idNum(t.ID); n >= s.next {
|
|
s.next = n + 1
|
|
}
|
|
}
|
|
if d.Next > s.next {
|
|
s.next = d.Next
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func idNum(id string) int {
|
|
n, _ := strconv.Atoi(strings.TrimPrefix(id, "INC-"))
|
|
return n
|
|
}
|
|
|
|
// save writes the file atomically; the caller holds mu.
|
|
func (s *Store) save() {
|
|
s.dirty = false
|
|
s.lastSave = s.now()
|
|
if s.path == "" {
|
|
return
|
|
}
|
|
d := disk{Next: s.next, Tickets: make([]*Ticket, 0, len(s.byID))}
|
|
for _, t := range s.byID {
|
|
d.Tickets = append(d.Tickets, t)
|
|
}
|
|
sort.Slice(d.Tickets, func(i, j int) bool { return idNum(d.Tickets[i].ID) < idNum(d.Tickets[j].ID) })
|
|
b, err := json.Marshal(d)
|
|
if err != nil {
|
|
s.log.Error("incidents: marshal", "err", err)
|
|
return
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
|
|
s.log.Error("incidents: mkdir", "err", err)
|
|
return
|
|
}
|
|
tmp := s.path + ".tmp"
|
|
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
|
|
if err != nil {
|
|
s.log.Error("incidents: write", "err", err)
|
|
return
|
|
}
|
|
_, werr := f.Write(b)
|
|
if serr := f.Sync(); werr == nil {
|
|
werr = serr
|
|
}
|
|
if cerr := f.Close(); werr == nil {
|
|
werr = cerr
|
|
}
|
|
if werr == nil {
|
|
werr = os.Rename(tmp, s.path)
|
|
}
|
|
if werr != nil {
|
|
os.Remove(tmp)
|
|
s.log.Error("incidents: save", "err", werr)
|
|
}
|
|
}
|
|
|
|
// Flush writes pending counter changes.
|
|
func (s *Store) Flush() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.dirty {
|
|
s.save()
|
|
}
|
|
}
|
|
|
|
// Stats is the occupancy of the store.
|
|
type Stats struct {
|
|
Size int `json:"size"`
|
|
Max int `json:"max"`
|
|
Untracked int `json:"untracked"`
|
|
}
|
|
|
|
// Stats returns the size, the cap and how many findings could not be tracked.
|
|
func (s *Store) Stats() Stats {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return Stats{Size: len(s.byID), Max: MaxTickets, Untracked: s.untracked}
|
|
}
|
|
|
|
func (s *Store) unix() int64 { return s.now().Unix() }
|
|
|
|
func (s *Store) audit(id, field, author string) {
|
|
s.log.Info("incident", "id", id, "field", field, "author", author)
|
|
}
|
|
|
|
func (t *Ticket) change(at int64, author, field, from, to string) {
|
|
t.History = append(t.History, Change{At: at, Author: author, Field: field, From: from, To: to})
|
|
if over := len(t.History) - MaxHistory; over > 0 {
|
|
t.History = append([]Change(nil), t.History[over:]...)
|
|
}
|
|
}
|
|
|
|
// evict frees one slot by dropping the oldest closed ticket; caller holds mu.
|
|
func (s *Store) evict() bool {
|
|
var old *Ticket
|
|
for _, t := range s.byID {
|
|
if closed(t.Status) && len(t.Comments) == 0 && t.Verdict == "" && (old == nil || t.UpdatedAt < old.UpdatedAt) {
|
|
old = t
|
|
}
|
|
}
|
|
if old == nil {
|
|
return false
|
|
}
|
|
delete(s.byID, old.ID)
|
|
if s.byKey[old.Key] == old {
|
|
delete(s.byKey, old.Key)
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Store) add(t *Ticket) bool {
|
|
if len(s.byID) >= MaxTickets && !s.evict() {
|
|
s.untracked++
|
|
s.log.Warn("incidents: store full, nothing can be evicted", "size", len(s.byID), "untracked", s.untracked)
|
|
return false
|
|
}
|
|
t.ID = "INC-" + strconv.Itoa(s.next)
|
|
s.next++
|
|
s.byID[t.ID] = t
|
|
s.byKey[t.Key] = t
|
|
return true
|
|
}
|
|
|
|
func clip(s string, n int) string {
|
|
if utf8.RuneCountInString(s) <= n {
|
|
return s
|
|
}
|
|
return string([]rune(s)[:n])
|
|
}
|
|
|
|
// Sync reconciles the findings (severity != info) with the tickets. It returns
|
|
// how many tickets were created and reopened.
|
|
func (s *Store) Sync(fs []Finding) (created, reopened int) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := s.unix()
|
|
state := false // an operator-visible change: written at once
|
|
active := map[string]int{}
|
|
for _, t := range s.byID {
|
|
if t.Status == "open" || t.Status == "investigating" {
|
|
active[t.Host]++
|
|
}
|
|
}
|
|
reopen := func(t *Ticket, field, from, to string) {
|
|
t.change(now, Robot, "status", from, "open")
|
|
t.change(now, Robot, field, "", to)
|
|
t.Status, t.Suppress, t.SuppressUntil, t.UpdatedAt = "open", false, 0, now
|
|
s.audit(t.ID, field, Robot)
|
|
active[t.Host]++
|
|
reopened++
|
|
state = true
|
|
}
|
|
for _, f := range fs {
|
|
if f.Severity == "info" || SevRank(f.Severity) < 0 {
|
|
continue
|
|
}
|
|
k := f.Key()
|
|
t := s.byKey[k]
|
|
if t == nil {
|
|
if active[f.Host] >= HostQuota && SevRank(f.Severity) <= SevRank("medium") {
|
|
if s.addFlood(f, now, active) {
|
|
state = true
|
|
}
|
|
continue
|
|
}
|
|
title := clip(f.Kind+" "+f.Workload+" -> "+f.Dst+":"+strconv.Itoa(int(f.DPort))+"/"+f.Proto, MaxTitle)
|
|
t = &Ticket{base: base{Key: k, Source: "egress", Host: clip(f.Host, MaxHost), Kind: f.Kind, Severity: f.Severity, MaxSeverity: f.Severity,
|
|
Workload: f.Workload, Dst: f.Dst, DPort: f.DPort, Proto: f.Proto, Title: title, Detail: clip(clean(f.Detail), MaxLong),
|
|
FirstSeen: f.First, LastSeen: f.Last, Count: f.Count, Status: "open", Tags: []string{}, CreatedAt: now, UpdatedAt: now},
|
|
Comments: []Comment{}, History: []Change{}}
|
|
if !s.add(t) {
|
|
continue
|
|
}
|
|
t.change(now, Robot, "created", "", f.Severity)
|
|
s.audit(t.ID, "created", Robot)
|
|
active[t.Host]++
|
|
created++
|
|
state = true
|
|
continue
|
|
}
|
|
if f.Last > t.LastSeen {
|
|
t.LastSeen = f.Last
|
|
s.dirty = true
|
|
}
|
|
if f.First > 0 && (t.FirstSeen == 0 || f.First < t.FirstSeen) {
|
|
t.FirstSeen = f.First
|
|
s.dirty = true
|
|
}
|
|
if f.Count > t.Count {
|
|
t.Count = f.Count
|
|
s.dirty = true
|
|
}
|
|
if SevRank(f.Severity) > SevRank(t.MaxSeverity) {
|
|
t.MaxSeverity = f.Severity
|
|
s.dirty = true
|
|
}
|
|
switch {
|
|
case t.Status == "resolved" && f.Last > t.UpdatedAt:
|
|
reopen(t, "reappeared", "resolved", strconv.FormatInt(f.Last, 10))
|
|
case suppressible(t.Status) && SevRank(f.Severity) > SevRank(t.SuppressedSev):
|
|
reopen(t, "reappeared", t.Status, f.Severity)
|
|
case t.Suppress && t.SuppressUntil > 0 && now > t.SuppressUntil:
|
|
reopen(t, "suppression expired", t.Status, strconv.FormatInt(t.SuppressUntil, 10))
|
|
}
|
|
if SevRank(f.Severity) > SevRank(t.Severity) && !t.SeverityManual {
|
|
t.change(now, Robot, "severity", t.Severity, f.Severity)
|
|
t.Severity, t.UpdatedAt = f.Severity, now
|
|
state = true
|
|
}
|
|
}
|
|
if state || (s.dirty && s.now().Sub(s.lastSave) >= SaveDebounce) {
|
|
s.save()
|
|
}
|
|
return
|
|
}
|
|
|
|
// addFlood groups a finding that would exceed the host quota into one
|
|
// "flood" ticket per host. It returns true when the ticket changed.
|
|
func (s *Store) addFlood(f Finding, now int64, active map[string]int) bool {
|
|
fk := floodKey(f.Host)
|
|
t := s.byKey[fk]
|
|
if t == nil {
|
|
t = &Ticket{base: base{Key: fk, Source: "egress", Host: clip(f.Host, MaxHost), Kind: "flood", Severity: "medium", MaxSeverity: f.Severity,
|
|
Title: "flood: more than " + strconv.Itoa(HostQuota) + " active tickets on " + clip(f.Host, 80), FirstSeen: f.First, LastSeen: f.Last,
|
|
Status: "open", Tags: []string{"flood"}, CreatedAt: now, UpdatedAt: now}, Comments: []Comment{}, History: []Change{}}
|
|
if !s.add(t) {
|
|
return false
|
|
}
|
|
t.change(now, Robot, "created", "", "flood")
|
|
s.audit(t.ID, "created", Robot)
|
|
active[t.Host]++
|
|
}
|
|
k := f.Key()
|
|
if s.flooded[k] {
|
|
if f.Last > t.LastSeen {
|
|
t.LastSeen = f.Last
|
|
s.dirty = true
|
|
}
|
|
return false
|
|
}
|
|
if len(s.flooded) > 100000 {
|
|
s.flooded = map[string]bool{}
|
|
}
|
|
s.flooded[k] = true
|
|
t.Count++
|
|
if f.Last > t.LastSeen {
|
|
t.LastSeen = f.Last
|
|
}
|
|
if SevRank(f.Severity) > SevRank(t.MaxSeverity) {
|
|
t.MaxSeverity = f.Severity
|
|
}
|
|
dst := clip(f.Dst, 64) + ":" + strconv.Itoa(int(f.DPort))
|
|
var lines []string
|
|
if t.Detail != "" {
|
|
lines = strings.Split(t.Detail, "\n")
|
|
if lines[0] == floodHead {
|
|
lines = lines[1:]
|
|
}
|
|
}
|
|
lines = append(lines, f.Kind+" "+dst)
|
|
if len(lines) > floodTailKeep {
|
|
lines = lines[len(lines)-floodTailKeep:]
|
|
}
|
|
t.Detail = floodHead + "\n" + strings.Join(lines, "\n")
|
|
t.change(now, Robot, "grouped", "", f.Kind+" "+dst)
|
|
if t.Status == "resolved" {
|
|
t.Status, t.UpdatedAt = "open", now
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Lookup returns the refs of the given keys (missing keys are absent).
|
|
func (s *Store) Lookup(keys []string) map[string]Ref {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
out := make(map[string]Ref, len(keys))
|
|
for _, k := range keys {
|
|
if t := s.byKey[k]; t != nil {
|
|
out[k] = Ref{ID: t.ID, Status: t.Status, Suppress: t.Suppress}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func copyTicket(t *Ticket) Ticket {
|
|
c := *t
|
|
c.Tags = append([]string{}, t.Tags...)
|
|
c.Comments = append([]Comment{}, t.Comments...)
|
|
c.History = append([]Change{}, t.History...)
|
|
return c
|
|
}
|
|
|
|
// Get returns a copy of the ticket.
|
|
func (s *Store) Get(id string) (Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
t := s.byID[id]
|
|
if t == nil {
|
|
return Ticket{}, ErrNotFound
|
|
}
|
|
return copyTicket(t), nil
|
|
}
|
|
|
|
// ---- validation
|
|
|
|
// line is text() for single-line fields: no newline or tab either.
|
|
func line(name, v string, max int, required bool) (string, error) {
|
|
v, err := text(name, v, max, required)
|
|
if err == nil && strings.ContainsAny(v, "\n\t") {
|
|
return "", invalid("%s must be a single line", name)
|
|
}
|
|
return v, err
|
|
}
|
|
|
|
func text(name, v string, max int, required bool) (string, error) {
|
|
v = strings.TrimSpace(v)
|
|
if required && v == "" {
|
|
return "", invalid("%s is required", name)
|
|
}
|
|
if utf8.RuneCountInString(v) > max {
|
|
return "", invalid("%s is longer than %d characters", name, max)
|
|
}
|
|
if !utf8.ValidString(v) {
|
|
return "", invalid("%s is not valid UTF-8", name)
|
|
}
|
|
for _, r := range v {
|
|
if (r < 0x20 && r != '\n' && r != '\t') || r == 0x7f || (r >= 0x80 && r < 0xa0) {
|
|
return "", invalid("%s has control characters", name)
|
|
}
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
func clean(v string) string {
|
|
return strings.Map(func(r rune) rune {
|
|
if (r < 0x20 && r != '\n' && r != '\t') || r == 0x7f || (r >= 0x80 && r < 0xa0) || r == utf8.RuneError {
|
|
return -1
|
|
}
|
|
return r
|
|
}, v)
|
|
}
|
|
|
|
func author(a, via string) (string, error) {
|
|
if strings.TrimSpace(a) == "" {
|
|
a = DefaultAuth
|
|
}
|
|
a, err := line("author", a, MaxShort, false)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if via != "" {
|
|
a += " (via " + via + ")"
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
func tags(in []string) ([]string, error) {
|
|
out := []string{}
|
|
if len(in) > MaxTags {
|
|
return nil, invalid("at most %d tags", MaxTags)
|
|
}
|
|
for _, t := range in {
|
|
if t == "" || len(t) > MaxTagLen {
|
|
return nil, invalid("tag must have 1 to %d characters", MaxTagLen)
|
|
}
|
|
for _, r := range t {
|
|
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.') {
|
|
return nil, invalid("tag %q: only a-z 0-9 - _ . are allowed", t)
|
|
}
|
|
}
|
|
if !inList(out, t) {
|
|
out = append(out, t)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// NewManual is the body of a manual ticket.
|
|
type NewManual struct {
|
|
Title string `json:"title"`
|
|
Detail string `json:"detail"`
|
|
Severity string `json:"severity"`
|
|
Host string `json:"host"`
|
|
Tags []string `json:"tags"`
|
|
Author string `json:"author"`
|
|
Via string `json:"-"`
|
|
}
|
|
|
|
// Create opens a manual ticket.
|
|
func (s *Store) Create(in NewManual) (Ticket, error) {
|
|
au, err := author(in.Author, in.Via)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
title, err := line("title", in.Title, MaxTitle, true)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
detail, err := text("detail", in.Detail, MaxLong, false)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
host, err := text("host", in.Host, MaxHost, false)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
sev := in.Severity
|
|
if sev == "" {
|
|
sev = "medium"
|
|
}
|
|
if !inList(severities, sev) {
|
|
return Ticket{}, invalid("severity must be one of %s", strings.Join(severities, ", "))
|
|
}
|
|
tg, err := tags(in.Tags)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := s.unix()
|
|
t := &Ticket{base: base{Source: "manual", Host: host, Kind: "manual", Severity: sev, MaxSeverity: sev, Title: title, Detail: detail,
|
|
FirstSeen: now, LastSeen: now, Count: 1, Status: "open", Tags: tg, CreatedAt: now, UpdatedAt: now},
|
|
Comments: []Comment{}, History: []Change{}}
|
|
t.Key = "manual|" + strconv.Itoa(s.next)
|
|
if !s.add(t) {
|
|
return Ticket{}, fmt.Errorf("%w: store is full of open tickets", ErrInvalid)
|
|
}
|
|
t.change(now, au, "created", "", sev)
|
|
s.audit(t.ID, "created", au)
|
|
s.save()
|
|
return copyTicket(t), nil
|
|
}
|
|
|
|
// Patch is a partial update; nil fields are left alone.
|
|
type Patch struct {
|
|
Status *string `json:"status"`
|
|
Severity *string `json:"severity"`
|
|
Assignee *string `json:"assignee"`
|
|
Tags *[]string `json:"tags"`
|
|
Title *string `json:"title"`
|
|
Verdict *string `json:"verdict"`
|
|
Suppress *bool `json:"suppress"`
|
|
Author string `json:"author"`
|
|
// SuppressUntil (unix s) ends the suppression; default 30 d, at most 90 d.
|
|
SuppressUntil *int64 `json:"suppress_until"`
|
|
// ExpectedUpdatedAt makes the write fail with 409 when the ticket changed meanwhile.
|
|
ExpectedUpdatedAt *int64 `json:"expected_updated_at"`
|
|
Via string `json:"-"`
|
|
}
|
|
|
|
// Update applies the patch; each changed field adds a history entry.
|
|
func (s *Store) Update(id string, p Patch) (Ticket, error) {
|
|
au, err := author(p.Author, p.Via)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
var status, sev, assignee, title, verdict string
|
|
var tg []string
|
|
if p.Status != nil {
|
|
if status = *p.Status; !inList(statuses, status) {
|
|
return Ticket{}, invalid("status must be one of %s", strings.Join(statuses, ", "))
|
|
}
|
|
}
|
|
if p.Severity != nil {
|
|
if sev = *p.Severity; !inList(severities, sev) {
|
|
return Ticket{}, invalid("severity must be one of %s", strings.Join(severities, ", "))
|
|
}
|
|
}
|
|
if p.Assignee != nil {
|
|
if assignee, err = line("assignee", *p.Assignee, MaxShort, false); err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
}
|
|
if p.Title != nil {
|
|
if title, err = line("title", *p.Title, MaxTitle, true); err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
}
|
|
if p.Verdict != nil {
|
|
if verdict, err = text("verdict", *p.Verdict, MaxLong, false); err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
}
|
|
if p.Tags != nil {
|
|
if tg, err = tags(*p.Tags); err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
t := s.byID[id]
|
|
if t == nil {
|
|
return Ticket{}, ErrNotFound
|
|
}
|
|
if p.ExpectedUpdatedAt != nil && *p.ExpectedUpdatedAt != t.UpdatedAt {
|
|
return Ticket{}, conflict("the ticket changed since it was read (updated_at %d)", t.UpdatedAt)
|
|
}
|
|
now := s.unix()
|
|
newStatus := t.Status
|
|
if p.Status != nil {
|
|
newStatus = status
|
|
}
|
|
newSup := t.Suppress
|
|
if p.Suppress != nil {
|
|
newSup = *p.Suppress
|
|
}
|
|
if !suppressible(newStatus) {
|
|
if p.Suppress != nil && *p.Suppress {
|
|
return Ticket{}, conflict("suppress is only allowed in false_positive or benign")
|
|
}
|
|
newSup = false // leaving false_positive/benign always drops the suppression
|
|
}
|
|
if newSup {
|
|
if t.Source != "egress" {
|
|
return Ticket{}, conflict("only egress tickets can suppress findings")
|
|
}
|
|
if SevRank(t.MaxSeverity) >= SevRank("high") || SevRank(t.Severity) >= SevRank("high") {
|
|
return Ticket{}, conflict("a high or critical finding cannot be suppressed")
|
|
}
|
|
}
|
|
until := now + int64(SuppressTTL/time.Second)
|
|
if t.Suppress && t.SuppressUntil > 0 {
|
|
until = t.SuppressUntil
|
|
}
|
|
if p.SuppressUntil != nil {
|
|
if *p.SuppressUntil <= now || *p.SuppressUntil > now+int64(SuppressMax/time.Second) {
|
|
return Ticket{}, invalid("suppress_until must be in the future and within 90 days")
|
|
}
|
|
until = *p.SuppressUntil
|
|
}
|
|
changed := false
|
|
set := func(field string, cur *string, nv string) {
|
|
if *cur != nv {
|
|
t.change(now, au, field, *cur, nv)
|
|
s.audit(t.ID, field, au)
|
|
*cur = nv
|
|
changed = true
|
|
}
|
|
}
|
|
if p.Severity != nil && sev != t.Severity {
|
|
t.SeverityManual = true
|
|
}
|
|
if suppressible(newStatus) && (!suppressible(t.Status) || newSup && !t.Suppress) {
|
|
t.SuppressedSev, t.SuppressedAt = t.MaxSeverity, now
|
|
}
|
|
if p.Status != nil {
|
|
set("status", &t.Status, status)
|
|
}
|
|
if p.Severity != nil {
|
|
set("severity", &t.Severity, sev)
|
|
}
|
|
if p.Assignee != nil {
|
|
set("assignee", &t.Assignee, assignee)
|
|
}
|
|
if p.Title != nil {
|
|
set("title", &t.Title, title)
|
|
}
|
|
if p.Verdict != nil {
|
|
set("verdict", &t.Verdict, verdict)
|
|
}
|
|
if p.Tags != nil {
|
|
if old, nw := strings.Join(t.Tags, ","), strings.Join(tg, ","); old != nw {
|
|
t.change(now, au, "tags", old, nw)
|
|
s.audit(t.ID, "tags", au)
|
|
t.Tags = tg
|
|
changed = true
|
|
}
|
|
}
|
|
if newSup != t.Suppress {
|
|
t.change(now, au, "suppress", strconv.FormatBool(t.Suppress), strconv.FormatBool(newSup))
|
|
s.audit(t.ID, "suppress", au)
|
|
t.Suppress = newSup
|
|
changed = true
|
|
}
|
|
if newSup {
|
|
if t.SuppressUntil != until {
|
|
t.SuppressUntil = until
|
|
changed = true
|
|
}
|
|
} else {
|
|
t.SuppressUntil = 0
|
|
}
|
|
if changed {
|
|
t.UpdatedAt = now
|
|
s.save()
|
|
}
|
|
return copyTicket(t), nil
|
|
}
|
|
|
|
// AddComment appends a comment.
|
|
func (s *Store) AddComment(id, txt, au, via string) (Ticket, error) {
|
|
au, err := author(au, via)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
txt, err = text("text", txt, MaxComment, true)
|
|
if err != nil {
|
|
return Ticket{}, err
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
t := s.byID[id]
|
|
if t == nil {
|
|
return Ticket{}, ErrNotFound
|
|
}
|
|
if len(t.Comments) >= MaxComments {
|
|
return Ticket{}, invalid("comment limit (%d) reached", MaxComments)
|
|
}
|
|
now := s.unix()
|
|
n := 1
|
|
for _, c := range t.Comments {
|
|
if c.ID >= n {
|
|
n = c.ID + 1
|
|
}
|
|
}
|
|
t.Comments = append(t.Comments, Comment{ID: n, At: now, Author: au, Text: txt})
|
|
t.UpdatedAt = now
|
|
s.audit(t.ID, "comment", au)
|
|
s.save()
|
|
return copyTicket(t), nil
|
|
}
|
|
|
|
// Query filters List.
|
|
type Query struct {
|
|
Status []string
|
|
Severity []string
|
|
Host string
|
|
Q string
|
|
Sort string // updated (default), severity, last_seen
|
|
Page int
|
|
PerPage int
|
|
}
|
|
|
|
// Page is the answer of List.
|
|
type Page struct {
|
|
Items []Summary `json:"items"`
|
|
Total int `json:"total"`
|
|
Counts map[string]int `json:"counts"`
|
|
Store Stats `json:"store"`
|
|
}
|
|
|
|
// ParseQuery validates the enums of q.
|
|
func (q Query) Validate() error {
|
|
for _, s := range q.Status {
|
|
if !inList(statuses, s) {
|
|
return invalid("unknown status %q", s)
|
|
}
|
|
}
|
|
for _, s := range q.Severity {
|
|
if !inList(severities, s) {
|
|
return invalid("unknown severity %q", s)
|
|
}
|
|
}
|
|
switch q.Sort {
|
|
case "", "updated", "severity", "last_seen":
|
|
default:
|
|
return invalid("sort must be updated, severity or last_seen")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (q Query) match(t *Ticket) bool {
|
|
if len(q.Severity) > 0 && !inList(q.Severity, t.Severity) {
|
|
return false
|
|
}
|
|
if q.Host != "" && t.Host != q.Host {
|
|
return false
|
|
}
|
|
if q.Q != "" {
|
|
n := strings.ToLower(q.Q)
|
|
h := strings.ToLower(strings.Join([]string{t.ID, t.Title, t.Detail, t.Host, t.Dst, t.Workload, t.Kind, t.Verdict, t.Assignee, strings.Join(t.Tags, " ")}, "\n"))
|
|
if !strings.Contains(h, n) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func summary(t *Ticket) Summary {
|
|
b := t.base
|
|
b.Tags = append([]string{}, t.Tags...)
|
|
return Summary{base: b, CommentCount: len(t.Comments)}
|
|
}
|
|
|
|
// List returns one page of tickets. counts ignore the status filter.
|
|
func (s *Store) List(q Query) Page {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
counts := map[string]int{}
|
|
for _, st := range statuses {
|
|
counts[st] = 0
|
|
}
|
|
var ts []*Ticket
|
|
for _, t := range s.byID {
|
|
if !q.match(t) {
|
|
continue
|
|
}
|
|
counts[t.Status]++
|
|
if len(q.Status) == 0 || inList(q.Status, t.Status) {
|
|
ts = append(ts, t)
|
|
}
|
|
}
|
|
sort.Slice(ts, func(i, j int) bool {
|
|
a, b := ts[i], ts[j]
|
|
switch q.Sort {
|
|
case "severity":
|
|
if ra, rb := SevRank(a.Severity), SevRank(b.Severity); ra != rb {
|
|
return ra > rb
|
|
}
|
|
case "last_seen":
|
|
if a.LastSeen != b.LastSeen {
|
|
return a.LastSeen > b.LastSeen
|
|
}
|
|
}
|
|
if a.UpdatedAt != b.UpdatedAt {
|
|
return a.UpdatedAt > b.UpdatedAt
|
|
}
|
|
return idNum(a.ID) > idNum(b.ID)
|
|
})
|
|
per := q.PerPage
|
|
if per <= 0 {
|
|
per = 50
|
|
}
|
|
if per > 200 {
|
|
per = 200
|
|
}
|
|
pg := q.Page
|
|
if pg < 1 {
|
|
pg = 1
|
|
}
|
|
lo := (pg - 1) * per
|
|
if lo > len(ts) {
|
|
lo = len(ts)
|
|
}
|
|
hi := lo + per
|
|
if hi > len(ts) {
|
|
hi = len(ts)
|
|
}
|
|
out := Page{Items: make([]Summary, 0, hi-lo), Total: len(ts), Counts: counts, Store: Stats{Size: len(s.byID), Max: MaxTickets, Untracked: s.untracked}}
|
|
for _, t := range ts[lo:hi] {
|
|
out.Items = append(out.Items, summary(t))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// All returns every ticket matching q (no paging), for the CSV export.
|
|
func (s *Store) All(q Query) []Summary {
|
|
var out []Summary
|
|
for p := 1; ; p++ {
|
|
q.Page, q.PerPage = p, 200
|
|
pg := s.List(q)
|
|
out = append(out, pg.Items...)
|
|
if len(out) >= pg.Total || len(pg.Items) == 0 {
|
|
return out
|
|
}
|
|
}
|
|
}
|