using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
///
/// An operator's block used to be forever. The model had ExpiresAt, the engine
/// honoured it (`DecisionEngine` asks `BlockEntry.IsLive`), the listing printed
/// it and the liveness rule around it was fixed in OPEN-28 — but nothing could
/// set it, so "block this for the night" meant "block this, and remember to
/// delete it in the morning". The exemption form already had a minutes field;
/// these tests are the block form getting the same lever (OPEN-51).
///
public sealed class OperatorBlockExpiryTests
{
private const string Blocked = "203.0.113.61";
private const string Other = "203.0.113.62";
private static async Task 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 BlockAsync(EdgeFixture f, object body)
=> await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", body);
private static async Task<(DateTimeOffset? ExpiresAt, bool Live, int Rows)> ReadRowAsync(EdgeFixture f, bool liveOnly)
{
using var response = await f.Client.GetAsync(
$"/admin-api/blocks?live={(liveOnly ? "true" : "false")}&token={EdgeFixture.AdminToken}");
var rows = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync())
.RootElement.EnumerateArray().ToList();
var mine = rows.FirstOrDefault(r => r.GetProperty("sourceKey").GetString() == Blocked);
return (mine.ValueKind == System.Text.Json.JsonValueKind.Undefined ? null : mine.GetProperty("expiresAt").GetDateTimeOffset(),
mine.ValueKind != System.Text.Json.JsonValueKind.Undefined && mine.GetProperty("live").GetBoolean(),
rows.Count);
}
[Fact]
public async Task An_operator_block_with_a_duration_carries_that_expiry_and_the_listing_says_so()
{
await using var f = new EdgeFixture();
var before = DateTimeOffset.UtcNow;
using (var created = await BlockAsync(f, new { ip = Blocked, reason = "incident: block for an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
// Enforced now, and the listing carries the expiry it will stop being
// enforced at — the two halves have to agree.
using (var blocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode);
var (expiresAt, live, _) = await ReadRowAsync(f, liveOnly: true);
Assert.True(live);
Assert.NotNull(expiresAt);
Assert.InRange(expiresAt!.Value, before.AddMinutes(59), DateTimeOffset.UtcNow.AddMinutes(61));
}
[Fact]
public async Task A_duration_outside_the_bound_is_refused_by_name_and_writes_no_block()
{
await using var f = new EdgeFixture();
foreach (var minutes in new[] { 0, -10, 5_256_001 })
{
using var response = await BlockAsync(f, new { ip = Blocked, reason = "bad duration", expiresInMinutes = minutes });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Contains("expiresInMinutes", body);
Assert.Contains(minutes.ToString(), body);
}
// And the refusal is a refusal: nothing was written, so the address is
// still itself.
using (var unblocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.NotFound, unblocked.StatusCode);
var (_, _, rows) = await ReadRowAsync(f, liveOnly: false);
Assert.Equal(0, rows);
}
[Fact]
public async Task An_operator_block_past_its_expiry_stops_being_enforced_and_shows_itself_as_dead()
{
await using var f = new EdgeFixture();
using (var created = await BlockAsync(f, new { ip = Blocked, reason = "block for an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
using (var blocked = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode);
// Move the clock by moving the row, the way the retention tests do: the
// hour passes for this block and for nothing else.
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService();
var row = await db.Blocks.SingleAsync(b => b.SourceKey == Blocked && b.Source == BlockSource.Operator);
row.ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1);
await db.SaveChangesAsync();
}
await f.Service().InvalidateAsync(CancellationToken.None);
// The engine honours the expiry it was always able to read: the source
// is served again, while a second blocked address stays blocked.
using (var created = await BlockAsync(f, new { ip = Other, reason = "still live", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, created.StatusCode);
using (var served = await GetAsync(f, "/anything", Blocked))
Assert.Equal(HttpStatusCode.NotFound, served.StatusCode);
using (var stillBlocked = await GetAsync(f, "/anything", Other))
Assert.Equal(HttpStatusCode.MovedPermanently, stillBlocked.StatusCode);
// And the operator can see the dead row rather than having it vanish
// from the only table that shows it — the OPEN-28 rule, now with an
// expiry the operator actually set.
// The live view is the operator's "who is blocked right now": one row,
// and it is not the expired one.
var (liveViewExpiry, _, liveRows) = await ReadRowAsync(f, liveOnly: true);
Assert.Equal(1, liveRows);
Assert.Null(liveViewExpiry);
var (expiresAt, live, allRows) = await ReadRowAsync(f, liveOnly: false);
Assert.Equal(2, allRows);
Assert.False(live);
Assert.NotNull(expiresAt);
}
[Fact]
public async Task Blocking_the_same_address_again_with_a_duration_moves_the_expiry()
{
await using var f = new EdgeFixture();
using (var first = await BlockAsync(f, new { ip = Blocked, reason = "an hour", expiresInMinutes = 60 }))
Assert.Equal(HttpStatusCode.NoContent, first.StatusCode);
var (firstExpiry, _, _) = await ReadRowAsync(f, liveOnly: true);
await Task.Delay(1100);
using (var second = await BlockAsync(f, new { ip = Blocked, reason = "a day instead", expiresInMinutes = 1440 }))
Assert.Equal(HttpStatusCode.NoContent, second.StatusCode);
var (secondExpiry, live, _) = await ReadRowAsync(f, liveOnly: true);
// The second call means what it says: the expiry moves to the new
// duration from now, it does not keep the hour typed a second ago.
Assert.True(live);
Assert.NotNull(firstExpiry);
Assert.NotNull(secondExpiry);
Assert.True(secondExpiry!.Value > firstExpiry!.Value.AddMinutes(60),
$"first {firstExpiry:O} then {secondExpiry:O}");
Assert.InRange(secondExpiry.Value, DateTimeOffset.UtcNow.AddMinutes(1439), DateTimeOffset.UtcNow.AddMinutes(1441));
}
}