A 404 explained one missing row and said nothing about another, and the page answered the silent one with "the admin API is off"
Measured on the shipped image (openwaf:ci 08bebf43, the tree with the
storage-failure fix):
DELETE /admin-api/countries/ZZ -> 404 {"error":"no country rule for \"ZZ\""}
DELETE /admin-api/allow/999999 -> 404, Content-Length: 0
Same status, two qualities of answer. The silent half is what the console then
had to invent an explanation for: apiRaw read EVERY 404 as
"admin api disabled — set OpenWaf__Admin__Token" and threw, so removing a row
that another tab had already removed told the operator to go configure a token
that is already configured. And because the throw landed in a catch that says
nothing, the status line ended up reading "refreshed" in the success colour —
measured in the console gate before the fix:
FAIL a missing row is reported as a missing row… — ok: refreshed 4:50:18 AM
After the fix, on the image built from this tree (4823e9ae):
DELETE /admin-api/allow/999999 -> 404 {"error":"no allow entry with id 999999"}
The page now shows that sentence instead of guessing:
ok a missing row is reported as a missing row, not as the admin API being switched off
— warn: no allow entry with id 999999
Whether the admin surface is switched off at all is no longer inferred from a
status code: the core read (/admin-api/state) is checked for a non-200 and the
edge's own body is shown — "admin api disabled: set OpenWaf__Admin__Token",
which the API already says and which a new test pins.
While in this handler, the most destructive button on the page was found doing
worse than lying: "clear the automatic bans" fired the DELETE and read nothing
back, so cleared 7, cleared 0 and a refused write looked identical after the
reload. It now reports the count the edge gave ("engine bans cleared: 0"), and
the note for the action just taken survives the refresh that action itself
triggered — load() used to overwrite it with "refreshed" inside a second, which
is shorter than the time it takes to read.
Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 109/109 (3 new in NotFoundExplanationTests), smoke 19/0,
compose 43/0, image 261 MB, console 47/47 (2 new assertions).
Dents: allow 404 silent again -> 2 tests fail; apiRaw reading every 404 as
"disabled" -> 2 console assertions fail; clearEngine reading nothing back -> 1;
the action note not held across its own refresh -> 1.
This commit is contained in:
@@ -143,20 +143,26 @@ async function apiRaw(path, opts = {}) {
|
||||
if (token) headers['X-Admin-Token'] = token;
|
||||
const r = await fetch(path, Object.assign({}, opts, { headers }));
|
||||
if (r.status === 401) { note('token rejected', true); throw new Error('401'); }
|
||||
if (r.status === 404) { note('admin api disabled — set OpenWaf__Admin__Token', true); throw new Error('404'); }
|
||||
let body = null;
|
||||
if (r.status !== 204) {
|
||||
try {
|
||||
body = await r.json();
|
||||
} catch (e) {
|
||||
// An empty 5xx is still an answer, and it used to be an answer the page
|
||||
// swallowed: r.json() threw, the caller's catch said "note() already said
|
||||
// why", and nothing had been said. The status line went quiet exactly
|
||||
// when the edge had the worst news to report.
|
||||
// An empty 4xx/5xx is still an answer, and it used to be an answer the
|
||||
// page swallowed: r.json() threw, the caller's catch said "note() already
|
||||
// said why", and nothing had been said. The status line went quiet
|
||||
// exactly when the edge had the worst news to report.
|
||||
body = r.ok ? null : { error: 'the edge answered ' + r.status + ' with no explanation' };
|
||||
}
|
||||
}
|
||||
return { body, total: r.headers.get('X-Total-Count'), truncated: r.headers.get('X-Truncated') === 'true' };
|
||||
// A 404 used to be read here as "the admin API is switched off" — for every
|
||||
// 404, including the one that means "that row is not there" (another tab
|
||||
// removed it, the list on screen is stale). That sentence sent the operator to
|
||||
// set a token that is already set. Whether the surface is off is not something
|
||||
// this function can know from one response; the edge says it in the body when
|
||||
// it is true, so the body is what gets shown.
|
||||
if (r.status === 404 && body === null) body = { error: 'nothing at ' + path };
|
||||
return { body, status: r.status, total: r.headers.get('X-Total-Count'), truncated: r.headers.get('X-Truncated') === 'true' };
|
||||
}
|
||||
|
||||
async function api(path, opts = {}) { return (await apiRaw(path, opts)).body; }
|
||||
@@ -167,6 +173,14 @@ async function api(path, opts = {}) { return (await apiRaw(path, opts)).body; }
|
||||
// repeating the API's old lie: "deleted 0" when nothing could be deleted.
|
||||
let holdNote = false;
|
||||
|
||||
// The note for the action the operator just took, held across the refresh that
|
||||
// action itself triggers. Without the hold, load() — which every action calls,
|
||||
// and which also runs on a 5 s interval — replaced the sentence with
|
||||
// "refreshed" inside a second, which is shorter than the time it takes to read
|
||||
// it. The next refresh says "refreshed" again, so nothing stays on screen
|
||||
// forever.
|
||||
function done(text) { note(text, false); holdNote = true; }
|
||||
|
||||
function failed(r) {
|
||||
if (r.body && r.body.error) { note(r.body.error, true); holdNote = true; return true; }
|
||||
return false;
|
||||
@@ -190,16 +204,27 @@ function row(cells) {
|
||||
async function load() {
|
||||
if (!token) { note('no token', true); return; }
|
||||
try {
|
||||
const [state, blocksRes, obsRes, streaks, countries, rules, allow, alertsRes, geo] = await Promise.all([
|
||||
api('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
|
||||
apiRaw('/admin-api/observations?limit=25'), api('/admin-api/streaks'),
|
||||
api('/admin-api/countries/summary'), api('/admin-api/countries'),
|
||||
api('/admin-api/allow'), apiRaw('/admin-api/alerts?limit=25'),
|
||||
api('/admin-api/geo')
|
||||
const [stateRes, blocksRes, obsRes, streaksRes, countriesRes, rulesRes, allowRes, alertsRes, geoRes] = await Promise.all([
|
||||
apiRaw('/admin-api/state'), apiRaw('/admin-api/blocks?live=false'),
|
||||
apiRaw('/admin-api/observations?limit=25'), apiRaw('/admin-api/streaks'),
|
||||
apiRaw('/admin-api/countries/summary'), apiRaw('/admin-api/countries'),
|
||||
apiRaw('/admin-api/allow'), apiRaw('/admin-api/alerts?limit=25'),
|
||||
apiRaw('/admin-api/geo')
|
||||
]);
|
||||
// The core read decides whether there is anything to draw. When the admin
|
||||
// surface is switched off the edge says so in the body — "admin api
|
||||
// disabled: set OpenWaf__Admin__Token" — and that sentence is what the
|
||||
// operator needs, not a guess this page makes about a status code.
|
||||
if (stateRes.status !== 200) {
|
||||
note((stateRes.body && stateRes.body.error) || ('the edge answered ' + stateRes.status + ' for /admin-api/state'), true);
|
||||
return;
|
||||
}
|
||||
const state = stateRes.body;
|
||||
const blocks = blocksRes.body;
|
||||
const obs = obsRes.body;
|
||||
const alerts = alertsRes.body;
|
||||
const streaks = streaksRes.body, countries = countriesRes.body, rules = rulesRes.body,
|
||||
allow = allowRes.body, geo = geoRes.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
|
||||
@@ -343,7 +368,7 @@ el('addBlock').onclick = async () => {
|
||||
if (!ip) { note('an address first', true); return; }
|
||||
if (await postJson('/admin-api/blocks', { ip, reason: el('blockReason').value.trim() || 'blocked from the console' })) {
|
||||
el('blockIp').value = ''; el('blockReason').value = '';
|
||||
note('blocked ' + ip, false);
|
||||
done('blocked ' + ip);
|
||||
load();
|
||||
}
|
||||
};
|
||||
@@ -368,7 +393,7 @@ el('addAllow').onclick = async () => {
|
||||
note: el('allowNote').value.trim() || 'allowlisted from the console',
|
||||
expiresInMinutes: ttl })) {
|
||||
el('allowMatch').value = ''; el('allowNote').value = ''; el('allowTtl').value = '';
|
||||
note('allowlisted ' + match, false);
|
||||
done('allowlisted ' + match);
|
||||
load();
|
||||
}
|
||||
};
|
||||
@@ -385,16 +410,16 @@ document.addEventListener('click', async (e) => {
|
||||
try {
|
||||
if (b.dataset.act === 'delblock') {
|
||||
const r = await apiRaw('/admin-api/blocks?key=' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||
if (!failed(r)) note('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)', false);
|
||||
if (!failed(r)) done('deleted ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?') + ' block(s)');
|
||||
} else if (b.dataset.act === 'delallow') {
|
||||
const r = await apiRaw('/admin-api/allow/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||
if (!failed(r)) note('allow entry removed', false);
|
||||
if (!failed(r)) done('allow entry removed');
|
||||
} else if (b.dataset.act === 'country') {
|
||||
const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k) + '?allowed=' + b.dataset.allowed, { method: 'PUT' });
|
||||
if (!failed(r)) note('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'), false);
|
||||
if (!failed(r)) done('country ' + b.dataset.k + ' → ' + (b.dataset.allowed === 'true' ? 'allowed' : 'denied'));
|
||||
} else if (b.dataset.act === 'countrydel') {
|
||||
const r = await apiRaw('/admin-api/countries/' + encodeURIComponent(b.dataset.k), { method: 'DELETE' });
|
||||
if (!failed(r)) note('country rule ' + b.dataset.k + ' removed', false);
|
||||
if (!failed(r)) done('country rule ' + b.dataset.k + ' removed');
|
||||
}
|
||||
load();
|
||||
} catch (err) { /* note() already said why */ }
|
||||
@@ -409,11 +434,16 @@ el('setMode').onclick = async () => {
|
||||
const wanted = el('mode').value;
|
||||
const r = await apiRaw('/admin-api/policy', { method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mode: wanted }) });
|
||||
if (!failed(r)) note('mode → ' + wanted, false);
|
||||
if (!failed(r)) done('mode → ' + wanted);
|
||||
load();
|
||||
};
|
||||
el('clearEngine').onclick = async () => {
|
||||
await api('/admin-api/blocks?source=engine', { method: 'DELETE' });
|
||||
// The most destructive button on the page, and it used to fire the DELETE and
|
||||
// read nothing back: whatever the edge answered — cleared 7, cleared 0, or
|
||||
// "the block list could not be written" — the page reloaded and looked the
|
||||
// same. The count is the only part of this the operator can act on.
|
||||
const r = await apiRaw('/admin-api/blocks?source=engine', { method: 'DELETE' });
|
||||
if (!failed(r)) done('engine bans cleared: ' + (r.body && r.body.deleted !== undefined ? r.body.deleted : '?'));
|
||||
load();
|
||||
};
|
||||
setInterval(load, 5000);
|
||||
|
||||
@@ -161,7 +161,13 @@ internal static class AdminEndpoints
|
||||
{
|
||||
var n = await db.AllowEntries.Where(a => a.Id == id).ExecuteDeleteAsync(ct);
|
||||
await state.InvalidateAsync(ct);
|
||||
return n > 0 ? Results.NoContent() : Results.NotFound();
|
||||
// The country-rule delete names the row it could not find. This one
|
||||
// answered 404 with Content-Length: 0, so the same API explained one
|
||||
// missing row and said nothing about another — and an empty 404 is
|
||||
// exactly the answer a page then has to guess about.
|
||||
return n > 0
|
||||
? Results.NoContent()
|
||||
: Results.NotFound(new { error = $"no allow entry with id {id}" });
|
||||
});
|
||||
|
||||
group.MapGet("/policy", (EdgePolicyProvider policy) => Results.Ok(ToDto(policy.Current)));
|
||||
|
||||
@@ -26,13 +26,17 @@ internal sealed class EdgeFixture : IAsyncDisposable
|
||||
string streakWindow = "00:05:00",
|
||||
string banDuration = "01:00:00",
|
||||
string geo = "Off",
|
||||
int? refreshTtlSeconds = null)
|
||||
int? refreshTtlSeconds = null,
|
||||
string? adminToken = AdminToken)
|
||||
{
|
||||
Factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:OpenWaf", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("Database:Provider", "sqlite");
|
||||
builder.UseSetting("OpenWaf:Admin:Token", AdminToken);
|
||||
// An empty token is a real configuration, not a missing one: it is
|
||||
// how the admin surface is switched off, and a test that asserts what
|
||||
// the page sees has to be able to ask for it.
|
||||
builder.UseSetting("OpenWaf:Admin:Token", adminToken ?? "");
|
||||
builder.UseSetting("OpenWaf:Policy:Mode", mode);
|
||||
builder.UseSetting("OpenWaf:Policy:StreakThreshold", threshold.ToString());
|
||||
builder.UseSetting("OpenWaf:Policy:StreakWindow", streakWindow);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OpenWaf.Tests.Integration;
|
||||
|
||||
/// <summary>
|
||||
/// A 404 is an answer, and until now this API gave two different qualities of
|
||||
/// answer and the page guessed across them.
|
||||
///
|
||||
/// Measured on the shipped image (openwaf:ci, 08bebf43):
|
||||
/// DELETE /admin-api/countries/ZZ → 404 {"error":"no country rule for \"ZZ\""}
|
||||
/// DELETE /admin-api/allow/999999 → 404, Content-Length: 0
|
||||
/// Same status, one explained and one silent. The silent half is what the
|
||||
/// console then had to invent an explanation for: apiRaw read every 404 as
|
||||
/// "admin api disabled — set OpenWaf__Admin__Token" and threw, so removing a row
|
||||
/// that another tab had already removed told the operator to configure a token
|
||||
/// that is already configured — and because the throw landed in a catch that
|
||||
/// said nothing, the status line ended up reading "refreshed" in the success
|
||||
/// colour. Measured in the console gate before the fix:
|
||||
/// FAIL a missing row is reported as a missing row… — ok: refreshed 4:50:18 AM
|
||||
/// </summary>
|
||||
public sealed class NotFoundExplanationTests
|
||||
{
|
||||
private static async Task<(HttpStatusCode Status, string Body)> AdminAsync(
|
||||
EdgeFixture f, HttpMethod method, string url, string? json = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, url);
|
||||
if (json is not null)
|
||||
request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
using var response = await f.Client.SendAsync(request);
|
||||
return (response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_missing_allow_entry_names_the_id_that_was_not_there()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
|
||||
var (status, body) = await AdminAsync(f, HttpMethod.Delete, "/admin-api/allow/999999");
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, status);
|
||||
Assert.NotEmpty(body);
|
||||
Assert.Equal("no allow entry with id 999999",
|
||||
JsonDocument.Parse(body).RootElement.GetProperty("error").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_allow_entry_that_is_there_is_removed_with_no_body_and_the_row_goes()
|
||||
{
|
||||
await using var f = new EdgeFixture();
|
||||
|
||||
var (created, _) = await AdminAsync(f, HttpMethod.Post, "/admin-api/allow",
|
||||
"""{"match":"203.0.113.77/32","note":"probe"}""");
|
||||
Assert.Equal(HttpStatusCode.NoContent, created);
|
||||
|
||||
var listed = await AdminAsync(f, HttpMethod.Get, "/admin-api/allow");
|
||||
var id = JsonDocument.Parse(listed.Body).RootElement[0].GetProperty("id").GetInt64();
|
||||
|
||||
var (removed, removedBody) = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/allow/{id}");
|
||||
Assert.Equal(HttpStatusCode.NoContent, removed);
|
||||
Assert.Equal("", removedBody);
|
||||
|
||||
var after = await AdminAsync(f, HttpMethod.Get, "/admin-api/allow");
|
||||
Assert.Equal("[]", after.Body);
|
||||
|
||||
// Removing it twice is the stale-tab case, and it names the id.
|
||||
var (again, againBody) = await AdminAsync(f, HttpMethod.Delete, $"/admin-api/allow/{id}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, again);
|
||||
Assert.Contains($"no allow entry with id {id}", againBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_closed_admin_surface_says_so_in_the_body_not_only_in_the_status()
|
||||
{
|
||||
// The console no longer guesses "the admin API is off" from a 404; it
|
||||
// shows what the edge said. That is only honest while the edge does say
|
||||
// it, so this pins the sentence.
|
||||
// "Closed" has to be asked for in both places. Program reads the token
|
||||
// from configuration and falls back to OPENWAF_ADMIN_TOKEN when that is
|
||||
// blank, and the gate scripts export a throwaway value into the test
|
||||
// process — so a blank configured token with the environment set is an
|
||||
// OPEN surface (measured: the request came back 401, not 404). Only this
|
||||
// fixture leaves its configured token blank, so clearing the variable
|
||||
// for the duration of this test cannot change what another one sees.
|
||||
var saved = Environment.GetEnvironmentVariable("OPENWAF_ADMIN_TOKEN");
|
||||
Environment.SetEnvironmentVariable("OPENWAF_ADMIN_TOKEN", null);
|
||||
try
|
||||
{
|
||||
await using var f = new EdgeFixture(adminToken: "");
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
|
||||
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
|
||||
using var response = await f.Client.SendAsync(request);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal("admin api disabled: set OpenWaf__Admin__Token",
|
||||
JsonDocument.Parse(body).RootElement.GetProperty("error").GetString());
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (saved is not null) Environment.SetEnvironmentVariable("OPENWAF_ADMIN_TOKEN", saved);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -372,6 +372,43 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
|
||||
/refusing to delete every block/.test(refusedStatus) && refusedClass === 'warn',
|
||||
`${refusedClass}: ${refusedStatus}`);
|
||||
|
||||
// The other half of the same handler: what a 404 means. apiRaw used to read
|
||||
// EVERY 404 as "the admin API is switched off" and throw, so a row that is
|
||||
// simply not there — the stale-tab case, another operator removed it first —
|
||||
// told this operator to go set a token that is already set. The button is
|
||||
// synthetic for the same reason as above: the page only renders a remove
|
||||
// button for a row it has, and the handler is delegated on the document.
|
||||
await page.evaluate(() => {
|
||||
const b = document.createElement('button');
|
||||
b.id = 'c27-refused-allow';
|
||||
b.dataset.act = 'delallow';
|
||||
b.dataset.k = '999999';
|
||||
document.body.appendChild(b);
|
||||
});
|
||||
await page.click('#c27-refused-allow');
|
||||
await page.waitForFunction(
|
||||
() => /allow entry|not found|no allow/i.test(document.getElementById('status').textContent),
|
||||
null, { timeout: 10000 }).catch(() => {});
|
||||
const missingStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||||
const missingClass = await page.getAttribute('#status', 'class');
|
||||
await page.evaluate(() => { const b = document.getElementById('c27-refused-allow'); if (b) b.remove(); });
|
||||
check('a missing row is reported as a missing row, not as the admin API being switched off',
|
||||
/no allow entry with id 999999/.test(missingStatus) && missingClass === 'warn',
|
||||
`${missingClass}: ${missingStatus}`);
|
||||
|
||||
// "Clear the automatic bans" is the most destructive button on the page and
|
||||
// used to read nothing back from the DELETE — cleared 7, cleared 0 and a
|
||||
// refused write all looked identical after the reload. The stand has no engine
|
||||
// bans at this point, so the honest answer is a count of 0, and the point of
|
||||
// the assertion is that a count is said at all.
|
||||
await page.click('#clearEngine');
|
||||
await page.waitForFunction(
|
||||
() => /engine bans cleared/.test(document.getElementById('status').textContent),
|
||||
null, { timeout: 10000 }).catch(() => {});
|
||||
const clearedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
|
||||
check('the button that clears automatic bans says what the edge answered',
|
||||
/engine bans cleared: \d+/.test(clearedStatus), clearedStatus);
|
||||
|
||||
// A phone in dark mode is the case an operator actually reaches the console
|
||||
// from — the address that got them blocked is the one they are typing about.
|
||||
// Both halves of this used to be broken and measured: the page overflowed a
|
||||
|
||||
Reference in New Issue
Block a user