A capped listing answered like it was the whole answer, and one said it was capped when it was not
?source= is refused by name now; a limit nobody meant still silently became a
different limit. Measured on the shipped image (openwaf:ci), 1103 sources
recorded:
GET /admin-api/observations?limit=100000 -> 200, 1000 rows, no total, no
truncation flag. 103 recorded sources were unreachable and the response
read like a complete answer.
GET /admin-api/observations?limit=0 and ?limit=-1 -> 200, one row each.
GET /admin-api/streaks?limit=1000 -> 200, 2 streaks, trackedSources 3,
X-Truncated: true. Nothing had been cut: the header compared the page
against the size of the streak map, and the map keeps a source whose
streak a clean answer ended while the listing leaves those out on purpose.
The block listing already carried X-Total-Count and X-Truncated, with a comment
saying that is what stops a page reading like a complete answer. The two
listings the console reads most had neither. Now every capped listing carries
both, takes an offset that reaches the rest, and refuses a limit outside its
range by name: "limit must be 1..1000; got 0". /streaks measures truncation
against standing streaks, reports standingStreaks next to trackedSources, and
pages.
The page says what it is showing. The console gate run printed "newest 25 of 42
recorded sources" and "Newest 25 of 274 alerts" — before this change both tables
rendered as if the page were the window, and the volume that survives compose
down is exactly where that matters.
Teeth, each reverted and counted, then restored: headers removed -> 2
integration failures; limit/offset clamped instead of refused -> 13; streak
header counted against the map again -> 1; standingTotal counted as the map size
-> 1 unit + 1 integration.
Gates on this tree: unit 128/128, integration 89/89, smoke passed 19 failed 0,
compose 43 passed 0 failed, console 42 assertions 0 failed.
This commit is contained in:
@@ -178,8 +178,25 @@ public sealed class StreakTracker
|
||||
/// threshold, and a list of zeroes is how you lose it.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LiveStreak> LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit)
|
||||
=> LiveStreaks(now, policy, limit, 0, out _);
|
||||
|
||||
/// <summary>
|
||||
/// The same listing, plus the number a caller needs to answer "is there
|
||||
/// more": how many streaks are standing in this process at all.
|
||||
///
|
||||
/// <c>TrackedCount</c> is not that number. The map keeps a source whose
|
||||
/// streak was ended by a clean answer — that is what <see cref="ResetIfTracked"/>
|
||||
/// does, and it is deliberate — while this listing leaves such a source out on
|
||||
/// purpose. Counting the map instead of the listing made the endpoint claim it
|
||||
/// had cut rows it had not: measured on the shipped image with two standing
|
||||
/// streaks and one reset source, <c>?limit=1000</c> returned 2 streaks, said
|
||||
/// <c>trackedSources: 3</c>, and answered <c>X-Truncated: true</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LiveStreak> LiveStreaks(
|
||||
DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal)
|
||||
{
|
||||
var take = Math.Max(1, limit);
|
||||
var skip = Math.Max(0, offset);
|
||||
lock (_gate)
|
||||
{
|
||||
EvictIdle(now, policy);
|
||||
@@ -191,10 +208,12 @@ public sealed class StreakTracker
|
||||
s.SourceKey, s.ConsecutiveRefusals, s.ConsecutiveServerErrors,
|
||||
s.LastStatusCode, s.LastPath, s.LastCountryCode, s.LastSeenAt));
|
||||
}
|
||||
standingTotal = list.Count;
|
||||
return list
|
||||
.OrderByDescending(x => x.ConsecutiveRefusals)
|
||||
.ThenByDescending(x => x.ConsecutiveServerErrors)
|
||||
.ThenByDescending(x => x.LastSeenAt)
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ internal static class AdminConsole
|
||||
<div class="scroll"><table id="allow"><thead><tr><th>match</th><th>note</th><th>expires</th><th></th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Sources the edge is watching</h2>
|
||||
<div id="obsnote" class="muted"></div>
|
||||
<div class="scroll"><table id="obs"><thead><tr><th>source</th><th class="num">consec.</th><th class="num">refusals</th><th>last status</th><th>path</th><th>geo</th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Streaks standing in this edge</h2>
|
||||
@@ -167,19 +168,28 @@ function row(cells) {
|
||||
async function load() {
|
||||
if (!token) { note('no token', true); return; }
|
||||
try {
|
||||
const [state, blocksRes, obs, streaks, countries, rules, allow, alerts, geo] = await Promise.all([
|
||||
const [state, blocksRes, obsRes, streaks, countries, rules, allow, alertsRes, geo] = await Promise.all([
|
||||
api('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
|
||||
api('/admin-api/observations?limit=25'), api('/admin-api/streaks'),
|
||||
apiRaw('/admin-api/observations?limit=25'), api('/admin-api/streaks'),
|
||||
api('/admin-api/countries/summary'), api('/admin-api/countries'),
|
||||
api('/admin-api/allow'), api('/admin-api/alerts?limit=25'),
|
||||
api('/admin-api/allow'), apiRaw('/admin-api/alerts?limit=25'),
|
||||
api('/admin-api/geo')
|
||||
]);
|
||||
const blocks = blocksRes.body;
|
||||
const obs = obsRes.body;
|
||||
const alerts = alertsRes.body;
|
||||
// The listing is capped server-side. Saying so is the difference between a
|
||||
// console and a misleading one: the delete beside this table is not capped.
|
||||
el('blocknote').textContent = blocksRes.truncated
|
||||
? 'showing the newest ' + blocks.length + ' of ' + blocksRes.total + ' — clearing by provenance removes all ' + blocksRes.total + ', not just this page'
|
||||
: blocksRes.total + (blocksRes.total === '1' ? ' entry' : ' entries');
|
||||
// The observation listing is capped too, and it is the table an operator
|
||||
// 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';
|
||||
const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed]));
|
||||
el('summary').innerHTML =
|
||||
'<span class="pill">mode ' + esc(state.mode) + '</span> ' +
|
||||
@@ -226,9 +236,10 @@ async function load() {
|
||||
])).join('') || row([{ v: 'nothing standing — every tracked source last saw a clean answer' }]);
|
||||
el('streaknote').textContent =
|
||||
streaks.scope === 'this-process'
|
||||
? 'this edge process only — ' + (streaks.streaks || []).length + ' of ' + streaks.trackedSources
|
||||
+ ' tracked sources have a streak standing; threshold ' + streaks.threshold
|
||||
+ ' within ' + streaks.windowMinutes + ' min; map capped at ' + streaks.maxTrackedSources
|
||||
? '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';
|
||||
// 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
|
||||
@@ -257,7 +268,8 @@ async function load() {
|
||||
{ v: (a.createdAt || '').replace('T', ' ').slice(0, 19) }
|
||||
])).join('') || row([{ v: 'nothing — no server-error streaks and no dry-run candidates' }]);
|
||||
el('alertnote').textContent = (alerts || []).length
|
||||
? 'server_error_streak = your upstream is failing, and the edge will not ban the visitor who saw it; candidate_ban = the rule would have banned, mode is Observe. Newest ' + (alerts || []).length + '.'
|
||||
? 'server_error_streak = your upstream is failing, and the edge will not ban the visitor who saw it; candidate_ban = the rule would have banned, mode is Observe. '
|
||||
+ (alertsRes.truncated ? 'Newest ' + alerts.length + ' of ' + alertsRes.total + ' alerts.' : 'All ' + alertsRes.total + ' alerts are listed.')
|
||||
: 'no alerts. server_error_streak means the upstream is failing; candidate_ban means a dry run would have banned.';
|
||||
|
||||
el('countries').tBodies[0].innerHTML = seen.map((c) => row([
|
||||
|
||||
@@ -72,9 +72,10 @@ internal static class AdminEndpoints
|
||||
group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryParseSource(source, out var wanted)) return BadSource(source);
|
||||
if (!TryPaging(limit, offset, BlockStore.ListDefaultLimit, BlockStore.ListMaxLimit,
|
||||
out var take, out var skip, out var pagingError))
|
||||
return Results.BadRequest(new { error = pagingError });
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var take = Math.Clamp(limit ?? BlockStore.ListDefaultLimit, 1, BlockStore.ListMaxLimit);
|
||||
var skip = Math.Max(0, offset ?? 0);
|
||||
var rows = await store.ListAsync(wanted, live ?? true, now, take, skip, ct);
|
||||
var total = await store.CountAsync(wanted, live ?? true, now, ct);
|
||||
// The listing is capped; the header is what stops a page of 500
|
||||
@@ -197,14 +198,25 @@ internal static class AdminEndpoints
|
||||
return Results.Ok(ToDto(policy.Current));
|
||||
});
|
||||
|
||||
group.MapGet("/observations", async (OpenWafDbContext db, int? limit, CancellationToken ct) =>
|
||||
Results.Ok(await db.Observations.AsNoTracking()
|
||||
group.MapGet("/observations", async (OpenWafDbContext db, int? limit, int? offset,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
|
||||
out var take, out var skip, out var pagingError))
|
||||
return Results.BadRequest(new { error = pagingError });
|
||||
var rows = await db.Observations.AsNoTracking()
|
||||
.OrderByDescending(o => o.LastSeenAt)
|
||||
.Take(Math.Clamp(limit ?? 100, 1, 1000))
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.Select(o => new ObservationDto(o.SourceKey, o.LastSeenAt, o.MaxConsecutiveRefusals,
|
||||
o.TotalRefusals, o.TotalServerErrorStreak, o.LastStatusCode, o.LastPath,
|
||||
o.LastCountryCode, o.LastCity))
|
||||
.ToListAsync(ct)));
|
||||
.ToListAsync(ct);
|
||||
var total = await db.Observations.CountAsync(ct);
|
||||
ctx.Response.Headers["X-Total-Count"] = total.ToString();
|
||||
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
|
||||
return Results.Ok(rows);
|
||||
});
|
||||
|
||||
// The streak map is per process, so the answer says which process it
|
||||
// came from instead of letting a console behind a load balancer imply
|
||||
@@ -212,30 +224,52 @@ 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) =>
|
||||
group.MapGet("/streaks", (StreakTracker tracker, EdgePolicyProvider policyProvider, HttpContext ctx, int? limit, int? offset) =>
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var policy = policyProvider.Current;
|
||||
var take = Math.Clamp(limit ?? 50, 1, 1000);
|
||||
var streaks = tracker.LiveStreaks(now, policy, take);
|
||||
ctx.Response.Headers["X-Truncated"] = (streaks.Count < tracker.TrackedCount).ToString().ToLowerInvariant();
|
||||
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);
|
||||
// "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
|
||||
// purpose, and counting them made this header claim a cut that never
|
||||
// happened — measured on the shipped image: 2 standing streaks, one
|
||||
// reset source, ?limit=1000, and X-Truncated: true.
|
||||
ctx.Response.Headers["X-Truncated"] = (skip + streaks.Count < standing).ToString().ToLowerInvariant();
|
||||
return Results.Ok(new
|
||||
{
|
||||
scope = "this-process",
|
||||
threshold = policy.StreakThreshold,
|
||||
windowMinutes = policy.StreakWindow.TotalMinutes,
|
||||
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.
|
||||
standingStreaks = standing,
|
||||
maxTrackedSources = policy.MaxTrackedSources,
|
||||
streaks = streaks.Select(st => new StreakDto(st.SourceKey, st.ConsecutiveRefusals,
|
||||
st.ConsecutiveServerErrors, st.LastStatusCode, st.LastPath, st.LastCountryCode, st.LastSeenAt))
|
||||
});
|
||||
});
|
||||
|
||||
group.MapGet("/alerts", async (OpenWafDbContext db, int? limit, CancellationToken ct) =>
|
||||
Results.Ok(await db.Alerts.AsNoTracking()
|
||||
group.MapGet("/alerts", async (OpenWafDbContext db, int? limit, int? offset,
|
||||
HttpContext ctx, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryPaging(limit, offset, ReadListDefaultLimit, ReadListMaxLimit,
|
||||
out var take, out var skip, out var pagingError))
|
||||
return Results.BadRequest(new { error = pagingError });
|
||||
var rows = await db.Alerts.AsNoTracking()
|
||||
.OrderByDescending(a => a.CreatedAt)
|
||||
.Take(Math.Clamp(limit ?? 100, 1, 1000))
|
||||
.ToListAsync(ct)));
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToListAsync(ct);
|
||||
var total = await db.Alerts.CountAsync(ct);
|
||||
ctx.Response.Headers["X-Total-Count"] = total.ToString();
|
||||
ctx.Response.Headers["X-Truncated"] = (skip + rows.Count < total).ToString().ToLowerInvariant();
|
||||
return Results.Ok(rows);
|
||||
});
|
||||
|
||||
group.MapGet("/countries", async (OpenWafDbContext db, CancellationToken ct) =>
|
||||
Results.Ok(await db.CountryRules.AsNoTracking().OrderBy(c => c.Code).ToListAsync(ct)));
|
||||
@@ -296,6 +330,40 @@ internal static class AdminEndpoints
|
||||
return app;
|
||||
}
|
||||
|
||||
private const int ReadListDefaultLimit = 100;
|
||||
private const int ReadListMaxLimit = 1000;
|
||||
private const int StreakListDefaultLimit = 50;
|
||||
private const int StreakListMaxLimit = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// A capped listing has two honest answers to a limit outside the cap:
|
||||
/// refuse it, or answer with what the response itself says is missing. The
|
||||
/// shipped image gave neither. Math.Clamp turned ?limit=0 and ?limit=-1 into
|
||||
/// one row and ?limit=100000 into 1000 rows of 1103 observations — every one
|
||||
/// a 200 that read like a complete answer, on the endpoint the console uses
|
||||
/// to decide which sources the edge has actually seen. So the range is
|
||||
/// refused by name, and every capped listing now carries X-Total-Count and
|
||||
/// X-Truncated plus an offset that reaches the rest.
|
||||
/// </summary>
|
||||
private static bool TryPaging(int? limit, int? offset, int defaultLimit, int maxLimit,
|
||||
out int take, out int skip, out string? error)
|
||||
{
|
||||
take = limit ?? defaultLimit;
|
||||
skip = offset ?? 0;
|
||||
error = null;
|
||||
if (limit is < 1 || limit > maxLimit)
|
||||
{
|
||||
error = $"limit must be 1..{maxLimit}; got {limit}";
|
||||
return false;
|
||||
}
|
||||
if (offset is < 0)
|
||||
{
|
||||
error = $"offset must be 0 or more; got {offset}";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one place that says no to a policy value, and says it with the key
|
||||
/// and the range so the operator can fix the call rather than guess which
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OpenWaf.Domain.Security;
|
||||
using OpenWaf.Infrastructure.Persistence;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// A capped listing is only honest if the response says it is capped. The block
|
||||
/// listing already carried X-Total-Count and X-Truncated; the two the console
|
||||
/// reads most did not, and every listing clamped its limit instead of refusing
|
||||
/// one nobody meant. All three were measured on the shipped image (openwaf:ci)
|
||||
/// with 1103 sources recorded:
|
||||
/// GET /admin-api/observations?limit=100000 → 200, 1000 rows, no total, no
|
||||
/// truncation flag — 103 recorded sources were unreachable, and the
|
||||
/// response read like the whole answer
|
||||
/// GET /admin-api/observations?limit=0 and ?limit=-1 → 200, one row
|
||||
/// GET /admin-api/streaks?limit=1000 → 200, 2 streaks, trackedSources 3,
|
||||
/// X-Truncated: true — nothing had been cut; the third source's streak had
|
||||
/// been ended by a clean answer and the listing leaves those out on purpose
|
||||
/// </summary>
|
||||
public sealed class ListingCompletenessTests
|
||||
{
|
||||
private static string? Header(HttpResponseMessage r, string name)
|
||||
=> r.Headers.TryGetValues(name, out var a) ? string.Join(",", a)
|
||||
: r.Content.Headers.TryGetValues(name, out var b) ? string.Join(",", b)
|
||||
: null;
|
||||
|
||||
private static async Task<(HttpStatusCode Status, JsonElement Body, string? Total, string? Truncated, string Text)> GetAsync(
|
||||
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();
|
||||
var body = response.StatusCode == HttpStatusCode.OK && text.Length > 0
|
||||
? JsonDocument.Parse(text).RootElement
|
||||
: default;
|
||||
return (response.StatusCode, body, Header(response, "X-Total-Count"), Header(response, "X-Truncated"), text);
|
||||
}
|
||||
|
||||
private static string[] KeysOf(JsonElement body) =>
|
||||
body.EnumerateArray().Select(e => e.GetProperty("sourceKey").GetString()!).ToArray();
|
||||
|
||||
[Fact]
|
||||
public async Task The_observation_listing_says_how_many_there_are_and_the_offset_reaches_the_rest()
|
||||
{
|
||||
await using var f = new EdgeFixture(threshold: 9);
|
||||
var sources = new[] { "203.0.113.201", "203.0.113.202", "203.0.113.203", "203.0.113.204", "203.0.113.205" };
|
||||
foreach (var ip in sources) await f.SendAsync(f.Client, "/nope", ip);
|
||||
await f.FlushObservationsAsync();
|
||||
|
||||
var first = await GetAsync(f, "/admin-api/observations?limit=2");
|
||||
Assert.Equal(HttpStatusCode.OK, first.Status);
|
||||
Assert.Equal("5", first.Total);
|
||||
Assert.Equal("true", first.Truncated);
|
||||
Assert.Equal(2, KeysOf(first.Body).Length);
|
||||
|
||||
var second = await GetAsync(f, "/admin-api/observations?limit=2&offset=2");
|
||||
Assert.Equal("5", second.Total);
|
||||
Assert.Equal("true", second.Truncated);
|
||||
Assert.Empty(KeysOf(first.Body).Intersect(KeysOf(second.Body)));
|
||||
|
||||
var whole = await GetAsync(f, "/admin-api/observations?limit=1000");
|
||||
Assert.Equal("false", whole.Truncated);
|
||||
Assert.Equal(5, KeysOf(whole.Body).Length);
|
||||
|
||||
// Paging is not decorative here: it is the only way to reach a row the
|
||||
// cap would otherwise hide, so every recorded source has to be reachable.
|
||||
var seen = new List<string>();
|
||||
for (var offset = 0; offset < 5; offset++)
|
||||
{
|
||||
var page = await GetAsync(f, $"/admin-api/observations?limit=1&offset={offset}");
|
||||
Assert.Equal("5", page.Total);
|
||||
seen.AddRange(KeysOf(page.Body));
|
||||
}
|
||||
Assert.Equal(sources.Length, seen.Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_alert_listing_says_the_same_about_itself()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
using (var scope = f.Factory.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
|
||||
for (var i = 1; i <= 4; i++)
|
||||
db.Alerts.Add(new EdgeAlert
|
||||
{
|
||||
SourceKey = $"203.0.113.21{i}", Kind = "server_error_streak", Count = i,
|
||||
CreatedAt = now.AddMinutes(-i), Detail = "seeded for the listing"
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var page = await GetAsync(f, "/admin-api/alerts?limit=3");
|
||||
Assert.Equal(HttpStatusCode.OK, page.Status);
|
||||
Assert.Equal("4", page.Total);
|
||||
Assert.Equal("true", page.Truncated);
|
||||
Assert.Equal(3, page.Body.GetArrayLength());
|
||||
|
||||
var rest = await GetAsync(f, "/admin-api/alerts?limit=3&offset=3");
|
||||
Assert.Equal("false", rest.Truncated);
|
||||
Assert.Equal(1, rest.Body.GetArrayLength());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/admin-api/observations?limit=0", "1..1000")]
|
||||
[InlineData("/admin-api/observations?limit=-1", "1..1000")]
|
||||
[InlineData("/admin-api/observations?limit=1001", "1..1000")]
|
||||
[InlineData("/admin-api/alerts?limit=0", "1..1000")]
|
||||
[InlineData("/admin-api/alerts?limit=1001", "1..1000")]
|
||||
[InlineData("/admin-api/blocks?limit=0", "1..2000")]
|
||||
[InlineData("/admin-api/blocks?limit=2001", "1..2000")]
|
||||
[InlineData("/admin-api/streaks?limit=0", "1..1000")]
|
||||
[InlineData("/admin-api/streaks?limit=1001", "1..1000")]
|
||||
public async Task A_limit_nobody_meant_is_refused_by_name_instead_of_becoming_one_row(string url, string range)
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
await f.SendAsync(f.Client, "/nope", "203.0.113.221");
|
||||
await f.FlushObservationsAsync();
|
||||
|
||||
var (status, _, _, _, text) = await GetAsync(f, url);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, status);
|
||||
Assert.Contains($"limit must be {range}", text);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/admin-api/observations?offset=-1")]
|
||||
[InlineData("/admin-api/alerts?offset=-1")]
|
||||
[InlineData("/admin-api/blocks?offset=-1")]
|
||||
[InlineData("/admin-api/streaks?offset=-1")]
|
||||
public async Task An_offset_before_the_first_row_is_refused(string url)
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
var (status, _, _, _, text) = await GetAsync(f, url);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, status);
|
||||
Assert.Contains("offset must be 0 or more", text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_streak_listing_is_not_called_truncated_by_sources_whose_streak_a_clean_answer_ended()
|
||||
{
|
||||
await using var f = new EdgeFixture(threshold: 5);
|
||||
f.Upstream.StatusFor = path => path == "/ok" ? 200 : 404;
|
||||
|
||||
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, "/probe", "203.0.113.231");
|
||||
await f.SendAsync(f.Client, "/probe", "203.0.113.232");
|
||||
await f.SendAsync(f.Client, "/probe", "203.0.113.233");
|
||||
await f.SendAsync(f.Client, "/ok", "203.0.113.233");
|
||||
|
||||
var all = await GetAsync(f, "/admin-api/streaks?limit=1000");
|
||||
Assert.Equal(HttpStatusCode.OK, all.Status);
|
||||
Assert.Equal("false", all.Truncated);
|
||||
Assert.Equal(3, all.Body.GetProperty("trackedSources").GetInt32());
|
||||
Assert.Equal(2, all.Body.GetProperty("standingStreaks").GetInt32());
|
||||
Assert.Equal(2, all.Body.GetProperty("streaks").GetArrayLength());
|
||||
|
||||
// And when something really is cut, the header says so and the offset
|
||||
// reaches the row that was cut.
|
||||
var one = await GetAsync(f, "/admin-api/streaks?limit=1");
|
||||
Assert.Equal("true", one.Truncated);
|
||||
Assert.Equal(1, one.Body.GetProperty("streaks").GetArrayLength());
|
||||
Assert.Equal("203.0.113.231", one.Body.GetProperty("streaks")[0].GetProperty("sourceKey").GetString());
|
||||
|
||||
var next = await GetAsync(f, "/admin-api/streaks?limit=1&offset=1");
|
||||
Assert.Equal("false", next.Truncated);
|
||||
Assert.Equal("203.0.113.232", next.Body.GetProperty("streaks")[0].GetProperty("sourceKey").GetString());
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,44 @@ public sealed class LiveStreaksTests
|
||||
Assert.Equal(1, t.Peek("1.1.1.1")!.MaxConsecutiveRefusals);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number a caller needs to answer "is there more" is the number of
|
||||
/// standing streaks, not the size of the map. The endpoint used to compare
|
||||
/// its page against TrackedCount and so reported a cut that had not
|
||||
/// happened: on the shipped image, two standing streaks plus one source whose
|
||||
/// streak a clean answer ended gave X-Truncated: true at limit=1000.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void The_standing_total_counts_what_the_listing_can_show_rather_than_every_record_the_map_holds()
|
||||
{
|
||||
var t = new StreakTracker();
|
||||
for (var i = 0; i < 3; i++) t.Observe("3.3.3.3", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i));
|
||||
t.Observe("2.2.2.2", 404, ResponseClass.Refusal, Policy, T0);
|
||||
t.Observe("1.1.1.1", 404, ResponseClass.Refusal, Policy, T0);
|
||||
t.Observe("1.1.1.1", 200, ResponseClass.Neutral, Policy, T0.AddSeconds(1));
|
||||
|
||||
Assert.Equal(3, t.TrackedCount);
|
||||
var page = t.LiveStreaks(T0.AddSeconds(2), Policy, 10, 0, out var standing);
|
||||
Assert.Equal(2, standing);
|
||||
Assert.Equal(2, page.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_offset_walks_the_standing_list_so_a_cap_hides_nothing_a_bigger_limit_could_reach()
|
||||
{
|
||||
var t = new StreakTracker();
|
||||
for (var i = 0; i < 3; i++) t.Observe("3.3.3.3", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i));
|
||||
for (var i = 0; i < 2; i++) t.Observe("2.2.2.2", 404, ResponseClass.Refusal, Policy, T0.AddSeconds(i));
|
||||
t.Observe("1.1.1.1", 404, ResponseClass.Refusal, Policy, T0);
|
||||
|
||||
var first = t.LiveStreaks(T0.AddSeconds(5), Policy, 2, 0, out var standing);
|
||||
var second = t.LiveStreaks(T0.AddSeconds(5), Policy, 2, 2, out _);
|
||||
|
||||
Assert.Equal(3, standing);
|
||||
Assert.Equal(new[] { "3.3.3.3", "2.2.2.2" }, first.Select(x => x.SourceKey).ToArray());
|
||||
Assert.Equal(new[] { "1.1.1.1" }, second.Select(x => x.SourceKey).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_server_error_streak_shows_up_because_it_is_the_other_way_a_source_escalates()
|
||||
{
|
||||
|
||||
@@ -94,6 +94,21 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||||
blockRows.some((r) => r[0] === SEED_BLOCK && /console gate/.test(r[2] || '')),
|
||||
JSON.stringify(blockRows.map((r) => [r[0], r[2]])));
|
||||
check('durable observations are listed', obsRows > 0, `${obsRows} rows`);
|
||||
// The observation listing is capped server-side, and until the API said how
|
||||
// many rows there are, a page of 25 and the whole window rendered the same
|
||||
// sentence. Measured on the shipped image: 1103 recorded sources, limit=1000,
|
||||
// 1000 rows back, no total and no flag.
|
||||
const obsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim();
|
||||
check('the observation table states how many sources were recorded, not only the rows it shows',
|
||||
/^\d+ sources? the edge has recorded$/.test(obsNote) || /^newest \d+ of \d+ recorded sources/.test(obsNote),
|
||||
obsNote);
|
||||
const streakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim();
|
||||
const standing = streakNote.match(/(\d+) of (\d+) standing streaks listed/);
|
||||
check('the streak note counts standing streaks, and its listed count matches the table',
|
||||
!!standing && Number(standing[1]) === streakRows.length && Number(standing[2]) >= Number(standing[1]),
|
||||
streakNote);
|
||||
check('the streak note keeps the map size separate, so tracked and standing are not confused',
|
||||
/\d+ sources tracked, map capped at \d+/.test(streakNote), streakNote);
|
||||
check('the per-country summary is listed', countryRows > 0, `${countryRows} rows`);
|
||||
// The country table is the page's answer to "where is this coming from", and a
|
||||
// column of numbers does not answer that. The bar has to be a real box with a
|
||||
|
||||
Reference in New Issue
Block a user