one address in, and the edge answers everything it knows about it

An operator investigating one source had to open six admin calls — blocks,
allow, streaks, observations, alerts, the dry run — and hold the join in their
head. The join is where the wrong answers are: a v6 address looked up in full
when the ban is filed on the /64, a CIDR ban looked up by equality that never
finds it, an exemption that expired last week read as a live one, a streak
counted in one process read as the deployment's.

GET /admin-api/source?ip=<address>[&path=<path>] answers it in one call, by
asking the same objects the request path asks rather than a second copy of
their logic. Three rulings hold it together:

  * Containment, not equality. operatorBlock carries cameFromRange and the
    match that covered the address, through the same NetworkBanIndex the wire
    matches with (longest prefix first) and NetworkMatch for the allowlist.
    There is no second matcher in this build to drift.
  * The key, not the address. sourceKey and the prefix lengths that produced
    it travel in the answer: bans, streaks and budgets are filed under the key,
    the allowlist and the range bans are matched against the address, and the
    answer separates them.
  * `none` and "not visible here" are different words. A live engine ban under
    Observe mode reports applies: false with a verdict of none; an expired row
    reports live: false rather than null, because "this address used to be
    exempt" is a fact an operator acts on.

Nothing is written and nothing is spent — the dry run's rule applied to the
whole dossier. RateRuleTracker.WindowsFor is a new read that lists every path
budget a source is already inside without being handed a path, so the dossier
does not have to guess from a path it was not given, and N dossiers leave every
counter where they found it. ip is required and must be a full address: a typo
is a 400 naming the value, never a none. The read-only token may ask it.

What the run caught, on this tree: the console scene waited for "an answer is
in the box", which the previous answer still sitting there satisfies — three
assertions read the address asked one click earlier. The scene now empties the
box and waits for the address it asked by name, and matches a range row by the
key its delete button holds rather than by a cell that prints a `range` badge.

build 0 warnings / 0 errors, unit 374/374, integration 356/356 in 39 s,
console 126 assertions / 0 failed, smoke passed 192 / failed 0, compose 311
passed / 0 failed against the built image at 262 MB.

Refs OPEN-70.
This commit is contained in:
Pavlo Ratushnyi
2026-10-05 09:43:39 +02:00
parent 6a65cbf344
commit bcfc83db40
9 changed files with 1178 additions and 7 deletions
+96 -6
View File
@@ -419,6 +419,11 @@ GET /admin-api/state snapshot age, tracked sources, counts, push
GET /admin-api/decide?ip=&path=&country= what the edge WOULD answer that request,
which pillar said so, and what the volume
counters say about that source right now
GET /admin-api/source?ip=&path= everything this edge knows about one address:
the exemption, the operator's block (its own
or a range that covers it), the engine's ban,
the standing streak, the budgets counting it,
its alerts and the netblocks that would cover it
```
`?source=` on `/admin-api/blocks` is a provenance filter, and it used to accept
@@ -880,6 +885,81 @@ guard every admin endpoint runs), and an `ip` that is not a full address is a 40
naming the value. `IPAddress.TryParse` alone would accept `203.0.113` as
`203.0.113.0`, which is exactly the typo that would otherwise be answered `pass`.
### One address, one answer
`GET /admin-api/source?ip=<address>[&path=<path>]` answers what this edge knows
about one source in one call. Every other surface here is a table with a filter
on it, so investigating one address meant opening six — blocks, allow, streaks,
observations, alerts, the dry run — and holding the join in one's head. The join
is where the mistakes are, and each of them is a wrong answer about a real
visitor:
* a v6 address looked up in its full form, when the ban is filed on the `/64` the
key rule groups it into — the lookup answers "nothing known";
* a CIDR ban looked up by equality, which never finds it, because a range is a
containment claim and not a key;
* an exemption that expired last week read as a live one, or as absent;
* a streak counted in one process read as the deployment's.
So the dossier asks the same objects the request path asks and never a second
copy of their logic: containment through `NetworkMatch` and `NetworkBanIndex`,
the identity through `SourceKey`, the verdict through `DecisionEngine`.
```
GET /admin-api/source?ip=203.0.113.21
{ "ip": "203.0.113.21", "sourceKey": "203.0.113.21",
"keyRule": { "ipv4PrefixLength": 32, "ipv6PrefixLength": 64 },
"verdict": "block_operator",
"answer": "the operator's range ban 203.0.113.16/28 covers this address and never expires",
"geo": { "country": "NL", "source": "geo-database", "rule": null, "mode": "DenyList", "wouldDeny": false },
"allow": null,
"operatorBlock": { "sourceKey": "203.0.113.21", "cameFromRange": true,
"match": "203.0.113.16/28", "reason": "netblock scanning",
"expiresAt": null, "live": true, "scope": "database" },
"engineBan": null,
"streak": { "scope": "this-process", "consecutiveRefusals": 2, "threshold": 10,
"maxConsecutiveEver": 7, "totalRefusalsEver": 41, "durableScope": "database" },
"volume": { "mode": "Enforce", "scope": "this-process",
"edgeBudget": { "count": 6, "limitPerWindow": 100, "secondsLeft": 41, "overBudget": false },
"pathBudgets": [ { "id": 3, "pattern": "/login*", "limitPerWindow": 5,
"count": 4, "overBudget": false, "secondsLeft": 12 } ] },
"alerts": [ … ], "netblockOffers": [ { "match": "203.0.113.16/28", "bans": 7 } ],
"wouldAnswer": null,
"scope": { "database": [ "allow", "operatorBlock", "engineBan", "alerts", "observations", "netblockOffers" ],
"thisProcess": [ "streak (unless sharedStreaks)", "volume counters" ] } }
```
Three rulings hold it together.
**Containment, not equality.** `cameFromRange: true` and the `match` that covered
the address are reported, because the address itself is not on the operator's
list and a listing that only shows rows keyed on it would say so. The same
`NetworkBanIndex` the wire matches with answers the question, longest prefix
first, so the most specific claim about that address is the one that speaks.
**The key, not the address.** `sourceKey` and the prefix lengths that produced it
travel in the answer, so a v6 `sourceKey` is not mistaken for a typo. Bans,
streaks and budgets are filed under the key; the allowlist and the range bans are
matched against the address itself — which is why the answer separates them.
**`none` and "not visible here" are different words.** A live engine ban under
`Observe` mode is reported with `applies: false` and a verdict of `none`, because
the ban is real and enforces nothing. An expired row is reported with
`live: false` rather than as absent: "this address used to be exempt" is a fact
an operator acts on, and `null` would say it never was.
With `path=` the answer carries `wouldAnswer`, the dry run's verdict for that
named request, so the parts and the verdict cannot disagree. Without it,
`answerScope` names the two pillars that need a path instead of leaving them
unmentioned.
Nothing is written and nothing is spent — the dry run's rule applied to the whole
dossier. `pathBudgets` comes from a new `RateRuleTracker.WindowsFor` read, so the
budgets a source is already inside are listed without asking for a path, and N
dossiers leave every counter where it was. `ip` is required and must be a full
address: a typo is a 400 naming the value, never a `none`. The read-only token
can ask it.
### The numbers leave the edge in Prometheus format
`GET /metrics` answers the counters `/admin-api/state` shows a human, in the
@@ -1192,7 +1272,15 @@ operator who wrote no budgets, which is the difference between a migration to
apply and a decision not to make. The page also asks the dry run
directly (OPEN-69): an address and a path, and the answer prints the verdict, the
path rule that spoke if one did, the edge-wide window with the seconds left in it,
and one line per path budget whose pattern matches the asked path. The volume line
and one line per path budget whose pattern matches the asked path.
Beside it sits the dossier (OPEN-70): one address in, and the page prints the key
that address is filed under, the verdict, the exemption or block behind it —
naming the range when the row is a range and not the address — the engine's ban
and whether this mode enforces it, the streak standing in this edge against the
threshold with the worst run the database remembers, the path budgets already
counting it, and its alerts. A read like the dry run above it, and the gate
asserts that asking three of them leaves the operator's table holding exactly the
two rows the page wrote. The volume line
is the part that makes the button safe to press on a live site — it is read off the
counters, and the gate asserts that asking leaves those counters where they were. The line under it
says which of the two answers an empty table is — "off, nothing is being
@@ -1390,11 +1478,13 @@ have not, so the two sets of numbers are labelled separately rather than merged
into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable
alert-push queue, the config transfer, the second token, the startup refusals, the change
log and that log on the console, the operator's ranges, the netblock watch and
the per-path request budgets and the volume answer of the dry run:
build 0 warnings / 0 errors, unit **371/371**, integration **345/345 in 43 s**,
console **122 assertions, 0 failed**, smoke **passed 182, failed 0**, and compose **304 passed,
0 failed** against the built image at 262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being
started from the repository root, where there is no `appsettings.json`, so it
the per-path request budgets, the volume answer of the dry run and one address
answered in one call:
build 0 warnings / 0 errors, unit **374/374**, integration **356/356 in 39 s**,
console **126 assertions, 0 failed**, smoke **passed 192, failed 0**, and compose **311 passed,
0 failed** against the built image at 262 MB, 0 containers left behind. The console run is the one that earned its keep: the dossier scene waited for "an answer is in the box", which the previous answer still sitting there satisfies, so every assertion after the first read the address asked one click earlier — three failures that named it exactly, and a scene that now empties the box and waits for the address it asked by name. The smoke story from the
previous cycle is kept here because the numbers are read next to it: the edge used
to be started from the repository root, where there is no `appsettings.json`, so it
loaded no `ReverseProxy` section, logged "Request reached the end of the
middleware pipeline without being handled by application code" for every request,
and answered 404 for a path the upstream was serving with 200 — the gate had been
@@ -133,6 +133,39 @@ public sealed class RateRuleTracker
}
}
/// <summary>Every rule this source currently has a running window on, without
/// moving a single counter. The source dossier (OPEN-70) needs it because it
/// answers "what does this edge know about this address" without being handed
/// a path: <see cref="Peek"/> is aimed at one rule and the preview's path
/// matcher is aimed at one path, and a dossier that had neither would have to
/// say "no path budgets" for a source that is three requests from a 429.
///
/// Live windows only, for the same reason the preview lists only live ones: a
/// window that has already run out restarts at zero, and "2 of 20" read off a
/// dead window is a different claim from "2 of 20". The rule's limit is not
/// here — the caller holds the rule and its own limit, and a limit copied into
/// this row is a second number that can disagree with the first.</summary>
public IReadOnlyList<RuleWindowObservation> WindowsFor(string sourceKey, DateTimeOffset now)
{
if (string.IsNullOrEmpty(sourceKey)) return [];
lock (_gate)
{
List<RuleWindowObservation>? rows = null;
foreach (var s in _states.Values)
{
if (!string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal)) continue;
var end = s.WindowStart + s.WindowLength;
if (now >= end) continue;
rows ??= [];
rows.Add(new RuleWindowObservation(
s.Rule, s.Count, s.WindowStart, end, (int)s.WindowLength.TotalSeconds));
}
if (rows is null) return [];
rows.Sort((a, b) => a.RuleId.CompareTo(b.RuleId));
return rows;
}
}
/// <summary>How many sources this rule is holding a window for, live or not —
/// the number that says whether the rule is counting anything at all.</summary>
public int TrackedCount(long ruleId)
@@ -234,3 +267,12 @@ public sealed record RuleRateObservation(
DateTimeOffset WindowStart,
DateTimeOffset WindowEnd,
bool BreachStarted);
/// <summary>One running window this source holds on one rule, as counted by this
/// process. No limit and no over-budget flag: the caller has the rule.</summary>
public sealed record RuleWindowObservation(
long RuleId,
int Count,
DateTimeOffset WindowStart,
DateTimeOffset WindowEnd,
int WindowSeconds);
+74
View File
@@ -154,6 +154,13 @@ internal static class AdminConsole
</div>
<div id="askanswer" class="muted"></div>
<h2>One address, one answer</h2>
<div class="bar">
<input id="dossierIp" placeholder="address" autocomplete="off" size="18">
<button id="askSource">what does this edge know about it?</button>
</div>
<div id="dossieranswer" class="muted"></div>
<h2>Sources the edge is watching</h2>
<div class="bar">
<input id="srcfilter" placeholder="filter observations and streaks by source key" autocomplete="off" size="28">
@@ -852,6 +859,73 @@ el('askDecide').onclick = async () => {
}
};
el('askSource').onclick = async () => {
// The dossier (OPEN-70). One address in, everything this edge knows about it
// out: the exemption that covers it, the operator's block on it or on a network
// containing it, the engine's own ban, the streak standing in this process, the
// budgets already counting it, its alerts, and the netblocks offered that would
// cover it. A read, like the dry run above it: nothing is written and no
// counter moves, so it is safe to press while the site is live.
const ip = el('dossierIp').value.trim();
if (!ip) { note('an address first - the dossier is a claim about a source', true); return; }
const r = await apiRaw('/admin-api/source?ip=' + encodeURIComponent(ip));
if (failed(r)) return;
const d = r.body || {};
const lines = [];
lines.push('key: ' + (d.sourceKey || '?') + ' - ' + (d.verdict || '?') + ' - ' + (d.answer || ''));
const g = d.geo || {};
lines.push('geo: ' + (g.country || 'unknown') + ' (' + (g.source || '?') + ')'
+ (g.rule ? ' - the country rule says ' + (g.rule.allowed ? 'allowed' : 'denied') : '')
+ (g.wouldDeny ? ' - the geo pillar refuses it' : ''));
const a = d.allow;
lines.push('allow: ' + (a ? a.match + (a.live ? '' : ' (EXPIRED)') + (a.note ? ' - ' + a.note : '')
: 'nothing covers this address'));
const b = d.operatorBlock;
lines.push('operator block: ' + (b
? (b.cameFromRange ? 'from the range ' + b.match : 'written on this key')
+ (b.live ? '' : ' (EXPIRED)') + (b.reason ? ' - ' + b.reason : '')
: 'none'));
const e = d.engineBan;
lines.push('engine ban: ' + (e
? (e.sourceKey || '?') + (e.live ? '' : ' (EXPIRED)')
+ (e.applies ? '' : ' - enforcing nothing in ' + (e.enforcementMode || '?') + ' mode')
+ (e.reason ? ' - ' + e.reason : '')
: 'none'));
const st = d.streak;
lines.push('streak: ' + (st
? st.consecutiveRefusals + ' of ' + st.threshold + ' (' + (st.scope || '?') + ')'
+ (st.maxConsecutiveEver === null || st.maxConsecutiveEver === undefined
? '' : ', worst ever ' + st.maxConsecutiveEver)
: 'nothing standing'));
const v = d.volume || {};
const eb = v.edgeBudget;
lines.push('volume: ' + (v.mode || '?') + ' - '
+ (eb ? 'edge budget ' + eb.count + ' of ' + eb.limitPerWindow + ' per ' + eb.windowSeconds
+ ' s, ' + eb.secondsLeft + ' s left' + (eb.overBudget ? ' - OVER' : '')
: 'no running edge window'));
const pb = v.pathBudgets || [];
lines.push('path budgets counting it: ' + (pb.length
? pb.map((x) => x.pattern + ' ' + x.count + ' of ' + x.limitPerWindow
+ ' per ' + x.windowSeconds + ' s' + (x.overBudget ? ' - OVER (this path only)' : '')).join(' | ')
: 'none'));
const al = d.alerts || [];
lines.push('alerts: ' + (al.length
? al.length + ' recent, newest ' + (al[0].kind || '?') + ' x' + (al[0].count || '?')
: 'none'));
const nb = (d.netblockOffers || []);
if (nb.length) {
lines.push('netblocks offered that cover it: ' + nb.map((c) => c.match + ' (' + c.bans
+ ' bans inside' + (c.alreadyBanned ? ', already banned' : '') + ')').join(' | '));
}
const box = el('dossieranswer');
box.textContent = '';
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line;
box.appendChild(div);
}
};
// One delegated handler for every row button, so no key or country code is ever
// spliced into an inline onclick string. The values live in data attributes,
// which went through esc() on the way in.
+385 -1
View File
@@ -852,6 +852,356 @@ note = t.Note
});
});
// OPEN-70: one address, one answer.
//
// Every other surface here is a table with a filter on it. Investigating
// one source means opening six of them — blocks, allow, streaks,
// observations, alerts, the dry run — and holding the join in one's head,
// and the join is where the mistakes are: a v6 address looked up in its
// full form when the ban is keyed on the /64, an expired exemption read as
// a live one, a per-process streak read as the deployment's, and a CIDR
// ban that an equality lookup never finds at all. This answers the whole
// question in one call.
//
// It does it by asking the same objects the request path asks, never a
// second copy of their logic: containment through NetworkMatch and
// NetworkBanIndex (the two places that already know what a CIDR means),
// the identity through SourceKey, the verdict through DecisionEngine. A
// dossier with its own matcher would be a dossier about a different edge.
//
// Nothing is written and nothing is spent — the dry run's rule (OPEN-69)
// applied to every part of it. And "no row" and "not visible from this
// process" are different words throughout, because the first is a fact
// about the source and the second is a fact about where the question was
// asked.
group.MapGet("/source", async (string? ip, string? path,
EdgeStateStore state, IGeoIpLookup geo, RateTracker rates, RateRuleTracker rateRules,
IStreakTracker streaks, NetblockWatcher netblocks, OpenWafDbContext db,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown, "ip", "path"))
return Results.BadRequest(new { error = unknown });
// Required here, unlike /decide where the path alone is a fair
// question: this surface's claim is that it knows something about a
// source, and a source cannot be inferred from an empty query.
if (string.IsNullOrWhiteSpace(ip))
return Results.BadRequest(new { error = "ip is required: this surface answers about one address" });
if (!IsAnAddress(ip.Trim()))
return Results.BadRequest(new { error = $"ip must be an address; got \"{ip}\"" });
var askedIp = ip.Trim();
string? askedPath = null;
if (path is not null)
{
askedPath = path.Trim().Length == 0 ? "/" : path.Trim();
if (!askedPath.StartsWith('/'))
return Results.BadRequest(new { error = $"path must start with /; got \"{askedPath}\"" });
}
var now = DateTimeOffset.UtcNow;
var snapshot = state.GetOrRefresh();
var policy = snapshot.Policy;
// The key, not the address. A v6 dossier looked up by the address the
// socket carried would answer "nothing known" about a source this edge
// has banned twice, because the ban is filed on the /64.
var key = SourceKey.For(askedIp, policy);
// --- what the geo pillar would say about this address -----------
var country = policy.Geo == GeoMode.Off ? null : geo.Lookup(askedIp);
var geoSource = policy.Geo == GeoMode.Off
? "geo-off"
: country is not null ? "geo-database" : "not-in-database";
CountryRule? countryRule = null;
if (!string.IsNullOrWhiteSpace(country))
snapshot.Countries.TryGetValue(country.Trim().ToUpperInvariant(), out countryRule);
var geoDenied = policy.Geo != GeoMode.Off && !string.IsNullOrWhiteSpace(country)
&& policy.Geo switch
{
// The same two lines the engine uses. Duplicated logic would
// be a dossier that disagrees with the wire about who is
// refused, which is the one failure this surface cannot have.
GeoMode.DenyList => countryRule is { IsAllowed: false },
GeoMode.AllowList => countryRule is not { IsAllowed: true },
_ => false
};
// --- the exemption: containment, not equality ------------------
AllowEntry? coveringAllow = null;
foreach (var entry in snapshot.AllowEntries)
{
if (!NetworkMatch.Matches(askedIp, entry.Match)) continue;
if (entry.IsLive(now)) { coveringAllow = entry; break; }
// A dead exemption is worth naming: "this address used to be
// let through" is the answer an operator acts on, and it is not
// the same answer as "never was".
coveringAllow ??= entry;
}
// --- the operator's list, in the order the engine reads it -----
snapshot.OperatorBlocks.TryGetValue(key, out var operatorBlock);
NetworkBan? coveringRange = null;
if (operatorBlock is null || !operatorBlock.IsLive(now))
snapshot.OperatorRanges.TryMatch(askedIp, now, out coveringRange!);
// --- the engine's own ban --------------------------------------
snapshot.EngineBans.TryGetValue(key, out var engineBan);
var engineBanApplies = engineBan is not null && engineBan.IsLive(now)
&& policy.Mode == EnforcementMode.Enforce;
// --- the streak: this process's standing, the database's memory -
var liveStreak = streaks.Peek(key);
var observation = await db.Observations.AsNoTracking()
.FirstOrDefaultAsync(o => o.SourceKey == key, ct);
var alerts = await db.Alerts.AsNoTracking()
.Where(a => a.SourceKey == key)
.OrderByDescending(a => a.CreatedAt)
.Take(DossierAlertLimit)
.ToListAsync(ct);
// --- the volume pillar, read without spending it ---------------
var counting = policy.Rate != RateMode.Off;
object? edgeBudget = null;
if (counting)
{
var live = rates.LiveRates(now, policy, 1, 0, key, out _);
if (live.Count > 0)
{
var w = live[0];
edgeBudget = new
{
count = w.Count,
limitPerWindow = policy.RateLimitPerWindow,
windowSeconds = Math.Round(policy.RateWindow.TotalSeconds, 1),
windowStartsAt = w.WindowStart,
windowEndsAt = w.WindowEnd,
secondsLeft = SecondsLeft(w.WindowEnd, now),
overBudget = w.OverBudget
};
}
}
// Every path budget this source is already inside, without being
// asked for a path — the preview needs one, the dossier does not.
var windows = counting
? rateRules.WindowsFor(key, now)
: Array.Empty<RuleWindowObservation>();
var pathBudgets = windows.Select(w =>
{
var rule = snapshot.RateRules.FirstOrDefault(r => r.Id == w.RuleId);
return new
{
id = w.RuleId,
// A window can outlive the budget that created it: the
// counters are dropped when the rule is deleted, but a
// snapshot a few seconds old may still name the rule.
// Naming nothing would be a guess about which of the two
// happened, so the row says what it is.
pattern = rule?.Pattern ?? "(no live rule with this id on this edge)",
note = rule?.Note,
limitPerWindow = rule?.LimitPerWindow ?? 0,
windowSeconds = w.WindowSeconds,
count = w.Count,
overBudget = rule is not null && rule.LimitPerWindow > 0
&& w.Count > rule.LimitPerWindow,
windowEndsAt = w.WindowEnd,
secondsLeft = SecondsLeft(w.WindowEnd, now)
};
}).ToList();
// --- the ranges this edge is offering, that would cover it -----
var candidates = await netblocks.ScanAsync(false, ct);
var offers = candidates
.Where(c => NetworkMatch.Matches(askedIp, c.Match))
.Select(c => new NetblockDto(c.Match, c.Prefix, c.Bans, c.FirstBanAt, c.LastBanAt,
c.Sample, c.AlreadyBanned))
.ToList();
// --- the one sentence, from the pillars that need no path ------
string answerVerdict;
string answer;
if (coveringAllow is not null && coveringAllow.IsLive(now))
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.PassAllowlisted);
answer = $"allowlisted by \"{coveringAllow.Match}\": no pillar below the allowlist is asked about this source";
}
else if (operatorBlock is not null && operatorBlock.IsLive(now))
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockOperator);
answer = $"the operator's block on {key} answers for this source"
+ (operatorBlock.ExpiresAt is null ? " and never expires" : $" until {operatorBlock.ExpiresAt:O}");
}
else if (coveringRange is not null)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockOperator);
answer = $"the operator's range ban {coveringRange.Match} covers this address"
+ (coveringRange.ExpiresAt is null ? " and never expires" : $" until {coveringRange.ExpiresAt:O}");
}
else if (engineBanApplies)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.BlockEngine);
answer = $"this edge banned {key} itself"
+ (engineBan!.ExpiresAt is null ? "" : $" until {engineBan.ExpiresAt:O}");
}
else if (geoDenied)
{
answerVerdict = EdgeVerdictLabel.For(EdgeVerdict.GeoReject);
answer = $"the geo pillar refuses {country} in {policy.Geo} mode";
}
else if (engineBan is not null && engineBan.IsLive(now))
{
answerVerdict = "none";
answer = $"a live engine ban exists for {key}, but {policy.Mode} mode enforces nothing: this source is served";
}
else
{
answerVerdict = "none";
answer = "no pillar that answers without a path refuses this source";
}
return Results.Ok(new
{
// The question, echoed exactly, plus the key the answer is filed
// under and the rule that produced it — without the rule the key
// looks like a typo of the address.
ip = askedIp,
sourceKey = key,
keyRule = new
{
ipv4PrefixLength = policy.Ipv4KeyPrefixLength,
ipv6PrefixLength = policy.Ipv6KeyPrefixLength,
note = "bans, streaks and budgets are filed under sourceKey, not under ip; the allowlist and range bans are matched against ip itself"
},
askedPath,
verdict = answerVerdict,
answer,
answerScope = "the pillars that need no path; request rules and the volume budget are path-dependent — pass path= for the full verdict",
geo = new
{
country,
source = geoSource,
rule = countryRule is null ? null : new
{
code = countryRule.Code,
allowed = countryRule.IsAllowed,
updatedAt = countryRule.UpdatedAt
},
mode = policy.Geo.ToString(),
wouldDeny = geoDenied
},
// Each part names its own store, because the two answer different
// questions: the database is what this deployment knows, this
// process is what this instance is currently counting.
allow = coveringAllow is null ? null : new
{
id = coveringAllow.Id,
match = coveringAllow.Match,
note = coveringAllow.Note,
createdAt = coveringAllow.CreatedAt,
expiresAt = coveringAllow.ExpiresAt,
live = coveringAllow.IsLive(now),
scope = "database"
},
operatorBlock = operatorBlock is null
? coveringRange is null ? null : new
{
sourceKey = key,
cameFromRange = true,
match = (string?)coveringRange.Match,
reason = coveringRange.Reason,
redirectTo = coveringRange.RedirectTo,
createdAt = coveringRange.CreatedAt,
expiresAt = coveringRange.ExpiresAt,
live = coveringRange.IsLive(now),
scope = "database"
}
: new
{
sourceKey = operatorBlock.SourceKey,
cameFromRange = false,
match = (string?)null,
reason = operatorBlock.Reason,
redirectTo = operatorBlock.RedirectTo,
createdAt = operatorBlock.CreatedAt,
expiresAt = operatorBlock.ExpiresAt,
live = operatorBlock.IsLive(now),
scope = "database"
},
engineBan = engineBan is null ? null : new
{
sourceKey = engineBan.SourceKey,
reason = engineBan.Reason,
redirectTo = engineBan.RedirectTo,
createdAt = engineBan.CreatedAt,
expiresAt = engineBan.ExpiresAt,
live = engineBan.IsLive(now),
applies = engineBanApplies,
lastStatusCode = engineBan.LastStatusCode,
lastPath = engineBan.LastPath,
consecutiveRefusals = engineBan.ConsecutiveRefusals,
enforcementMode = policy.Mode.ToString(),
scope = "database"
},
streak = liveStreak is null ? null : new
{
scope = policy.SharedStreaks ? "shared-database" : "this-process",
consecutiveRefusals = liveStreak.MaxConsecutiveRefusals,
totalRefusals = liveStreak.TotalRefusals,
consecutiveServerErrors = liveStreak.MaxConsecutiveServerErrors,
lastStatusCode = liveStreak.LastStatusCode,
lastPath = liveStreak.LastPath,
lastSeenAt = liveStreak.LastSeenAt,
threshold = policy.StreakThreshold,
windowMinutes = policy.StreakWindow.TotalMinutes,
// The durable shadow of the same counter: the live map forgets
// a source when it ages out or the process restarts, and "this
// source has done this before" is the question that decides
// whether to ban the range around it.
maxConsecutiveEver = observation?.MaxConsecutiveRefusals,
totalRefusalsEver = observation?.TotalRefusals,
firstSeenAt = observation?.FirstSeenAt,
lastSeenAtDurable = observation?.LastSeenAt,
durableScope = observation is null ? "no observation row" : "database"
},
volume = new
{
mode = policy.Rate.ToString(),
scope = "this-process",
edgeBudget,
pathBudgets,
note = counting
? "counters live in this process, so N edges allow N budgets; nothing here was spent by asking"
: "the volume pillar is off: nothing is counted on this edge, so no budget can be crossed"
},
alerts = alerts.Select(a => new
{
id = a.Id,
kind = a.Kind,
count = a.Count,
lastStatusCode = a.LastStatusCode,
lastPath = a.LastPath,
createdAt = a.CreatedAt,
detail = a.Detail,
scope = "database"
}),
netblockOffers = offers,
// The dry run, only when a path was asked for. The same
// DecisionEngine over the same snapshot the wire reads, so the
// dossier's parts and this verdict cannot disagree.
wouldAnswer = askedPath is null ? null : DescribeSourceVerdict(
DecisionEngine.Decide(snapshot, askedIp, askedPath, now, country),
VolumePreview.For(policy, snapshot, askedPath, key, rates, rateRules, now,
// The guard counts only a request no other pillar answered.
true)),
scope = new
{
database = new[] { "allow", "operatorBlock", "engineBan", "alerts", "observations", "netblockOffers" },
thisProcess = new[] { "streak (unless sharedStreaks)", "volume counters" },
snapshotAgeSeconds = Math.Round((now - snapshot.GeneratedAt).TotalSeconds, 1),
snapshotTtlSeconds = Math.Round(state.RefreshTtl.TotalSeconds, 1),
snapshotStale = state.IsStale
}
});
});
// The record of deliberate changes to the operator's config (OPEN-64).
// Newest first, capped and paged like every other listing, and readable
// by the read-only token: it is a read, and a dashboard that can see the
@@ -1075,7 +1425,41 @@ note = t.Note
private const int AllowListDefaultLimit = 500;
private const int AllowListMaxLimit = 2000;
private const int ReadListDefaultLimit = 100;
/// <summary>How many of a source's alerts the dossier returns. Five is the
/// shortest list that still shows whether an alert is a one-off or a run, and
/// the full listing is one call away with ?source=.
/// <summary>The dry run's answer in the words /decide uses, so the two
/// surfaces cannot name the same verdict differently. The volume part is the
/// same projection the preview makes, kept short: the dossier is a summary and
/// the full narration is one /decide call away.</summary>
private static object DescribeSourceVerdict(EdgeDecision decision, VolumeAnswer volume) => new
{
verdict = EdgeVerdictLabel.For(decision.Verdict),
blocked = decision.IsBlocked,
status = decision.StatusCode,
location = decision.Location,
reason = decision.Reason,
expiresAt = decision.ExpiresAt,
range = decision.Range,
rulePattern = decision.RulePattern,
volume = new
{
mode = volume.Mode,
scope = volume.Scope,
verdict = volume.Verdict,
reached = volume.Reached,
note = volume.Note
}
};
private const int DossierAlertLimit = 5;
/// <summary>Whole seconds left in a window, never negative: a window that has
/// run out has nothing left, and "-3" would read as a clock error.</summary>
private static int SecondsLeft(DateTimeOffset windowEnd, DateTimeOffset now)
=> Math.Max(0, (int)Math.Ceiling((windowEnd - now).TotalSeconds));
private const int ReadListDefaultLimit = 100;
private const int ReadListMaxLimit = 1000;
private const int StreakListDefaultLimit = 50;
private const int StreakListMaxLimit = 1000;
@@ -0,0 +1,364 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// One address, one answer (OPEN-70).
///
/// Every operator surface here is a table with a filter on it, so investigating
/// one source meant opening six calls and holding the join in one's head. The
/// join is where the mistakes live: a v6 address looked up in full when the ban
/// is keyed on the /64, an expired exemption read as a live one, a CIDR ban an
/// equality lookup never finds, a per-process streak read as the deployment's.
///
/// What these tests hold the surface to, in order: containment rather than
/// equality for ranges and exemptions; the key rather than the address for bans
/// and budgets; an expired row named as expired rather than as absent; the scope
/// of every part named in the answer; a question it cannot answer refused by
/// name; the read-only token able to ask it; and nothing spent by asking it.
/// </summary>
public sealed class SourceDossierTests
{
private const string Range = "203.0.113.16/28"; // .16 – .31
private const string Inside = "203.0.113.21";
private const string Outside = "203.0.113.32";
private const string Source = "203.0.113.77";
private static async Task<JsonElement> DossierAsync(
EdgeFixture f, string query, string? token = EdgeFixture.AdminToken)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/source?{query}");
if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
using var r = await f.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, r.StatusCode);
return JsonDocument.Parse(await r.Content.ReadAsStringAsync()).RootElement.Clone();
}
private static async Task<(HttpStatusCode Status, string Error)> AskAsync(EdgeFixture f, string query)
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"/admin-api/source?{query}");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var r = await f.Client.SendAsync(request);
return (r.StatusCode, await r.Content.ReadAsStringAsync());
}
private static async Task<HttpResponseMessage> GetAsync(EdgeFixture f, string path, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, path);
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
return await f.Client.SendAsync(request);
}
private static async Task<HttpResponseMessage> AdminAsync(
EdgeFixture f, HttpMethod method, string url, object? body = null,
string token = EdgeFixture.AdminToken)
{
using var request = new HttpRequestMessage(method, url);
request.Headers.TryAddWithoutValidation("X-Admin-Token", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await f.Client.SendAsync(request);
}
/// <summary>Three refusals in a row from one address: the engine's own ban,
/// the streak that produced it and the durable row that remembers it.</summary>
private static async Task BanByTheEngineAsync(EdgeFixture f, string ip)
{
for (var i = 0; i < 3; i++)
using (var r = await GetAsync(f, "/wp-login.php", ip))
Assert.Equal(HttpStatusCode.NotFound, r.StatusCode);
await f.FlushObservationsAsync();
}
[Fact]
public async Task One_call_answers_what_this_edge_knows_about_one_address()
{
await using var f = new EdgeFixture();
await BanByTheEngineAsync(f, Source);
var body = await DossierAsync(f, $"ip={Source}");
Assert.Equal(Source, body.GetProperty("ip").GetString());
Assert.Equal(Source, body.GetProperty("sourceKey").GetString());
// The key rule travels with the key: without it, a v6 sourceKey looks
// like a typo of the address the operator typed.
Assert.Equal(32, body.GetProperty("keyRule").GetProperty("ipv4PrefixLength").GetInt32());
Assert.Equal(64, body.GetProperty("keyRule").GetProperty("ipv6PrefixLength").GetInt32());
Assert.Equal("block_engine", body.GetProperty("verdict").GetString());
Assert.Contains("banned", body.GetProperty("answer").GetString()!);
var ban = body.GetProperty("engineBan");
Assert.True(ban.GetProperty("live").GetBoolean());
Assert.True(ban.GetProperty("applies").GetBoolean());
Assert.Equal("database", ban.GetProperty("scope").GetString());
Assert.False(string.IsNullOrEmpty(ban.GetProperty("reason").GetString()));
Assert.Equal("/wp-login.php", ban.GetProperty("lastPath").GetString());
// The two stores of the same source's history, named apart: the standing
// counter is this process's, the maximum is the database's.
var streak = body.GetProperty("streak");
Assert.Equal("this-process", streak.GetProperty("scope").GetString());
Assert.Equal(3, streak.GetProperty("consecutiveRefusals").GetInt32());
Assert.Equal(3, streak.GetProperty("threshold").GetInt32());
Assert.Equal(3, streak.GetProperty("maxConsecutiveEver").GetInt32());
Assert.Equal("database", streak.GetProperty("durableScope").GetString());
Assert.Equal("this-process", body.GetProperty("volume").GetProperty("scope").GetString());
Assert.Empty(body.GetProperty("netblockOffers").EnumerateArray());
// No path was asked for, so the path-dependent pillars are named as
// unasked rather than answered as clear.
Assert.True(body.GetProperty("wouldAnswer").ValueKind == JsonValueKind.Null);
Assert.Contains("path", body.GetProperty("answerScope").GetString()!);
}
[Fact]
public async Task A_range_ban_answers_for_every_address_it_covers_and_says_where_it_came_from()
{
await using var f = new EdgeFixture();
using (var created = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Range, reason = "netblock scanning" }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
var covered = await DossierAsync(f, $"ip={Inside}");
Assert.Equal("block_operator", covered.GetProperty("verdict").GetString());
var ban = covered.GetProperty("operatorBlock");
// The distinction the operator has to be able to see: this address is not
// on the list, a network that contains it is.
Assert.True(ban.GetProperty("cameFromRange").GetBoolean());
Assert.Equal(Range, ban.GetProperty("match").GetString());
Assert.Equal("netblock scanning", ban.GetProperty("reason").GetString());
Assert.Contains(Range, covered.GetProperty("answer").GetString()!);
// The neighbour one address past the end is not answered by that row, and
// "nothing" is said as none rather than as an empty object.
var neighbour = await DossierAsync(f, $"ip={Outside}");
Assert.Equal("none", neighbour.GetProperty("verdict").GetString());
Assert.True(neighbour.GetProperty("operatorBlock").ValueKind == JsonValueKind.Null);
}
[Fact]
public async Task An_exemption_inside_a_banned_range_is_an_exemption()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range })) { }
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
new { match = Inside, note = "the office" })) { }
var body = await DossierAsync(f, $"ip={Inside}");
Assert.Equal("pass_allowlisted", body.GetProperty("verdict").GetString());
Assert.Equal("the office", body.GetProperty("allow").GetProperty("note").GetString());
Assert.True(body.GetProperty("allow").GetProperty("live").GetBoolean());
// The dossier and the wire agree: the same containment rule, asked once.
using (var served = await GetAsync(f, "/anything", Inside))
Assert.NotEqual(HttpStatusCode.MovedPermanently, served.StatusCode);
}
[Fact]
public async Task An_expired_row_is_named_as_expired_rather_than_as_absent()
{
await using var f = new EdgeFixture();
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.AllowEntries.Add(new AllowEntry
{
Match = Source, Note = "was exempt",
CreatedAt = DateTimeOffset.UtcNow.AddDays(-3),
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1)
});
db.Blocks.Add(new BlockEntry
{
SourceKey = Source, Source = BlockSource.Operator,
CreatedAt = DateTimeOffset.UtcNow.AddDays(-3),
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1),
Reason = "an incident that ended"
});
await db.SaveChangesAsync();
await f.Service<EdgeStateStore>().InvalidateAsync();
}
var body = await DossierAsync(f, $"ip={Source}");
// Both rows exist and neither answers: an operator deciding whether to
// re-ban needs to know the row was there, and "null" would say it never was.
Assert.False(body.GetProperty("allow").GetProperty("live").GetBoolean());
Assert.Equal("was exempt", body.GetProperty("allow").GetProperty("note").GetString());
Assert.False(body.GetProperty("operatorBlock").GetProperty("live").GetBoolean());
Assert.Equal("an incident that ended", body.GetProperty("operatorBlock").GetProperty("reason").GetString());
// Nothing live refuses this source, so the answer is none — not a verdict
// borrowed from the dead rows.
Assert.Equal("none", body.GetProperty("verdict").GetString());
}
[Fact]
public async Task A_live_engine_ban_in_observe_mode_is_reported_and_said_not_to_apply()
{
// The shape this actually takes: the ban was written while the edge
// enforced, and the operator switched the mode afterwards. A ban that is
// standing and enforcing nothing is the reading an operator has to be able
// to see, because the mode going back to Enforce puts it back on the wire.
await using var f = new EdgeFixture();
await BanByTheEngineAsync(f, Source);
using (await AdminAsync(f, HttpMethod.Put, "/admin-api/policy", new { mode = "Observe" })) { }
var body = await DossierAsync(f, $"ip={Source}");
var ban = body.GetProperty("engineBan");
Assert.True(ban.GetProperty("live").GetBoolean());
Assert.False(ban.GetProperty("applies").GetBoolean());
Assert.Equal("Observe", ban.GetProperty("enforcementMode").GetString());
Assert.Equal("none", body.GetProperty("verdict").GetString());
Assert.Contains("enforces nothing", body.GetProperty("answer").GetString()!);
}
[Fact]
public async Task An_ipv6_source_is_answered_on_its_key_and_not_on_its_address()
{
await using var f = new EdgeFixture();
// One /64, two addresses: the allocation is one source, which is the only
// way a v6 streak rule means anything.
await BanByTheEngineAsync(f, "2001:db8:1:2::10");
var body = await DossierAsync(f, "ip=2001:db8:1:2::11");
Assert.Equal("2001:db8:1:2::/64", body.GetProperty("sourceKey").GetString());
// Looked up by the address the operator typed, this dossier would have
// answered "nothing known" about a source this edge has already banned.
Assert.Equal("block_engine", body.GetProperty("verdict").GetString());
Assert.Equal("2001:db8:1:2::/64", body.GetProperty("engineBan").GetProperty("sourceKey").GetString());
Assert.Equal(3, body.GetProperty("streak").GetProperty("consecutiveRefusals").GetInt32());
}
[Fact]
public async Task A_path_budget_this_source_is_inside_appears_without_a_path_being_asked()
{
// A path budget counts only while the volume pillar counts at all, so the
// edge-wide limit is set far above the rule's: the rule is what is being
// asked about here, not the site-wide number.
await using var f = new EdgeFixture(rate: "Observe", rateLimitPerWindow: 100, rateWindowSeconds: 300);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
new { pattern = "/login*", limitPerWindow = 5, windowSeconds = 120, note = "stuffing" })) { }
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/rate-rules",
new { pattern = "/other*", limitPerWindow = 5 })) { }
for (var i = 0; i < 2; i++)
using (await GetAsync(f, "/login", Source)) { }
var budgets = (await DossierAsync(f, $"ip={Source}"))
.GetProperty("volume").GetProperty("pathBudgets");
// Only the budget this source is actually inside, with the pattern it was
// written under — an id alone is a number an operator cannot read.
var row = Assert.Single(budgets.EnumerateArray());
Assert.Equal("/login*", row.GetProperty("pattern").GetString());
Assert.Equal(2, row.GetProperty("count").GetInt32());
Assert.Equal(5, row.GetProperty("limitPerWindow").GetInt32());
Assert.Equal(120, row.GetProperty("windowSeconds").GetInt32());
Assert.False(row.GetProperty("overBudget").GetBoolean());
Assert.True(row.GetProperty("secondsLeft").GetInt32() > 0);
}
[Fact]
public async Task Asking_the_dossier_spends_none_of_the_budget_it_reports()
{
await using var f = new EdgeFixture(rate: "Enforce", rateLimitPerWindow: 2, rateWindowSeconds: 300);
using (await GetAsync(f, "/catalog", Source)) { }
for (var i = 0; i < 4; i++)
{
var body = await DossierAsync(f, $"ip={Source}");
// The same number every time: the dossier reads the counters and does
// not move them.
Assert.Equal(1, body.GetProperty("volume").GetProperty("edgeBudget").GetProperty("count").GetInt32());
}
using (await GetAsync(f, "/catalog", Source)) { }
using (var refused = await GetAsync(f, "/catalog", Source))
Assert.Equal((HttpStatusCode)429, refused.StatusCode);
// The refusal is the third real request, not the fourth look at a page.
}
[Fact]
public async Task With_a_path_the_dossier_and_the_dry_run_answer_the_same_verdict()
{
await using var f = new EdgeFixture();
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", new { ip = Range })) { }
var dossier = await DossierAsync(f, $"ip={Inside}&path=/anything");
Assert.Equal("/anything", dossier.GetProperty("askedPath").GetString());
var would = dossier.GetProperty("wouldAnswer");
Assert.Equal("block_operator", would.GetProperty("verdict").GetString());
Assert.True(would.GetProperty("blocked").GetBoolean());
Assert.Equal(301, would.GetProperty("status").GetInt32());
Assert.Equal(Range, would.GetProperty("range").GetString());
// The volume pillar is answered, not left silent, and it says it spent
// nothing: an earlier pillar answers, so the counter is never reached.
Assert.Equal("not_counted", would.GetProperty("volume").GetProperty("verdict").GetString());
using var preview = await AdminAsync(f, HttpMethod.Get,
$"/admin-api/decide?ip={Inside}&path=/anything");
using var doc = JsonDocument.Parse(await preview.Content.ReadAsStringAsync());
Assert.Equal(
would.GetProperty("verdict").GetString(),
doc.RootElement.GetProperty("verdict").GetString());
}
[Fact]
public async Task A_question_this_surface_cannot_answer_is_refused_by_name()
{
await using var f = new EdgeFixture();
var missing = await AskAsync(f, "");
Assert.Equal(HttpStatusCode.BadRequest, missing.Status);
Assert.Contains("ip is required", missing.Error);
var blank = await AskAsync(f, "ip=");
Assert.Equal(HttpStatusCode.BadRequest, blank.Status);
// A typo in the address must not answer "nothing known about this source".
var typo = await AskAsync(f, "ip=203.0.113");
Assert.Equal(HttpStatusCode.BadRequest, typo.Status);
Assert.Contains("must be an address", typo.Error);
var badPath = await AskAsync(f, $"ip={Source}&path=anything");
Assert.Equal(HttpStatusCode.BadRequest, badPath.Status);
Assert.Contains("path must start with /", badPath.Error);
var unknown = await AskAsync(f, $"ip={Source}&addres={Source}");
Assert.Equal(HttpStatusCode.BadRequest, unknown.Status);
Assert.Contains("addres", unknown.Error);
}
[Fact]
public async Task The_read_only_token_reads_a_dossier_and_changes_nothing()
{
await using var f = new EdgeFixture(readOnlyToken: EdgeFixture.ReadOnlyToken);
using (await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks",
new { ip = Source, reason = "written by the operator" })) { }
var body = await DossierAsync(f, $"ip={Source}", EdgeFixture.ReadOnlyToken);
Assert.Equal("block_operator", body.GetProperty("verdict").GetString());
// The list is what it was, and the change log holds only the operator's
// own write — a read that left a record would be a write wearing a mask.
using (var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?live=false",
token: EdgeFixture.ReadOnlyToken))
{
Assert.Equal(HttpStatusCode.OK, blocks.StatusCode);
using var doc = JsonDocument.Parse(await blocks.Content.ReadAsStringAsync());
Assert.Single(doc.RootElement.EnumerateArray());
}
using (var changes = await AdminAsync(f, HttpMethod.Get, "/admin-api/changes",
token: EdgeFixture.ReadOnlyToken))
{
Assert.Equal(HttpStatusCode.OK, changes.StatusCode);
using var doc = JsonDocument.Parse(await changes.Content.ReadAsStringAsync());
Assert.Single(doc.RootElement.EnumerateArray());
}
// No token at all is not the read-only level: the surface stays shut.
using (var anonymous = await f.Client.GetAsync($"/admin-api/source?ip={Source}"))
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
}
}
@@ -156,6 +156,71 @@ public sealed class RateRuleTrackerTests
Assert.Equal((0, 0), tracker.LiveCounts(1, 2, T0.AddSeconds(120)));
}
// The dossier (OPEN-70) asks "which path budgets is this source already
// inside" without naming a path, because the operator is asking about the
// source, not about a request.
[Fact]
public void One_source_can_be_asked_which_budgets_are_counting_it()
{
var tracker = new RateRuleTracker();
var login = Rule(1, "/login*", 2);
var api = Rule(7, "/api/*", 5, windowSeconds: 120);
var other = Rule(9, "/other*", 5);
tracker.Record(login, "203.0.113.1", T0);
tracker.Record(login, "203.0.113.1", T0.AddSeconds(1));
tracker.Record(api, "203.0.113.1", T0.AddSeconds(2));
tracker.Record(login, "someone-else", T0);
tracker.Record(other, "someone-else", T0);
var rows = tracker.WindowsFor("203.0.113.1", T0.AddSeconds(3));
// Only this source's windows, ordered by rule id so two calls answer in
// the same order, and the window length travels with the row.
Assert.Equal(2, rows.Count);
Assert.Equal(1L, rows[0].RuleId);
Assert.Equal(2, rows[0].Count);
Assert.Equal(T0.AddSeconds(60), rows[0].WindowEnd);
Assert.Equal(60, rows[0].WindowSeconds);
Assert.Equal(7L, rows[1].RuleId);
Assert.Equal(1, rows[1].Count);
Assert.Equal(120, rows[1].WindowSeconds);
}
[Fact]
public void A_window_that_has_run_out_is_not_a_budget_this_source_is_inside()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 5);
tracker.Record(rule, "203.0.113.1", T0);
Assert.Single(tracker.WindowsFor("203.0.113.1", T0.AddSeconds(59)));
// "0 of 5" from a dead window is a different claim from "nothing yet", and
// the dossier has to be able to tell them apart — so it reports neither.
Assert.Empty(tracker.WindowsFor("203.0.113.1", T0.AddSeconds(61)));
// A source nobody ever counted answers with nothing, not with a row at
// zero, and an empty key never reaches into the map at all.
Assert.Empty(tracker.WindowsFor("never-seen", T0));
Assert.Empty(tracker.WindowsFor("", T0));
}
[Fact]
public void Asking_which_budgets_are_counting_a_source_spends_none_of_them()
{
var tracker = new RateRuleTracker();
var rule = Rule(1, "/login*", 2);
tracker.Record(rule, "203.0.113.1", T0);
tracker.Record(rule, "203.0.113.1", T0.AddSeconds(1));
tracker.WindowsFor("203.0.113.1", T0.AddSeconds(2));
tracker.WindowsFor("203.0.113.1", T0.AddSeconds(2));
// The dossier's whole rule: a page that answers by counting its own
// question would refuse the next real request because somebody looked.
var next = tracker.Record(rule, "203.0.113.1", T0.AddSeconds(3));
Assert.Equal(3, next.Count);
Assert.Equal(T0, next.WindowStart);
}
[Fact]
public void An_unidentifiable_source_is_not_counted()
{
+34
View File
@@ -1754,6 +1754,40 @@ check 'the scene cleans itself, so the volume is left as it was found' 'not_coun
admin "$EDGE/admin-api/decide?ip=$DRY_IP&path=/dryrun" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["volume"]["verdict"])')"
# One address, one answer (OPEN-70), on the shipped image. The point is the join:
# an address the operator blocked on its own key, and an address a banned range
# covers without any row naming it. The second is the one every single-table
# listing answered "nothing".
echo '- the shipped edge answers one address in one call'
DOS_IP=198.51.100.141
DOS_NET=198.51.100.144/29 # .144 - .151
DOS_INSIDE=198.51.100.147
DOS_OUTSIDE=198.51.100.152
check 'the shipped edge takes an address block and a range block' '204 204' \
"$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_IP"'","reason":"dossier scene"}' "$EDGE/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_NET"'","reason":"dossier range"}' "$EDGE/admin-api/blocks")"
check 'the shipped dossier answers on the key and names the row behind it' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and d["sourceKey"]=="'"$DOS_IP"'" and b and not b["cameFromRange"] and b["live"] else "no")')"
check 'the shipped dossier finds the range that covers an address no row names' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_INSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and b and b["cameFromRange"] and b["match"]=="'"$DOS_NET"'" else "no")')"
check 'the shipped dossier says none for a source it knows nothing about' 'yes' \
"$(admin "$EDGE/admin-api/source?ip=$DOS_OUTSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["verdict"]=="none" and not d["operatorBlock"] and not d["allow"] and not d["engineBan"] else "no")')"
check 'the shipped dossier refuses a question it cannot answer' '400 400' \
"$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/source?ip=198.51.100") \
$(code -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/source")"
check 'asking it six times wrote nothing to the operator list' 2 \
"$(for _ in 1 2 3 4 5 6; do admin "$EDGE/admin-api/source?ip=$DOS_IP" >/dev/null; done; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$DOS_IP"'","'"$DOS_NET"'")]))')"
check 'the scene cleans itself' 0 \
"$(admin -X DELETE "$EDGE/admin-api/blocks?key=$DOS_IP" >/dev/null; \
admin -X DELETE "$EDGE/admin-api/blocks?key=${DOS_NET//\//%2F}" >/dev/null; \
admin "$EDGE/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("'"$DOS_IP"'","'"$DOS_NET"'")]))')"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+66
View File
@@ -578,6 +578,72 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
check('the volume switch is left off, as the stack was seeded',
(await page.$$eval('#rateMode', (s) => s[0].value)) === 'off', await page.$$eval('#rateMode', (s) => s[0].value));
// One address, one answer (OPEN-70), asked from the page. Two shapes are worth
// asserting because they are the two the six separate listings got wrong: a
// block written on the address itself, and a block written on a network that
// contains the address - the second is invisible to anything that compares keys.
const DOSSIER_IP = '192.0.2.211';
const DOSSIER_NET = '192.0.2.216/29'; // .216 - .223
const DOSSIER_INSIDE = '192.0.2.219';
const DOSSIER_OUTSIDE = '192.0.2.224';
await page.fill('#blockIp', DOSSIER_IP);
await page.fill('#blockReason', 'console gate: dossier address');
await page.click('#addBlock');
await page.waitForFunction((ip) => [...document.querySelectorAll('#blocks tbody tr')]
.some((tr) => tr.children[0].textContent === ip), DOSSIER_IP, { timeout: 15000 }).catch(() => {});
await page.fill('#blockIp', DOSSIER_NET);
await page.fill('#blockReason', 'console gate: dossier range');
await page.click('#addBlock');
// The row's first cell carries the `range` badge, so the row is matched by the
// key its delete button holds - the same name the delete is keyed by.
const blockKeys = () => page.$$eval('#blocks tbody button[data-act="delblock"]',
(bs) => bs.map((b) => b.dataset.k));
await page.waitForFunction((net) => [...document.querySelectorAll('#blocks tbody button[data-act="delblock"]')]
.some((b) => b.dataset.k === net), DOSSIER_NET, { timeout: 15000 }).catch(() => {});
const askDossier = async (ip) => {
// The box is emptied first and then waited on for this address by name. The
// console gate caught why: waiting only for "an answer is there" is satisfied
// by the previous answer still sitting in the box, so every assertion after
// the first reads the address asked one click earlier.
await page.evaluate(() => { document.getElementById('dossieranswer').textContent = ''; });
await page.fill('#dossierIp', ip);
await page.click('#askSource');
await page.waitForFunction((asked) => (document.getElementById('dossieranswer').textContent || '')
.indexOf('key: ' + asked) === 0, ip, { timeout: 15000 }).catch(() => {});
return (await page.textContent('#dossieranswer')).replace(/\s+/g, ' ');
};
const onKey = await askDossier(DOSSIER_IP);
check('the page answers for an address the operator blocked on its own key',
/block_operator/.test(onKey) && /written on this key/.test(onKey) && /dossier address/.test(onKey),
onKey.slice(0, 300));
const fromRange = await askDossier(DOSSIER_INSIDE);
check('an address inside a banned range is answered by that range, not by a row that does not exist',
/block_operator/.test(fromRange) && /from the range 192\.0\.2\.216\/29/.test(fromRange),
fromRange.slice(0, 300));
const outside = await askDossier(DOSSIER_OUTSIDE);
check('an address on no list is answered as none rather than as a verdict',
/- none -/.test(outside) && /operator block: none/.test(outside),
outside.slice(0, 300));
// A read, like the dry run: the dossier wrote nothing, so the operator's table
// still holds exactly the two rows the page wrote and no third one.
const dossierRows = await blockKeys();
check('asking the dossier wrote nothing to the operator list',
dossierRows.filter((k) => k === DOSSIER_IP || k === DOSSIER_NET).length === 2,
JSON.stringify(dossierRows));
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${DOSSIER_IP}"]`);
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${DOSSIER_NET}"]`);
await page.waitForFunction((pair) => ![...document.querySelectorAll('#blocks tbody tr')]
.some((tr) => pair.indexOf(tr.children[0].textContent) !== -1),
[DOSSIER_IP, DOSSIER_NET], { timeout: 15000 }).catch(() => {});
await page.fill('#allowMatch', WRITE_CIDR);
await page.fill('#allowNote', 'console gate: allow entry');
+52
View File
@@ -799,6 +799,58 @@ check 'the scene cleans itself, so the rest of the gate runs on the stack it exp
| python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')"
rm -f /tmp/openwaf-upstream/dryrun.txt
# One address, one answer (OPEN-70). Every other listing here answers one table;
# an operator investigating one source had to open six and hold the join in their
# head. The two shapes this scene checks are the two that join got wrong: a block
# written on the address itself, and a block written on a network that contains
# the address - the second is invisible to anything that compares keys.
echo '- one address, one answer'
DOS_IP=192.0.2.121
DOS_NET=192.0.2.128/29 # .128 - .135
DOS_INSIDE=192.0.2.131
DOS_OUTSIDE=192.0.2.136
dossier() { curl -s -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=$1${2:+&path=$2}"; }
check 'the operator writes an address and a range' '204 204' \
"$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"192.0.2.121","reason":"dossier scene"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks") \
$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \
--data-binary '{"ip":"'"$DOS_NET"'","reason":"dossier range"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the dossier answers on the key, and names the rule that made it' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["sourceKey"]=="192.0.2.121" and d["keyRule"]["ipv4PrefixLength"]==32 else "no")')"
check 'an address the operator blocked on its own key is answered by that row' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and b and not b["cameFromRange"] and b["live"] and b["reason"]=="dossier scene" else "no")')"
check 'an address inside a banned range is answered by that range, not by a row that does not exist' yes \
"$(dossier "$DOS_INSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);b=d["operatorBlock"];print("yes" if d["verdict"]=="block_operator" and b and b["cameFromRange"] and b["match"]=="192.0.2.128/29" else "no")')"
check 'an address on no list is answered as none, with nothing invented for it' yes \
"$(dossier "$DOS_OUTSIDE" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["verdict"]=="none" and d["operatorBlock"] is None and d["allow"] is None and d["engineBan"] is None and d["streak"] is None else "no")')"
check 'the answer says which store each part came from' yes \
"$(dossier "$DOS_IP" | python3 -c 'import sys,json;d=json.load(sys.stdin);print("yes" if d["operatorBlock"]["scope"]=="database" and d["volume"]["scope"]=="this-process" and "allow" in d["scope"]["database"] else "no")')"
check 'with a path the dossier and the dry run give the same verdict' yes \
"$(python3 -c '
import json,subprocess
d=json.loads(subprocess.run(["curl","-s","-H","X-Admin-Token: '$TOKEN'",
"http://127.0.0.1:'$EDGE_PORT'/admin-api/source?ip='$DOS_INSIDE'&path=/wp-admin"],capture_output=True,text=True).stdout)
p=json.loads(subprocess.run(["curl","-s","-H","X-Admin-Token: '$TOKEN'",
"http://127.0.0.1:'$EDGE_PORT'/admin-api/decide?ip='$DOS_INSIDE'&path=/wp-admin"],capture_output=True,text=True).stdout)
print("yes" if d["wouldAnswer"]["verdict"]==p["verdict"]==d["verdict"]=="block_operator" else "no")')"
check 'a question it cannot answer is refused by name' '400 400' \
"$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/source?ip=192.0.2") \
$(code -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/source")"
check 'asking it six times wrote nothing: the operator list still holds those two rows' 2 \
"$(for _ in 1 2 3 4 5 6; do dossier "$DOS_IP" >/dev/null; dossier "$DOS_INSIDE" >/dev/null; done; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')"
check 'the scene cleans itself' 0 \
"$(code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=192.0.2.121" >/dev/null; \
code -X DELETE -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks?key=${DOS_NET//\//%2F}" >/dev/null; \
curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \
| python3 -c 'import sys,json;print(len([r for r in json.load(sys.stdin) if r["sourceKey"] in ("192.0.2.121","192.0.2.128/29")]))')"
echo '- admin surface'
check 'no token is refused' 401 "$(code "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the policy is readable' Enforce \