The edge-wide budget is one number for the whole site, and for a login path that number is always wrong: a hundred requests a minute does not stop a credential-stuffing run that makes twenty attempts a minute — twenty looks like a person — while five a minute locks an honest office behind one NAT out of every page they own. The only way to make both statements true is to price the paths differently. The rulings this had to make, and the answer each one got: * A rate rule is not a path rule. A path rule refuses a request because of what it asked for; a budget refuses it because of how often that source asked. The pattern language is shared because the thing being described — this path and what hangs off it — is the same. * Crossing a budget writes no engine ban. The claim is about one path, so a ban would refuse the rest of the site as punishment for a login-page rate. The answer is 429 with Retry-After for the rest of that source's window, and the reason names the rule, its count, its limit and the pattern it was written for. * The counters are a separate tracker, not a scope inside RateTracker. The edge-wide counter reads its limit and window from the policy; a rule carries its own. One map whose parameters change per entry is a map whose eviction and idle rules stop meaning anything. * The budgets hang off rateMode rather than getting a switch of their own: Enforce refuses, Observe counts and raises one rate_breach alert per source per window naming the pattern, Off counts nothing at all. A half-counting edge is the state an operator cannot reason about. * A second live budget for one pattern is a 409 — two live numbers for one path mean the stricter one wins by accident rather than by the operator's choice. * The bounds are the policy's own (1..100000 requests, 1..3600 seconds), so one vocabulary of numbers covers both budgets and a document cannot bring in a budget the API would have refused. * The listing answers with three counters — sources counted, windows running, over budget now — because "nobody has blown this" and "nobody can" look identical on paper and are different decisions. What the runs caught, in order: * The smoke scene first ran on 198.51.100.0/24, which an earlier scene of the same gate allowlists. An allowlisted source never reaches the counter, so the scene would have printed a row of 200s while measuring nothing. It runs on TEST-NET-1 now. * The console scene drew three 404s of its own and the streak pillar banned the address, so the reopen assertion read the streak's 403 instead of the absence of the budget. The engine list is cleared before that probe and the comment says which pillar the clearing belongs to. * The compose assertion compared a JSON boolean against the word "yes". * The change-log vocabulary test still listed six sections; there are seven now. * A unit expectation counted requests where the tracker holds windows: one (rule, source) pair is one window, and the count inside it is what the budget is measured against. Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit 361/361, integration 337/337 in 30 s, console 120 assertions 0 failed, smoke passed 169 failed 0, compose 300 passed 0 failed against the built image at 262 MB, 0 containers left behind. Refs OPEN-68.
245 lines
11 KiB
C#
245 lines
11 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// Twelve 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>();
|
|
public DbSet<NetworkBan> NetworkBans => Set<NetworkBan>();
|
|
public DbSet<RateRule> RateRules => Set<RateRule>();
|
|
|
|
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<NetworkBan>(e =>
|
|
{
|
|
// A ban on a network rather than an address (OPEN-66). Its own table
|
|
// rather than a flag on block_entries: block_entries is keyed on the
|
|
// source key, and a range is not a key — the exact-key lookup that
|
|
// enforces an address block would answer "is this address exactly
|
|
// this network address", which is not the question.
|
|
e.ToTable("network_bans");
|
|
e.HasKey(b => b.Id);
|
|
// One row per normalised network: 198.51.100.37/24 and
|
|
// 198.51.100.0/24 are one claim, and two rows for it is two rows an
|
|
// operator has to notice and remove.
|
|
e.HasIndex(b => b.Match).IsUnique();
|
|
e.HasIndex(b => b.ExpiresAt);
|
|
e.Property(b => b.Match).HasMaxLength(64).IsRequired();
|
|
e.Property(b => b.Reason).HasMaxLength(1024);
|
|
e.Property(b => b.RedirectTo).HasMaxLength(512);
|
|
});
|
|
|
|
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<RateRule>(e =>
|
|
{
|
|
// A request budget written for one path (OPEN-68). Its own table
|
|
// rather than a kind of request_rules: a path rule refuses a request
|
|
// for what it asked for, a rate rule refuses it for how often that
|
|
// source asked, and the two have different parameters, different
|
|
// counters and different reasons to expire.
|
|
e.ToTable("rate_rules");
|
|
e.HasKey(r => r.Id);
|
|
// Not unique, for the same reason request_rules is not: an expired
|
|
// budget 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);
|
|
});
|
|
|
|
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;
|
|
}
|