feat: 1.5.0 incident management (tickets from egress findings, triage, comments, suppression with expiry)
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
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>
This commit is contained in:
1 parent
3ae72e27d6
commit
e5058968e2
22 files changed
+2651
-20
No files matched your search
@@ -4,6 +4,14 @@
|
||||
|
||||
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
|
||||
|
||||
## [1.5.0] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- Incident management: every egress finding (severity above info) becomes a ticket `INC-<n>` keyed by `host|kind|workload|dst|dport|proto`, created by a sync on each merged egress report and every 60 s. Tickets have status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severity, assignee, tags, verdict, comments and a change history; a resolved ticket reopens when the finding reappears. Stored in `<data-dir>/incidents.json` (atomic write, 0600; a corrupt file is moved to `.corrupt`); limits of 5000 tickets, 200 comments and 500 history entries each. Every write is also logged (id, field, author).
|
||||
- A ticket in `false_positive` or `benign` can suppress the findings with exactly its key: they leave `/api/v1/egress` (and the egress report) unless `?suppressed=1`. Findings now carry `ticket_id`, `ticket_status` and `suppressed`, and the response has `suppressed_count`.
|
||||
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` and `GET /api/v1/incidents/export.csv` (not open to the peer token; writes refuse cross-site requests).
|
||||
|
||||
## [1.4.8] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -4,6 +4,14 @@
|
||||
|
||||
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
|
||||
|
||||
## [1.5.0] - 2026-11-15
|
||||
|
||||
### Adicionado
|
||||
|
||||
- Gestão de incidentes: cada achado de egress (severidade acima de info) vira um chamado `INC-<n>` com chave `host|kind|workload|dst|dport|proto`, criado por uma sincronização a cada relatório de egress mesclado e a cada 60 s. O chamado tem status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severidade, responsável, etiquetas, conclusão, comentários e histórico de mudanças; um chamado resolvido reabre quando o achado reaparece. Fica em `<data-dir>/incidents.json` (escrita atômica, 0600; arquivo corrompido vai para `.corrupt`); limites de 5000 chamados, 200 comentários e 500 entradas de histórico cada. Toda escrita também vai para o log (id, campo, autor).
|
||||
- Um chamado em `false_positive` ou `benign` pode suprimir os achados com exatamente a sua chave: eles saem de `/api/v1/egress` (e do relatório de egress), salvo com `?suppressed=1`. Os achados agora trazem `ticket_id`, `ticket_status` e `suppressed`, e a resposta tem `suppressed_count`.
|
||||
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` e `GET /api/v1/incidents/export.csv` (fechada ao token de peer; escritas recusam requisições cross-site).
|
||||
|
||||
## [1.4.8] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
@@ -138,6 +138,12 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
|
||||
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) |
|
||||
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
|
||||
| `GET /api/v1/incidents` | session or bearer | incident tickets (no comments or history, with `comment_count`). Query: `status` (comma list), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (max 200). Returns `{items,total,counts}` |
|
||||
| `GET /api/v1/incidents/{id}` | session or bearer | full ticket with `comments` and `history` |
|
||||
| `GET /api/v1/incidents/export.csv` | session or bearer | the filtered list as CSV |
|
||||
| `POST /api/v1/incidents` | session or bearer | opens a manual ticket `{title,detail,severity,host,tags,author}` (body up to 64 KiB, unknown fields refused; cross-site refused) |
|
||||
| `PATCH /api/v1/incidents/{id}` | session or bearer | partial update `{status,severity,assignee,tags,title,verdict,suppress,author}`; each change is a history entry. `suppress` only in `false_positive` or `benign`, and hides findings with the exact same key in `/api/v1/egress` (add `suppressed=1` to see them) |
|
||||
| `POST /api/v1/incidents/{id}/comments` | session or bearer | adds a comment `{text,author}` |
|
||||
|
||||
An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds).
|
||||
|
||||
|
||||
@@ -135,6 +135,12 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
|
||||
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) |
|
||||
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
|
||||
| `GET /api/v1/incidents` | sessão ou bearer | chamados de incidente (sem comentários e histórico, com `comment_count`). Query: `status` (lista separada por vírgula), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (máx. 200). Devolve `{items,total,counts}` |
|
||||
| `GET /api/v1/incidents/{id}` | sessão ou bearer | chamado completo, com `comments` e `history` |
|
||||
| `GET /api/v1/incidents/export.csv` | sessão ou bearer | a lista filtrada em CSV |
|
||||
| `POST /api/v1/incidents` | sessão ou bearer | abre um chamado manual `{title,detail,severity,host,tags,author}` (corpo até 64 KiB, campos desconhecidos recusados; cross-site recusado) |
|
||||
| `PATCH /api/v1/incidents/{id}` | sessão ou bearer | atualização parcial `{status,severity,assignee,tags,title,verdict,suppress,author}`; cada mudança vira uma entrada no histórico. `suppress` só em `false_positive` ou `benign`, e esconde de `/api/v1/egress` os achados com exatamente a mesma chave (use `suppressed=1` para vê-los) |
|
||||
| `POST /api/v1/incidents/{id}/comments` | sessão ou bearer | adiciona um comentário `{text,author}` |
|
||||
|
||||
Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos).
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
@@ -99,8 +100,13 @@ func Serve(c Config) error {
|
||||
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
|
||||
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
bindHost, _, _ := net.SplitHostPort(c.Bind)
|
||||
incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub,
|
||||
Incidents: incStore})
|
||||
egressSrc, err := newEgress(c, st, log)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -132,6 +138,7 @@ func Serve(c Config) error {
|
||||
go func() { defer wg.Done(); elog.Run(ctx) }()
|
||||
}
|
||||
runner.Start(ctx, offsets, &wg)
|
||||
server.StartIncidentSync(ctx, &wg)
|
||||
if egressSrc != nil {
|
||||
egressSrc.Start(ctx, &wg)
|
||||
}
|
||||
|
||||
@@ -2,4 +2,4 @@ package app
|
||||
|
||||
// Version is the release version (SemVer). Release builds may override it with
|
||||
// -ldflags "-X .../internal/app.Version=...".
|
||||
var Version = "1.4.8"
|
||||
var Version = "1.5.0"
|
||||
@@ -22,6 +22,10 @@ type Finding struct {
|
||||
Last int64 `json:"last"`
|
||||
Detail string `json:"detail"`
|
||||
Host string `json:"host,omitempty"`
|
||||
// Ticket fields are filled by the server from the incident store.
|
||||
TicketID string `json:"ticket_id"`
|
||||
TicketStatus string `json:"ticket_status"`
|
||||
Suppressed bool `json:"suppressed"`
|
||||
// Samples are the unix times of the last connections (beacons only, at most MaxSamples).
|
||||
Samples []int64 `json:"samples,omitempty"`
|
||||
}
|
||||
@@ -286,6 +290,15 @@ func clip(s string) string {
|
||||
}
|
||||
|
||||
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
|
||||
// KnownKind reports whether k is a finding kind produced by the engine.
|
||||
func KnownKind(k string) bool {
|
||||
switch k {
|
||||
case "scan", "bad_dst", "tor", "port", "dns_bypass", "new_geo", "beacon", "infra":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *Report) Sanitize(host string) {
|
||||
if len(r.Workloads) > maxPeerWorkloads {
|
||||
r.Workloads = r.Workloads[:maxPeerWorkloads]
|
||||
@@ -303,6 +316,14 @@ func (r *Report) Sanitize(host string) {
|
||||
w := &r.Workloads[i]
|
||||
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
|
||||
}
|
||||
// a peer may send only the kinds this package produces; the rest is dropped
|
||||
kept := r.Findings[:0]
|
||||
for _, f := range r.Findings {
|
||||
if KnownKind(f.Kind) {
|
||||
kept = append(kept, f)
|
||||
}
|
||||
}
|
||||
r.Findings = kept
|
||||
for i := range r.Findings {
|
||||
f := &r.Findings[i]
|
||||
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,311 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fnd(sev string, last int64, count int) Finding {
|
||||
return Finding{Host: "oracle", Kind: "port", Severity: sev, Workload: "container 10.0.3.5", Dst: "203.0.113.3", DPort: 6667, Proto: "tcp",
|
||||
Detail: "irc", First: 100, Last: last, Count: count}
|
||||
}
|
||||
|
||||
func newStore(t *testing.T) (*Store, string, *int64) {
|
||||
p := filepath.Join(t.TempDir(), "incidents.json")
|
||||
s, err := Open(p, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clock := int64(1000)
|
||||
s.now = func() time.Time { return time.Unix(clock, 0) }
|
||||
return s, p, &clock
|
||||
}
|
||||
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func TestPersistenceAndCorrupt(t *testing.T) {
|
||||
s, p, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 3)})
|
||||
if _, err := s.AddComment("INC-1", "visto", "ana", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Stat(p)
|
||||
if err != nil || st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("file: %v %v", st, err)
|
||||
}
|
||||
if _, err := os.Stat(p + ".tmp"); err == nil {
|
||||
t.Fatal("tmp left behind")
|
||||
}
|
||||
s2, _ := Open(p, nil)
|
||||
tk, err := s2.Get("INC-1")
|
||||
if err != nil || tk.Count != 3 || len(tk.Comments) != 1 || tk.History[0].Field != "created" || tk.History[0].Author != "urutau" {
|
||||
t.Fatalf("reload: %+v %v", tk, err)
|
||||
}
|
||||
if m, _ := s2.Create(NewManual{Title: "x"}); m.ID != "INC-2" {
|
||||
t.Fatalf("sequence after reload: %s", m.ID)
|
||||
}
|
||||
os.WriteFile(p, []byte("{not json"), 0o600)
|
||||
s3, err := Open(p, nil)
|
||||
if err != nil || s3.List(Query{}).Total != 0 {
|
||||
t.Fatalf("corrupt store not empty: %v", err)
|
||||
}
|
||||
if m, _ := filepath.Glob(p + ".corrupt-*"); len(m) != 1 {
|
||||
t.Fatal("no timestamped .corrupt file")
|
||||
}
|
||||
// a read error that is not "does not exist" aborts
|
||||
dir := t.TempDir()
|
||||
if _, err := Open(dir, nil); err == nil {
|
||||
t.Fatal("unreadable store accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSync(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
if c, _ := s.Sync([]Finding{fnd("info", 500, 1)}); c != 0 {
|
||||
t.Fatal("info created a ticket")
|
||||
}
|
||||
if c, _ := s.Sync([]Finding{fnd("medium", 500, 3)}); c != 1 {
|
||||
t.Fatal("not created")
|
||||
}
|
||||
s.Sync([]Finding{fnd("high", 600, 5)})
|
||||
tk, _ := s.Get("INC-1")
|
||||
if tk.Status != "open" || tk.Count != 5 || tk.LastSeen != 600 || tk.Severity != "high" || tk.MaxSeverity != "high" || len(s.byID) != 1 {
|
||||
t.Fatalf("update: %+v", tk)
|
||||
}
|
||||
// resolved, finding older than the resolution: stays resolved; newer: reopens
|
||||
*clock = 2000
|
||||
s.Update("INC-1", Patch{Status: str("resolved"), Author: "ana"})
|
||||
s.Sync([]Finding{fnd("medium", 1500, 5)})
|
||||
if tk, _ = s.Get("INC-1"); tk.Status != "resolved" {
|
||||
t.Fatal("reopened by an old finding")
|
||||
}
|
||||
*clock = 3000
|
||||
if _, r := s.Sync([]Finding{fnd("medium", 2500, 6)}); r != 1 {
|
||||
t.Fatal("not reopened")
|
||||
}
|
||||
tk, _ = s.Get("INC-1")
|
||||
last := tk.History[len(tk.History)-1]
|
||||
if tk.Status != "open" || last.Field != "reappeared" {
|
||||
t.Fatalf("reopen: %+v", tk.History)
|
||||
}
|
||||
// false positive is never reopened and only counts
|
||||
*clock = 4000
|
||||
s.Update("INC-1", Patch{Status: str("false_positive")})
|
||||
s.Sync([]Finding{fnd("high", 3500, 9)})
|
||||
tk, _ = s.Get("INC-1")
|
||||
if tk.Status != "false_positive" || tk.Count != 9 {
|
||||
t.Fatalf("fp: %+v", tk)
|
||||
}
|
||||
// leaving the status drops the suppression
|
||||
s.Update("INC-1", Patch{Status: str("open")})
|
||||
if tk, _ = s.Get("INC-1"); tk.Suppress {
|
||||
t.Fatal("suppress kept")
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Suppress: &[]bool{true}[0]}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatal("suppress allowed in open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimits(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
s.Create(NewManual{Title: "a"})
|
||||
for i := 0; i < MaxComments; i++ {
|
||||
if _, err := s.AddComment("INC-1", "c", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.AddComment("INC-1", "c", "", ""); err == nil {
|
||||
t.Fatal("201st comment accepted")
|
||||
}
|
||||
for i := 0; i < MaxHistory+20; i++ {
|
||||
*clock++
|
||||
st := "investigating"
|
||||
if i%2 == 1 {
|
||||
st = "open"
|
||||
}
|
||||
s.Update("INC-1", Patch{Status: &st})
|
||||
}
|
||||
if tk, _ := s.Get("INC-1"); len(tk.History) != MaxHistory {
|
||||
t.Fatalf("history %d", len(tk.History))
|
||||
}
|
||||
// ticket cap: oldest closed goes first, open tickets are kept
|
||||
s2, _, c2 := newStore(t)
|
||||
for i := 0; i < MaxTickets; i++ {
|
||||
*c2++
|
||||
s2.Create(NewManual{Title: "t"})
|
||||
s2.save() // keep the test honest about cost? no: cheap enough
|
||||
if i > 50 {
|
||||
break
|
||||
}
|
||||
}
|
||||
s2.mu.Lock()
|
||||
for i := len(s2.byID); i < MaxTickets; i++ {
|
||||
s2.add(&Ticket{base: base{Key: "k" + string(rune(i)) + "x", Status: "open", UpdatedAt: 5000}})
|
||||
}
|
||||
s2.mu.Unlock()
|
||||
s2.Update("INC-3", Patch{Status: str("resolved")})
|
||||
s2.Update("INC-2", Patch{Status: str("benign"), Verdict: str("kept")}) // a verdict protects it from eviction
|
||||
if tk, err := s2.Create(NewManual{Title: "new"}); err != nil || len(s2.byID) != MaxTickets {
|
||||
t.Fatalf("create at cap: %v %d", err, len(s2.byID))
|
||||
} else if _, err := s2.Get("INC-3"); err == nil && tk.ID != "" {
|
||||
t.Fatal("INC-3 not evicted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Create(NewManual{Title: "a"})
|
||||
bad := []Patch{
|
||||
{Status: str("nope")}, {Severity: str("urgent")}, {Title: str("")}, {Title: str(strings.Repeat("a", 201))},
|
||||
{Verdict: str(strings.Repeat("a", 4001))}, {Verdict: str("a\x00b")}, {Assignee: str(strings.Repeat("a", 65))},
|
||||
{Tags: &[]string{"UP"}}, {Tags: &[]string{"a b"}}, {Tags: &[]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"}},
|
||||
{Author: strings.Repeat("a", 65)}, {Author: "a\nb"},
|
||||
}
|
||||
for i, p := range bad {
|
||||
if _, err := s.Update("INC-1", p); err == nil {
|
||||
t.Errorf("patch %d accepted", i)
|
||||
}
|
||||
}
|
||||
if _, err := s.Update("INC-9", Patch{}); err != ErrNotFound {
|
||||
t.Fatal("404 expected")
|
||||
}
|
||||
if tk, err := s.Update("INC-1", Patch{Verdict: str("a\nb\tc"), Tags: &[]string{"ok-1", "x.y_z"}}); err != nil || tk.Verdict != "a\nb\tc" {
|
||||
t.Fatalf("good patch: %v", err)
|
||||
}
|
||||
if _, err := s.AddComment("INC-1", strings.Repeat("a", 5001), "", ""); err == nil {
|
||||
t.Fatal("long comment accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListFilters(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 3), {Host: "h2", Kind: "bad_dst", Severity: "high", Workload: "host", Dst: "198.51.100.9", DPort: 22, Proto: "tcp", Last: 700, Count: 1}})
|
||||
s.Update("INC-2", Patch{Status: str("investigating")})
|
||||
pg := s.List(Query{Status: []string{"investigating"}, Sort: "severity"})
|
||||
if pg.Total != 1 || pg.Counts["open"] != 1 || pg.Counts["investigating"] != 1 || pg.Items[0].ID != "INC-2" {
|
||||
t.Fatalf("%+v", pg)
|
||||
}
|
||||
if s.List(Query{Host: "oracle"}).Total != 1 || s.List(Query{Q: "BAD_DST"}).Total != 1 || s.List(Query{Severity: []string{"high"}}).Total != 1 {
|
||||
t.Fatal("filters")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuppressionPolicy(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
yes := true
|
||||
s.Sync([]Finding{fnd("medium", 500, 3)})
|
||||
*clock = 2000
|
||||
if _, err := s.Update("INC-1", Patch{Status: str("false_positive"), Suppress: &yes, SuppressUntil: &[]int64{2000 + 91*86400}[0]}); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("91 days accepted: %v", err)
|
||||
}
|
||||
tk, err := s.Update("INC-1", Patch{Status: str("false_positive"), Suppress: &yes, Author: "ana"})
|
||||
if err != nil || !tk.Suppress || tk.SuppressedSev != "medium" || tk.SuppressUntil != 2000+30*86400 {
|
||||
t.Fatalf("suppress: %+v %v", tk, err)
|
||||
}
|
||||
if tk.History[len(tk.History)-1].Author != "ana" {
|
||||
t.Fatal("author")
|
||||
}
|
||||
// same severity: stays suppressed; worse severity: reopens
|
||||
s.Sync([]Finding{fnd("medium", 2100, 4)})
|
||||
if tk, _ = s.Get("INC-1"); !tk.Suppress || tk.Status != "false_positive" {
|
||||
t.Fatal("reopened without cause")
|
||||
}
|
||||
s.Sync([]Finding{fnd("high", 2200, 4)})
|
||||
tk, _ = s.Get("INC-1")
|
||||
if tk.Suppress || tk.Status != "open" || tk.Severity != "high" || tk.History[len(tk.History)-2].Field != "reappeared" {
|
||||
t.Fatalf("worse severity: %+v", tk)
|
||||
}
|
||||
// high/critical can never be suppressed
|
||||
if _, err := s.Update("INC-1", Patch{Status: str("benign"), Suppress: &yes}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("high suppressed: %v", err)
|
||||
}
|
||||
// TTL
|
||||
s2, _, c2 := newStore(t)
|
||||
s2.Sync([]Finding{fnd("low", 500, 1)})
|
||||
*c2 = 5000
|
||||
until := int64(5000 + 86400)
|
||||
s2.Update("INC-1", Patch{Status: str("benign"), Suppress: &yes, SuppressUntil: &until})
|
||||
*c2 = 5000 + 2*86400
|
||||
s2.Sync([]Finding{fnd("low", *c2, 2)})
|
||||
if tk, _ = s2.Get("INC-1"); tk.Suppress || tk.Status != "open" || tk.History[len(tk.History)-1].Field != "suppression expired" {
|
||||
t.Fatalf("ttl: %+v", tk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFollowsFinding(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("low", 500, 1)})
|
||||
s.Sync([]Finding{fnd("high", 600, 1)})
|
||||
if tk, _ := s.Get("INC-1"); tk.Severity != "high" || tk.History[len(tk.History)-1].Field != "severity" {
|
||||
t.Fatalf("%+v", tk)
|
||||
}
|
||||
s.Create(NewManual{Title: "m"})
|
||||
s.Sync([]Finding{{Host: "h", Kind: "port", Severity: "low", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 1}})
|
||||
s.Update("INC-3", Patch{Severity: str("critical")})
|
||||
s.Sync([]Finding{{Host: "h", Kind: "port", Severity: "high", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 2}})
|
||||
if tk, _ := s.Get("INC-3"); tk.Severity != "critical" || !tk.SeverityManual {
|
||||
t.Fatalf("manual severity overwritten: %+v", tk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloodQuota(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
var fs []Finding
|
||||
for i := 0; i < HostQuota+20; i++ {
|
||||
fs = append(fs, Finding{Host: "h", Kind: "port", Severity: "low", Workload: "w", Dst: "10.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250), DPort: 80, Proto: "tcp", Last: int64(i)})
|
||||
}
|
||||
s.Sync(fs)
|
||||
s.Sync(fs) // idempotent
|
||||
fs = append(fs, Finding{Host: "h", Kind: "bad_dst", Severity: "high", Workload: "w", Dst: "9.9.9.9", DPort: 22, Proto: "tcp", Last: 5})
|
||||
s.Sync(fs)
|
||||
pg := s.List(Query{Host: "h"})
|
||||
if pg.Total != HostQuota+2 { // quota + flood + the high one, never grouped
|
||||
t.Fatalf("total %d", pg.Total)
|
||||
}
|
||||
var flood *Summary
|
||||
for i := range pg.Items {
|
||||
if pg.Items[i].Kind == "flood" {
|
||||
flood = &pg.Items[i]
|
||||
}
|
||||
}
|
||||
if flood == nil || flood.Count != 20 || !strings.Contains(flood.Detail, "port 10.0.") {
|
||||
t.Fatalf("flood: %+v", flood)
|
||||
}
|
||||
// other hosts are unaffected
|
||||
s.Sync([]Finding{{Host: "other", Kind: "port", Severity: "low", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 1}})
|
||||
if s.List(Query{Host: "other"}).Total != 1 {
|
||||
t.Fatal("other host grouped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConflictAndKeyMigration(t *testing.T) {
|
||||
s, p, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 1)})
|
||||
tk, _ := s.Get("INC-1")
|
||||
stale := tk.UpdatedAt - 1
|
||||
if _, err := s.Update("INC-1", Patch{Verdict: str("x"), ExpectedUpdatedAt: &stale}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("stale write: %v", err)
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Verdict: str("x"), ExpectedUpdatedAt: &tk.UpdatedAt, Via: "token"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tk, _ = s.Get("INC-1"); tk.History[len(tk.History)-1].Author != "operator (via token)" {
|
||||
t.Fatalf("author: %+v", tk.History)
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Title: str("a\nb")}); err == nil {
|
||||
t.Fatal("newline in title")
|
||||
}
|
||||
// an old-format key is recomputed on load
|
||||
b, _ := os.ReadFile(p)
|
||||
old := strings.Replace(string(b), tk.Key, "oracle|port|old", 1)
|
||||
os.WriteFile(p, []byte(old), 0o600)
|
||||
s2, _ := Open(p, nil)
|
||||
if r := s2.Lookup([]string{fnd("medium", 1, 1).Key()}); len(r) != 1 {
|
||||
t.Fatal("key not migrated")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -23,6 +24,7 @@ type egressOut struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Source egress.SourceInfo `json:"source"`
|
||||
egress.Report
|
||||
SuppressedCount int `json:"suppressed_count"`
|
||||
}
|
||||
|
||||
// egressAPI: GET /api/v1/egress?range=24h&host=all|<name>. On a hub the
|
||||
@@ -48,7 +50,21 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
out.Source = eng.Info()
|
||||
out.Enabled = true
|
||||
}
|
||||
rep := egress.EmptyReport()
|
||||
rep, peerOn := s.egressReport(r.Context(), from, to, local, peers, only)
|
||||
if peerOn {
|
||||
out.Enabled = true
|
||||
}
|
||||
// incidents are fed only by the 60 s loop, never by a request
|
||||
out.Report = rep
|
||||
out.SuppressedCount = s.annotateFindings(&out.Report, r.URL.Query().Get("suppressed") == "1")
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// egressReport builds the report of the window: the local engine and, on a hub,
|
||||
// the peers' reports merged (items carrying "host"). peerOn is true when a peer answered.
|
||||
func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers bool, only string) (rep egress.Report, peerOn bool) {
|
||||
eng := egressEngine.Load()
|
||||
rep = egress.EmptyReport()
|
||||
if local && eng != nil {
|
||||
rep = eng.Report(from, to)
|
||||
}
|
||||
@@ -59,7 +75,7 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
rep.Stamp(s.opt.Store.Name())
|
||||
merged.Merge(rep, s.opt.Store.Name())
|
||||
}
|
||||
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
|
||||
raws := s.opt.Hub.EgressFor(ctx, from, to, only)
|
||||
names := make([]string, 0, len(raws))
|
||||
for n := range raws {
|
||||
names = append(names, n)
|
||||
@@ -72,12 +88,11 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
pr.Sanitize(n)
|
||||
merged.Merge(pr, n)
|
||||
out.Enabled = true
|
||||
peerOn = true
|
||||
}
|
||||
rep = merged
|
||||
}
|
||||
out.Report = rep
|
||||
writeJSON(w, 200, out)
|
||||
return rep, peerOn
|
||||
}
|
||||
|
||||
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func incRig(t *testing.T) http.Handler {
|
||||
t.Helper()
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
inc, err := incidents.Open(filepath.Join(t.TempDir(), "incidents.json"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st, Incidents: inc})
|
||||
}
|
||||
|
||||
func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
h := incRig(t)
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
SetEgress(e)
|
||||
defer SetEgress(nil)
|
||||
now := time.Now()
|
||||
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.3.5"), Dst: netip.MustParseAddr("203.0.113.3"), Proto: "tcp", DPort: 6667, In: "br-1"})
|
||||
|
||||
d := getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if w := req(h, "GET", "/api/v1/incidents", ``, auth); !strings.Contains(w.Body.String(), `"total":0`) {
|
||||
t.Fatalf("a request fed the incidents: %s", w.Body)
|
||||
}
|
||||
incidentServer.Load().syncNow(context.Background())
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
var f map[string]any
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if m := x.(map[string]any); m["kind"] == "port" {
|
||||
f = m
|
||||
}
|
||||
}
|
||||
if f == nil || f["ticket_id"] != "INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
t.Fatalf("annotated: %v", d)
|
||||
}
|
||||
// suppression needs false_positive/benign
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
t.Fatalf("list: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"suppress":true}`, auth); w.Code != 409 {
|
||||
t.Fatalf("suppress in open: %d", w.Code)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"status":"false_positive","suppress":true,"author":"ana"}`, auth); w.Code != 200 {
|
||||
t.Fatalf("patch: %d %s", w.Code, w.Body)
|
||||
}
|
||||
incidentServer.Load().syncNow(context.Background())
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if x.(map[string]any)["kind"] == "port" {
|
||||
t.Fatalf("suppressed finding still listed: %v", x)
|
||||
}
|
||||
}
|
||||
if d["suppressed_count"].(float64) != 1 {
|
||||
t.Fatalf("suppressed_count: %v", d["suppressed_count"])
|
||||
}
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h&suppressed=1", auth)
|
||||
shown := false
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if m := x.(map[string]any); m["kind"] == "port" && m["suppressed"] == true && m["ticket_status"] == "false_positive" {
|
||||
shown = true
|
||||
}
|
||||
}
|
||||
if !shown {
|
||||
t.Fatalf("?suppressed=1: %v", d["findings"])
|
||||
}
|
||||
// another destination is not covered by the exact key
|
||||
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.3.5"), Dst: netip.MustParseAddr("203.0.113.4"), Proto: "tcp", DPort: 6667, In: "br-1"})
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if len(d["findings"].([]any)) == 0 {
|
||||
t.Fatal("a different key was suppressed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncidentsAPI(t *testing.T) {
|
||||
h := incRig(t)
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
paths := [][2]string{{"GET", "/api/v1/incidents"}, {"GET", "/api/v1/incidents/INC-1"}, {"POST", "/api/v1/incidents"}, {"PATCH", "/api/v1/incidents/INC-1"}, {"POST", "/api/v1/incidents/INC-1/comments"}, {"GET", "/api/v1/incidents/export.csv"}}
|
||||
for _, p := range paths {
|
||||
if w := req(h, p[0], p[1], `{}`, nil); w.Code != 401 {
|
||||
t.Errorf("%v no auth: %d", p, w.Code)
|
||||
}
|
||||
if w := req(h, p[0], p[1], `{}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Errorf("%v peer token: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
for _, p := range paths[2:5] {
|
||||
if w := req(h, p[0], p[1], `{"title":"x"}`, cross); w.Code != 403 {
|
||||
t.Errorf("%v cross-site: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
w := req(h, "POST", "/api/v1/incidents", `{"title":"Servidor estranho","detail":"d","severity":"high","host":"oracle","tags":["a-b"],"author":"ana"}`, auth)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("create: %d %s", w.Code, w.Body)
|
||||
}
|
||||
var tk map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &tk)
|
||||
if tk["id"] != "INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
t.Fatalf("ticket: %v", tk)
|
||||
}
|
||||
bad := []struct{ m, p, b string }{
|
||||
{"POST", "/api/v1/incidents", `nope`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x","extra":1}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":""}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x","severity":"urgent"}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x"}{"title":"y"}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"` + strings.Repeat("a", 70<<10) + `"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"status":"bogus"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"tags":["BAD"]}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"title":"a\u0000b"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"id":"INC-2"}`},
|
||||
{"POST", "/api/v1/incidents/INC-1/comments", `{"text":""}`},
|
||||
{"POST", "/api/v1/incidents/INC-1/comments", `{"text":"` + strings.Repeat("a", 5001) + `"}`},
|
||||
{"GET", "/api/v1/incidents?status=nope", ``},
|
||||
{"GET", "/api/v1/incidents?sort=x", ``},
|
||||
{"GET", "/api/v1/incidents?page=0", ``},
|
||||
}
|
||||
for _, c := range bad {
|
||||
if w := req(h, c.m, c.p, c.b, auth); w.Code != 400 {
|
||||
t.Errorf("%s %s %.40q: %d", c.m, c.p, c.b, w.Code)
|
||||
}
|
||||
}
|
||||
for _, p := range [][2]string{{"GET", "/api/v1/incidents/INC-99"}, {"PATCH", "/api/v1/incidents/INC-99"}, {"POST", "/api/v1/incidents/INC-99/comments"}} {
|
||||
body := `{"title":"x"}`
|
||||
if strings.HasSuffix(p[1], "/comments") {
|
||||
body = `{"text":"x"}`
|
||||
}
|
||||
if w := req(h, p[0], p[1], body, auth); w.Code != 404 {
|
||||
t.Errorf("%v: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := req(h, "POST", "/api/v1/incidents/INC-1/comments", `{"text":"visto"}`, auth); w.Code != 201 || !strings.Contains(w.Body.String(), `operator (via token)`) {
|
||||
t.Fatalf("comment: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"status":"resolved","verdict":"ok","assignee":"bia"}`, auth); w.Code != 200 {
|
||||
t.Fatalf("patch: %d %s", w.Code, w.Body)
|
||||
}
|
||||
d := getJSON(t, h, "/api/v1/incidents/INC-1", auth)
|
||||
if d["status"] != "resolved" || len(d["history"].([]any)) != 4 || len(d["comments"].([]any)) != 1 {
|
||||
t.Fatalf("full: %v", d)
|
||||
}
|
||||
l := getJSON(t, h, "/api/v1/incidents?status=resolved,open&per_page=1&page="+strconv.Itoa(1), auth)
|
||||
if l["total"].(float64) != 1 || l["counts"].(map[string]any)["resolved"].(float64) != 1 {
|
||||
t.Fatalf("list: %v", l)
|
||||
}
|
||||
if w := req(h, "GET", "/api/v1/incidents/export.csv", ``, auth); w.Code != 200 || !strings.HasPrefix(w.Body.String(), "id,status") || !strings.Contains(w.Body.String(), "INC-1") {
|
||||
t.Fatalf("csv: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,9 @@ type enforceView struct {
|
||||
|
||||
// egressView is the outbound-traffic data of the report (nil: analysis not running).
|
||||
type egressView struct {
|
||||
Source egress.SourceInfo
|
||||
Report egress.Report
|
||||
Source egress.SourceInfo
|
||||
Report egress.Report
|
||||
Suppressed int // findings hidden by tickets
|
||||
}
|
||||
|
||||
// reportInput is everything the renderer needs. To wire another source, fill a
|
||||
@@ -543,6 +544,9 @@ func (r *renderer) build(in reportInput, genTS int64) viewV {
|
||||
} else {
|
||||
v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh))))
|
||||
}
|
||||
if x.Suppressed > 0 {
|
||||
v.XNotes = append(v.XNotes, r.t("x.supp", r.num(float64(x.Suppressed))))
|
||||
}
|
||||
v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State))
|
||||
v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}}
|
||||
var items []chartItem
|
||||
@@ -693,7 +697,9 @@ func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput {
|
||||
in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent}
|
||||
}
|
||||
if e := egressEngine.Load(); e != nil {
|
||||
in.Egress = &egressView{Source: e.Info(), Report: e.Report(rc.from, rc.to)}
|
||||
rep := e.Report(rc.from, rc.to)
|
||||
sup := s.annotateFindings(&rep, false) // tickets marked false positive/benign leave the report
|
||||
in.Egress = &egressView{Source: e.Info(), Report: rep, Suppressed: sup}
|
||||
}
|
||||
}
|
||||
return in
|
||||
|
||||
@@ -158,6 +158,7 @@ var reportText = map[string][2]string{
|
||||
"e.werr": {"Erros de gravação", "Write errors"},
|
||||
"x.lead": {"Tráfego de saída é o que os seus servidores iniciam em direção à internet. Um servidor sadio fala com poucos destinos conhecidos; conversas periódicas com destinos estranhos podem indicar invasão.", "Outbound traffic is what your servers start towards the internet. A healthy server talks to a few known destinations; periodic talks to strange destinations may indicate a breach."},
|
||||
"x.nof": {"Nenhum alerta de saída no período.", "No outbound alerts in this period."},
|
||||
"x.supp": {"%s achado(s) suprimido(s) por chamados de incidente.", "%s finding(s) suppressed by incident tickets."},
|
||||
"x.sev": {"%s alerta(s) de saída, %s de severidade alta.", "%s outbound alert(s), %s of high severity."},
|
||||
"x.src": {"Fonte dos dados: %s.", "Data source: %s."},
|
||||
"stage.recon": {"reconhecimento", "reconnaissance"},
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
@@ -67,7 +68,9 @@ type Options struct {
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
// Incidents is the ticket store (nil: incident management off).
|
||||
Incidents *incidents.Store
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Server is the HTTP handler.
|
||||
@@ -126,6 +129,9 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
if opt.Incidents != nil {
|
||||
incidentServer.Store(s)
|
||||
}
|
||||
return s.headers(m)
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
* pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00"
|
||||
* Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice
|
||||
* Urutau.toast(msg) short confirmation toast
|
||||
* Urutau.setNavBadge(pageId, n, title?) counter on the page's rail/tab item (0 removes it)
|
||||
* Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby,
|
||||
* popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }.
|
||||
* Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat.<category>,
|
||||
@@ -1251,7 +1252,7 @@
|
||||
// rail groups; ids not listed go to the end of their group (page.group, else Analyze)
|
||||
var GROUPS = [
|
||||
['monitor', ['overview', 'live', 'slo']],
|
||||
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search']],
|
||||
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search', 'incidents']],
|
||||
['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']],
|
||||
['operate', ['defense', 'sources', 'integrity']],
|
||||
['reports', ['reports']]
|
||||
@@ -1912,6 +1913,22 @@
|
||||
}
|
||||
|
||||
function navId() { return current ? (current.id === 'ip' ? 'ips' : current.id) : null; }
|
||||
// small counter on a rail/tab item (e.g. open incidents); n <= 0 removes it. Set by page scripts.
|
||||
var navBadges = {};
|
||||
function setNavBadge(id, n, label) {
|
||||
n = Math.max(0, Math.floor(Number(n) || 0));
|
||||
var old = navBadges[id];
|
||||
if (old ? old.n === n && old.label === label : n === 0) return;
|
||||
if (n) navBadges[id] = { n: n, label: label || '' }; else delete navBadges[id];
|
||||
if (booted) renderNav();
|
||||
}
|
||||
function navBadgeNode(id) {
|
||||
var b = navBadges[id];
|
||||
if (!b) return null;
|
||||
var n = h('span', 'nav-badge', b.n > 99 ? '99+' : String(b.n));
|
||||
if (b.label) n.title = b.label;
|
||||
return n;
|
||||
}
|
||||
function renderNav() {
|
||||
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
|
||||
clear(nav); clear(bar); clear(more);
|
||||
@@ -1919,13 +1936,13 @@
|
||||
list.forEach(function (p) {
|
||||
var label = t(p.titleKey), gr = groupOf(p);
|
||||
if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; }
|
||||
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label));
|
||||
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
nav.appendChild(a);
|
||||
});
|
||||
var direct = list.length <= 5 ? list : list.slice(0, 4), rest = list.length <= 5 ? [] : list.slice(4);
|
||||
direct.forEach(function (p) {
|
||||
var a = el('a', { class: 'tab', href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
|
||||
var a = el('a', { class: 'tab', href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
bar.appendChild(a);
|
||||
});
|
||||
@@ -1939,7 +1956,7 @@
|
||||
rest.forEach(function (p) {
|
||||
var g2 = groupOf(p);
|
||||
if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; }
|
||||
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
|
||||
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
more.appendChild(a);
|
||||
});
|
||||
@@ -2111,7 +2128,7 @@
|
||||
|
||||
window.Urutau = {
|
||||
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP,
|
||||
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast, apiSend: apiSend, unbanDialog: unbanDialog,
|
||||
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast, apiSend: apiSend, unbanDialog: unbanDialog, setNavBadge: setNavBadge,
|
||||
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
|
||||
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
|
||||
charts: charts, help: help, glossary: glossary,
|
||||
|
||||
@@ -153,3 +153,9 @@
|
||||
.eg-bursts li { grid-template-columns: 84px minmax(0, 1fr); }
|
||||
.eg-b-chips { grid-column: 1 / -1; }
|
||||
}
|
||||
|
||||
/* ticket badge and suppressed findings (v1.5.0) */
|
||||
.eg-ticket { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: var(--ink); max-width: 100%; }
|
||||
.eg-ticket:hover .badge, .eg-ticket:focus-visible .badge { border-color: var(--line-strong); }
|
||||
.eg-ev-sup { opacity: .7; }
|
||||
.eg-sup-toggle { display: inline-flex; align-items: center; gap: 6px; font-size: .875rem; color: var(--ink-muted); cursor: pointer; min-height: 36px; }
|
||||
@@ -14,6 +14,8 @@
|
||||
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo', 'tor'];
|
||||
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo', tor: 'term.tor' };
|
||||
var LAT_TOP = 84, LAT_SPAN = 142;
|
||||
var TICKET_STATUS = ['open', 'investigating', 'true_positive', 'false_positive', 'benign', 'resolved'];
|
||||
var TICKET_TONE = { open: 'warn', investigating: 'info', true_positive: 'danger', false_positive: 'neutral', benign: 'neutral', resolved: 'ok' };
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
@@ -250,7 +252,7 @@
|
||||
});
|
||||
|
||||
var el = U.el, t = U.t, nf = U.fmt.num;
|
||||
var root = null, seq = 0, alive = false, ctx = null, data = null, hosts = null;
|
||||
var root = null, seq = 0, alive = false, ctx = null, data = null, hosts = null, showSup = false;
|
||||
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function help(node, key) { if (U.help) U.help(node, key); return node; }
|
||||
@@ -344,6 +346,12 @@
|
||||
if (kind) help(title, KIND_HELP[kind]);
|
||||
var head = el('div', { class: 'eg-ev-head' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title);
|
||||
if (st.multi && f.host) head.appendChild(el('span', { class: 'chip' }, t('eg.f.host', { h: f.host })));
|
||||
if (f.ticket_id) {
|
||||
var ts = TICKET_STATUS.indexOf(f.ticket_status) >= 0 ? f.ticket_status : 'open';
|
||||
head.appendChild(el('a', { class: 'eg-ticket', href: U.href('incidents', [String(f.ticket_id)]), title: t('eg.f.ticket', { id: String(f.ticket_id) }) },
|
||||
el('span', { class: 'mono' }, String(f.ticket_id)), U.ui.badge(t('inc.status.' + ts), TICKET_TONE[ts])));
|
||||
}
|
||||
if (f.suppressed) head.appendChild(el('span', { class: 'chip' }, t('eg.suppressed.chip')));
|
||||
|
||||
var route = el('div', { class: 'eg-route' },
|
||||
el('span', { class: 'eg-node' }, el('span', { class: 'eg-node-k' }, t('eg.f.from')), el('strong', { class: 'mono' }, f.workload || '-')),
|
||||
@@ -368,7 +376,7 @@
|
||||
el('div', { class: 'eg-ev-todo' }, el('p', { class: 'eg-ev-lab' }, t('eg.f.todo')), el('p', null, t('eg.do.' + kind)))));
|
||||
}
|
||||
if (f.dst) body.appendChild(el('a', { class: 'btn eg-ev-btn', href: U.href('ip', [f.dst]) }, t('eg.f.open') + ' →'));
|
||||
return el('article', { class: 'eg-ev eg-sev-' + sev }, head, body);
|
||||
return el('article', { class: 'eg-ev eg-sev-' + sev + (f.suppressed ? ' eg-ev-sup' : '') }, head, body);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ map
|
||||
@@ -543,7 +551,14 @@
|
||||
if (st.infra.length) root.appendChild(infraLine(st));
|
||||
|
||||
var grid = el('div', { class: 'grid-12' });
|
||||
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
|
||||
var supN = data.suppressed_count || 0, fpActs = null;
|
||||
if (supN || showSup) {
|
||||
var cb = el('input', { type: 'checkbox', id: 'eg-sup' });
|
||||
cb.checked = showSup;
|
||||
cb.addEventListener('change', function () { showSup = cb.checked; load(); });
|
||||
fpActs = el('label', { class: 'eg-sup-toggle', for: 'eg-sup' }, cb, el('span', null, t('eg.suppressed.toggle', { n: nf(supN) })));
|
||||
}
|
||||
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12', actions: fpActs });
|
||||
if (!st.fnd.length) {
|
||||
fp.body.appendChild(el('div', { class: 'eg-calm' }, el('span', { class: 'eg-calm-ico', 'aria-hidden': 'true' }, '✓'),
|
||||
el('div', null, el('strong', null, t('eg.calm')), el('p', null, t('eg.calm.sub')))));
|
||||
@@ -590,6 +605,7 @@
|
||||
var my = ++seq;
|
||||
var p = Object.assign({}, U.rangeParams());
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
if (showSup) p.suppressed = 1;
|
||||
if (!hosts) {
|
||||
hosts = [];
|
||||
U.api('/api/v1/summary', { range: '1h', host: 'all' }).then(function (s) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/* Urutau - INCIDENTS page. Ticket text is untrusted: long words wrap, nothing forces horizontal scroll. */
|
||||
.inc-page { min-width: 0; }
|
||||
.inc-lead { color: var(--ink-muted); max-width: 70ch; margin: 0 0 var(--s-3); }
|
||||
.inc-hint { font-size: .8125rem; color: var(--ink-muted); overflow-wrap: anywhere; }
|
||||
.inc-author { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2) var(--s-3); margin-bottom: var(--s-3); }
|
||||
.inc-author label { font-size: .875rem; color: var(--ink-muted); }
|
||||
.inc-author input { width: 12rem; max-width: 100%; min-height: 32px; padding: 3px 10px; }
|
||||
|
||||
.inc-tabs { display: flex; flex-wrap: wrap; gap: var(--s-2); margin-bottom: var(--s-3); }
|
||||
.inc-tab { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 4px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-raised); color: var(--ink); cursor: pointer; font: inherit; }
|
||||
.inc-tab:hover { border-color: var(--line-strong); }
|
||||
.inc-tab:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-tab.on { background: var(--accent-soft); border-color: var(--accent); font-weight: 600; }
|
||||
.inc-n { font-size: .8125rem; color: var(--ink-muted); }
|
||||
.inc-toolbar select { max-width: 100%; }
|
||||
|
||||
.inc-list { display: grid; gap: var(--s-2); }
|
||||
.inc-row {
|
||||
display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; gap: var(--s-2) var(--s-3); align-items: center;
|
||||
padding: var(--s-3) var(--s-4); background: var(--surface-panel); border: 1px solid var(--line); border-left: 4px solid var(--line-strong);
|
||||
border-radius: var(--radius-sm); color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.inc-row:hover { border-color: var(--line-strong); background: var(--surface-raised); }
|
||||
.inc-row:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-sev-critical, .inc-sev-high { border-left-color: var(--danger); }
|
||||
.inc-sev-medium { border-left-color: var(--warn); }
|
||||
.inc-sev-low { border-left-color: var(--info); }
|
||||
.inc-id { font-weight: 600; white-space: nowrap; }
|
||||
.inc-badges { display: inline-flex; gap: 6px; flex-wrap: wrap; }
|
||||
.inc-main { min-width: 0; display: grid; gap: 2px; }
|
||||
.inc-title { overflow-wrap: anywhere; }
|
||||
.inc-meta { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; color: var(--ink-muted); min-width: 0; }
|
||||
.inc-route { overflow-wrap: anywhere; }
|
||||
.inc-side { display: grid; gap: 2px; justify-items: end; font-size: .8125rem; color: var(--ink-muted); white-space: nowrap; }
|
||||
|
||||
.inc-back { display: inline-block; margin-bottom: var(--s-3); color: var(--accent); text-decoration: none; }
|
||||
.inc-back:hover { text-decoration: underline; }
|
||||
.inc-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2) var(--s-3); margin-bottom: var(--s-4); padding: var(--s-3) var(--s-4); background: var(--surface-panel); border: 1px solid var(--line); border-left: 4px solid var(--line-strong); border-radius: var(--radius-sm); }
|
||||
.inc-h-title { flex: 1 1 100%; margin: 0; font-size: 1.25rem; overflow-wrap: anywhere; }
|
||||
.inc-tags { display: inline-flex; flex-wrap: wrap; gap: 4px; }
|
||||
.inc-detail.busy { opacity: .6; pointer-events: none; }
|
||||
.inc-grid { align-items: start; }
|
||||
|
||||
.inc-quick { display: flex; flex-wrap: wrap; gap: var(--s-2); margin-bottom: var(--s-4); }
|
||||
.inc-q-fp:not(:disabled) { border-color: var(--line-strong); }
|
||||
.inc-q-tp:not(:disabled) { border-color: var(--danger); color: var(--danger); }
|
||||
.inc-q-ok:not(:disabled) { border-color: var(--ok); color: var(--ok); }
|
||||
.inc-form { display: grid; gap: var(--s-3); }
|
||||
.inc-two { align-items: start; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--s-3); }
|
||||
.inc-field { display: grid; gap: 4px; min-width: 0; }
|
||||
.inc-field label { font-size: .875rem; font-weight: 600; }
|
||||
.inc-field input[type="text"], .inc-field select, .inc-field textarea, .inc-newc textarea { width: 100%; min-width: 0; box-sizing: border-box; }
|
||||
.inc-page textarea, .inc-dlg textarea {
|
||||
background: var(--surface-raised); color: var(--ink); border: 1px solid var(--line); border-radius: var(--radius-sm);
|
||||
padding: 8px 12px; font: inherit; resize: vertical; min-height: 72px;
|
||||
}
|
||||
.inc-page textarea:focus-visible, .inc-dlg textarea:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-check { display: flex; align-items: center; gap: var(--s-2); }
|
||||
.inc-check input { width: 18px; height: 18px; flex: none; }
|
||||
.inc-btns { display: flex; flex-wrap: wrap; gap: var(--s-2); justify-content: flex-end; margin-top: var(--s-3); }
|
||||
.inc-err { color: var(--danger); margin: var(--s-2) 0 0; }
|
||||
.inc-dlg { width: min(34rem, calc(100vw - 32px)); }
|
||||
|
||||
.inc-dl { display: grid; grid-template-columns: minmax(0, auto) minmax(0, 1fr); gap: 6px var(--s-3); margin: 0; }
|
||||
.inc-dl dt { color: var(--ink-muted); font-size: .8125rem; }
|
||||
.inc-dl dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
|
||||
.inc-key { font-size: .75rem; }
|
||||
|
||||
.inc-comments { list-style: none; margin: 0 0 var(--s-3); padding: 0; display: grid; gap: var(--s-3); }
|
||||
.inc-comments li { padding: var(--s-3); background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); }
|
||||
.inc-c-h { display: flex; flex-wrap: wrap; gap: var(--s-2) var(--s-3); align-items: baseline; margin-bottom: 4px; }
|
||||
.inc-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
|
||||
.inc-tl { list-style: none; margin: 0; padding: 0 0 0 var(--s-3); border-left: 2px solid var(--line); display: grid; gap: var(--s-3); }
|
||||
.inc-tl li { display: grid; gap: 2px; min-width: 0; }
|
||||
.inc-tl-when { font-size: .75rem; color: var(--ink-muted); }
|
||||
.inc-tl-what { overflow-wrap: anywhere; }
|
||||
.inc-tl-chg { overflow-wrap: anywhere; font-size: .875rem; }
|
||||
.inc-from { color: var(--ink-muted); text-decoration: line-through; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.inc-row { grid-template-columns: minmax(0, 1fr); }
|
||||
.inc-side { justify-items: start; grid-auto-flow: column; gap: var(--s-3); }
|
||||
.inc-two { grid-template-columns: minmax(0, 1fr); }
|
||||
.inc-quick .btn { flex: 1 1 100%; white-space: normal; }
|
||||
.inc-tab { flex: 1 1 auto; }
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
/* Urutau - INCIDENTS page: every finding of the outbound traffic (egress) becomes a ticket that
|
||||
people triage (open, investigating, true/false positive, benign, resolved), comment on and,
|
||||
for false positives, suppress. #/incidents is the list, #/incidents/<id> the ticket.
|
||||
Data: /api/v1/incidents (GET list, GET one, PATCH, POST comments, POST create).
|
||||
Ticket text (workload names, details, comments, tags) comes from hostile logs and from users:
|
||||
dynamic text goes through textContent only. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var STATUSES = ['open', 'investigating', 'true_positive', 'false_positive', 'benign', 'resolved'];
|
||||
var STATUS_TONE = { open: 'warn', investigating: 'info', true_positive: 'danger', false_positive: 'neutral', benign: 'neutral', resolved: 'ok' };
|
||||
var SEVS = ['critical', 'high', 'medium', 'low', 'info'];
|
||||
var SEV_TONE = { critical: 'danger', high: 'danger', medium: 'warn', low: 'info', info: 'neutral' };
|
||||
var SORTS = ['updated', 'severity', 'last_seen'];
|
||||
var SUPPRESSIBLE = ['false_positive', 'benign'];
|
||||
var PER_PAGE = 25;
|
||||
var AUTHOR_KEY = 'urutau.author';
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerPage) return false;
|
||||
var el = U.el, t = U.t;
|
||||
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'inc.title': 'Incidents',
|
||||
'inc.nav.open': '{n} open or under investigation',
|
||||
'inc.lead': 'Every outbound finding is a ticket. Open it, investigate, write down what you found, and close it as a real incident, a false positive or benign.',
|
||||
'inc.author': 'Your name',
|
||||
'inc.author.hint': 'Saved in this browser and shown next to your comments and changes.',
|
||||
'inc.new': 'New ticket',
|
||||
'inc.search': 'Search tickets',
|
||||
'inc.sev.all': 'All severities',
|
||||
'inc.sev.critical': 'Critical', 'inc.sev.high': 'High', 'inc.sev.medium': 'Medium', 'inc.sev.low': 'Low', 'inc.sev.info': 'Info',
|
||||
'inc.sort': 'Sort by',
|
||||
'inc.sort.updated': 'Recently updated', 'inc.sort.severity': 'Severity', 'inc.sort.last_seen': 'Last seen',
|
||||
'inc.status.open': 'Open', 'inc.status.investigating': 'Investigating', 'inc.status.true_positive': 'True positive',
|
||||
'inc.status.false_positive': 'False positive', 'inc.status.benign': 'Benign', 'inc.status.resolved': 'Resolved',
|
||||
'inc.tab.active': 'Active', 'inc.tab.all': 'All',
|
||||
'inc.tabs': 'Filter by status',
|
||||
'inc.list.empty': 'No tickets here',
|
||||
'inc.list.empty.sub': 'Nothing matches these filters. Findings from the outbound traffic page appear here by themselves.',
|
||||
'inc.list.err': 'Could not load the tickets.',
|
||||
'inc.retry': 'Try again',
|
||||
'inc.comments.n.one': '{n} comment', 'inc.comments.n.other': '{n} comments',
|
||||
'inc.seen': 'seen {when}',
|
||||
'inc.source.egress': 'Outbound traffic', 'inc.source.manual': 'Manual',
|
||||
'inc.back': 'All incidents',
|
||||
'inc.notfound': 'Ticket not found',
|
||||
'inc.notfound.sub': 'It may have been removed, or the link is wrong.',
|
||||
'inc.f.title': 'Title', 'inc.f.severity': 'Severity', 'inc.f.status': 'Status', 'inc.f.assignee': 'Assigned to',
|
||||
'inc.f.tags': 'Tags', 'inc.f.tags.hint': 'Separate with commas.',
|
||||
'inc.f.verdict': 'Conclusion', 'inc.f.verdict.hint': 'What you found and why you closed it this way.',
|
||||
'inc.f.detail': 'Details', 'inc.f.host': 'Server',
|
||||
'inc.f.suppress': 'Suppress identical alerts',
|
||||
'inc.f.suppress.help': 'Only for false positive or benign. Future findings with the same fingerprint stop showing on the outbound traffic page (they stay behind "show suppressed").',
|
||||
'inc.f.suppress.off': 'Pick False positive or Benign to enable this.',
|
||||
'inc.edit': 'Ticket',
|
||||
'inc.save': 'Save changes',
|
||||
'inc.saved': 'Ticket updated',
|
||||
'inc.quick': 'Quick actions',
|
||||
'inc.quick.fp': 'Mark false positive', 'inc.quick.tp': 'Confirm incident', 'inc.quick.resolve': 'Resolve',
|
||||
'inc.tech': 'Technical data',
|
||||
'inc.t.kind': 'Pattern', 'inc.t.source': 'Source', 'inc.t.workload': 'Workload', 'inc.t.dst': 'Destination', 'inc.t.port': 'Port',
|
||||
'inc.t.proto': 'Protocol', 'inc.t.host': 'Server', 'inc.t.first': 'First seen', 'inc.t.last': 'Last seen', 'inc.t.count': 'Occurrences',
|
||||
'inc.t.key': 'Fingerprint', 'inc.t.created': 'Opened', 'inc.t.updated': 'Updated',
|
||||
'inc.comments': 'Comments',
|
||||
'inc.comments.none': 'No comments yet.',
|
||||
'inc.comment.ph': 'Write what you checked or decided',
|
||||
'inc.comment.add': 'Add comment',
|
||||
'inc.comment.added': 'Comment added',
|
||||
'inc.history': 'History',
|
||||
'inc.history.none': 'No changes yet.',
|
||||
'inc.h.line': '{who} changed {field}',
|
||||
'inc.h.field.status': 'status', 'inc.h.field.severity': 'severity', 'inc.h.field.assignee': 'assignee', 'inc.h.field.tags': 'tags',
|
||||
'inc.h.field.title': 'title', 'inc.h.field.verdict': 'conclusion', 'inc.h.field.suppress': 'alert suppression',
|
||||
'inc.h.empty': 'empty', 'inc.h.on': 'on', 'inc.h.off': 'off',
|
||||
'inc.err.save': 'Could not save. Check the fields and try again.',
|
||||
'inc.err.suppress': 'Suppression is only allowed for False positive or Benign.',
|
||||
'inc.err.comment': 'Could not add the comment.',
|
||||
'inc.err.create': 'Could not create the ticket.',
|
||||
'inc.new.title': 'New ticket',
|
||||
'inc.new.explain': 'Open a ticket by hand for something you saw that the system did not flag.',
|
||||
'inc.new.create': 'Create ticket',
|
||||
'inc.cancel': 'Cancel',
|
||||
'inc.required': 'Title is required.',
|
||||
'eg.f.ticket': 'Ticket {id}',
|
||||
'eg.suppressed.toggle': 'Show suppressed ({n})',
|
||||
'eg.suppressed.chip': 'suppressed'
|
||||
},
|
||||
'pt-BR': {
|
||||
'inc.title': 'Incidentes',
|
||||
'inc.nav.open': '{n} em aberto ou em investigação',
|
||||
'inc.lead': 'Cada achado de tráfego de saída é um chamado. Abra, investigue, anote o que descobriu e encerre como incidente real, falso positivo ou benigno.',
|
||||
'inc.author': 'Seu nome',
|
||||
'inc.author.hint': 'Fica salvo neste navegador e aparece junto dos seus comentários e alterações.',
|
||||
'inc.new': 'Novo chamado',
|
||||
'inc.search': 'Buscar chamados',
|
||||
'inc.sev.all': 'Todas as severidades',
|
||||
'inc.sev.critical': 'Crítica', 'inc.sev.high': 'Alta', 'inc.sev.medium': 'Média', 'inc.sev.low': 'Baixa', 'inc.sev.info': 'Informativa',
|
||||
'inc.sort': 'Ordenar por',
|
||||
'inc.sort.updated': 'Atualizados recentemente', 'inc.sort.severity': 'Severidade', 'inc.sort.last_seen': 'Última ocorrência',
|
||||
'inc.status.open': 'Aberto', 'inc.status.investigating': 'Em investigação', 'inc.status.true_positive': 'Verdadeiro positivo',
|
||||
'inc.status.false_positive': 'Falso positivo', 'inc.status.benign': 'Benigno', 'inc.status.resolved': 'Resolvido',
|
||||
'inc.tab.active': 'Ativos', 'inc.tab.all': 'Todos',
|
||||
'inc.tabs': 'Filtrar por status',
|
||||
'inc.list.empty': 'Nenhum chamado aqui',
|
||||
'inc.list.empty.sub': 'Nada corresponde a estes filtros. Os achados da página de tráfego de saída aparecem aqui sozinhos.',
|
||||
'inc.list.err': 'Não foi possível carregar os chamados.',
|
||||
'inc.retry': 'Tentar de novo',
|
||||
'inc.comments.n.one': '{n} comentário', 'inc.comments.n.other': '{n} comentários',
|
||||
'inc.seen': 'visto {when}',
|
||||
'inc.source.egress': 'Tráfego de saída', 'inc.source.manual': 'Manual',
|
||||
'inc.back': 'Todos os incidentes',
|
||||
'inc.notfound': 'Chamado não encontrado',
|
||||
'inc.notfound.sub': 'Ele pode ter sido removido ou o link está errado.',
|
||||
'inc.f.title': 'Título', 'inc.f.severity': 'Severidade', 'inc.f.status': 'Status', 'inc.f.assignee': 'Responsável',
|
||||
'inc.f.tags': 'Etiquetas', 'inc.f.tags.hint': 'Separe com vírgulas.',
|
||||
'inc.f.verdict': 'Conclusão', 'inc.f.verdict.hint': 'O que você descobriu e por que encerrou assim.',
|
||||
'inc.f.detail': 'Detalhes', 'inc.f.host': 'Servidor',
|
||||
'inc.f.suppress': 'Suprimir alertas iguais',
|
||||
'inc.f.suppress.help': 'Só para falso positivo ou benigno. Os próximos achados com a mesma impressão digital deixam de aparecer na página de tráfego de saída (ficam atrás de "mostrar suprimidos").',
|
||||
'inc.f.suppress.off': 'Escolha Falso positivo ou Benigno para habilitar.',
|
||||
'inc.edit': 'Chamado',
|
||||
'inc.save': 'Salvar alterações',
|
||||
'inc.saved': 'Chamado atualizado',
|
||||
'inc.quick': 'Ações rápidas',
|
||||
'inc.quick.fp': 'Marcar falso positivo', 'inc.quick.tp': 'Confirmar incidente', 'inc.quick.resolve': 'Resolver',
|
||||
'inc.tech': 'Dados técnicos',
|
||||
'inc.t.kind': 'Padrão', 'inc.t.source': 'Origem', 'inc.t.workload': 'Carga de trabalho', 'inc.t.dst': 'Destino', 'inc.t.port': 'Porta',
|
||||
'inc.t.proto': 'Protocolo', 'inc.t.host': 'Servidor', 'inc.t.first': 'Primeira vez', 'inc.t.last': 'Última vez', 'inc.t.count': 'Ocorrências',
|
||||
'inc.t.key': 'Impressão digital', 'inc.t.created': 'Aberto em', 'inc.t.updated': 'Atualizado em',
|
||||
'inc.comments': 'Comentários',
|
||||
'inc.comments.none': 'Nenhum comentário ainda.',
|
||||
'inc.comment.ph': 'Escreva o que você verificou ou decidiu',
|
||||
'inc.comment.add': 'Comentar',
|
||||
'inc.comment.added': 'Comentário adicionado',
|
||||
'inc.history': 'Histórico',
|
||||
'inc.history.none': 'Nenhuma alteração ainda.',
|
||||
'inc.h.line': '{who} alterou {field}',
|
||||
'inc.h.field.status': 'o status', 'inc.h.field.severity': 'a severidade', 'inc.h.field.assignee': 'o responsável', 'inc.h.field.tags': 'as etiquetas',
|
||||
'inc.h.field.title': 'o título', 'inc.h.field.verdict': 'a conclusão', 'inc.h.field.suppress': 'a supressão de alertas',
|
||||
'inc.h.empty': 'vazio', 'inc.h.on': 'ligada', 'inc.h.off': 'desligada',
|
||||
'inc.err.save': 'Não foi possível salvar. Confira os campos e tente de novo.',
|
||||
'inc.err.suppress': 'A supressão só é permitida em Falso positivo ou Benigno.',
|
||||
'inc.err.comment': 'Não foi possível adicionar o comentário.',
|
||||
'inc.err.create': 'Não foi possível criar o chamado.',
|
||||
'inc.new.title': 'Novo chamado',
|
||||
'inc.new.explain': 'Abra um chamado à mão para algo que você viu e o sistema não sinalizou.',
|
||||
'inc.new.create': 'Criar chamado',
|
||||
'inc.cancel': 'Cancelar',
|
||||
'inc.required': 'O título é obrigatório.',
|
||||
'eg.f.ticket': 'Chamado {id}',
|
||||
'eg.suppressed.toggle': 'Mostrar suprimidos ({n})',
|
||||
'eg.suppressed.chip': 'suprimido'
|
||||
}
|
||||
});
|
||||
|
||||
var root = null, ctx = null, view = null;
|
||||
|
||||
// ------------------------------------------------------------ helpers
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function pick(list, v, d) { return list.indexOf(v) >= 0 ? v : d; }
|
||||
function nf(n) { return U.fmt.num(n || 0); }
|
||||
function sevOf(s) { return pick(SEVS, s, 'info'); }
|
||||
function statusOf(s) { return pick(STATUSES, s, 'open'); }
|
||||
function sevBadge(s) { s = sevOf(s); return U.ui.badge(t('inc.sev.' + s), SEV_TONE[s]); }
|
||||
function statusBadge(s) { s = statusOf(s); return U.ui.badge(t('inc.status.' + s), STATUS_TONE[s]); }
|
||||
function isIP(s) { s = String(s || ''); return /^\d{1,3}(\.\d{1,3}){3}$/.test(s) || (s.indexOf(':') > 0 && /^[0-9a-f:.]+$/i.test(s)); }
|
||||
function tr(key, fallback) { var v = t(key); return v === key ? fallback : v; }
|
||||
function tags(list) { return el('span', { class: 'inc-tags' }, (Array.isArray(list) ? list : []).map(function (x) { return el('span', { class: 'chip' }, String(x)); })); }
|
||||
function getAuthor() {
|
||||
var v = '';
|
||||
try { v = (localStorage.getItem(AUTHOR_KEY) || '').trim(); } catch (e) { /* storage blocked */ }
|
||||
return v.slice(0, 64);
|
||||
}
|
||||
function authorName() { return getAuthor() || 'operator'; }
|
||||
function authorBox() {
|
||||
var inp = el('input', { type: 'text', id: 'inc-author', maxlength: '64', autocomplete: 'name', placeholder: 'operator', 'aria-describedby': 'inc-author-h' });
|
||||
inp.value = getAuthor();
|
||||
inp.addEventListener('input', function () {
|
||||
try { localStorage.setItem(AUTHOR_KEY, inp.value.trim().slice(0, 64)); } catch (e) { /* storage blocked */ }
|
||||
});
|
||||
return el('div', { class: 'inc-author' }, el('label', { for: 'inc-author' }, t('inc.author')), inp, el('span', { id: 'inc-author-h', class: 'inc-hint' }, t('inc.author.hint')));
|
||||
}
|
||||
function field(label, control, hint, id) {
|
||||
return el('div', { class: 'inc-field' }, el('label', { for: id }, label), control, hint ? el('span', { class: 'inc-hint' }, hint) : null);
|
||||
}
|
||||
function selectOf(id, values, labelFn, cur) {
|
||||
var s = el('select', { id: id });
|
||||
values.forEach(function (v) { var o = el('option', { value: v }, labelFn(v)); if (v === cur) o.selected = true; s.appendChild(o); });
|
||||
return s;
|
||||
}
|
||||
function parseTags(s) {
|
||||
var out = [];
|
||||
String(s || '').split(',').forEach(function (x) { x = x.trim().slice(0, 40); if (x && out.indexOf(x) < 0) out.push(x); });
|
||||
return out.slice(0, 20);
|
||||
}
|
||||
function sameList(a, b) { return JSON.stringify(a || []) === JSON.stringify(b || []); }
|
||||
|
||||
// open + investigating counter in the rail
|
||||
function pollBadge() {
|
||||
if (document.hidden) return;
|
||||
U.api('/api/v1/incidents', { status: 'open,investigating', per_page: 1 }).then(function (r) {
|
||||
var c = (r && r.counts) || {};
|
||||
var n = (c.open || 0) + (c.investigating || 0);
|
||||
U.setNavBadge('incidents', n, n ? t('inc.nav.open', { n: nf(n) }) : '');
|
||||
}, function () { /* the page itself shows its errors */ });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ list
|
||||
function listView(host) {
|
||||
var seq = 0, on = true, timer = 0;
|
||||
var results = el('div', { class: 'inc-results' });
|
||||
var tabsBox = el('div', { class: 'inc-tabs', role: 'group', 'aria-label': t('inc.tabs') });
|
||||
var counts = null;
|
||||
|
||||
function cur() {
|
||||
var s = U.param('s') || 'active';
|
||||
return { s: s === 'active' || s === 'all' || STATUSES.indexOf(s) >= 0 ? s : 'active', sev: pick(SEVS, U.param('sev'), ''), q: (U.param('q') || '').slice(0, 200), sort: pick(SORTS, U.param('sort'), 'updated'), p: U.pageParam() };
|
||||
}
|
||||
function query(f) {
|
||||
var p = { per_page: PER_PAGE, page: f.p, sort: f.sort };
|
||||
if (f.s === 'active') p.status = 'open,investigating';
|
||||
else if (f.s !== 'all') p.status = f.s;
|
||||
if (f.sev) p.severity = f.sev;
|
||||
if (f.q) p.q = f.q;
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
return p;
|
||||
}
|
||||
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('inc.search'), 'aria-label': t('inc.search') });
|
||||
search.value = cur().q;
|
||||
var sevSel = el('select', { 'aria-label': t('inc.f.severity') });
|
||||
sevSel.appendChild(el('option', { value: '' }, t('inc.sev.all')));
|
||||
SEVS.forEach(function (s) { sevSel.appendChild(el('option', { value: s }, t('inc.sev.' + s))); });
|
||||
sevSel.value = cur().sev;
|
||||
var sortSel = el('select', { 'aria-label': t('inc.sort') });
|
||||
SORTS.forEach(function (s) { sortSel.appendChild(el('option', { value: s }, t('inc.sort.' + s))); });
|
||||
sortSel.value = cur().sort;
|
||||
var newBtn = el('button', { type: 'button', class: 'btn primary' }, t('inc.new'));
|
||||
newBtn.addEventListener('click', function () { newDialog(); });
|
||||
|
||||
function reload() { U.setParam('p', ''); load(); }
|
||||
search.addEventListener('input', function () {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(function () { U.setParam('q', search.value.trim()); reload(); }, 300);
|
||||
});
|
||||
sevSel.addEventListener('change', function () { U.setParam('sev', sevSel.value); reload(); });
|
||||
sortSel.addEventListener('change', function () { U.setParam('sort', sortSel.value === 'updated' ? '' : sortSel.value); reload(); });
|
||||
|
||||
host.appendChild(el('p', { class: 'inc-lead' }, t('inc.lead')));
|
||||
host.appendChild(authorBox());
|
||||
host.appendChild(tabsBox);
|
||||
host.appendChild(el('div', { class: 'toolbar inc-toolbar' }, search, sevSel, sortSel, newBtn));
|
||||
host.appendChild(results);
|
||||
|
||||
function paintTabs(f) {
|
||||
clear(tabsBox);
|
||||
var c = counts || {}, total = 0;
|
||||
STATUSES.forEach(function (s) { total += c[s] || 0; });
|
||||
var items = [['active', t('inc.tab.active'), (c.open || 0) + (c.investigating || 0)]]
|
||||
.concat(STATUSES.map(function (s) { return [s, t('inc.status.' + s), c[s] || 0]; }))
|
||||
.concat([['all', t('inc.tab.all'), total]]);
|
||||
items.forEach(function (it) {
|
||||
var b = el('button', { type: 'button', class: 'inc-tab' + (f.s === it[0] ? ' on' : ''), 'aria-pressed': f.s === it[0] ? 'true' : 'false' },
|
||||
el('span', null, it[1]), counts ? el('span', { class: 'inc-n num' }, nf(it[2])) : null);
|
||||
b.addEventListener('click', function () { U.setParam('s', it[0] === 'active' ? '' : it[0]); reload(); });
|
||||
tabsBox.appendChild(b);
|
||||
});
|
||||
}
|
||||
function row(it) {
|
||||
var sev = sevOf(it.severity);
|
||||
var n = it.comment_count || 0;
|
||||
var route = it.workload || it.dst ? [(it.workload || '-'), ' → ', (it.dst || '-') + (it.dport ? ':' + it.dport : '')].join('') : '';
|
||||
var meta = el('div', { class: 'inc-meta' });
|
||||
if (route) meta.appendChild(el('span', { class: 'mono inc-route' }, route));
|
||||
if (it.host) meta.appendChild(el('span', { class: 'chip' }, String(it.host)));
|
||||
var a = el('a', { class: 'inc-row inc-sev-' + sev, href: U.href('incidents', [String(it.id)]) },
|
||||
el('span', { class: 'inc-id mono' }, String(it.id)),
|
||||
el('span', { class: 'inc-badges' }, sevBadge(it.severity), statusBadge(it.status)),
|
||||
el('span', { class: 'inc-main' }, el('strong', { class: 'inc-title' }, String(it.title || it.id)), meta),
|
||||
el('span', { class: 'inc-side' },
|
||||
el('span', { class: 'inc-when', title: it.last_seen ? U.fmt.date(it.last_seen) : '' }, t('inc.seen', { when: U.fmt.ago(it.last_seen) })),
|
||||
n ? el('span', { class: 'inc-cm' }, U.pl('inc.comments.n', n)) : null));
|
||||
return a;
|
||||
}
|
||||
function paint(r, f) {
|
||||
clear(results);
|
||||
var items = Array.isArray(r.items) ? r.items : [];
|
||||
if (!items.length) { results.appendChild(U.ui.empty(t('inc.list.empty'), t('inc.list.empty.sub'))); return; }
|
||||
var list = el('div', { class: 'inc-list' });
|
||||
items.forEach(function (it) { list.appendChild(row(it)); });
|
||||
results.appendChild(list);
|
||||
var total = r.total || items.length, pages = Math.max(1, Math.ceil(total / PER_PAGE));
|
||||
var pg = U.ui.pager({ page: f.p, pages: pages, total: total, onPage: function (n) { U.setParam('p', n); load(); window.scrollTo(0, 0); } });
|
||||
if (pg) results.appendChild(pg);
|
||||
}
|
||||
function load() {
|
||||
var my = ++seq, f = cur();
|
||||
paintTabs(f);
|
||||
if (!results.firstChild) results.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } }));
|
||||
U.api('/api/v1/incidents', query(f)).then(function (r) {
|
||||
if (!on || my !== seq) return;
|
||||
counts = r.counts || {};
|
||||
paintTabs(f);
|
||||
paint(r, f);
|
||||
var n = (counts.open || 0) + (counts.investigating || 0);
|
||||
U.setNavBadge('incidents', n, n ? t('inc.nav.open', { n: nf(n) }) : '');
|
||||
}, function () {
|
||||
if (!on || my !== seq) return;
|
||||
clear(results);
|
||||
var b = el('button', { type: 'button', class: 'btn' }, t('inc.retry'));
|
||||
b.addEventListener('click', load);
|
||||
results.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('inc.list.err')), b));
|
||||
});
|
||||
}
|
||||
load();
|
||||
return { refresh: load, update: load, destroy: function () { on = false; seq++; clearTimeout(timer); } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ new ticket dialog
|
||||
function newDialog() {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg inc-dlg', 'aria-labelledby': 'inc-new-h', 'aria-describedby': 'inc-new-p' });
|
||||
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
|
||||
var title = el('input', { type: 'text', id: 'inc-n-title', maxlength: '200', required: true });
|
||||
var detail = el('textarea', { id: 'inc-n-detail', rows: '4', maxlength: '4000' });
|
||||
var sev = selectOf('inc-n-sev', SEVS, function (s) { return t('inc.sev.' + s); }, 'medium');
|
||||
var hostIn = el('input', { type: 'text', id: 'inc-n-host', maxlength: '100' });
|
||||
if (ctx && ctx.host && ctx.host !== 'all') hostIn.value = ctx.host;
|
||||
var tg = el('input', { type: 'text', id: 'inc-n-tags', maxlength: '300' });
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('inc.new.create'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('inc.cancel'));
|
||||
dlg.appendChild(el('h2', { id: 'inc-new-h' }, t('inc.new.title')));
|
||||
dlg.appendChild(el('p', { id: 'inc-new-p' }, t('inc.new.explain')));
|
||||
dlg.appendChild(el('div', { class: 'inc-form' },
|
||||
field(t('inc.f.title'), title, null, 'inc-n-title'),
|
||||
field(t('inc.f.detail'), detail, null, 'inc-n-detail'),
|
||||
field(t('inc.f.severity'), sev, null, 'inc-n-sev'),
|
||||
field(t('inc.f.host'), hostIn, null, 'inc-n-host'),
|
||||
field(t('inc.f.tags'), tg, t('inc.f.tags.hint'), 'inc-n-tags')));
|
||||
dlg.appendChild(err);
|
||||
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
||||
function close() { dlg.close(); }
|
||||
cancel.addEventListener('click', close);
|
||||
dlg.addEventListener('close', function () {
|
||||
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
|
||||
if (prev && prev.focus && document.contains(prev)) prev.focus();
|
||||
});
|
||||
ok.addEventListener('click', function () {
|
||||
var ttl = title.value.trim();
|
||||
if (!ttl) { err.textContent = t('inc.required'); err.hidden = false; title.focus(); return; }
|
||||
ok.disabled = true;
|
||||
U.apiSend('POST', '/api/v1/incidents', { title: ttl, detail: detail.value.trim(), severity: sev.value, host: hostIn.value.trim(), tags: parseTags(tg.value), author: authorName() }).then(function (r) {
|
||||
close();
|
||||
pollBadge();
|
||||
if (r && r.id) location.hash = U.href('incidents', [String(r.id)]); else if (view && view.update) view.update();
|
||||
}, function () {
|
||||
ok.disabled = false;
|
||||
err.textContent = t('inc.err.create');
|
||||
err.hidden = false;
|
||||
});
|
||||
});
|
||||
document.body.appendChild(dlg);
|
||||
if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', '');
|
||||
title.focus();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ one ticket
|
||||
function detailView(host, id) {
|
||||
var seq = 0, on = true, tk = null, busy = false;
|
||||
var box = el('div', { class: 'inc-detail' });
|
||||
host.appendChild(el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back')));
|
||||
host.appendChild(authorBox());
|
||||
host.appendChild(box);
|
||||
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || ''); }
|
||||
function fail(node, key) { node.textContent = t(key); node.hidden = false; }
|
||||
function send(method, suffix, body, errNode, errKey, okKey) {
|
||||
if (busy) return;
|
||||
busy = true; box.classList.add('busy');
|
||||
body.author = authorName();
|
||||
U.apiSend(method, url(suffix), body).then(function () {
|
||||
busy = false; box.classList.remove('busy');
|
||||
if (okKey) U.toast(t(okKey));
|
||||
pollBadge();
|
||||
load(true);
|
||||
}, function (e) {
|
||||
busy = false; box.classList.remove('busy');
|
||||
fail(errNode, e && e.status === 409 ? 'inc.err.suppress' : errKey);
|
||||
});
|
||||
}
|
||||
|
||||
function techRow(dl, k, v) {
|
||||
if (v === undefined || v === null || v === '') return;
|
||||
dl.appendChild(el('dt', null, t(k)));
|
||||
dl.appendChild(el('dd', null, v));
|
||||
}
|
||||
function techPanel(x) {
|
||||
var dl = el('dl', { class: 'inc-dl' });
|
||||
var kind = String(x.kind || '');
|
||||
techRow(dl, 'inc.t.source', tr('inc.source.' + x.source, String(x.source || '')));
|
||||
techRow(dl, 'inc.t.kind', kind ? tr('eg.kind.' + kind, kind) : '');
|
||||
techRow(dl, 'inc.t.workload', x.workload ? el('span', { class: 'mono' }, String(x.workload)) : '');
|
||||
techRow(dl, 'inc.t.dst', x.dst ? (isIP(x.dst) ? el('a', { class: 'mono', href: U.href('ip', [String(x.dst)]) }, String(x.dst)) : el('span', { class: 'mono' }, String(x.dst))) : '');
|
||||
techRow(dl, 'inc.t.port', x.dport ? el('span', { class: 'mono' }, String(x.dport)) : '');
|
||||
techRow(dl, 'inc.t.proto', x.proto ? el('span', { class: 'mono' }, String(x.proto)) : '');
|
||||
techRow(dl, 'inc.t.host', x.host ? String(x.host) : '');
|
||||
techRow(dl, 'inc.t.first', x.first_seen ? U.fmt.date(x.first_seen) : '');
|
||||
techRow(dl, 'inc.t.last', x.last_seen ? U.fmt.date(x.last_seen) : '');
|
||||
techRow(dl, 'inc.t.count', x.count ? nf(x.count) : '');
|
||||
techRow(dl, 'inc.t.created', x.created_at ? U.fmt.date(x.created_at) : '');
|
||||
techRow(dl, 'inc.t.updated', x.updated_at ? U.fmt.date(x.updated_at) : '');
|
||||
techRow(dl, 'inc.t.key', x.key ? el('span', { class: 'mono inc-key' }, String(x.key)) : '');
|
||||
var p = U.ui.panel({ title: t('inc.tech'), cls: 'span-4' }, dl);
|
||||
return p;
|
||||
}
|
||||
|
||||
function histValue(field, v) {
|
||||
if (v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length)) return t('inc.h.empty');
|
||||
if (field === 'status') return tr('inc.status.' + v, String(v));
|
||||
if (field === 'severity') return tr('inc.sev.' + v, String(v));
|
||||
if (field === 'suppress') return t(v === true || v === 'true' ? 'inc.h.on' : 'inc.h.off');
|
||||
if (Array.isArray(v)) return v.join(', ');
|
||||
return String(v);
|
||||
}
|
||||
function histPanel(x) {
|
||||
var hist = Array.isArray(x.history) ? x.history.slice().reverse() : [];
|
||||
var p = U.ui.panel({ title: t('inc.history'), cls: 'span-4' });
|
||||
if (!hist.length) { p.body.appendChild(el('p', { class: 'inc-hint' }, t('inc.history.none'))); return p; }
|
||||
var ol = el('ol', { class: 'inc-tl' });
|
||||
hist.forEach(function (h) {
|
||||
var f = String(h.field || '');
|
||||
var fl = tr('inc.h.field.' + f, f);
|
||||
ol.appendChild(el('li', null,
|
||||
el('span', { class: 'inc-tl-when' }, U.fmt.date(h.at)),
|
||||
el('span', { class: 'inc-tl-what' }, t('inc.h.line', { who: String(h.author || '-'), field: fl })),
|
||||
el('span', { class: 'inc-tl-chg' }, el('span', { class: 'inc-from' }, histValue(f, h.from)), ' → ', el('strong', null, histValue(f, h.to)))));
|
||||
});
|
||||
p.body.appendChild(ol);
|
||||
return p;
|
||||
}
|
||||
|
||||
function commentsPanel(x) {
|
||||
var p = U.ui.panel({ title: t('inc.comments'), cls: 'span-8' });
|
||||
var list = Array.isArray(x.comments) ? x.comments : [];
|
||||
if (!list.length) p.body.appendChild(el('p', { class: 'inc-hint' }, t('inc.comments.none')));
|
||||
else {
|
||||
var ul = el('ul', { class: 'inc-comments' });
|
||||
list.forEach(function (c) {
|
||||
ul.appendChild(el('li', null,
|
||||
el('div', { class: 'inc-c-h' }, el('strong', null, String(c.author || '-')), el('span', { class: 'inc-hint' }, c.at ? U.fmt.date(c.at) : '')),
|
||||
el('p', { class: 'inc-text' }, String(c.text || ''))));
|
||||
});
|
||||
p.body.appendChild(ul);
|
||||
}
|
||||
var ta = el('textarea', { id: 'inc-comment', rows: '3', maxlength: '4000', placeholder: t('inc.comment.ph'), 'aria-label': t('inc.comment.ph') });
|
||||
var err = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
var add = el('button', { type: 'button', class: 'btn primary' }, t('inc.comment.add'));
|
||||
function submit() {
|
||||
var txt = ta.value.trim();
|
||||
if (!txt) { ta.focus(); return; }
|
||||
err.hidden = true;
|
||||
send('POST', '/comments', { text: txt }, err, 'inc.err.comment', 'inc.comment.added');
|
||||
}
|
||||
add.addEventListener('click', submit);
|
||||
ta.addEventListener('keydown', function (e) { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } });
|
||||
p.body.appendChild(el('div', { class: 'inc-newc' }, ta, err, el('div', { class: 'inc-btns' }, add)));
|
||||
return p;
|
||||
}
|
||||
|
||||
function formPanel(x) {
|
||||
var title = el('input', { type: 'text', id: 'inc-e-title', maxlength: '200', value: String(x.title || '') });
|
||||
var sev = selectOf('inc-e-sev', SEVS, function (s) { return t('inc.sev.' + s); }, sevOf(x.severity));
|
||||
var st = selectOf('inc-e-status', STATUSES, function (s) { return t('inc.status.' + s); }, statusOf(x.status));
|
||||
var asg = el('input', { type: 'text', id: 'inc-e-asg', maxlength: '64', value: String(x.assignee || '') });
|
||||
var tg = el('input', { type: 'text', id: 'inc-e-tags', maxlength: '300', value: (x.tags || []).join(', ') });
|
||||
var vd = el('textarea', { id: 'inc-e-verdict', rows: '4', maxlength: '4000' });
|
||||
vd.value = String(x.verdict || '');
|
||||
var sup = el('input', { type: 'checkbox', id: 'inc-e-sup' });
|
||||
sup.checked = !!x.suppress;
|
||||
var supHelp = el('span', { class: 'inc-hint', id: 'inc-e-sup-h' });
|
||||
sup.setAttribute('aria-describedby', 'inc-e-sup-h');
|
||||
var err = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
var save = el('button', { type: 'button', class: 'btn primary' }, t('inc.save'));
|
||||
|
||||
function syncSup() {
|
||||
var okSt = SUPPRESSIBLE.indexOf(st.value) >= 0;
|
||||
sup.disabled = !okSt;
|
||||
if (!okSt) sup.checked = false;
|
||||
supHelp.textContent = t('inc.f.suppress.help') + (okSt ? '' : ' ' + t('inc.f.suppress.off'));
|
||||
}
|
||||
function diff() {
|
||||
var d = {}, ttl = title.value.trim();
|
||||
if (ttl && ttl !== x.title) d.title = ttl;
|
||||
if (sev.value !== sevOf(x.severity)) d.severity = sev.value;
|
||||
if (st.value !== statusOf(x.status)) d.status = st.value;
|
||||
if (asg.value.trim() !== (x.assignee || '')) d.assignee = asg.value.trim();
|
||||
var tl = parseTags(tg.value);
|
||||
if (!sameList(tl, x.tags)) d.tags = tl;
|
||||
if (vd.value.trim() !== (x.verdict || '').trim()) d.verdict = vd.value.trim();
|
||||
if (sup.checked !== !!x.suppress) d.suppress = sup.checked;
|
||||
return d;
|
||||
}
|
||||
function sync() { syncSup(); save.disabled = busy || !Object.keys(diff()).length; }
|
||||
[title, sev, st, asg, tg, vd, sup].forEach(function (c) { c.addEventListener('input', sync); c.addEventListener('change', sync); });
|
||||
sync();
|
||||
save.addEventListener('click', function () {
|
||||
var d = diff();
|
||||
if (!Object.keys(d).length) return;
|
||||
err.hidden = true;
|
||||
send('PATCH', '', d, err, 'inc.err.save', 'inc.saved');
|
||||
});
|
||||
|
||||
function quick(label, status, tone) {
|
||||
var b = el('button', { type: 'button', class: 'btn inc-q-' + tone }, label);
|
||||
b.disabled = statusOf(x.status) === status;
|
||||
b.addEventListener('click', function () {
|
||||
var d = { status: status };
|
||||
if (x.suppress && SUPPRESSIBLE.indexOf(status) < 0) d.suppress = false;
|
||||
err.hidden = true;
|
||||
send('PATCH', '', d, err, 'inc.err.save', 'inc.saved');
|
||||
});
|
||||
return b;
|
||||
}
|
||||
var q = el('div', { class: 'inc-quick', role: 'group', 'aria-label': t('inc.quick') },
|
||||
quick(t('inc.quick.fp'), 'false_positive', 'fp'), quick(t('inc.quick.tp'), 'true_positive', 'tp'), quick(t('inc.quick.resolve'), 'resolved', 'ok'));
|
||||
|
||||
var supRow = el('div', { class: 'inc-field inc-sup' },
|
||||
el('div', { class: 'inc-check' }, sup, el('label', { for: 'inc-e-sup' }, t('inc.f.suppress'))), supHelp);
|
||||
var p = U.ui.panel({ title: t('inc.edit'), cls: 'span-8' },
|
||||
q,
|
||||
el('div', { class: 'inc-form' },
|
||||
field(t('inc.f.title'), title, null, 'inc-e-title'),
|
||||
el('div', { class: 'inc-two' }, field(t('inc.f.status'), st, null, 'inc-e-status'), field(t('inc.f.severity'), sev, null, 'inc-e-sev')),
|
||||
el('div', { class: 'inc-two' }, field(t('inc.f.assignee'), asg, null, 'inc-e-asg'), field(t('inc.f.tags'), tg, t('inc.f.tags.hint'), 'inc-e-tags')),
|
||||
field(t('inc.f.verdict'), vd, t('inc.f.verdict.hint'), 'inc-e-verdict'),
|
||||
supRow),
|
||||
err, el('div', { class: 'inc-btns' }, save));
|
||||
return p;
|
||||
}
|
||||
|
||||
function paint() {
|
||||
clear(box);
|
||||
var x = tk;
|
||||
var sev = sevOf(x.severity);
|
||||
var head = el('header', { class: 'inc-head inc-sev-' + sev },
|
||||
el('span', { class: 'inc-id mono' }, String(x.id)),
|
||||
sevBadge(x.severity), statusBadge(x.status),
|
||||
x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null,
|
||||
el('h2', { class: 'inc-h-title' }, String(x.title || x.id)),
|
||||
tags(x.tags));
|
||||
var grid = el('div', { class: 'grid-12 inc-grid' });
|
||||
grid.appendChild(formPanel(x));
|
||||
grid.appendChild(techPanel(x));
|
||||
if (x.detail) {
|
||||
var dp = U.ui.panel({ title: t('inc.f.detail'), cls: 'span-8' }, el('p', { class: 'inc-text mono' }, String(x.detail)));
|
||||
grid.appendChild(dp);
|
||||
grid.appendChild(histPanel(x));
|
||||
grid.appendChild(commentsPanel(x));
|
||||
} else {
|
||||
grid.appendChild(commentsPanel(x));
|
||||
grid.appendChild(histPanel(x));
|
||||
}
|
||||
box.appendChild(head);
|
||||
box.appendChild(grid);
|
||||
}
|
||||
function load(keepScroll) {
|
||||
var my = ++seq;
|
||||
var y = window.scrollY;
|
||||
U.api(url()).then(function (r) {
|
||||
if (!on || my !== seq) return;
|
||||
tk = r; paint();
|
||||
if (keepScroll) window.scrollTo(0, y);
|
||||
}, function (e) {
|
||||
if (!on || my !== seq) return;
|
||||
clear(box);
|
||||
if (e && e.status === 404) { box.appendChild(U.ui.empty(t('inc.notfound'), t('inc.notfound.sub'))); return; }
|
||||
var b = el('button', { type: 'button', class: 'btn' }, t('inc.retry'));
|
||||
b.addEventListener('click', function () { load(); });
|
||||
box.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('inc.list.err')), b));
|
||||
});
|
||||
}
|
||||
box.appendChild(el('div', { class: 'skeleton', style: { height: '10rem' } }));
|
||||
load();
|
||||
return { refresh: null, update: function () { load(true); }, destroy: function () { on = false; seq++; } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ page
|
||||
function render() {
|
||||
if (view) { view.destroy(); view = null; }
|
||||
clear(root);
|
||||
var seg = ctx && ctx.params && ctx.params.segments ? ctx.params.segments : [];
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '';
|
||||
view = id ? detailView(root, id) : listView(root);
|
||||
}
|
||||
|
||||
U.registerPage({
|
||||
id: 'incidents', group: 'investigate', titleKey: 'inc.title',
|
||||
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 5h16v11H9l-5 4z"/><path d="M12 8.5v3.5"/><path d="M12 14.2h.01"/></svg>',
|
||||
mount: function (node, cx) { root = el('div', { class: 'inc-page' }); node.appendChild(root); ctx = cx; render(); },
|
||||
update: function (cx) { ctx = cx; if (root) render(); },
|
||||
refresh: function () { if (view && view.refresh) view.refresh(); },
|
||||
unmount: function () { if (view) { view.destroy(); view = null; } if (root && root.parentNode) root.parentNode.removeChild(root); root = null; }
|
||||
});
|
||||
|
||||
// the rail counter works from any page
|
||||
pollBadge();
|
||||
setInterval(function () { if (!document.hidden) pollBadge(); }, 30000);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!boot()) {
|
||||
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
|
||||
}
|
||||
})();
|
||||
@@ -71,6 +71,10 @@
|
||||
{
|
||||
"name": "egress",
|
||||
"css": true
|
||||
},
|
||||
{
|
||||
"name": "incidents",
|
||||
"css": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -191,6 +191,10 @@ h1, h2, h3, p, dl, dd, ul { margin: 0; }
|
||||
.nav-item[aria-current="page"] { background: var(--rail-active); color: #fff; border-left-color: var(--accent); }
|
||||
.nav-ico { width: 20px; height: 20px; flex: none; display: inline-flex; }
|
||||
.nav-ico svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.nav-item, .tab { position: relative; }
|
||||
.nav-badge { margin-left: auto; min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--danger); color: var(--surface-base); font-size: .75rem; font-weight: 700; line-height: 20px; text-align: center; font-variant-numeric: tabular-nums; }
|
||||
.more-sheet .nav-badge { margin-left: auto; }
|
||||
.tab .nav-badge { position: absolute; top: 4px; left: calc(50% + 4px); min-width: 18px; line-height: 18px; padding: 0 5px; font-size: .6875rem; }
|
||||
.rail-foot { margin-top: auto; padding: var(--s-2); color: var(--rail-ink-muted); font-size: .8125rem; }
|
||||
.main { min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
@@ -385,6 +389,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
.rail { padding: var(--s-3) var(--s-2); align-items: center; }
|
||||
.brand-name, .nav-label, .rail-foot { display: none; }
|
||||
.nav-item { justify-content: center; padding: 8px; border-left: 0; width: 44px; }
|
||||
.nav-item .nav-badge { position: absolute; top: 2px; right: 0; min-width: 16px; padding: 0 4px; font-size: .625rem; line-height: 16px; }
|
||||
.nav-item[aria-current="page"] { box-shadow: inset 3px 0 0 var(--accent); }
|
||||
.grid.g3 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@@ -417,7 +422,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
}
|
||||
.tab { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: 56px; border: 0; background: none; color: var(--rail-ink); text-decoration: none; font-size: .75rem; border-radius: var(--radius-sm); cursor: pointer; padding: 4px 2px; }
|
||||
.tab .nav-ico svg { width: 22px; height: 22px; }
|
||||
.tab span:last-child { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab span:not(.nav-ico):not(.nav-badge) { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab[aria-current="page"], .tab[aria-expanded="true"] { background: var(--rail-active); color: #fff; }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
|
||||
.more-sheet:not([hidden]) { display: block; }
|
||||
|
||||
Reference in new issue
Block a user