A country rule made of any two characters was stored, shown to the operator, and obeyed by nobody
PUT /admin-api/countries/{code} checked one thing about the code: that it was
two characters long. Measured on the shipped image (openwaf:ci):
PUT /admin-api/countries/12?allowed=false -> 204
PUT /admin-api/countries/U.?allowed=false -> 204
GET /admin-api/countries -> "12: denied", "U.: denied", "US: allowed"
probe from a source the geo database puts in a real country -> 404
A country rule is matched against the two-letter code the geo database returns,
so "12" and "U." can never match anything: the operator's table said two
countries were denied and the edge enforced nothing. With US denied for real the
same probe answers 451, which is the difference the table was hiding. And there
was no DELETE, so the row was permanent — the console gate's own comment used to
read "a country rule cannot be deleted, only overwritten", and the residue out
lived `compose down` because it lives in the data volume.
Now the code must be two ASCII letters or the write is refused by name:
"code must be a two-letter ISO country code; got \"12\"". DELETE
/admin-api/countries/{code} removes a rule and invalidates the snapshot, and
says `no country rule for "ZZ"` when there is nothing to remove. The page offers
"remove rule" on a row that has a rule, and the gate's cleanup deletes the US
rule it sets instead of leaving it behind.
The country part of the console gate was also fixed, and it was a gate bug worth
naming: it assumed a US rule already existed. With residue in the volume the
first click denied the country; on a fresh volume it allowed it, so the
assertion only ever passed on leftover state. It now starts from no rule and
asserts — → allowed → denied → removed.
Teeth, each reverted and counted, then restored: length-only code check -> 5
integration failures; DELETE endpoint removed -> 2; both out -> 9.
Gates on this tree: unit 128/128, integration 99/99, smoke passed 19 failed 0,
compose 43 passed 0 failed, console 44 assertions 0 failed, image 261 MB.
This commit is contained in:
@@ -279,7 +279,12 @@ async function load() {
|
||||
{ v: allowed.has(c.code) ? (allowed.get(c.code) ? 'allowed' : 'denied') : '—' },
|
||||
{ h: '<button data-act="country" data-k="' + esc(c.code) + '" data-allowed="'
|
||||
+ (allowed.has(c.code) && allowed.get(c.code) ? 'false' : 'true') + '">'
|
||||
+ (allowed.has(c.code) && allowed.get(c.code) ? 'deny' : 'allow') + '</button>' }
|
||||
+ (allowed.has(c.code) && allowed.get(c.code) ? 'deny' : 'allow') + '</button>'
|
||||
// Flipping a rule to "allowed" leaves the row behind; removing it is the
|
||||
// only way the table stops claiming a country has a rule at all.
|
||||
+ (allowed.has(c.code)
|
||||
? ' <button data-act="countrydel" data-k="' + esc(c.code) + '">remove rule</button>'
|
||||
: '') }
|
||||
])).join('') || row([{ v: 'none' }]);
|
||||
note('refreshed ' + new Date().toLocaleTimeString(), false);
|
||||
} catch (e) { /* note() already said why */ }
|
||||
@@ -354,6 +359,9 @@ document.addEventListener('click', async (e) => {
|
||||
} else if (b.dataset.act === 'country') {
|
||||
await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' });
|
||||
note('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'), false);
|
||||
} else if (b.dataset.act === 'countrydel') {
|
||||
await api('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||
note('country rule ' + b.dataset.k + ' removed', false);
|
||||
}
|
||||
load();
|
||||
} catch (err) { /* note() already said why */ }
|
||||
|
||||
@@ -276,16 +276,33 @@ internal static class AdminEndpoints
|
||||
|
||||
group.MapPut("/countries/{code}", async (string code, bool allowed, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) =>
|
||||
{
|
||||
code = code.Trim().ToUpperInvariant();
|
||||
if (code.Length != 2) return Results.BadRequest(new { error = "code must be a two-letter ISO country code" });
|
||||
var row = await db.CountryRules.FindAsync([code], ct);
|
||||
if (row is null) db.CountryRules.Add(new CountryRule { Code = code, IsAllowed = allowed, UpdatedAt = DateTimeOffset.UtcNow });
|
||||
if (!TryCountryCode(code, out var normalized, out var codeError))
|
||||
return Results.BadRequest(new { error = codeError });
|
||||
var row = await db.CountryRules.FindAsync([normalized], ct);
|
||||
if (row is null) db.CountryRules.Add(new CountryRule { Code = normalized, IsAllowed = allowed, UpdatedAt = DateTimeOffset.UtcNow });
|
||||
else { row.IsAllowed = allowed; row.UpdatedAt = DateTimeOffset.UtcNow; }
|
||||
await db.SaveChangesAsync(ct);
|
||||
await state.InvalidateAsync(ct);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
// A country rule cannot be un-set by writing the other way: the only way
|
||||
// to stop enforcing one is to remove it. Until now there was no way to
|
||||
// remove one at all, which is what made a mistyped code permanent — the
|
||||
// console gate's own comment used to read "a country rule cannot be
|
||||
// deleted, only overwritten".
|
||||
group.MapDelete("/countries/{code}", async (string code, OpenWafDbContext db, EdgeStateStore state, CancellationToken ct) =>
|
||||
{
|
||||
if (!TryCountryCode(code, out var normalized, out var codeError))
|
||||
return Results.BadRequest(new { error = codeError });
|
||||
var row = await db.CountryRules.FindAsync([normalized], ct);
|
||||
if (row is null) return Results.NotFound(new { error = $"no country rule for \"{normalized}\"" });
|
||||
db.CountryRules.Remove(row);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await state.InvalidateAsync(ct);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
// What the console's country table reads: the sources the edge has
|
||||
// actually seen, counted from the observation aggregates rather than from
|
||||
// a request log (there isn't one). A read, not new decision logic.
|
||||
@@ -345,6 +362,24 @@ internal static class AdminEndpoints
|
||||
/// refused by name, and every capped listing now carries X-Total-Count and
|
||||
/// X-Truncated plus an offset that reaches the rest.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// A country rule is matched against the two-letter code the geo database
|
||||
/// returns, so a code made of any other two characters can never match
|
||||
/// anything. The shipped image only checked the length: PUT
|
||||
/// /admin-api/countries/12?allowed=false answered 204, GET /countries listed
|
||||
/// "12: denied", and a source from the busiest country still got through —
|
||||
/// the operator's table said a country was denied while the engine enforced
|
||||
/// nothing. And there was no DELETE, so the row was permanent.
|
||||
/// </summary>
|
||||
private static bool TryCountryCode(string? raw, out string code, out string? error)
|
||||
{
|
||||
code = (raw ?? string.Empty).Trim().ToUpperInvariant();
|
||||
error = null;
|
||||
if (code.Length == 2 && char.IsAsciiLetter(code[0]) && char.IsAsciiLetter(code[1])) return true;
|
||||
error = $"code must be a two-letter ISO country code; got \"{raw}\"";
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryPaging(int? limit, int? offset, int defaultLimit, int maxLimit,
|
||||
out int take, out int skip, out string? error)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// A country rule is matched against the two-letter code the geo database
|
||||
/// returns, so a code made of any other two characters can never match
|
||||
/// anything. The shipped image checked only the length. Measured on openwaf:ci:
|
||||
/// PUT /admin-api/countries/12?allowed=false → 204
|
||||
/// PUT /admin-api/countries/U.?allowed=false → 204
|
||||
/// GET /admin-api/countries → "12: denied", "U.: denied", "US: allowed"
|
||||
/// probe from a source the database puts in the busiest country → 404, i.e.
|
||||
/// nothing was denied while the operator's table said two countries were.
|
||||
/// And there was no DELETE, so the row was permanent: the console gate's own
|
||||
/// comment used to read "a country rule cannot be deleted, only overwritten".
|
||||
/// </summary>
|
||||
public sealed class CountryRuleTests
|
||||
{
|
||||
private const string Scanner = "203.0.113.66";
|
||||
|
||||
private static async Task<(HttpStatusCode Status, string Body)> AdminAsync(
|
||||
EdgeFixture f, HttpMethod method, string url)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url);
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
using var response = await f.Client.SendAsync(request);
|
||||
return (response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
private static async Task<string[]> CodesAsync(EdgeFixture f)
|
||||
{
|
||||
var (_, body) = await AdminAsync(f, HttpMethod.Get, "/admin-api/countries");
|
||||
return JsonDocument.Parse(body).RootElement.EnumerateArray()
|
||||
.Select(e => e.GetProperty("code").GetString()!).ToArray();
|
||||
}
|
||||
|
||||
private static async Task<HttpStatusCode> ProbeAsync(EdgeFixture f, string? country)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/anything");
|
||||
request.Headers.TryAddWithoutValidation("X-Forwarded-For", Scanner);
|
||||
if (country is not null) request.Headers.TryAddWithoutValidation("CF-IPCountry", country);
|
||||
using var response = await f.Client.SendAsync(request);
|
||||
return response.StatusCode;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("12")]
|
||||
[InlineData("U.")]
|
||||
[InlineData("??")]
|
||||
[InlineData("USA")]
|
||||
[InlineData("1A")]
|
||||
[InlineData("U S")]
|
||||
public async Task A_country_code_that_is_not_two_ASCII_letters_is_refused_by_name(string code)
|
||||
{
|
||||
await using var f = new EdgeFixture(geo: "DenyList");
|
||||
|
||||
var (status, body) = await AdminAsync(f, HttpMethod.Put,
|
||||
$"/admin-api/countries/{Uri.EscapeDataString(code)}?allowed=false");
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, status);
|
||||
Assert.Contains("code must be a two-letter ISO country code", body);
|
||||
Assert.Contains(code, body);
|
||||
Assert.Empty(await CodesAsync(f));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_lowercase_code_is_normalised_and_then_actually_enforced()
|
||||
{
|
||||
await using var f = new EdgeFixture(geo: "DenyList");
|
||||
|
||||
var (status, _) = await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/de?allowed=false");
|
||||
Assert.Equal(HttpStatusCode.NoContent, status);
|
||||
Assert.Equal(new[] { "DE" }, await CodesAsync(f));
|
||||
Assert.Equal((HttpStatusCode)451, await ProbeAsync(f, "DE"));
|
||||
Assert.Equal(HttpStatusCode.NotFound, await ProbeAsync(f, "FR"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_country_rule_can_be_removed_and_stops_being_enforced_on_the_wire()
|
||||
{
|
||||
await using var f = new EdgeFixture(geo: "DenyList");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NoContent,
|
||||
(await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/DE?allowed=false")).Status);
|
||||
Assert.Equal((HttpStatusCode)451, await ProbeAsync(f, "DE"));
|
||||
|
||||
var (removed, _) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/countries/DE");
|
||||
Assert.Equal(HttpStatusCode.NoContent, removed);
|
||||
Assert.Empty(await CodesAsync(f));
|
||||
|
||||
// The rule is gone from the engine too, not only from the table — the
|
||||
// snapshot is invalidated by the delete, so the next request is decided
|
||||
// without it.
|
||||
Assert.Equal(HttpStatusCode.NotFound, await ProbeAsync(f, "DE"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Removing_a_rule_that_was_never_written_names_the_code_instead_of_passing_for_success()
|
||||
{
|
||||
await using var f = new EdgeFixture(geo: "DenyList");
|
||||
|
||||
var (status, body) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/countries/ZZ");
|
||||
Assert.Equal(HttpStatusCode.NotFound, status);
|
||||
// Parsed, not substring-matched: the quotes are inside a JSON string, so
|
||||
// a substring assertion here would have to quote the escaping too.
|
||||
Assert.Equal("no country rule for \"ZZ\"",
|
||||
JsonDocument.Parse(body).RootElement.GetProperty("error").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_refused_country_code_leaves_the_rule_that_was_already_there_alone()
|
||||
{
|
||||
await using var f = new EdgeFixture(geo: "DenyList");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NoContent,
|
||||
(await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/DE?allowed=false")).Status);
|
||||
Assert.Equal(HttpStatusCode.BadRequest,
|
||||
(await AdminAsync(f, HttpMethod.Put, "/admin-api/countries/12?allowed=false")).Status);
|
||||
|
||||
Assert.Equal(new[] { "DE" }, await CodesAsync(f));
|
||||
Assert.Equal((HttpStatusCode)451, await ProbeAsync(f, "DE"));
|
||||
}
|
||||
}
|
||||
+39
-11
@@ -300,21 +300,49 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||||
!rowsAfterBad.some((r) => r[0] === 'not-an-ip'), JSON.stringify(rowsAfterBad.map((r) => r[0])));
|
||||
|
||||
// The country rule toggle is the one control here that changes policy for
|
||||
// everyone, so the gate turns it and turns it back. There is no DELETE for a
|
||||
// country rule — PUT allowed=true is as close to "back to how it was" as the
|
||||
// API gets, and the row stays behind; worth knowing when reading the table.
|
||||
// everyone, so the gate turns it and turns it back, and then removes it: PUT
|
||||
// allowed=true leaves a row behind, and only DELETE takes the rule out.
|
||||
const ruleOf = async (code) => page.$$eval('#countries tbody tr',
|
||||
(rows, c) => { const r = rows.find((tr) => tr.children[0].textContent === c); return r ? r.children[4].textContent : 'no row'; }, 'US');
|
||||
(rows, c) => { const r = rows.find((tr) => tr.children[0].textContent === c); return r ? r.children[4].textContent : 'no row'; }, code);
|
||||
const waitRule = (code, want) => page.waitForFunction((a) => {
|
||||
const rows = document.querySelectorAll('#countries tbody tr');
|
||||
for (const tr of rows) {
|
||||
if (tr.children[0].textContent === a.c) return tr.children[4].textContent === a.w;
|
||||
}
|
||||
return a.w === '—';
|
||||
}, { c: code, w: want }, { timeout: 15000 }).catch(() => {});
|
||||
const REMOVE_SEL = '#countries tbody button[data-act="countrydel"][data-k="US"]';
|
||||
const hasRemove = () => page.$(REMOVE_SEL).then((h) => h !== null);
|
||||
|
||||
// Start from no rule at all. The gate used to depend on whatever a previous
|
||||
// run left in the data volume: with a US rule already present the first click
|
||||
// denied the country, and with a fresh volume it allowed it, so the old
|
||||
// assertion only ever passed on residue.
|
||||
if (await hasRemove()) {
|
||||
await page.click(REMOVE_SEL);
|
||||
await waitRule('US', '—');
|
||||
}
|
||||
const before = await ruleOf('US');
|
||||
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
|
||||
await page.waitForFunction(() => /denied/.test(document.querySelector('#countries tbody') ? document.querySelector('#countries tbody').textContent : ''), null, { timeout: 15000 }).catch(() => {});
|
||||
const denied = await ruleOf('US');
|
||||
await waitRule('US', 'allowed');
|
||||
const first = await ruleOf('US');
|
||||
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
|
||||
await page.waitForFunction(() => /allowed/.test(document.querySelector('#countries tbody') ? document.querySelector('#countries tbody').textContent : ''), null, { timeout: 15000 }).catch(() => {});
|
||||
const restored = await ruleOf('US');
|
||||
check('a country rule can be set from the page and put back',
|
||||
denied === 'denied' && restored === 'allowed' && before !== 'denied',
|
||||
`before ${before} → ${denied} → ${restored}`);
|
||||
await waitRule('US', 'denied');
|
||||
const second = await ruleOf('US');
|
||||
check('a country rule can be written from the page and toggled both ways',
|
||||
before === '—' && first === 'allowed' && second === 'denied',
|
||||
`before ${before} → ${first} → ${second}`);
|
||||
|
||||
// Setting a rule back to "allowed" is not the same as having no rule: the row
|
||||
// stays in the table and claims a policy that does nothing. The page has to be
|
||||
// able to take it out.
|
||||
check('a rule row offers removal only when a rule actually exists', await hasRemove(), REMOVE_SEL);
|
||||
await page.click(REMOVE_SEL);
|
||||
await waitRule('US', '—');
|
||||
const afterRemove = await ruleOf('US');
|
||||
check('a country rule can be removed from the page, not only flipped to allowed',
|
||||
afterRemove === '—' && !(await hasRemove()),
|
||||
`rule cell after remove: ${afterRemove}, remove button gone: ${!(await hasRemove())}`);
|
||||
|
||||
// A phone in dark mode is the case an operator actually reaches the console
|
||||
// from — the address that got them blocked is the one they are typing about.
|
||||
|
||||
@@ -36,11 +36,11 @@ cleanup() {
|
||||
for id in $(admin "$EDGE/admin-api/allow" | tr ',' '\n' | sed -n 's/.*"id":\([0-9]*\).*/\1/p'); do
|
||||
admin -X DELETE "$EDGE/admin-api/allow/$id" >/dev/null 2>&1
|
||||
done
|
||||
# A country rule set by the gate cannot be deleted, only overwritten: the API
|
||||
# has PUT /countries/{code}?allowed= and no DELETE. The gate puts US back to
|
||||
# allowed=true, so the residue is a row that means "not denied", not a policy
|
||||
# change — but it is residue, and the row outlives `compose down` because it
|
||||
# lives in the data volume.
|
||||
# The gate sets a US country rule and removes it again. PUT allowed=true would
|
||||
# leave a row behind that only says "not denied"; DELETE /countries/{code} takes
|
||||
# the rule out, which matters because the row lives in the data volume and
|
||||
# outlives `compose down`.
|
||||
admin -X DELETE "$EDGE/admin-api/countries/US" >/dev/null 2>&1
|
||||
[ "${KEEP_UP:-0}" = 1 ] || docker compose down >/dev/null 2>&1
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
Reference in New Issue
Block a user