diff --git a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs index c1ddfd0..ac47491 100644 --- a/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs +++ b/dotnet/OpenWaf.Domain/Engine/StreakTracker.cs @@ -194,6 +194,20 @@ public sealed class StreakTracker /// public IReadOnlyList LiveStreaks( DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal) + => LiveStreaks(now, policy, limit, offset, null, out standingTotal); + + /// + /// The same listing with the operator's "tell me about this one address" + /// question, which the console now asks. Exact match on the source key, and + /// standingTotal counts the FILTERED set: the truncation flag is computed + /// against it, so a filtered page cannot claim a cut that did not happen and + /// a source with nothing standing cannot be reported as one of many. This is + /// the same rule the observation and alert listings learned in OPEN-33 — a + /// filter that narrows the rows without narrowing the total is a half-fix. + /// + public IReadOnlyList LiveStreaks( + DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey, + out int standingTotal) { var take = Math.Max(1, limit); var skip = Math.Max(0, offset); @@ -203,6 +217,8 @@ public sealed class StreakTracker var list = new List(); foreach (var s in _states.Values) { + if (sourceKey is not null && !string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal)) + continue; if (s.ConsecutiveRefusals == 0 && s.ConsecutiveServerErrors == 0) continue; list.Add(new LiveStreak( s.SourceKey, s.ConsecutiveRefusals, s.ConsecutiveServerErrors, diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs index 37e5a5b..08a061f 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs @@ -115,6 +115,11 @@ internal static class AdminConsole
matchnoteexpires

Sources the edge is watching

+
+ + + +
sourceconsec.refusalslast statuspathgeo
@@ -137,6 +142,11 @@ const el = (id) => document.getElementById(id); const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({'&':'&','<':'<','>':'>','"':'"'}[c])); let token = sessionStorage.getItem('openwaf.token') || ''; el('token').value = token; +// The source key the per-source tables are narrowed to. The empty string means +// "no filter at all": the parameter is left off rather than sent empty, because +// an empty value is a 400 since OPEN-23 and a console that sends one shows the +// operator an error where it meant to show a table. +let obsSource = ''; async function apiRaw(path, opts = {}) { const headers = Object.assign({}, opts.headers || {}); @@ -196,6 +206,27 @@ function note(text, bad) { // country bar) and nothing else. Every value that came from the API is text. const plural = (n, word) => (n === 1 ? word : word + 's'); +// One filter, shared by the observations table and the streaks table, so the +// two per-source listings always answer about the same address. The separator +// is decided per path, not assumed: the observations call already carries +// ?limit=25 and the streaks call carries nothing, and the first version of this +// appended "&source=" to a bare path — which is not a query parameter, it is a +// different route, and the edge answered 404. The page then printed "unknown +// scope" for the streak line, which is the honest thing to print about an answer +// that never arrived and the wrong thing to print about a filter. +const withSrc = (path) => path + (obsSource + ? (path.indexOf('?') === -1 ? '?' : '&') + 'source=' + encodeURIComponent(obsSource) + : ''); + +// Every source key printed on this page is a question the operator can ask +// back: "what else does the edge know about this address?" The key still goes +// through esc() on its way into the attribute, so the escaping invariant the +// console gate checks is unchanged by making the cell clickable. A row with no +// source at all — a durability alert — stays plain text: there is nothing to +// filter to. +const srcBtn = (k) => (!k ? '' : ''); + function row(cells) { return '' + cells.map((c) => '' + (c.h !== undefined ? c.h : esc(c.v)) + '').join('') + ''; @@ -206,7 +237,8 @@ async function load() { try { const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, alertsRes, geoRes] = await Promise.all([ apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'), - apiRaw('/admin-api/observations?limit=25'), apiRaw('/admin-api/streaks'), + apiRaw(withSrc('/admin-api/observations?limit=25')), + apiRaw(withSrc('/admin-api/streaks')), apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'), apiRaw('/admin-api/allow?live=false&limit=500'), apiRaw('/admin-api/alerts?limit=25'), apiRaw('/admin-api/geo') @@ -234,9 +266,19 @@ async function load() { // reads to decide which sources the edge has actually seen. Until the API // said how many there are, "newest 25" and "the whole window" looked the // same on this page. - el('obsnote').textContent = obsRes.truncated - ? 'newest ' + obs.length + ' of ' + obsRes.total + ' recorded sources — the rest are older and this table is not the whole window' - : obsRes.total + ' ' + plural(Number(obsRes.total), 'source') + ' the edge has recorded'; + // Under a filter the total is the FILTERED total — the API narrowed the + // count along with the rows — and a source with nothing recorded is named + // in words instead of drawn as an empty table. That is how an operator + // tells "this address was never seen" from "the page stopped working". + el('obsnote').textContent = obsSource + ? (Number(obsRes.total) === 0 + ? 'no recorded observations for ' + obsSource + : 'filtered to ' + obsSource + ': ' + (obsRes.truncated + ? 'newest ' + obs.length + ' of ' + obsRes.total + ' rows for this source — the rest are older' + : obsRes.total + ' ' + plural(Number(obsRes.total), 'row') + ' recorded for this source')) + : obsRes.truncated + ? 'newest ' + obs.length + ' of ' + obsRes.total + ' recorded sources — the rest are older and this table is not the whole window' + : obsRes.total + ' ' + plural(Number(obsRes.total), 'source') + ' the edge has recorded'; const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed])); // A failed write is not a stale read: the row never existed, and the // listing kept answering 200 with the count it already had. Measured on the @@ -297,7 +339,7 @@ async function load() { : 'geo database not loaded'); el('mode').value = state.mode; el('blocks').tBodies[0].innerHTML = (blocks || []).map((b) => row([ - { v: b.sourceKey }, { v: b.source }, { v: b.reason }, + { h: srcBtn(b.sourceKey) }, { v: b.source }, { v: b.reason }, { v: b.live ? (b.expiresAt || '').replace('T', ' ').slice(0, 19) : 'expired' }, { v: (b.lastStatusCode || '') + ' ' + (b.lastPath || ''), n: true }, { h: '' } @@ -322,22 +364,34 @@ async function load() { + (allowExpired ? ' · ' + allowExpired + ' EXPIRED: those rows no longer exempt anyone' : '') : 'nothing allowlisted'; el('obs').tBodies[0].innerHTML = (obs || []).map((o) => row([ - { v: o.sourceKey }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, + { h: srcBtn(o.sourceKey) }, { v: o.maxConsecutiveRefusals, n: true }, { v: o.totalRefusals, n: true }, { v: o.lastStatusCode }, { v: o.lastPath }, { v: [o.lastCountryCode, o.lastCity].filter(Boolean).join(' / ') } - ])).join('') || row([{ v: 'none' }]); + ])).join('') || row([{ v: obsSource ? 'nothing recorded for ' + obsSource : 'none' }]); el('streaks').tBodies[0].innerHTML = (streaks.streaks || []).map((st) => row([ - { v: st.sourceKey }, { v: st.consecutiveRefusals + ' / ' + streaks.threshold, n: true }, + { h: srcBtn(st.sourceKey) }, { v: st.consecutiveRefusals + ' / ' + streaks.threshold, n: true }, { v: st.consecutiveServerErrors, n: true }, { v: st.lastStatusCode }, { v: st.lastPath }, { v: st.lastCountryCode }, { v: (st.lastSeenAt || '').replace('T', ' ').slice(0, 19) } - ])).join('') || row([{ v: 'nothing standing — every tracked source last saw a clean answer' }]); + ])).join('') || row([{ v: obsSource + ? 'nothing standing for ' + obsSource : 'nothing standing — every tracked source last saw a clean answer' }]); + // "this edge process only" is the scope sentence OPEN-16 earned; the filter + // sentence is the one OPEN-36 adds. Under a filter standingStreaks is the + // FILTERED count while trackedSources stays the whole map, and that pair is + // the honest reading of "one of these many". el('streaknote').textContent = - streaks.scope === 'this-process' - ? 'this edge process only — ' + (streaks.streaks || []).length + ' of ' + streaks.standingStreaks - + ' standing streaks listed; threshold ' + streaks.threshold - + ' within ' + streaks.windowMinutes + ' min; ' + streaks.trackedSources - + ' sources tracked, map capped at ' + streaks.maxTrackedSources - : 'unknown scope'; + streaks.scope !== 'this-process' ? 'unknown scope' + : 'this edge process only — ' + + (obsSource + ? (Number(streaks.standingStreaks) === 0 + ? 'filtered to ' + obsSource + ': nothing standing for this source' + : 'filtered to ' + obsSource + ': ' + (streaks.streaks || []).length + ' of ' + + streaks.standingStreaks + ' standing streaks for this source listed') + : (streaks.streaks || []).length + ' of ' + streaks.standingStreaks + + ' standing streaks listed') + + '; threshold ' + streaks.threshold + + ' within ' + streaks.windowMinutes + ' min; ' + + (obsSource ? 'the unfiltered map holds ' : '') + streaks.trackedSources + + ' sources tracked, map capped at ' + streaks.maxTrackedSources; // The bar is a share of the busiest country, not of some absolute scale: // what an operator wants out of this table is "where is the traffic coming // from right now", and that is a comparison. Widths are percentages of the @@ -359,7 +413,7 @@ async function load() { el('alerts').tBodies[0].innerHTML = (alerts || []).map((a) => row([ { h: a.kind === 'server_error_streak' ? '' + esc(a.kind) + '' : esc(a.kind) }, - { v: a.sourceKey }, + { h: srcBtn(a.sourceKey) }, { v: a.count, n: true }, { v: (a.lastStatusCode || '') + ' ' + (a.lastPath || ''), n: true }, { v: (a.createdAt || '').replace('T', ' ').slice(0, 19) } @@ -470,6 +524,18 @@ document.addEventListener('click', async (e) => { } else if (b.dataset.act === 'countrydel') { const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' }); if (!failed(r)) done('country rule ' + b.dataset.k + ' removed'); + } else if (b.dataset.act === 'srcfilter') { + // A row button carries the key it was drawn from; the filter bar's button + // reads what the operator typed. Either way the box and the filter end up + // saying the same thing, so the page never narrows to a key it is not + // showing. An empty box is "everything", not an empty parameter. + obsSource = b.dataset.k !== undefined ? b.dataset.k : el('srcfilter').value.trim(); + el('srcfilter').value = obsSource; + done(obsSource ? 'filtered to ' + obsSource : 'showing every source'); + } else if (b.dataset.act === 'srcclear') { + obsSource = ''; + el('srcfilter').value = ''; + done('showing every source'); } load(); } catch (err) { /* note() already said why */ } @@ -477,6 +543,13 @@ document.addEventListener('click', async (e) => { }); el('refresh').onclick = () => { holdNote = false; load(); }; +el('srcfilter').onkeydown = (e) => { + if (e.key !== 'Enter') return; + obsSource = el('srcfilter').value.trim(); + el('srcfilter').value = obsSource; + holdNote = false; + load(); +}; el('setMode').onclick = async () => { // The mode select is the one control that decides whether this edge bans // anyone at all. It used to fire the PUT, ignore the answer and reload: a diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index e2868f8..6b779a0 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -319,15 +319,23 @@ internal static class AdminEndpoints // measured what that assumption costs: round-robin over two edges // multiplied the effective threshold, and four refusals split 2+2 at a // threshold of 3 produced no ban at all. - group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset) => + group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset, string? source) => { - if (!TryKnownQuery(ctx, out var unknown, "limit", "offset")) return Results.BadRequest(new { error = unknown }); + if (!TryKnownQuery(ctx, out var unknown, "limit", "offset", "source")) return Results.BadRequest(new { error = unknown }); var now = DateTimeOffset.UtcNow; var policy = policyProvider.Current; if (!TryPaging(limit, offset, StreakListDefaultLimit, StreakListMaxLimit, out var take, out var skip, out var pagingError)) return Results.BadRequest(new { error = pagingError }); - var streaks = tracker.LiveStreaks(now, policy, take, skip, out var standing); + // The same question the observation and alert listings answer, asked + // of the live map. An empty value is refused rather than read as + // "every source" — the OPEN-23 shape — and the answer names the + // filter it applied, because a page that shows one address and + // reports the whole map's counts is the lie this endpoint already + // fixed once for X-Truncated. + if (source is not null && string.IsNullOrWhiteSpace(source)) + return Results.BadRequest(new { error = "source must not be empty; omit the parameter to list every source" }); + var streaks = tracker.LiveStreaks(now, policy, take, skip, source, out var standing); // "Is there more" has to be measured against what is listable, not // against what the map happens to hold. The map keeps a source whose // streak a clean answer ended; the listing leaves those out on @@ -343,7 +351,11 @@ internal static class AdminEndpoints trackedSources = tracker.TrackedCount, // The two numbers side by side are the explanation: the map holds // this many sources, this many of them have something standing. + // With a filter, standingStreaks is the filtered count and + // trackedSources stays the map size — that difference is the + // honest reading of "one of these many". standingStreaks = standing, + sourceFilter = source, maxTrackedSources = policy.MaxTrackedSources, streaks = streaks.Select(st => new StreakDto(st.SourceKey, st.ConsecutiveRefusals, st.ConsecutiveServerErrors, st.LastStatusCode, st.LastPath, st.LastCountryCode, st.LastSeenAt)) diff --git a/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs b/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs index 07253a0..ec48159 100644 --- a/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/AdminStreaksTests.cs @@ -14,6 +14,7 @@ public sealed class AdminStreaksTests { private const string Building = "203.0.113.180"; private const string Recovered = "203.0.113.181"; + private const string Second = "203.0.113.182"; private static async Task GetAsync(EdgeFixture f, string path, string sourceIp) { @@ -83,4 +84,87 @@ public sealed class AdminStreaksTests using var proxied = await f.Client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, proxied.StatusCode); } + + // ── OPEN-36: the streak map learned the same filter the observation and + // alert listings learned in OPEN-33, for the same reason. Measured before + // the change: GET /admin-api/streaks?source=203.0.113.180 answered 200 with + // every standing source and standingStreaks counting all of them, because + // the endpoint had never heard of the parameter and Minimal APIs drop what a + // handler does not declare. + private static async Task<(HttpStatusCode Status, string Text, JsonElement Body)> StreaksAtAsync( + EdgeFixture f, string url) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + using var response = await f.Client.SendAsync(request); + var text = await response.Content.ReadAsStringAsync(); + return (response.StatusCode, text, response.StatusCode == HttpStatusCode.OK + ? JsonDocument.Parse(text).RootElement + : default); + } + + [Fact] + public async Task A_source_filter_narrows_the_streaks_and_the_standing_count_with_them() + { + await using var f = new EdgeFixture(threshold: 5); + f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404; + + for (var i = 0; i < 3; i++) await GetAsync(f, "/probe", Building); + for (var i = 0; i < 2; i++) await GetAsync(f, "/probe", Second); + await GetAsync(f, "/probe", Recovered); + await GetAsync(f, "/ok", Recovered); + + var (_, _, all) = await StreaksAtAsync(f, "/admin-api/streaks"); + Assert.Equal(2, all.GetProperty("standingStreaks").GetInt32()); + // With no filter the answer names no filter at all — the field is there + // and null, so a reader never has to guess whether an absent key means + // "unfiltered" or "this build forgot to say". + Assert.True(all.GetProperty("sourceFilter").ValueKind is JsonValueKind.Null); + + var (status, text, one) = await StreaksAtAsync(f, "/admin-api/streaks?source=" + Building); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal("this-process", one.GetProperty("scope").GetString()); + Assert.Contains(Building, text); + // The rows narrowed, so the count narrowed. A page showing one source + // and reporting the whole map's standing count is the same lie the + // X-Truncated fix removed one level up. + Assert.Equal(1, one.GetProperty("streaks").GetArrayLength()); + Assert.Equal(Building, one.GetProperty("streaks")[0].GetProperty("sourceKey").GetString()); + Assert.Equal(1, one.GetProperty("standingStreaks").GetInt32()); + // trackedSources stays the map size: "one of these many" is only honest + // if the many is still printed next to the one. + Assert.Equal(3, one.GetProperty("trackedSources").GetInt32()); + Assert.Equal(Building, one.GetProperty("sourceFilter").GetString()); + } + + [Fact] + public async Task A_source_with_nothing_standing_answers_an_empty_page_and_says_so_with_a_zero() + { + await using var f = new EdgeFixture(threshold: 5); + f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404; + + for (var i = 0; i < 3; i++) await GetAsync(f, "/probe", Building); + await GetAsync(f, "/probe", Recovered); + await GetAsync(f, "/ok", Recovered); + + var (_, _, one) = await StreaksAtAsync(f, "/admin-api/streaks?source=" + Recovered); + Assert.Equal(0, one.GetProperty("streaks").GetArrayLength()); + Assert.Equal(0, one.GetProperty("standingStreaks").GetInt32()); + // The map still holds the address — that is the difference between "this + // source was never seen" and "this source was seen and last saw a clean + // answer", and the console prints both numbers. + Assert.Equal(2, one.GetProperty("trackedSources").GetInt32()); + Assert.Equal(Recovered, one.GetProperty("sourceFilter").GetString()); + } + + [Fact] + public async Task An_empty_source_is_refused_rather_than_read_as_every_streak() + { + await using var f = new EdgeFixture(threshold: 5); + for (var i = 0; i < 3; i++) await GetAsync(f, "/probe", Building); + + var (status, text, _) = await StreaksAtAsync(f, "/admin-api/streaks?source="); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Contains("source must not be empty", text); + } } diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 5b2e04f..5d687ce 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -351,6 +351,30 @@ check 'and so is a near miss of the parameter that does work' 'yes' \ "$(admin "$EDGE/admin-api/observations?limit=1000&src=203.0.113.250" | grep -qi "unknown query parameter 'src'" && echo yes || echo no)" check 'the alert listing refuses it the same way' 'yes' \ "$(admin "$EDGE/admin-api/alerts?limit=1000&zzz=1" | grep -qi "unknown query parameter 'zzz'" && echo yes || echo no)" +# The live streak map is the other per-source listing the console shows, and it +# had the same hole: ?source= was a parameter it had never heard of, so it was +# dropped and the answer kept its shape. The source this scene just created has +# one standing refusal, so it is in the map — and the filtered answer has to +# count one standing streak while still naming the whole map size next to it. +check 'the streak map answers the same source filter, and only that source' '1' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | streaks_where "b['sourceKey']=='203.0.113.250'")" +check 'and it leaves every other standing source out' '0' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | streaks_where "b['sourceKey']!='203.0.113.250'")" +check 'its standing count is the FILTERED count while the map size stays the map size' 'yes' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000&source=203.0.113.250" | python3 -c "import json,sys +try: + d=json.load(sys.stdin) + print('yes' if d['standingStreaks']==1 and d['sourceFilter']=='203.0.113.250' + and d['trackedSources']>=2 and len(d['streaks'])==1 else 'no') +except Exception: + print('no')")" +check 'an unfiltered streak answer names no filter at all' 'yes' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000" | python3 -c "import json,sys +d=json.load(sys.stdin); print('yes' if d.get('sourceFilter') is None else 'no')")" +check 'an empty source is refused there too, not read as every source' 'yes' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000&source=" | grep -qi 'source must not be empty' && echo yes || echo no)" +check 'and a near miss on the streak endpoint is refused by name' 'yes' \ + "$(admin "$EDGE/admin-api/streaks?limit=1000&src=203.0.113.250" | grep -qi "unknown query parameter 'src'" && echo yes || echo no)" # The guard is only worth having if it never fires on a parameter the endpoint # really does honour — the console calls this one with live/source/limit every # page load, and a refusal there would be a worse bug than the one prevented. diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs index ae9e85f..32a308e 100644 --- a/scripts/console-check.cjs +++ b/scripts/console-check.cjs @@ -577,6 +577,126 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number); JSON.stringify(cleanPill)); } + // ── OPEN-36: one source key, every per-source table. The operator's question + // is "what else does the edge know about THIS address", and until now the + // console could only answer it by eye: the observations table showed the newest + // 25 of every source and the streaks table showed every standing source. The + // API half is proven in scripts/compose-smoke.sh; what is proven here is that + // the control exists, that a click on a key narrows BOTH tables to it, that + // the totals printed under them are the FILTERED totals, and that a source + // with nothing recorded is answered in words rather than with an empty box. + { + const srcCells = () => page.$$eval('#obs tbody tr', + (rows) => rows.map((tr) => tr.children[0].textContent)); + const streakCells = () => page.$$eval('#streaks tbody tr', + (rows) => rows.map((tr) => tr.children[0].textContent)); + const noteOf = async (sel) => (await page.textContent(sel)).replace(/\s+/g, ' ').trim(); + + const filterBox = await page.$('#srcfilter'); + const acts = await page.$$eval('div.bar button[data-act]', (b) => b.map((x) => x.dataset.act)); + check('the page offers a source filter and a way to clear it', + !!filterBox && acts.includes('srcfilter') && acts.includes('srcclear'), + JSON.stringify(acts)); + + // A key printed in one table is a question the operator can ask back without + // typing it. The key is read out of the streaks table instead of hard-coded + // to the seed: by the time the write-side scenes have run, the source seeded + // at the top of the run is legitimately out of the streak window, and an + // assertion that demanded it still be standing would be the gate disagreeing + // with the product rather than with the page. The click is on a standing + // streaks row; the observations table has to follow it, and both notes have + // to say which key they are answering about. + const rxEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const standingKey = await page.$$eval('#streaks tbody tr', (rows) => { + for (const tr of rows) { + const b = tr.children[0] && tr.children[0].querySelector('button[data-act="srcfilter"]'); + if (b) return b.textContent; + } + return ''; + }); + check('a standing source row offers its key as a filter control', + standingKey !== '', JSON.stringify(standingKey)); + await page.click(`#streaks tbody button[data-act="srcfilter"][data-k="${standingKey}"]`); + await page.waitForFunction((k) => new RegExp('^filtered to ' + k + ':') + .test(document.getElementById('obsnote').textContent.replace(/\s+/g, ' ').trim()), + rxEsc(standingKey), { timeout: 15000 }).catch(() => {}); + const filteredObs = await srcCells(); + const filteredStreaks = await streakCells(); + const filteredObsNote = await noteOf('#obsnote'); + const filteredStreakNote = await noteOf('#streaknote'); + const filterBoxValue = await page.inputValue('#srcfilter'); + check('clicking a source key narrows the observation table to that key alone', + filteredObs.length > 0 && filteredObs.every((c) => c === standingKey), + JSON.stringify(filteredObs)); + check('and the streaks table is narrowed to the same key', + filteredStreaks.length === 1 && filteredStreaks[0] === standingKey, + JSON.stringify(filteredStreaks)); + check('the observation line states the FILTERED total, not the whole window', + new RegExp('^filtered to ' + rxEsc(standingKey) + + ': (\\d+ rows? recorded for this source|newest \\d+ of \\d+ rows for this source)') + .test(filteredObsNote), filteredObsNote); + check('the streak line counts that source\'s standing streaks and keeps the map size beside it', + new RegExp('^this edge process only — filtered to ' + rxEsc(standingKey) + + ': 1 of 1 standing streaks for this source listed').test(filteredStreakNote) + && /the unfiltered map holds \d+ sources tracked/.test(filteredStreakNote), + filteredStreakNote); + check('the filter box shows the key the page is actually filtered to', + filterBoxValue === standingKey, JSON.stringify({ box: filterBoxValue, key: standingKey })); + + // A key nobody ever saw has to be answered in words. An empty table and a + // broken page look identical, and this is exactly the case where the page + // used to print "none" about a filter the operator had just typed. + const NO_MATCH = '192.0.2.77'; + await page.fill('#srcfilter', NO_MATCH); + await page.click('div.bar button[data-act="srcfilter"]'); + await page.waitForFunction((k) => document.getElementById('obsnote').textContent.includes(k), + NO_MATCH, { timeout: 15000 }).catch(() => {}); + const emptyObsNote = await noteOf('#obsnote'); + const emptyObsRow = await srcCells(); + const emptyStreakNote = await noteOf('#streaknote'); + check('a source with nothing recorded is named in words, with a total of zero', + emptyObsNote === 'no recorded observations for ' + NO_MATCH + && emptyObsRow.length === 1 && emptyObsRow[0] === 'nothing recorded for ' + NO_MATCH, + `${JSON.stringify(emptyObsNote)} row=${JSON.stringify(emptyObsRow)}`); + check('and the streak line says nothing is standing for that source', + /filtered to 192\.0\.2\.77: nothing standing for this source/.test(emptyStreakNote), + emptyStreakNote); + + // The filter value reaches the page the same way any wire value does — + // through esc() — and it is also free text a human typed. This is the + // markup-seed invariant above, proven for the filter echo instead of for a + // row cell. + const MARKUP_KEY = ''; + await page.fill('#srcfilter', MARKUP_KEY); + await page.click('div.bar button[data-act="srcfilter"]'); + await page.waitForFunction((k) => document.getElementById('obsnote').textContent.includes(k), + MARKUP_KEY, { timeout: 15000 }).catch(() => {}); + const markupInjected = await page.$$eval('#obs tbody, #streaks tbody, #alerts tbody', + (bodies) => bodies.reduce((n, b) => n + b.querySelectorAll('img,svg,script,iframe,object,embed').length, 0)); + const markupNote = await noteOf('#obsnote'); + const markupTitle = await page.title(); + check('a filter value containing markup is printed as text and creates no element', + markupInjected === 0 && markupTitle.indexOf('XSS3') === -1 + && markupNote === 'no recorded observations for ' + MARKUP_KEY, + `${markupInjected} injected elements, title ${JSON.stringify(markupTitle)}, note ${JSON.stringify(markupNote)}`); + + // And back out. Clearing has to restore the unfiltered totals, not leave a + // narrowed count wearing the unfiltered sentence. + await page.click('div.bar button[data-act="srcclear"]'); + await page.waitForFunction( + () => /^(\d+ sources? the edge has recorded|newest \d+ of \d+ recorded sources)/ + .test(document.getElementById('obsnote').textContent.replace(/\s+/g, ' ').trim()), + null, { timeout: 15000 }).catch(() => {}); + const clearedObsNote = await noteOf('#obsnote'); + const clearedStreakNote = await noteOf('#streaknote'); + const clearedObsCount = (await srcCells()).length; + const clearedBox = await page.inputValue('#srcfilter'); + check('showing every source restores the unfiltered tables and totals', + clearedObsCount > 1 && clearedBox === '' && !/filtered to/.test(clearedObsNote) + && !/filtered to/.test(clearedStreakNote) + && /\d+ of \d+ standing streaks listed/.test(clearedStreakNote), + `${JSON.stringify(clearedObsNote)} | ${JSON.stringify(clearedStreakNote)}`); + } // A phone in dark mode is the case an operator actually reaches the console // from — the address that got them blocked is the one they are typing about. // Both halves of this used to be broken and measured: the page overflowed a