perf(replay): threats-only by default, no duplicate first-page or summary fetch

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Sonnet 5.5 committed 2026-11-23 10:15:50 -03:00
1 parent 19bec553f4
commit 91cdb4acbf
12 files changed
+111 -23

No files matched your search

+8
View File
@@ -6,6 +6,14 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
### Changed
- Replay plays threats only by default. 96% of the events the page downloaded were `ok` (legitimate traffic, such as crawlers browsing a Git forge), so a 2000-event page covered about 44 minutes and 24 h took about 21 pages. The events API accepts a negated category list (`cat=!ok`, a leading `!` excludes), the Replay category filter has "Threats (default)" and "All, including legitimate traffic" (`cat=all` in the link), and the timeline strip and lead sentence count the same filter.
### Fixed
- Opening Replay no longer downloads the same first events page twice (the page was rebuilt when the period study arrived; loaded events are now annotated in place, and a campaign link or "Only incidents" still rebuild) and no longer requests the summary twice (it reuses the shell's request).
## [2.3.0] - 2026-11-23
### Added
+8
View File
@@ -6,6 +6,14 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
### Alterado
- O Replay toca só ameaças por padrão. 96% dos eventos que a página baixava eram `ok` (tráfego legítimo, como robôs navegando num servidor Git), então uma página de 2000 eventos cobria cerca de 44 minutos e 24 h levavam cerca de 21 páginas. A API de eventos aceita uma lista de categorias negada (`cat=!ok`, um `!` no início exclui), o filtro de categoria do Replay tem "Ameaças (padrão)" e "Tudo, inclusive tráfego legítimo" (`cat=all` no link), e a faixa da linha do tempo e a frase de abertura contam o mesmo filtro.
### Corrigido
- Abrir o Replay não baixa mais a mesma primeira página de eventos duas vezes (a página era refeita quando o estudo do período chegava; os eventos carregados agora são anotados no lugar, e um link de campanha ou "Só incidentes" ainda refazem) e não pede mais o resumo duas vezes (reaproveita a requisição do shell).
## [2.3.0] - 2026-11-23
### Adicionado
+1 -1
View File
@@ -327,7 +327,7 @@ The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cook
| `GET /api/health` | `{"status":"ok"}`, no authentication |
| `GET /login`, `POST /login`, `POST /logout` | session cookie |
| `GET /api/v1/summary` (also `own`: web requests of `--trusted` and `--ignore` origins, counted apart; `totals.trusted`, `totals.internal` and `totals.requests_all` = `requests` + both; `totals.counts.trusted` and `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions. `cat` takes a list of categories; a leading `!` negates it (`cat=!ok`, at most 100 characters) |
| `GET /api/v1/events/stream` | live stream over SSE (`?visits=1` adds anonymous visits) |
| `GET /api/v1/live/recent`, `/geo` | latest live events, geography |
| `GET /api/v1/metrics`, `/evolution`, `/concentration`, `/survival`, `/techniques`, `/sessions/funnel` | stable metrics and analytics |
+2 -2
View File
@@ -68,7 +68,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
<p align="center"><img src="img/campaigns-dark.png" width="900" alt="Page: Campaigns"><br><sub>Campaigns: coordinated groups of addresses (Gantt and similarity).</sub></p>
<p align="center"><img src="img/campaign-detail-dark.png" width="900" alt="Page: Campaign detail"><br><sub>Campaign detail: members, timeline and shared traits.</sub></p>
**Replay** (`#/replay`): a period played back on the map with the ordered event list and the incident timeline, from the event registry.
**Replay** (`#/replay`): a period played back on the map with the ordered event list and the incident timeline, from the event registry. It plays threats only by default (every category but `ok`, so crawlers browsing a public site do not fill the pages): the category filter also offers "All, including legitimate traffic" or a single category, and the choice is kept in the link (`cat=all`; threats is the absence of `cat`). The timeline strip and the lead sentence count the same filter. Opening the page costs one events request, one period request and one (shared) summary request.
<p align="center"><img src="img/replay-dark.png" width="900" alt="Replay page: a period replayed on the map with the ordered event list and the incident timeline"><br><sub>Replay: a period played back, with incidents on the timeline.</sub></p>
@@ -174,7 +174,7 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
| `GET /api/v1/traffic` | session or bearer | web analytics of legitimate traffic. Query: `range`, `domain` (`all` or one domain), `host`. Returns visitors, pages, requests, bots, bytes, status classes, `p50_ms`, `p95_ms`, a timeline, top pages, referrers, countries, cities, browsers, operating systems, devices and bot names |
| `GET /api/v1/geo` | session or `URUTAU_TOKEN` | attacker geography. Without `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (up to 250). With `cc=XX` (and optionally `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regions, 200 cities, 50 IPs). Query: `range`, `host`. Cached for 5 s |
| `GET /api/v1/live/recent` | session or `URUTAU_TOKEN` | `{"events":[...]}`: the latest malicious events of every probe, newest first, in the stream format. Query: `limit` (default 200, at most 500) |
| `GET /api/v1/events` | session or bearer | events of the registry, newest first. Query: `range` or `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events` | session or bearer | events of the registry, newest first. Query: `range` or `from`/`to`, `host`, `ip`, `cat` (a list; a leading `!` excludes instead, so `cat=!ok` is every threat), `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | session or bearer | sessions (bursts with a stage) of the period, optionally for one `ip` |
| `GET /api/v1/period` | session or bearer | the study of a period: sessions, campaigns, first-seen techniques, escalations, spikes, new vs returning, top targets, families, techniques, users and ASNs. Query: `range` or `from`/`to`, `host`, `gap` (seconds between sessions, 30 to 86400) |
| `GET /api/v1/period/events` | session or bearer | the events of a period in the stream format, for replay |
+1 -1
View File
@@ -327,7 +327,7 @@ As rotas de usuário em `/api/v1/*` exigem `URUTAU_TOKEN` (bearer) ou um cookie
| `GET /api/health` | `{"status":"ok"}`, sem autenticação |
| `GET /login`, `POST /login`, `POST /logout` | cookie de sessão |
| `GET /api/v1/summary` (também `own`: requisições web de origens `--trusted` e `--ignore`, contadas à parte; `totals.trusted`, `totals.internal` e `totals.requests_all` = `requests` + ambas; `totals.counts.trusted` e `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totais, web analytics, tabela de IPs, um endereço, bundle STIX 2.1 |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | estudo de um período, busca no registro de eventos (cursor), sessões |
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | estudo de um período, busca no registro de eventos (cursor), sessões. `cat` aceita uma lista de categorias; um `!` no início a nega (`cat=!ok`, até 100 caracteres) |
| `GET /api/v1/events/stream` | stream ao vivo por SSE (`?visits=1` inclui visitas anônimas) |
| `GET /api/v1/live/recent`, `/geo` | últimos eventos ao vivo, geografia |
| `GET /api/v1/metrics`, `/evolution`, `/concentration`, `/survival`, `/techniques`, `/sessions/funnel` | métricas estáveis e análises |
+2 -2
View File
@@ -68,7 +68,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
<p align="center"><img src="../img/campaigns-dark-pt.png" width="900" alt="Página: Campanhas"><br><sub>Campanhas: grupos coordenados de endereços (Gantt e similaridade).</sub></p>
<p align="center"><img src="../img/campaign-detail-dark-pt.png" width="900" alt="Página: Detalhe da campanha"><br><sub>Detalhe da campanha: membros, linha do tempo e traços em comum.</sub></p>
**Replay** (`#/replay`): um período reproduzido no mapa com a lista ordenada de eventos e a linha do tempo de incidentes, a partir do registro de eventos.
**Replay** (`#/replay`): um período reproduzido no mapa com a lista ordenada de eventos e a linha do tempo de incidentes, a partir do registro de eventos. Por padrão toca só ameaças (toda categoria menos `ok`, para que robôs navegando num site público não encham as páginas): o filtro de categoria também oferece "Tudo, inclusive tráfego legítimo" ou uma só categoria, e a escolha fica no link (`cat=all`; ameaças é a ausência de `cat`). A faixa da linha do tempo e a frase de abertura contam o mesmo filtro. Abrir a página custa uma requisição de eventos, uma de período e uma de resumo (compartilhada).
<p align="center"><img src="../img/replay-dark-pt.png" width="900" alt="Página Replay: um período reproduzido no mapa com a lista ordenada de eventos e a linha do tempo de incidentes"><br><sub>Replay: um período reproduzido, com incidentes na linha do tempo.</sub></p>
@@ -174,7 +174,7 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
| `GET /api/v1/traffic` | sessão ou bearer | web analytics do tráfego legítimo. Query: `range`, `domain` (`all` ou um domínio), `host`. Retorna visitantes, páginas, requisições, bots, bytes, classes de status, `p50_ms`, `p95_ms`, linha do tempo, top de páginas, referrers, países, cidades, navegadores, sistemas operacionais, dispositivos e nomes de bots |
| `GET /api/v1/geo` | sessão ou `URUTAU_TOKEN` | geografia dos atacantes. Sem `cc`: `{"countries":[{"cc","events","ips","hostile","suspicious","cats"}]}` (até 250). Com `cc=XX` (e opcionalmente `region`): `{"cc","events","ips","hostile","suspicious","cats","regions":[...],"cities":[{"name","region","lat","lon","events","ips"}],"top_ips":[...]}` (64 regiões, 200 cidades, 50 IPs). Query: `range`, `host`. Cache de 5 s |
| `GET /api/v1/live/recent` | sessão ou `URUTAU_TOKEN` | `{"events":[...]}`: os últimos eventos maliciosos de todas as sondas, do mais novo ao mais velho, no formato do stream. Query: `limit` (padrão 200, máximo 500) |
| `GET /api/v1/events` | sessão ou bearer | eventos do registro, do mais novo ao mais antigo. Query: `range` ou `from`/`to`, `host`, `ip`, `cat`, `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events` | sessão ou bearer | eventos do registro, do mais novo ao mais antigo. Query: `range` ou `from`/`to`, `host`, `ip`, `cat` (uma lista; um `!` no início exclui em vez de selecionar, então `cat=!ok` é toda ameaça), `fam`, `q`, `order`, `limit`, `cursor` |
| `GET /api/v1/events/sessions` | sessão ou bearer | sessões (rajadas com estágio) do período, opcionalmente de um `ip` |
| `GET /api/v1/period` | sessão ou bearer | o estudo de um período: sessões, campanhas, técnicas vistas pela primeira vez, escaladas, picos, novos vs recorrentes, principais alvos, famílias, técnicas, usuários e ASNs. Query: `range` ou `from`/`to`, `host`, `gap` (segundos entre sessões, 30 a 86400) |
| `GET /api/v1/period/events` | sessão ou bearer | os eventos de um período no formato do stream, para o replay |
+6 -1
View File
@@ -54,7 +54,12 @@ func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan
eq.IP = ip
}
if cats := q.Get("cat"); cats != "" {
for _, c := range strings.Split(cats, ",") {
if len(cats) > 100 {
badRequest(w, "invalid cat")
return eq, false
}
// a leading "!" excludes the listed categories instead of selecting them ("!ok" is every threat)
for _, c := range strings.Split(strings.TrimPrefix(cats, "!"), ",") {
if core.Category(c).Index() < 0 {
badRequest(w, "invalid cat")
return eq, false
+20 -1
View File
@@ -115,7 +115,26 @@ func TestEventsAPI(t *testing.T) {
if m = getJSON(t, h, "/api/v1/events?q=SQLMAP&host=oracle", auth); len(m["events"].([]any)) != 6 {
t.Fatalf("q filter: %v", len(m["events"].([]any)))
}
for _, bad := range []string{"limit=0", "limit=x", "order=up", "cat=nope", "ip=zzz", "cursor=!!", "host=" + strings.Repeat("a", 100)} {
// "!" excludes: "!ok" keeps every category but ok, and nothing else is dropped
all := getJSON(t, h, "/api/v1/events?limit=100", auth)["events"].([]any)
nOK, kept := 0, getJSON(t, h, "/api/v1/events?limit=100&cat=!ok", auth)["events"].([]any)
for _, e := range all {
if e.(map[string]any)["cat"] == "ok" {
nOK++
}
}
for _, e := range kept {
if e.(map[string]any)["cat"] == "ok" {
t.Fatal("cat=!ok returned an ok event")
}
}
if len(kept) != len(all)-nOK {
t.Fatalf("cat=!ok kept %d of %d (%d ok)", len(kept), len(all), nOK)
}
if n := len(getJSON(t, h, "/api/v1/events?limit=100&cat=!scanner,exploit", auth)["events"].([]any)); n == 0 || n >= len(all) {
t.Fatalf("cat=!scanner,exploit: %d of %d", n, len(all))
}
for _, bad := range []string{"limit=0", "limit=x", "order=up", "cat=nope", "cat=!nope", "cat=!ok,", "cat=!" + strings.Repeat("ok,", 40), "ip=zzz", "cursor=!!", "host=" + strings.Repeat("a", 100)} {
if w := do(h, "GET", "/api/v1/events?"+bad, cloneHdr(auth), nil); w.Code != 400 {
t.Errorf("%s: %d", bad, w.Code)
}
+1 -1
View File
@@ -2454,7 +2454,7 @@
}
window.Urutau = {
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP,
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, summary: getSummary, onEvent: onEvent, openIP: openIP,
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,
+31 -14
View File
@@ -11,6 +11,9 @@
var CAT_OK = {};
CATS.forEach(function (c) { CAT_OK[c] = 1; });
CAT_OK.ok = 1;
// category filter: '' = threats (everything but "ok", the default), 'all' = no filter, else one category
function catVal(c) { return c === 'all' || CAT_OK[c] ? c : ''; }
function catParam(c) { return c === '' ? '!ok' : c === 'all' ? '' : c; }
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
var RANK = { recon: 1, probe: 2, exploit: 3, access: 4, banned: 5 };
var WEIGHT = { notfound: 1, scanner: 3, bruteforce: 4, 'ssh-fail': 2, 'ssh-probe': 3, exploit: 15, 'ssh-ok': 30, ban: 0, ok: 0 };
@@ -57,7 +60,8 @@
'rp.restart': 'Restart',
'rp.follow': 'Follow cursor',
'rp.cat': 'Category',
'rp.cat.all': 'All categories',
'rp.cat.all': 'Threats (default)',
'rp.cat.every': 'All, including legitimate traffic',
'rp.fam': 'Family',
'rp.fam.all': 'All families',
'rp.q': 'IP or country',
@@ -153,7 +157,8 @@
'rp.restart': 'Reiniciar',
'rp.follow': 'Seguir o cursor',
'rp.cat': 'Categoria',
'rp.cat.all': 'Todas as categorias',
'rp.cat.all': 'Ameaças (padrão)',
'rp.cat.every': 'Tudo, inclusive tráfego legítimo',
'rp.fam': 'Família',
'rp.fam.all': 'Todas as famílias',
'rp.q': 'IP ou país',
@@ -348,7 +353,7 @@
from = r.from; to = r.to;
tooBig = to - from > MAX_SPAN + 3600;
var cat = qget(params, 'cat');
F.cat = CAT_OK[cat] ? cat : '';
F.cat = catVal(cat);
F.fam = str(qget(params, 'fam'), 40);
F.q = str(qget(params, 'ip'), 60);
campId = str(qget(params, 'campaign'), 80);
@@ -392,6 +397,7 @@
function normStage(s) { s = String(s || '').toLowerCase(); return s === 'ban' ? 'banned' : RANK[s] ? s : ''; }
function prepare(e) {
e.t = num(e.t);
delete e._st; // prepare() also re-annotates events already in the buffer
e.ip = str(e.ip, 64);
e.cat = CAT_OK[e.cat] ? e.cat : 'notfound';
e.status = num(e.status);
@@ -436,7 +442,7 @@
function evParams(extra) {
var o = { from: Math.floor(startFrom), to: Math.ceil(to), limit: PAGE, order: 'asc' };
if (F.host) o.host = F.host;
if (F.cat) o.cat = F.cat;
if (catParam(F.cat)) o.cat = catParam(F.cat);
if (F.fam) o.fam = F.fam;
if (F.q && !/^[A-Za-z]{2}$/.test(F.q) && !/^AS?\d+$/i.test(F.q)) o.ip = F.q;
if (extra) for (var k in extra) o[k] = extra[k];
@@ -516,7 +522,7 @@
if (tooBig) { periodLoading = false; period = null; buildDerived(); return; }
var p = { from: Math.floor(from), to: Math.ceil(to) };
if (F.host) p.host = F.host;
if (F.cat) p.cat = F.cat;
if (catParam(F.cat)) p.cat = catParam(F.cat);
if (F.fam) p.fam = F.fam;
if (F.q && ipLike(F.q)) p.ip = F.q;
U.api('/api/v1/period', p).then(function (d) {
@@ -531,15 +537,24 @@
// transitions come from the period: rebuild the buffer so rows pick them up
if (tooBig) return;
if (campId && campById[campId] && !routeT && !campStarted) { campStarted = true; clock = clamp(campById[campId].first, from, to); }
if (campId || Object.keys(ipChain).length) { var c = clock; resetBuffer(c); fetchMore(); }
// a campaign link jumps and filters by IP, "only incidents" and country/ASN filters depend on the
// chains: those need a fresh buffer. Otherwise annotate what is loaded in place (a page still in
// flight is prepared against the new chains when it arrives), without downloading it again.
if (campId || only || (F.q && !ipLike(F.q))) { var c = clock; resetBuffer(c); fetchMore(); return; }
if (!buf.length) return;
ipSt = {}; resetChains();
for (var i = 0; i < buf.length; i++) prepare(buf[i]);
listDirty = true; detailDirty = true; tlDirty = true; kick();
}
function loadSummary() {
// histogram (timeline) and server locations from the summary of the same window
var my = ++summarySeq; sumDone = false;
var p = { from: Math.floor(from), to: Math.ceil(to) };
if (F.host) p.host = F.host;
U.api('/api/v1/summary', p).then(function (d) {
// same request as the shell's, so its short-lived cache serves both
var req;
if (typeof U.summary === 'function') req = U.summary(ctx);
else { var p = { from: Math.floor(from), to: Math.ceil(to) }; if (F.host) p.host = F.host; req = U.api('/api/v1/summary', p); }
req.then(function (d) {
if (!alive || my !== summarySeq || !d) return;
(d.hosts || []).forEach(function (x) { if (x && x.location && typeof x.location.lat === 'number') { var nm = str(x.name, 80); dests[nm] = { host: nm, lat: x.location.lat, lon: x.location.lon, label: str(x.location.label || nm, 60) }; } });
pushDests();
@@ -597,14 +612,15 @@
detailDirty = true; tlDirty = true; clockDirty = true;
drawStrip(); fillFam(); kick();
}
// histogram of the period: the summary timeline (all categories but plain "ok"),
// histogram of the period: the summary timeline (filtered like the events),
// else the sessions spread over their span
function buildBins() {
var span = Math.max(1, to - from), i, k;
var tl = tlData;
if (tl && tl.series && num(tl.step) > 0) {
binStep = num(tl.step); binStart = ts(tl.start);
var n0 = 0, cats = Object.keys(tl.series).filter(function (c) { return c !== 'ok'; });
// the strip counts what the filter lets through: threats (all but "ok"), everything, or one category
var n0 = 0, cats = Object.keys(tl.series).filter(function (c) { return F.cat === '' ? c !== 'ok' : F.cat === 'all' || c === F.cat; });
cats.forEach(function (c) { n0 = Math.max(n0, tl.series[c].length); });
bins = new Array(n0);
for (i = 0; i < n0; i++) { var v = 0; for (k = 0; k < cats.length; k++) v += num(tl.series[cats[k]][i]); bins[i] = v; }
@@ -735,7 +751,7 @@
hashAt = performance.now();
var x = { t: Math.floor(clock), speed: speed };
if (F.q) x.ip = F.q;
if (F.cat) x.cat = F.cat;
if (F.cat) x.cat = F.cat; // default (threats) is the absence of cat
if (F.fam) x.fam = F.fam;
if (campId) x.campaign = campId;
if (compress) x.compress = '1';
@@ -776,7 +792,8 @@
var fb = h('div', 'rp-filters');
ui.cat = h('select', 'rp-sel'); ui.cat.setAttribute('aria-label', t('rp.cat'));
ui.cat.appendChild(opt('', t('rp.cat.all')));
CATS.forEach(function (c) { ui.cat.appendChild(opt(c, t('cat.' + c))); });
ui.cat.appendChild(opt('all', t('rp.cat.every')));
['ok'].concat(CATS).forEach(function (c) { ui.cat.appendChild(opt(c, t('cat.' + c))); });
ui.cat.value = F.cat;
ui.cat.addEventListener('change', function () { F.cat = ui.cat.value; refilter(); });
ui.fam = h('select', 'rp-sel'); ui.fam.setAttribute('aria-label', t('rp.fam'));
@@ -1390,7 +1407,7 @@
var filtersLink = (linkT || q2.camp !== campId) && (q2.cat !== F.cat || q2.fam !== F.fam || q2.q !== F.q || q2.camp !== campId);
if (rangeChanged || hostNew !== F.host || filtersLink) {
from = f2; to = t2; tooBig = to - from > MAX_SPAN + 3600; F.host = hostNew;
if (filtersLink || rangeChanged) { F.cat = CAT_OK[q2.cat] ? q2.cat : ''; F.fam = q2.fam; F.q = q2.q; campId = q2.camp; campStarted = false; campIps = null; ui.cat.value = F.cat; ui.q.value = F.q; }
if (filtersLink || rangeChanged) { F.cat = catVal(q2.cat); F.fam = q2.fam; F.q = q2.q; campId = q2.camp; campStarted = false; campIps = null; ui.cat.value = F.cat; ui.q.value = F.q; }
clock = linkT && linkT >= from && linkT <= to ? linkT : (rangeChanged ? from : clamp(clock, from, to));
playing = false; ended = false; syncPlay();
tlData = null; paintChips(); loadPeriod(); loadSummary(); resetBuffer(clock); if (!tooBig) fetchMore(); kick();
+12
View File
@@ -71,10 +71,22 @@ type EventsPage struct {
Enabled bool `json:"enabled"`
}
// catSet turns a comma list into a set. A leading "!" negates it: the set is
// then every known category except those listed (for example "!ok").
func catSet(list string) map[string]bool {
if list == "" {
return nil
}
if rest, neg := strings.CutPrefix(list, "!"); neg {
skip := catSet(rest)
m := map[string]bool{}
for _, c := range core.Categories {
if !skip[string(c)] {
m[string(c)] = true
}
}
return m
}
m := map[string]bool{}
start := 0
for i := 0; i <= len(list); i++ {
+19
View File
@@ -0,0 +1,19 @@
package store
import "testing"
func TestCatSet(t *testing.T) {
if catSet("") != nil {
t.Fatal("empty list must mean no filter")
}
if m := catSet("exploit,ban"); len(m) != 2 || !m["exploit"] || !m["ban"] {
t.Fatalf("plain list: %v", m)
}
m := catSet("!ok")
if m["ok"] || len(m) != 8 || !m["notfound"] || !m["scanner"] || !m["exploit"] || !m["bruteforce"] || !m["ssh-fail"] || !m["ssh-probe"] || !m["ssh-ok"] || !m["ban"] {
t.Fatalf("!ok must keep every other category: %v", m)
}
if m := catSet("!ok,notfound"); m["ok"] || m["notfound"] || len(m) != 7 {
t.Fatalf("!ok,notfound: %v", m)
}
}