Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/OpenWafDbContext.cs
T
Pavlo Ratushnyi 3959f1fe6b a change to the operator's config leaves a record of itself
Every operator write already changes a row; what was missing is the answer an operator actually asks at 03:00 - when did this rule get here, who cleared that ban, did a document bring this edge's config. Since the transfer landed, an edge can be different from yesterday with nothing on it saying how.

config_changes carries one row per deliberate change: the instant, the section (block, allow, rule, country, policy, config), the action (added, removed, changed, imported), the target the operator typed, their own sentence where one was given, and the surface the change came through. GET /admin-api/changes answers it newest first, capped and paged like every other listing, filterable by section and since, readable by the read-only token because it is a read. A policy record says what moved ("mode Enforce->Off, streakThreshold 3->4") rather than only that something did. /admin-api/state counts the rows and the write failures.

The rulings, because each is a decision and not a detail:

 * Engine bans are not in the log. A ban the engine earned is not a decision somebody made, and the block row already carries its evidence - consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic.
 * An import is one record per section, not one per row: "3 added, 1 already there, 0 past expiry, 0 rejected". A 2 000-row document would otherwise bury a table whose whole use is being readable.
 * The record names the surface, never a person. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record.
 * A record that cannot be written never undoes the change it describes. Enforcement is the product, so the change stands and the failure is counted - changeWriteFailures, changesNotWritten, changeLastError - because "the config changed and the record of it did not land" has to be a sentence an operator can read rather than one that silently never happened.
 * Bounded twice, both keys the operator's: ChangeRetentionDays (30) and ChangeLogMaxRows (5000, oldest dropped first). The age window alone would let a scripted churn grow the table without limit; the cap alone would drop last month's incident record the week someone did a lot of editing.

What the run caught, in order: (1) Two gate assertions were wrong rather than the product - a policy record was asserted in a scene where no policy write had happened yet, and "one imported record per section" was asserted against a stack that had already imported twice, so the assertion now reads the newest imported record instead of counting them. (2) DELETE /admin-api/countries/{code} answers 204, and the new assertion expected 200. (3) A shell trap in the new scene: a $VAR inside a single-quoted python -c is not interpolated, so the first version would have handed python a literal "$CHANGES_BEFORE" instead of a number.

Gates on this tree: build 0 warnings / 0 errors, unit 313/313, integration 298/298 in 23s, smoke 127 passed / 0 failed (14 new), image 262 MB, compose-smoke 278 passed / 0 failed with 0 containers left behind (11 new, against the shipped image), console 90 assertions / 0 failed.

Refs OPEN-64.
2026-10-05 05:58:42 +02:00

204 lines
8.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Ten tables, all small. The edge never queries them on the request path —
/// <see cref="EdgeStateStore"/> holds the snapshot it reads — so the schema is
/// sized for operator inspection and for explaining a ban after the fact, not
/// for throughput.
/// </summary>
public sealed class OpenWafDbContext(DbContextOptions<OpenWafDbContext> options) : DbContext(options)
{
public DbSet<BlockEntry> Blocks => Set<BlockEntry>();
public DbSet<AllowEntry> AllowEntries => Set<AllowEntry>();
public DbSet<SourceObservation> Observations => Set<SourceObservation>();
public DbSet<CountryRule> CountryRules => Set<CountryRule>();
public DbSet<EdgeAlert> Alerts => Set<EdgeAlert>();
public DbSet<PolicySetting> PolicySettings => Set<PolicySetting>();
public DbSet<SourceStreak> Streaks => Set<SourceStreak>();
public DbSet<RequestRule> RequestRules => Set<RequestRule>();
public DbSet<AlertPush> AlertPushes => Set<AlertPush>();
public DbSet<ConfigChange> ConfigChanges => Set<ConfigChange>();
protected override void OnModelCreating(ModelBuilder mb)
{
StoreTimestampsAsIntegersOnSqlite(mb);
mb.Entity<BlockEntry>(e =>
{
e.ToTable("block_entries");
e.HasKey(b => b.Id);
// One row per (source key, provenance): an operator block and an
// engine ban on the same address coexist on purpose — the operator
// entry outlives the ban and must not be overwritten by it.
e.HasIndex(b => new { b.SourceKey, b.Source }).IsUnique();
e.HasIndex(b => b.ExpiresAt);
e.Property(b => b.SourceKey).HasMaxLength(128).IsRequired();
e.Property(b => b.Reason).HasMaxLength(1024);
e.Property(b => b.RedirectTo).HasMaxLength(512);
e.Property(b => b.LastPath).HasMaxLength(512);
e.Property(b => b.LastUserAgent).HasMaxLength(256);
e.Property(b => b.LastCountryCode).HasMaxLength(2);
e.Property(b => b.LastCity).HasMaxLength(128);
e.Property(b => b.LastRegion).HasMaxLength(128);
e.Property(b => b.Source).HasConversion<int>();
});
mb.Entity<ConfigChange>(e =>
{
// The change log (OPEN-64): one row per deliberate change to the
// operator's config. Indexed on the instant because the surface
// reads newest first, and on the section because "what happened to
// the rules" is the question an operator actually asks.
e.ToTable("config_changes");
e.HasKey(c => c.Id);
e.HasIndex(c => c.At);
e.HasIndex(c => c.Section);
e.Property(c => c.Section).HasMaxLength(16).IsRequired();
e.Property(c => c.Action).HasMaxLength(16).IsRequired();
e.Property(c => c.Target).HasMaxLength(ConfigChangeLog.MaxTargetLength).IsRequired();
e.Property(c => c.Detail).HasMaxLength(ConfigChangeLog.MaxDetailLength);
e.Property(c => c.Actor).HasMaxLength(16).IsRequired();
});
mb.Entity<AllowEntry>(e =>
{
e.ToTable("allow_entries");
e.HasKey(a => a.Id);
e.HasIndex(a => a.Match).IsUnique();
e.Property(a => a.Match).HasMaxLength(128).IsRequired();
e.Property(a => a.Note).HasMaxLength(512);
});
mb.Entity<SourceObservation>(e =>
{
e.ToTable("source_observations");
e.HasKey(o => o.SourceKey);
e.Property(o => o.SourceKey).HasMaxLength(128);
e.HasIndex(o => o.LastSeenAt);
e.Property(o => o.LastPath).HasMaxLength(512);
e.Property(o => o.LastUserAgent).HasMaxLength(256);
e.Property(o => o.LastCountryCode).HasMaxLength(2);
e.Property(o => o.LastCity).HasMaxLength(128);
e.Property(o => o.LastRegion).HasMaxLength(128);
});
mb.Entity<SourceStreak>(e =>
{
e.ToTable("source_streaks");
e.HasKey(t => t.SourceKey);
e.Property(t => t.SourceKey).HasMaxLength(128);
e.HasIndex(t => t.LastSeenAt);
e.Property(t => t.LastPath).HasMaxLength(512);
e.Property(t => t.LastUserAgent).HasMaxLength(256);
e.Property(t => t.LastCountryCode).HasMaxLength(2);
e.Property(t => t.LastCity).HasMaxLength(128);
e.Property(t => t.LastRegion).HasMaxLength(128);
// The streak row is written by every edge that sees the source, so
// it is the one table in this schema where two writers routinely
// collide. The token is what turns that collision into a retry
// instead of a lost refusal.
e.Property(t => t.Version).IsConcurrencyToken();
});
mb.Entity<CountryRule>(e =>
{
e.ToTable("country_rules");
e.HasKey(c => c.Code);
e.Property(c => c.Code).HasMaxLength(2);
e.Property(c => c.Name).HasMaxLength(128);
});
mb.Entity<EdgeAlert>(e =>
{
e.ToTable("edge_alerts");
e.HasKey(a => a.Id);
e.HasIndex(a => a.CreatedAt);
e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired();
e.Property(a => a.Kind).HasMaxLength(64).IsRequired();
e.Property(a => a.Detail).HasMaxLength(1024).IsRequired();
});
mb.Entity<RequestRule>(e =>
{
e.ToTable("request_rules");
e.HasKey(r => r.Id);
// Not unique: an expired rule keeps its row, and a unique index
// would let a rule that stopped being true last month refuse the
// same pattern forever. "Two live rules for one pattern" is the
// real mistake, and the API refuses that one by name.
e.HasIndex(r => r.Pattern);
e.HasIndex(r => r.ExpiresAt);
e.Property(r => r.Pattern).HasMaxLength(PathPattern.MaxLength).IsRequired();
e.Property(r => r.Note).HasMaxLength(512);
e.Property(r => r.Action).HasConversion<int>();
});
mb.Entity<AlertPush>(e =>
{
e.ToTable("alert_pushes");
e.HasKey(a => a.Id);
// The worker's query is "not delivered, not given up, due now, not
// claimed", and it runs every couple of seconds against a table that
// retention keeps short. Without this index that query is a scan of
// every delivery this edge has ever owed.
e.HasIndex(a => new { a.PushedAt, a.GivenUpAt, a.NextAttemptAt });
e.HasIndex(a => a.AlertId);
e.Property(a => a.Kind).HasMaxLength(64).IsRequired();
e.Property(a => a.SourceKey).HasMaxLength(128).IsRequired();
e.Property(a => a.Detail).HasMaxLength(1024).IsRequired();
e.Property(a => a.LastError).HasMaxLength(512);
e.Property(a => a.ClaimedBy).HasMaxLength(128);
});
mb.Entity<PolicySetting>(e =>
{
e.ToTable("policy_settings");
e.HasKey(p => p.Key);
e.Property(p => p.Key).HasMaxLength(64);
e.Property(p => p.Value).HasMaxLength(256).IsRequired();
});
}
/// <summary>
/// SQLite has no timestamp type: the provider stores a DateTimeOffset as
/// text and then refuses to compare it, so every "is this ban still live"
/// and "has this observation aged out" query dies at translation time.
/// Storing the instant as an integer makes those comparisons ordinary
/// integer comparisons and keeps the retention rules working on the default
/// provider. PostgreSQL keeps its native timestamptz, where an operator can
/// read the column.
/// </summary>
private void StoreTimestampsAsIntegersOnSqlite(ModelBuilder mb)
{
if (Database.ProviderName?.Contains("Sqlite") != true) return;
var converter = new Microsoft.EntityFrameworkCore.Storage.ValueConversion.DateTimeOffsetToBinaryConverter();
foreach (var entityType in mb.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
var clr = property.ClrType;
if (clr == typeof(DateTimeOffset) || clr == typeof(DateTimeOffset?))
{
property.SetValueConverter(converter);
}
}
}
}
}
/// <summary>
/// Operator-set policy overrides, one row per key, layered over what comes
/// from configuration. Stored as text on purpose: the set of knobs is small and
/// a column per knob would need a migration every time one is added.
/// </summary>
public sealed class PolicySetting
{
public string Key { get; init; } = string.Empty;
public string Value { get; set; } = string.Empty;
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}