A healed storage failure returned the edge to ready without waiting for traffic

OPEN-34, measured on the shipped image before this change. With writes to
block_entries aborted, five refusals produced counted write failures and
/readyz 503. The triggers were then REMOVED — write path healthy, zero triggers
left — and no further request was sent from that source:

  t+30 s  /readyz 503   /state: banWriteFailures 3, bansNotWritten 3
  t+60 s  /readyz 503   unchanged
  t+90 s  /readyz 503   unchanged
  t+120 s /readyz 503   unchanged

The ban pillar clears only on a successful ban write, and the only thing that
produced one was the source crossing the threshold again. Readiness — the
signal an orchestrator uses to keep an edge in rotation — was therefore coupled
to attack traffic: the quieter the site, the longer a repaired edge sat out of
service, enforcing everything except one ban nobody had written.

The fix is on the write side, not on the gate. A ban the engine decided and
could not write is kept as a PendingBan and re-attempted by a hosted loop on the
same 15 s cadence the other writers use; the sentence still runs from the moment
the ban was decided, so a retry that lands late cannot quietly lengthen it, and a
pending ban whose sentence expired before it could be written is counted
(bansNeverEnforced) and reported rather than rewritten as a fresh, longer ban.
/state gained bansPendingRetry and bansNeverEnforced, because without the first
a healed storage failure is indistinguishable from a quiet site.

Teeth: PendingBanRetryTests (3) — the retry landing with no further request, the
hosted loop doing it on its own (nobody calls it in that test), and an expired
pending ban reported rather than written late. Compose gate gained a 5-assertion
scene against the shipped image: the failed ban is queued, readiness returns
after the repair with no traffic from that source, the ban reaches storage, the
queue empties, and the source that was never banned during the break answers 403
afterwards.

Gates at this commit — macOS host: unit 128/128, integration 141/141, smoke
28/0, compose 86/0, console 58/0, 0 containers left behind. Linux rehearsal,
all three stages: PASS — source (128/128, 141/141, 28/0), compose 86/0 with
enforcement lag 13 ms, console 58/0, 0 containers left behind.
This commit is contained in:
Pavlo Ratushnyi
2026-10-02 11:34:44 +02:00
parent db146271c8
commit dcf8a733a9
6 changed files with 396 additions and 21 deletions
+7 -1
View File
@@ -426,7 +426,7 @@ internal static class AdminEndpoints
supportsCity = geo.Info?.SupportsCity ?? false
}));
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability) =>
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability, BlockStore blockStore) =>
{
var now = DateTimeOffset.UtcNow;
var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now));
@@ -483,6 +483,12 @@ internal static class AdminEndpoints
bansNotWritten = durability.Get(DurabilityHealth.Bans).EntriesLost,
banLastWriteError = durability.Get(DurabilityHealth.Bans).LastError,
banLastWriteAt = durability.Get(DurabilityHealth.Bans).LastSuccessAt,
// The two numbers that say what happens to a ban that failed to
// reach storage: how many are waiting to be written again, and how
// many expired before a retry could land. Without the first, a
// healed storage failure looks indistinguishable from a quiet site.
bansPendingRetry = blockStore.PendingBanRetries,
bansNeverEnforced = blockStore.BansNeverEnforced,
observationWriteFailures = durability.Get(DurabilityHealth.Observations).Failures,
observationsLost = durability.Get(DurabilityHealth.Observations).EntriesLost,
observationLastWriteError = durability.Get(DurabilityHealth.Observations).LastError,
+1
View File
@@ -68,6 +68,7 @@ builder.Services.AddSingleton<ObservationWriter>();
builder.Services.AddSingleton<RetentionWorker>();
builder.Services.AddHostedService(sp => sp.GetRequiredService<ObservationWriter>());
builder.Services.AddHostedService(sp => sp.GetRequiredService<RetentionWorker>());
builder.Services.AddHostedService<PendingBanRetryWorker>();
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -51,13 +52,90 @@ public sealed class BlockStore
/// blocked must not be able to extend its own sentence indefinitely. Its
/// evidence is refreshed so the operator sees the latest probe.
/// </summary>
public async Task<BlockEntry?> BanAsync(StreakSnapshot streak, int statusCode, DateTimeOffset now, CancellationToken ct = default)
public Task<BlockEntry?> BanAsync(StreakSnapshot streak, int statusCode, DateTimeOffset now, CancellationToken ct = default)
=> WriteBanAsync(PendingBan.From(streak, statusCode, now), now, ct);
/// <summary>
/// A ban the engine decided and could not write, kept in memory so the retry
/// does not depend on the source offending again.
///
/// Measured on the shipped image (2026-10-02): with writes to block_entries
/// aborted, five refusals produced three counted write failures and
/// /readyz 503. The triggers were then REMOVED — the write path healthy,
/// zero triggers left — and no further traffic was sent. /readyz answered 503
/// at t+30, t+60, t+90 and t+120 s with the counters unmoved. The only thing
/// that clears the counter is a successful ban write, and the only thing that
/// produced one was the attacker coming back. So an edge that enforces
/// everything except one ban it decided during a storage blip sat out of
/// rotation for as long as the site stayed quiet: the recovery signal was
/// attacker traffic.
///
/// The sentence still runs from DecidedAt, so a retry that lands late does
/// not quietly extend a ban; and a pending ban whose sentence has already
/// expired is reported as never enforced rather than written as a fresh one.
/// </summary>
public sealed record PendingBan(
string SourceKey, int ConsecutiveRefusals, int StatusCode, string? Path, string? UserAgent,
string? CountryCode, string? City, string? Region, DateTimeOffset DecidedAt)
{
public static PendingBan From(StreakSnapshot s, int statusCode, DateTimeOffset now) => new(
s.SourceKey, s.MaxConsecutiveRefusals, statusCode, s.LastPath, s.LastUserAgent,
s.LastCountryCode, s.LastCity, s.LastRegion, now);
}
/// <summary>Pending bans waiting to be written. Bounded by the number of
/// distinct sources the engine has decided to ban, which is bounded by the
/// streak map; a dead database cannot grow it without limit.</summary>
private readonly ConcurrentDictionary<string, PendingBan> _pendingBans = new(StringComparer.Ordinal);
private long _bansNeverEnforced;
public int PendingBanRetries => _pendingBans.Count;
/// <summary>Bans that were decided, failed to reach storage, and whose
/// sentence expired before a retry could land. Cumulative: a ban that was
/// never enforced is a hole in the record, not a gauge.</summary>
public long BansNeverEnforced => Interlocked.Read(ref _bansNeverEnforced);
/// <summary>
/// Re-attempt every ban that failed to reach storage. Called by
/// <see cref="PendingBanRetryWorker"/> on the same cadence the other writers
/// use, so a storage failure that heals returns the edge to ready without
/// waiting for traffic.
/// </summary>
public async Task<int> RetryPendingBansAsync(CancellationToken ct = default)
{
if (_pendingBans.IsEmpty) return 0;
var now = DateTimeOffset.UtcNow;
var policy = _policy.Current;
var written = 0;
foreach (var (_, ban) in _pendingBans.ToArray())
{
if (ban.DecidedAt + policy.BanDuration <= now)
{
if (_pendingBans.TryRemove(ban.SourceKey, out _))
{
Interlocked.Increment(ref _bansNeverEnforced);
_log.LogWarning(
"BlockStore: a ban decided for {Key} at {Decided} expired before it could be written. "
+ "It was never enforced by any edge.", ban.SourceKey, ban.DecidedAt);
}
continue;
}
await WriteBanAsync(ban, now, ct);
if (!_pendingBans.ContainsKey(ban.SourceKey)) written++;
}
return written;
}
private async Task<BlockEntry?> WriteBanAsync(PendingBan ban, DateTimeOffset now, CancellationToken ct)
{
var policy = _policy.Current;
var expiresAt = now + policy.BanDuration;
var reason = $"{streak.MaxConsecutiveRefusals} consecutive refusals " +
// From when the ban was decided, not from when a retry landed: a write
// that arrives late must not silently lengthen the sentence.
var expiresAt = ban.DecidedAt + policy.BanDuration;
var reason = $"{ban.ConsecutiveRefusals} consecutive refusals " +
$"({policy.RefusalRange}) within {policy.StreakWindow.TotalMinutes:0.#} min; " +
$"last {statusCode} {(streak.LastPath is null ? "" : streak.LastPath)}";
$"last {ban.StatusCode} {(ban.Path is null ? "" : ban.Path)}";
// Serialised: the observer runs after the response has been written,
// so the next request from the same source can arrive while this ban is
@@ -69,18 +147,18 @@ public sealed class BlockStore
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var existing = await db.Blocks
.FirstOrDefaultAsync(b => b.SourceKey == streak.SourceKey && b.Source == BlockSource.Engine, ct);
.FirstOrDefaultAsync(b => b.SourceKey == ban.SourceKey && b.Source == BlockSource.Engine, ct);
if (existing is null)
{
existing = new BlockEntry
{
SourceKey = streak.SourceKey,
SourceKey = ban.SourceKey,
Source = BlockSource.Engine,
CreatedAt = now,
ExpiresAt = expiresAt,
Reason = reason,
ConsecutiveRefusals = streak.MaxConsecutiveRefusals
ConsecutiveRefusals = ban.ConsecutiveRefusals
};
db.Blocks.Add(existing);
}
@@ -89,21 +167,22 @@ public sealed class BlockStore
existing.CreatedAt = now;
existing.ExpiresAt = expiresAt;
existing.Reason = reason;
existing.ConsecutiveRefusals = streak.MaxConsecutiveRefusals;
existing.ConsecutiveRefusals = ban.ConsecutiveRefusals;
}
existing.LastStatusCode = statusCode;
existing.LastPath = streak.LastPath;
existing.LastUserAgent = streak.LastUserAgent;
existing.LastCountryCode = streak.LastCountryCode;
existing.LastCity = streak.LastCity;
existing.LastRegion = streak.LastRegion;
existing.LastStatusCode = ban.StatusCode;
existing.LastPath = ban.Path;
existing.LastUserAgent = ban.UserAgent;
existing.LastCountryCode = ban.CountryCode;
existing.LastCity = ban.City;
existing.LastRegion = ban.Region;
await db.SaveChangesAsync(ct);
// Clears the counter only when a ban actually reached storage, so
// readiness comes back on evidence rather than on the passage of
// time.
_health.RecordSuccess(DurabilityHealth.Bans, 1);
_pendingBans.TryRemove(ban.SourceKey, out _);
await _state.InvalidateAsync(ct);
return existing;
}
@@ -125,17 +204,21 @@ public sealed class BlockStore
// for this source and provenance means somebody won the race; no
// row — or a read that cannot run either — means the write never
// happened and the ban is not in force anywhere.
if (await HasLiveEngineBanAsync(streak.SourceKey, now, ct))
if (await HasLiveEngineBanAsync(ban.SourceKey, now, ct))
{
_log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", streak.SourceKey);
// Somebody else's ban is in force, so this one is not pending:
// leaving it queued would retry a write that is already settled.
_pendingBans.TryRemove(ban.SourceKey, out _);
_log.LogWarning(ex, "BlockStore: concurrent ban on {Key}; keeping the winner.", ban.SourceKey);
return null;
}
_health.RecordFailure(DurabilityHealth.Bans, ex, 1);
_pendingBans[ban.SourceKey] = ban;
_log.LogWarning(ex,
"BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement "
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The next refusal "
+ "from this source retries the write.", streak.SourceKey);
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The write is "
+ "queued for retry; it does not wait for this source to offend again.", ban.SourceKey);
return null;
}
catch (Exception ex)
@@ -143,10 +226,11 @@ public sealed class BlockStore
// A ban that could not be written must not take the request down.
// The streak is still in memory, so the next refusal retries.
_health.RecordFailure(DurabilityHealth.Bans, ex, 1);
_pendingBans[ban.SourceKey] = ban;
_log.LogWarning(ex,
"BlockStore: could not persist a ban for {Key}. This edge is NOT enforcing it — enforcement "
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The next refusal "
+ "from this source retries the write.", streak.SourceKey);
+ "reads the snapshot, and the snapshot is built from storage — so no edge is. The write is "
+ "queued for retry; it does not wait for this source to offend again.", ban.SourceKey);
return null;
}
finally
@@ -0,0 +1,62 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Re-attempts the bans the engine decided and could not write.
///
/// Without this, a ban-write failure is only repaired by the attacker coming
/// back. Measured on the shipped image (2026-10-02): writes to block_entries
/// aborted by triggers, five refusals, then the triggers REMOVED — write path
/// healthy, zero triggers — and no further traffic. /readyz answered 503 at
/// t+30, t+60, t+90 and t+120 s with banWriteFailures and bansNotWritten
/// unmoved, because the only event that clears the ban pillar is a successful
/// ban write and the only thing that produced one was a fresh threshold
/// crossing. Readiness — what an orchestrator uses to keep an edge in rotation
/// — was coupled to attack traffic.
///
/// The cadence matches the other writers (15 s) and the work is bounded by the
/// pending set, which is bounded by the number of distinct sources the engine
/// has decided to ban. A dead database cannot turn this into a hot loop over an
/// unbounded set; it retries the same small set, and the ban pillar's counter
/// already says that is happening.
/// </summary>
public sealed class PendingBanRetryWorker : BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(15);
private readonly BlockStore _store;
private readonly ILogger<PendingBanRetryWorker> _log;
public PendingBanRetryWorker(BlockStore store, ILogger<PendingBanRetryWorker> log)
{
_store = store;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(Interval, stoppingToken); }
catch (TaskCanceledException) { return; }
try
{
var written = await _store.RetryPendingBansAsync(stoppingToken);
if (written > 0)
_log.LogInformation("PendingBanRetry: {Count} ban(s) that had failed to reach storage are "
+ "now in force; readiness returns on this write, not on a timer.", written);
}
catch (OperationCanceledException) { return; }
catch (Exception ex)
{
// The retry pass failing is itself a write-path event, and the
// ban pillar's counter is what the operator sees; logging here
// keeps the loop alive so the next pass can try again.
_log.LogWarning(ex, "PendingBanRetry: the retry pass failed; {Count} ban(s) still pending.",
_store.PendingBanRetries);
}
}
}
}
@@ -0,0 +1,169 @@
using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// A ban the engine decided and could not write used to be repaired only by the
/// attacker coming back. Measured on the shipped image (2026-10-02): writes to
/// block_entries aborted by SQLite triggers, five refusals from one source at a
/// threshold of 3, then the triggers REMOVED — write path healthy, zero
/// triggers — and no further traffic sent:
///
/// t+30 s GET /readyz → 503 /state: banWriteFailures 3, bansNotWritten 3
/// t+60 s GET /readyz → 503 (unchanged)
/// t+90 s GET /readyz → 503 (unchanged)
/// t+120 s GET /readyz → 503 (unchanged)
///
/// The ban pillar's counter clears only on a successful ban write, and the only
/// thing that produced one was a fresh threshold crossing. So readiness — the
/// signal an orchestrator uses to keep an edge in rotation — was coupled to
/// attack traffic: the quieter the site, the longer a healed edge stayed out of
/// service, enforcing everything except one ban nobody had written.
/// </summary>
public sealed class PendingBanRetryTests
{
private const string Scanner = "203.0.113.241";
private static async Task RunSql(EdgeFixture f, string sql)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
await db.Database.ExecuteSqlRawAsync(sql);
}
private static async Task BlockBanWrites(EdgeFixture f)
{
foreach (var op in new[] { "INSERT", "UPDATE" })
await RunSql(f, $"""CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END""");
}
private static async Task UnblockWrites(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var names = await db.Database
.SqlQueryRaw<string>(""""SELECT name FROM sqlite_master WHERE type='trigger'"""")
.ToListAsync();
foreach (var name in names) await RunSql(f, $"""DROP TRIGGER IF EXISTS "{name}" """);
}
private static async Task<JsonElement> StateAsync(EdgeFixture f)
{
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);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
}
private static async Task<HttpStatusCode> ReadyAsync(EdgeFixture f)
=> (await f.Client.GetAsync("/readyz")).StatusCode;
private static async Task<string> BlocksRawAsync(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var rows = await db.Blocks.AsNoTracking().ToListAsync();
return string.Join(" | ", rows.Select(b =>
$"{b.SourceKey}/{b.Source} created={b.CreatedAt:HH:mm:ss} expires={b.ExpiresAt:HH:mm:ss} now={DateTimeOffset.UtcNow:HH:mm:ss}"));
}
private static async Task<int> EngineBansAsync(EdgeFixture f)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/blocks?source=engine&limit=1000");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetArrayLength();
}
private static async Task RefuseAsync(EdgeFixture f, int times)
{
for (var i = 1; i <= times; i++) await f.SendAsync(f.Client, $"/probe-{i}", Scanner);
}
[Fact]
public async Task A_ban_that_failed_to_write_lands_without_the_source_offending_again()
{
await using var f = new EdgeFixture(threshold: 3);
await BlockBanWrites(f);
await RefuseAsync(f, 4);
Assert.Equal(HttpStatusCode.ServiceUnavailable, await ReadyAsync(f));
var broken = await StateAsync(f);
Assert.True(broken.GetProperty("banWriteFailures").GetInt32() >= 1, $"/state: {broken}");
Assert.True(broken.GetProperty("bansPendingRetry").GetInt32() >= 1,
$"the failed ban was not queued for retry: {broken}");
Assert.Equal(0, await EngineBansAsync(f));
// The storage failure is repaired. Nothing else happens: no further
// request from this source, no new threshold crossing.
await UnblockWrites(f);
await f.Service<BlockStore>().RetryPendingBansAsync();
Assert.Equal(1, await EngineBansAsync(f));
Assert.Equal(HttpStatusCode.OK, await ReadyAsync(f));
var healed = await StateAsync(f);
Assert.Equal(0, healed.GetProperty("banWriteFailures").GetInt32());
Assert.Equal(0, healed.GetProperty("bansPendingRetry").GetInt32());
// And the ban is actually in force on the wire, which is the whole point
// of writing it: this request is the proof, not the trigger.
// The request has to carry the same source address the ban was written
// for: the fixture trusts proxy headers, and a request without one is a
// different source and answers 404 honestly.
using var request = new HttpRequestMessage(HttpMethod.Get, "/probe-1");
request.Headers.TryAddWithoutValidation("X-Forwarded-For", Scanner);
using var blocked = await f.Client.SendAsync(request);
var rows = await BlocksRawAsync(f);
Assert.True(blocked.StatusCode == HttpStatusCode.Forbidden,
$"expected the retried ban to be in force on the wire; got {(int)blocked.StatusCode}; "
+ $"raw block rows: {rows}; state: {await StateAsync(f)}");
}
[Fact]
public async Task The_retry_loop_runs_on_its_own_so_readiness_does_not_wait_for_traffic()
{
await using var f = new EdgeFixture(threshold: 3);
await BlockBanWrites(f);
await RefuseAsync(f, 4);
Assert.Equal(HttpStatusCode.ServiceUnavailable, await ReadyAsync(f));
await UnblockWrites(f);
// Nobody calls RetryPendingBansAsync here: the assertion is that the
// hosted loop does, on the same cadence the other writers use.
var status = HttpStatusCode.ServiceUnavailable;
for (var attempt = 0; attempt < 12 && status != HttpStatusCode.OK; attempt++)
{
await Task.Delay(2000);
status = await ReadyAsync(f);
}
Assert.Equal(HttpStatusCode.OK, status);
Assert.Equal(1, await EngineBansAsync(f));
}
[Fact]
public async Task A_pending_ban_whose_sentence_expired_is_reported_rather_than_written_late()
{
// One second of ban duration, so the sentence really does expire while the
// write is pending. Writing it after that would hand the operator a ban
// that starts later than the one the engine decided — a different, longer
// sentence wearing the old decision's clothes.
await using var f = new EdgeFixture(threshold: 3, banDuration: "00:00:01");
await BlockBanWrites(f);
await RefuseAsync(f, 4);
await UnblockWrites(f);
await Task.Delay(2000);
await f.Service<BlockStore>().RetryPendingBansAsync();
var state = await StateAsync(f);
Assert.Equal(0, state.GetProperty("bansPendingRetry").GetInt32());
Assert.True(state.GetProperty("bansNeverEnforced").GetInt64() >= 1,
$"an expired pending ban was dropped without being counted: {state}");
Assert.Equal(0, await EngineBansAsync(f));
}
}
+53
View File
@@ -584,6 +584,59 @@ check 'the ban lands on a later refusal once the write path heals' 'yes' \
"$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$BAN_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'and readiness returns on that write, not on a timer' '200' "$(code "$EDGE/readyz")"
echo '- a ban that failed to write is retried without waiting for the attacker'
# The consequence of the fix above, measured before it existed: with the ban
# write path broken and then REPAIRED (triggers dropped, zero triggers left) and
# no further traffic from the source, /readyz answered 503 at t+30, t+60, t+90
# and t+120 s with banWriteFailures and bansNotWritten unmoved. The only event
# that cleared the ban pillar was a successful ban write, and the only thing
# that produced one was the source crossing the threshold again — so the signal
# an orchestrator uses to keep an edge in rotation was coupled to attack
# traffic, and the quieter the site, the longer a healed edge sat out of service.
RETRY_SRC=203.0.113.242
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for op in ("INSERT", "UPDATE"):
c.execute(f'CREATE TRIGGER "gate_block_entries_{op}" BEFORE {op} ON "block_entries" '
"BEGIN SELECT RAISE(ABORT, 'gate: ban write blocked'); END")
print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
admin -X PUT -H 'Content-Type: application/json' \
-d '{"streakThreshold":3,"trustProxyHeaders":true}' "$EDGE/admin-api/policy" >/dev/null
for i in $(seq 1 5); do code -H "$(xff "$RETRY_SRC")" "$EDGE/retry-$i" >/dev/null; done
PENDING=0
for _ in $(seq 1 10); do
PENDING=$(admin "$EDGE/admin-api/state" | jval bansPendingRetry)
[ "${PENDING:-0}" != "0" ] && break
sleep 3
done
printf ' info bans queued for retry while storage refuses them: %s\n' "$PENDING"
check 'the failed ban is queued for retry rather than left to the next attack' 'yes' \
"$([ "${PENDING:-0}" -ge 1 ] && echo yes || echo no)"
# Repair the storage failure. Nothing else is sent from this source: that is the
# whole point of the scene.
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for r in list(c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")):
c.execute(f'DROP TRIGGER "{r[0]}"')
print("triggers after repair:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
RETRY_READY=000
for _ in $(seq 1 20); do
RETRY_READY=$(code "$EDGE/readyz")
[ "$RETRY_READY" = "200" ] && break
sleep 3
done
printf ' info readiness after the repair, with no further request from that source: %s\n' "$RETRY_READY"
check 'readiness returns on the retry, not on attacker traffic' '200' "$RETRY_READY"
check 'and the ban the edge decided hours of polling ago is now in storage' 'yes' \
"$(admin "$EDGE/admin-api/blocks?source=engine" | jcount "b['sourceKey']=='$RETRY_SRC'" | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'the pending queue is empty again' '0' "$(admin "$EDGE/admin-api/state" | jval bansPendingRetry)"
check 'and the source that was never banned during the break is banned on the wire' '403' \
"$(code -H "$(xff "$RETRY_SRC")" "$EDGE/retry-6")"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]