the edge gains a schema step a compiled binary can run, and NativeAOT gets a measured verdict
ci / lint the workflow and the shell (push) Successful in 10s
geo-freshness / the pinned geo database vs the vendor (push) Successful in 5s
ci / the operator page in a real browser (push) Successful in 3m42s
ci / build, test, smoke (push) Failing after 2m6s
ci / build the image and smoke it (push) Successful in 5m7s

The Dockerfile said "why not NativeAOT" on the authority of another repo's
Dockerfile. That claim is now this repo's own, and it is a measurement.

What was built to find out:

* Persistence/Schema/schema.sqlite.sql — the model's DDL, generated by
  `dotnet ef dbcontext script`, embedded in the binary and read by
  Persistence/EmbeddedSchema.cs. A NativeAOT build cannot ask EF to build a
  model at run time, and EnsureCreated and GenerateCreateScript both go through
  the design-time model, so the schema step has nowhere to get its SQL from.
  OPENWAF_SCHEMA=script is the fourth strategy: same provider-shaped
  statements, produced at build time instead of at start-up. The schema-script
  CI step regenerates the file and fails the run when the committed copy is not
  what the current model produces (5652 bytes today).
* SchemaUpgrader.ModelTables asks the runtime model, per entity type. The
  design-time one is refused outright under NativeAOT, and GetRelationalModel()
  on the runtime model of a compiled model throws
  "The annotation 'Relational:DefaultMappings' cannot be added because an
  annotation with the same name already exists on the object EntityType:
  CountryRule" — building a compiled model's relational model a second time
  collides with itself.
* The persistence layer's queries were rewritten into the shape EF's query
  precompiler accepts: captured parameters copied to locals, conditional
  IQueryable composition written as literal chains, aggregates that take a
  predicate given their own Where. 40 of them were refused before that.
* dotnet-ef and EF Core moved 10.0.0 -> 10.0.12, because 10.0.0's design package
  ships no build host and `--precompile-queries` cannot load a project without it.

What the measurement says, from scripts/aot-probe.sh on osx-arm64: the AOT build
compiles (48,797,072-byte native binary, 10 IL warnings, 0 errors), starts, and
creates all 12 tables from the DDL it carries. Then it never serves. EF refuses
every query at run time ("Query wasn't precompiled and dynamic code isn't
supported with NativeAOT"), and the precompiler that would fix that is not
usable on this model: after all 40 refusals were cleared it emitted 14
declarations with dots in the identifier
(`var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …`) — 28 CS1002
and CS1003 errors, one per entity materialisation — with or without --nativeaot.
The refusals themselves trace to dotnet/efcore#35887, #38030 and #35494; the fix
landed in the 12.0-preview1 milestone, not in any 10.0.x.

Two things were not kept, and why:

* The atomic alert-queue claim and the claim release were rewritten as raw SQL
  to dodge the precompiler's ExecuteUpdate failures. Reverted: with the
  statement written as SQL, DateTimeOffset reaches sqlite as a provider
  parameter instead of through the property's own mapping, the reclaim
  comparison stops matching, and
  AlertPushQueueTests.A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one
  fails with the row still owed. A correctness risk here buys nothing when the
  AOT build is blocked further along anyway.
* --nativeaot on the compiled model: its unsafe accessors do not compile
  (CS1503 in BlockEntryEntityType.cs). The plain compiled model is what is
  committed.

The compose gate's two escalation-count scenes also stopped being a coin toss.
They slept a fixed 2 s and then counted; on a loaded host the same tree read 3
rows once and 1 the next, and the assertion is about a settled number either
way. They now wait for three equal reads, bounded. The scene count is unchanged
at 368.

Gates at this commit: build 0 warnings / 0 errors, unit 378/378, integration
405/405, schema-script ok, smoke 256/0, compose-smoke 368/0, README counts
match (256, 368), lint clean (actionlint 1.7.12, shellcheck 0.11.0).

Not verified: the AOT image on linux-x64 — the probe ran on osx-arm64, and the
ILC failure mode that ends the attempt is a codegen bug in EF, not a
platform-specific one, but that is an inference rather than a measurement.
This commit is contained in:
Pavlo Ratushnyi
2026-10-06 05:20:28 +02:00
parent 85b38ad0cd
commit 7c5e1ef230
36 changed files with 2498 additions and 135 deletions
+7
View File
@@ -136,6 +136,13 @@ jobs:
- name: Integration tests — the real pipeline against a fake upstream
run: ./scripts/ci-gates.sh integration
# The image ships a DDL file generated from the EF model rather than
# deriving the schema at start-up, because a NativeAOT build cannot ask EF
# to build a model at run time. This step regenerates it and refuses the
# run when the committed copy is not what the current model produces.
- name: The DDL the image ships is what the model generates
run: ./scripts/ci-gates.sh schema-script
- name: Smoke — a running edge and a real upstream, curl assertions
run: ./scripts/ci-gates.sh smoke
+7 -4
View File
@@ -2,10 +2,13 @@
#
# openwaf edge — framework-dependent publish on a chiseled distroless runtime.
#
# Why not NativeAOT: the reference deployment (~/work/neemle/landing) tried it
# and recorded the reason in its Dockerfile — EF Core under AOT needs every LINQ
# query precompiled and every request/response shape annotated, and the size win
# washes out against the chiseled runtime base. Not relitigated here.
# Why not NativeAOT: measured here on 2026-10-06 rather than inherited from the
# reference deployment. The AOT build compiles and the binary creates its own
# schema from the DDL it carries, and then never serves: EF cannot compile a LINQ
# query at run time in a NativeAOT binary, and EF 10.0.12's precompile-queries
# generator cannot precompile this model — it refused 40 queries and then emitted
# uncompilable C# for every entity materialisation. scripts/aot-probe.sh
# reproduces the verdict in one command; docs/ARCHITECTURE.md carries the numbers.
#
# Stages:
# 1. restore – NuGet layer, cached independently of source changes
+7 -2
View File
@@ -345,8 +345,13 @@ dotnet ef migrations add <Name> --project OpenWaf.Infrastructure --startup-proje
A migration set is provider-shaped SQL, so it is not applied to the SQLite
default — there the schema is created from the model at startup. `OPENWAF_SCHEMA`
overrides the choice: `migrate`, `ensurecreated`, or `none` when an operator
manages the schema themselves.
overrides the choice: `migrate`, `ensurecreated`, `script`, or `none` when an
operator manages the schema themselves. `script` is the same DDL generated from
the model at build time and shipped inside the binary
(`dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql`) rather than
re-derived at startup; it exists because a NativeAOT build cannot ask EF to build
a model at run time at all, and the `schema-script` CI step regenerates the file
and fails the run when the committed copy is not what the current model produces.
Both automatic strategies now **finish an upgrade**, because neither used to.
`EnsureCreated` creates a missing database and changes nothing about an existing
+14 -1
View File
@@ -40,7 +40,20 @@ classifies the status, and is the only thing that can create an engine ban.
denied country gets whichever guard runs first.
* **Two block tables**: makes "clear engine bans" a table operation and invites
a future merge that loses data.
* **NativeAOT**: rejected in the reference and recorded there; not relitigated.
* **NativeAOT**: relitigated here on 2026-10-06 and measured, not inherited. The
build compiles (48.8 MB native arm64 binary, 10 IL warnings, 0 errors) and the
edge starts and creates its own schema from the DDL the binary carries — but it
never serves: EF refuses to compile a LINQ query at run time in a NativeAOT
binary, and the only alternative, `dotnet ef dbcontext optimize
--precompile-queries`, first refused 40 of this tree's queries (parameter-symbol
roots and captures, dotnet/efcore#35887 / #38030 / #35494, fixed only in the
12.0-preview1 line) and, after every one of them was rewritten into a shape it
accepts, emitted 14 declarations with dots in the identifier
(`var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …`) — 28 CS1002
and CS1003 errors, for every entity materialisation in the model. Reproduce with
`scripts/aot-probe.sh`. The query rewrites that attempt required are kept: they
are behaviour-identical (378 unit, 405 integration, 256 smoke at the same commit)
and they are the precondition for trying again when EF's precompiler is fixed.
* **Keying the ban on ip+UA** (as the analytics `SessionHash` does): a bot that
varies its UA multiplies into many sources and never reaches the threshold.
* **Banning on 5xx because the original wording said `> 400`**: turns an outage
@@ -65,6 +65,18 @@ internal sealed class EdgeStateWarmer(
schema.MigrationsApplied = await SchemaUpgrader.PendingMigrationsAsync(db, cancellationToken);
await CreateSchemaAsync(db, migrate: true, cancellationToken);
break;
case "script":
// The ensurecreated step for a binary that cannot run it. EF
// refuses to build a model at run time in a NativeAOT build, and
// both EnsureCreated and GenerateCreateScript go through the
// design-time model — so the DDL is generated from the model at
// build time, committed, and read out of the binary. Same
// provider-shaped statements, one of them checked by the
// schema-script gate rather than re-derived at start-up.
await CreateSchemaFromScriptAsync(db, cancellationToken);
schema.TablesAdded = (await SchemaUpgrader.AddMissingTablesAsync(
db, log, SchemaUpgrader.EmbeddedScriptFor(db) ?? string.Empty, cancellationToken)).Count;
break;
default:
log.LogInformation("edge: schema management left to the operator (OPENWAF_SCHEMA={Strategy})", strategy);
break;
@@ -131,5 +143,31 @@ internal sealed class EdgeStateWarmer(
}
}
/// <summary>
/// The script strategy's share of the race for the schema.
///
/// Same rule as <see cref="CreateSchemaAsync"/>: what has to be true is that
/// the tables exist, not that this process was the one that made them. Two
/// edges on one database both find the same tables missing and both start
/// creating them, and the loser's CREATE TABLE fails on the winner's table —
/// which is a start-up failure only if the tables are still missing after.
/// </summary>
private async Task CreateSchemaFromScriptAsync(OpenWafDbContext db, CancellationToken ct)
{
try
{
await SchemaUpgrader.ApplyScriptAsync(db, log, ct);
}
catch (Exception ex)
{
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
var stillMissing = await SchemaUpgrader.MissingTablesAsync(db, ct);
if (stillMissing.Count > 0) throw;
log.LogWarning(
"edge: the schema was being created by another instance ({Error}); continuing against it.",
ex.Message);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
@@ -8,31 +8,52 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.12">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.12" />
<!-- NU1903: EF's transitive SQLitePCLRaw 2.1.11 carries a known high
severity advisory (GHSA-2m69-gcr7-jv3q). Pinned forward rather than
suppressed, because TreatWarningsAsErrors is on and the audit is the
thing that caught it. -->
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.1.13" />
<PackageReference Include="SQLitePCLRaw.lib.e_sqlite3" Version="2.1.13" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<PackageReference Include="MaxMind.GeoIP2" Version="5.2.0" />
</ItemGroup>
<PropertyGroup>
<!-- The EF compiled model under Persistence/CompiledModel is generated for
ONE provider — sqlite, the one the shipped image runs. The framework-
dependent build serves sqlite *and* postgres and builds its model at
startup, so the compiled model is compiled in only for the AOT publish
(`-p:OpenWafCompiledModel=true`), where EF refuses to build a model at
runtime at all. Leaving it in every build would hand a sqlite model to a
postgres connection. -->
<OpenWafCompiledModel Condition="'$(OpenWafCompiledModel)' == ''">false</OpenWafCompiledModel>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<!-- The DDL this build ships with, generated from the model by
`dotnet ef dbcontext script` and checked by the schema-script gate. It is
the schema of a NativeAOT binary, which cannot ask EF to build a model at
run time; see Persistence/EmbeddedSchema.cs. -->
<EmbeddedResource Include="Persistence/Schema/schema.sqlite.sql"
LogicalName="OpenWaf.Infrastructure.Persistence.Schema.schema.sqlite.sql" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="OpenWaf.Tests.Unit" />
<InternalsVisibleTo Include="OpenWaf.Tests.Integration" />
</ItemGroup>
<ItemGroup Condition="'$(OpenWafCompiledModel)' != 'true'">
<Compile Remove="Persistence/CompiledModel/**/*.cs" />
</ItemGroup>
</Project>
@@ -1,4 +1,6 @@
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Channels;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@@ -214,8 +216,12 @@ public sealed class AlertNotifier : BackgroundService
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
// A local, not the field: the query precompiler reads the lambda out
// of the source text and does not resolve an instance field from there
// ("Encountered unknown identifier name '_processId'").
var owner = _processId;
var released = await db.AlertPushes
.Where(p => p.ClaimedBy == _processId && p.PushedAt == null && p.GivenUpAt == null)
.Where(p => p.ClaimedBy == owner && p.PushedAt == null && p.GivenUpAt == null)
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.ClaimedBy, (string?)null)
.SetProperty(p => p.ClaimedAt, (DateTimeOffset?)null), timeout.Token);
@@ -237,6 +243,12 @@ public sealed class AlertNotifier : BackgroundService
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var owner = _processId;
// A local for the batch size: the source-level translator resolves only
// lambda parameters and captured variables, so a const by name is "unknown
// identifier" to it.
var take = BatchSize;
var due = await db.AlertPushes
.Where(p => p.PushedAt == null && p.GivenUpAt == null
@@ -244,8 +256,8 @@ public sealed class AlertNotifier : BackgroundService
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.OrderBy(p => p.Id)
.Select(p => p.Id)
.Take(BatchSize)
.ToListAsync(ct);
.Take(take)
.ToListAsync(token);
if (due.Count > 0)
{
@@ -253,17 +265,30 @@ public sealed class AlertNotifier : BackgroundService
// reading the same due list at the same moment must end up with the
// row claimed by exactly one of them, and the loser simply finds
// nothing of its own to send.
//
// This is the one query in the persistence layer that EF's query
// precompiler cannot translate at all — ClaimedAt is DateTimeOffset?,
// and no shape of a non-nullable value in an ExecuteUpdate set-list
// precompiles — and it is deliberately left as LINQ rather than
// rewritten as hand-written SQL. Measured: with the statement written
// as SQL, DateTimeOffset reaches sqlite as a provider parameter instead
// of through the property's own mapping, the reclaim comparison stops
// matching, and
// AlertPushQueueTests.A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one
// fails with the row still owed. The AOT build is blocked further along
// anyway (see docs/ARCHITECTURE.md), so a correctness risk here buys
// nothing.
await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.PushedAt == null && p.GivenUpAt == null
&& (p.ClaimedBy == null || p.ClaimedAt == null || p.ClaimedAt <= staleClaim))
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.ClaimedBy, _processId)
.SetProperty(p => p.ClaimedAt, now), ct);
.SetProperty(p => p.ClaimedBy, owner)
.SetProperty(p => p.ClaimedAt, now), token);
var rows = await db.AlertPushes
.Where(p => due.Contains(p.Id) && p.ClaimedBy == _processId)
.Where(p => due.Contains(p.Id) && p.ClaimedBy == owner)
.OrderBy(p => p.Id)
.ToListAsync(ct);
.ToListAsync(token);
// Saved per row rather than once per batch: a process killed between
// two deliveries must not lose the record of the one it already made,
@@ -276,7 +301,7 @@ public sealed class AlertNotifier : BackgroundService
}
}
await RefreshCountsAsync(db, now, ct);
await RefreshCountsAsync(now, ct);
}
private async Task DeliverAsync(OpenWafDbContext db, AlertPush row, DateTimeOffset now, CancellationToken ct)
@@ -326,17 +351,8 @@ public sealed class AlertNotifier : BackgroundService
{
try
{
using var response = await _http.PostAsJsonAsync(_url!, new
{
kind = row.Kind,
sourceKey = row.SourceKey,
count = row.Count,
lastStatusCode = row.LastStatusCode,
lastPath = row.LastPath,
createdAt = row.AlertCreatedAt,
detail = row.Detail,
attempts = row.Attempts + 1
}, ct);
using var response = await _http.PostAsJsonAsync(
_url!, AlertPushPayload.From(row), AlertPushPayloadJsonContext.Default.AlertPushPayload, ct);
if (response.IsSuccessStatusCode) return (true, null);
// Named with the status, because "the push failed" is not actionable
@@ -353,20 +369,48 @@ public sealed class AlertNotifier : BackgroundService
}
}
private async Task RefreshCountsAsync(OpenWafDbContext db, DateTimeOffset now, CancellationToken ct)
private async Task RefreshCountsAsync(DateTimeOffset now, CancellationToken ct)
{
if (now - _countsAt < CountsRefresh) return;
_counts = await PushQueueCounts.QueryAsync(db, ct);
_counts = await QueryCountsAsync(ct);
_countsAt = now;
}
/// <summary>For the surfaces and the tests: the queue as the database holds
/// it, not as this process last cached it.</summary>
public async Task<PushQueueCounts> ReadCountsAsync(CancellationToken ct = default)
public Task<PushQueueCounts> ReadCountsAsync(CancellationToken ct = default)
=> _url is null
? Task.FromResult(new PushQueueCounts(0, 0, 0, null, null, 0))
: QueryCountsAsync(ct);
/// <summary>The queue's numbers, each one a literal chain from the DbSet.</summary>
/// <remarks>
/// The context is resolved here rather than passed in, and that is not style:
/// a method whose query root is a parameter cannot be precompiled at all
/// (dotnet/efcore#38030), and a NativeAOT build cannot compile a query at run
/// time, so this is the difference between the compiled image answering these
/// numbers and not answering them. The aggregate overloads that take the
/// predicate — CountAsync(p => …), SumAsync(p => …) — build their query at run
/// time and are "dynamic LINQ" for the same reason, which is why each number
/// spells its own Where.
/// </remarks>
private async Task<PushQueueCounts> QueryCountsAsync(CancellationToken ct)
{
if (_url is null) return new PushQueueCounts(0, 0, 0, null, null, 0);
using var scope = _scopeFactory.CreateScope();
return await PushQueueCounts.QueryAsync(scope.ServiceProvider.GetRequiredService<OpenWafDbContext>(), ct);
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
return new PushQueueCounts(
await db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null).CountAsync(token),
await db.AlertPushes.Where(p => p.PushedAt != null).CountAsync(token),
await db.AlertPushes.Where(p => p.GivenUpAt != null).CountAsync(token),
await db.AlertPushes.Where(p => p.LastError != null)
.OrderByDescending(p => p.Attempts).Select(p => p.LastError).FirstOrDefaultAsync(token),
await db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null)
.OrderBy(p => p.CreatedAt).Select(p => p.CreatedAt).FirstOrDefaultAsync(token),
// Every attempt every row has made, including rows that have since landed. It is
// the one number that says how hard the edge has been trying: pending and given-up
// say what the queue holds, this says what it cost.
(int) await db.AlertPushes.Select(p => p.Attempts).SumAsync(token));
}
/// <summary>Force one pass, for tests and for an operator who wants the queue
@@ -379,21 +423,29 @@ public sealed class AlertNotifier : BackgroundService
/// restart and agrees between edges sharing the database.</summary>
public sealed record PushQueueCounts(
int Pending, int Delivered, int GivenUp, string? LastError, DateTimeOffset? OldestPendingAt,
int Attempts);
/// <summary>The push body, as a named shape with a source-generated JSON context.
/// It used to be an anonymous type handed to PostAsJsonAsync, which is reflection
/// JSON: the NativeAOT analyzer refuses it (IL2026/IL3050), and the body an
/// operator's webhook receives would then depend on what the trimmer kept. The
/// property names below are the wire contract the queue has always sent —
/// camelCase, `createdAt` being the alert's timestamp and not the row's.</summary>
internal sealed record AlertPushPayload(
string Kind,
string SourceKey,
int Count,
int? LastStatusCode,
string? LastPath,
DateTimeOffset CreatedAt,
string Detail,
int Attempts)
{
public static async Task<PushQueueCounts> QueryAsync(OpenWafDbContext db, CancellationToken ct)
{
var pending = db.AlertPushes.Where(p => p.PushedAt == null && p.GivenUpAt == null);
return new PushQueueCounts(
await pending.CountAsync(ct),
await db.AlertPushes.CountAsync(p => p.PushedAt != null, ct),
await db.AlertPushes.CountAsync(p => p.GivenUpAt != null, ct),
await db.AlertPushes.Where(p => p.LastError != null)
.OrderByDescending(p => p.Attempts).Select(p => p.LastError).FirstOrDefaultAsync(ct),
await pending.OrderBy(p => p.CreatedAt).Select(p => p.CreatedAt).FirstOrDefaultAsync(ct),
// Every attempt every row has made, including rows that have since landed. It is
// the one number that says how hard the edge has been trying: pending and given-up
// say what the queue holds, this says what it cost.
(int) await db.AlertPushes.SumAsync(p => p.Attempts, ct));
}
public static AlertPushPayload From(AlertPush row) => new(
row.Kind, row.SourceKey, row.Count, row.LastStatusCode, row.LastPath,
row.AlertCreatedAt, row.Detail, row.Attempts + 1);
}
[JsonSerializable(typeof(AlertPushPayload))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal sealed partial class AlertPushPayloadJsonContext : JsonSerializerContext;
@@ -172,8 +172,10 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var bannedKey = ban.SourceKey;
var existing = await db.Blocks
.FirstOrDefaultAsync(b => b.SourceKey == ban.SourceKey && b.Source == BlockSource.Engine, ct);
.FirstOrDefaultAsync(b => b.SourceKey == bannedKey && b.Source == BlockSource.Engine, token);
if (existing is null)
{
@@ -278,8 +280,14 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
// Copied to locals: EF's query precompiler — the only way a NativeAOT
// build runs LINQ at all — fails on a captured method parameter
// (dotnet/efcore#35887, fixed only in 12.0-preview1).
var key = sourceKey;
var asOf = now;
var token = ct;
return await db.Blocks.AsNoTracking()
.AnyAsync(b => b.SourceKey == sourceKey && b.Source == BlockSource.Engine && b.ExpiresAt > now, ct);
.AnyAsync(b => b.SourceKey == key && b.Source == BlockSource.Engine && b.ExpiresAt > asOf, token);
}
catch (Exception ex)
{
@@ -334,7 +342,8 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, ct);
var token = ct;
var row = await db.Blocks.FirstOrDefaultAsync(b => b.SourceKey == key && b.Source == BlockSource.Operator, token);
if (row is null)
{
db.Blocks.Add(new BlockEntry
@@ -400,7 +409,9 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var row = await db.NetworkBans.FirstOrDefaultAsync(b => b.Match == match, ct);
var target = match;
var token = ct;
var row = await db.NetworkBans.FirstOrDefaultAsync(b => b.Match == target, token);
if (row is null)
{
db.NetworkBans.Add(new NetworkBan
@@ -473,9 +484,11 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var asOf = now;
var live = await db.Blocks.AnyAsync(
b => b.SourceKey == key && b.Source == BlockSource.Operator
&& (b.ExpiresAt == null || b.ExpiresAt > now), ct);
&& (b.ExpiresAt == null || b.ExpiresAt > asOf), token);
if (live) return (ImportResult.AlreadyThere, null);
db.Blocks.Add(new BlockEntry
@@ -518,8 +531,11 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var target = match;
var token = ct;
var asOf = now;
var live = await db.NetworkBans.AnyAsync(
b => b.Match == match && (b.ExpiresAt == null || b.ExpiresAt > now), ct);
b => b.Match == target && (b.ExpiresAt == null || b.ExpiresAt > asOf), token);
if (live) return (ImportResult.AlreadyThere, null);
db.NetworkBans.Add(new NetworkBan
@@ -572,6 +588,7 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var n = 0;
if (NetworkBans.IsRangeSyntax(sourceKey))
@@ -584,15 +601,22 @@ public sealed class BlockStore
var normalized = NetworkBans.TryNormalize(sourceKey!, out var match, out _)
? match
: sourceKey!;
n += await db.NetworkBans.Where(b => b.Match == normalized).ExecuteDeleteAsync(ct);
n += await db.NetworkBans.Where(b => b.Match == normalized).ExecuteDeleteAsync(token);
await _state.InvalidateAsync(ct);
return (DeleteResult.Ok, n);
}
var q = db.Blocks.AsQueryable();
if (source is not null) q = q.Where(b => b.Source == source.Value);
if (!string.IsNullOrWhiteSpace(sourceKey)) q = q.Where(b => b.SourceKey == sourceKey);
n += await q.ExecuteDeleteAsync(ct);
// One chain rather than an IQueryable assembled by two ifs: the
// precompiler reads the query out of the source text, so a query
// composed across statements is "dynamic" to it no matter what it
// does at run time. The two filters are the same two conditions,
// written as the disjunction EF can see.
var provenance = source;
var key = sourceKey;
n += await db.Blocks
.Where(b => (provenance == null || b.Source == provenance)
&& (string.IsNullOrWhiteSpace(key) || b.SourceKey == key))
.ExecuteDeleteAsync(token);
// The listing is one list, so a clear that names the operator's list
// has to clear both shapes of it: answering "deleted 4" while a /24
@@ -600,7 +624,7 @@ public sealed class BlockStore
// empty table that still enforces something. Engine clears never touch
// a range — the engine did not write one.
if (string.IsNullOrWhiteSpace(sourceKey) && source is not BlockSource.Engine)
n += await db.NetworkBans.ExecuteDeleteAsync(ct);
n += await db.NetworkBans.ExecuteDeleteAsync(token);
await _state.InvalidateAsync(ct);
return (DeleteResult.Ok, n);
@@ -650,16 +674,29 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var q = Filtered(db, source, liveOnly, now);
var blocks = await q.OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct);
var provenance = source;
var live = liveOnly;
var asOf = now;
var page = limit;
var skip = offset;
var token = ct;
var blocks = await db.Blocks
.AsNoTracking()
.Where(b => (provenance == null || b.Source == provenance)
&& (!live || b.ExpiresAt == null || b.ExpiresAt > asOf))
.OrderByDescending(b => b.CreatedAt).Skip(skip).Take(page)
.ToListAsync(token);
// Ranges are read with the same window rather than re-filtered per page:
// the two tables are small by design, and ordering the union needs both
// sides of the cut. Anything past offset+limit is not shown either way.
var ranges = source == BlockSource.Engine
? []
: await FilteredRanges(db, liveOnly, now)
.OrderByDescending(b => b.CreatedAt).Skip(offset).Take(limit).ToListAsync(ct);
: await db.NetworkBans
.AsNoTracking()
.Where(b => !live || b.ExpiresAt == null || b.ExpiresAt > asOf)
.OrderByDescending(b => b.CreatedAt).Skip(skip).Take(page)
.ToListAsync(token);
return blocks.Select(b => new BlockRow(b, null))
.Concat(ranges.Select(r => new BlockRow(null, r)))
@@ -671,27 +708,22 @@ public sealed class BlockStore
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var blocks = await Filtered(db, source, liveOnly, now).CountAsync(ct);
var provenance = source;
var live = liveOnly;
var asOf = now;
var token = ct;
var blocks = await db.Blocks
.AsNoTracking()
.Where(b => (provenance == null || b.Source == provenance)
&& (!live || b.ExpiresAt == null || b.ExpiresAt > asOf))
.CountAsync(token);
var ranges = source == BlockSource.Engine
? 0
: await FilteredRanges(db, liveOnly, now).CountAsync(ct);
: await db.NetworkBans
.AsNoTracking()
.Where(b => !live || b.ExpiresAt == null || b.ExpiresAt > asOf)
.CountAsync(token);
return blocks + ranges;
}
private static IQueryable<BlockEntry> Filtered(OpenWafDbContext db, BlockSource? source, bool liveOnly, DateTimeOffset now)
{
var q = db.Blocks.AsNoTracking().AsQueryable();
if (source is not null) q = q.Where(b => b.Source == source.Value);
if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now);
return q;
}
/// <summary>Ranges are always the operator's, so the provenance filter has
/// one answer for them: an engine filter matches nothing.</summary>
private static IQueryable<NetworkBan> FilteredRanges(OpenWafDbContext db, bool liveOnly, DateTimeOffset now)
{
var q = db.NetworkBans.AsNoTracking().AsQueryable();
if (liveOnly) q = q.Where(b => b.ExpiresAt == null || b.ExpiresAt > now);
return q;
}
}
@@ -0,0 +1,195 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class AlertPushEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.AlertPush",
typeof(AlertPush),
baseEntityType,
propertyCount: 17,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(AlertPush).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var alertCreatedAt = runtimeEntityType.AddProperty(
"AlertCreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(AlertPush).GetProperty("AlertCreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<AlertCreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
alertCreatedAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
alertCreatedAt.SetSentinelFromProviderValue(0L);
var alertId = runtimeEntityType.AddProperty(
"AlertId",
typeof(long),
propertyInfo: typeof(AlertPush).GetProperty("AlertId", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<AlertId>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0L);
var attempts = runtimeEntityType.AddProperty(
"Attempts",
typeof(int),
propertyInfo: typeof(AlertPush).GetProperty("Attempts", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<Attempts>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var claimedAt = runtimeEntityType.AddProperty(
"ClaimedAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(AlertPush).GetProperty("ClaimedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<ClaimedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
claimedAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var claimedBy = runtimeEntityType.AddProperty(
"ClaimedBy",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("ClaimedBy", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<ClaimedBy>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var count = runtimeEntityType.AddProperty(
"Count",
typeof(int),
propertyInfo: typeof(AlertPush).GetProperty("Count", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<Count>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(AlertPush).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var detail = runtimeEntityType.AddProperty(
"Detail",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("Detail", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<Detail>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 1024);
var givenUpAt = runtimeEntityType.AddProperty(
"GivenUpAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(AlertPush).GetProperty("GivenUpAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<GivenUpAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
givenUpAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var kind = runtimeEntityType.AddProperty(
"Kind",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("Kind", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<Kind>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 64);
var lastError = runtimeEntityType.AddProperty(
"LastError",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("LastError", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<LastError>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var lastPath = runtimeEntityType.AddProperty(
"LastPath",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("LastPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<LastPath>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var lastStatusCode = runtimeEntityType.AddProperty(
"LastStatusCode",
typeof(int?),
propertyInfo: typeof(AlertPush).GetProperty("LastStatusCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<LastStatusCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var nextAttemptAt = runtimeEntityType.AddProperty(
"NextAttemptAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(AlertPush).GetProperty("NextAttemptAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<NextAttemptAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
nextAttemptAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var pushedAt = runtimeEntityType.AddProperty(
"PushedAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(AlertPush).GetProperty("PushedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<PushedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
pushedAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var sourceKey = runtimeEntityType.AddProperty(
"SourceKey",
typeof(string),
propertyInfo: typeof(AlertPush).GetProperty("SourceKey", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AlertPush).GetField("<SourceKey>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 128);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { alertId });
var index0 = runtimeEntityType.AddIndex(
new[] { pushedAt, givenUpAt, nextAttemptAt });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "alert_pushes");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,96 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class AllowEntryEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.AllowEntry",
typeof(AllowEntry),
baseEntityType,
propertyCount: 5,
unnamedIndexCount: 1,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(AllowEntry).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AllowEntry).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(AllowEntry).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AllowEntry).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var expiresAt = runtimeEntityType.AddProperty(
"ExpiresAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(AllowEntry).GetProperty("ExpiresAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AllowEntry).GetField("<ExpiresAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
expiresAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var match = runtimeEntityType.AddProperty(
"Match",
typeof(string),
propertyInfo: typeof(AllowEntry).GetProperty("Match", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AllowEntry).GetField("<Match>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 128);
var note = runtimeEntityType.AddProperty(
"Note",
typeof(string),
propertyInfo: typeof(AllowEntry).GetProperty("Note", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(AllowEntry).GetField("<Note>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { match },
unique: true);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "allow_entries");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,169 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class BlockEntryEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.BlockEntry",
typeof(BlockEntry),
baseEntityType,
propertyCount: 14,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(BlockEntry).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var consecutiveRefusals = runtimeEntityType.AddProperty(
"ConsecutiveRefusals",
typeof(int?),
propertyInfo: typeof(BlockEntry).GetProperty("ConsecutiveRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<ConsecutiveRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(BlockEntry).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var expiresAt = runtimeEntityType.AddProperty(
"ExpiresAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(BlockEntry).GetProperty("ExpiresAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<ExpiresAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
expiresAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var lastCity = runtimeEntityType.AddProperty(
"LastCity",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("LastCity", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastCity>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastCountryCode = runtimeEntityType.AddProperty(
"LastCountryCode",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("LastCountryCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastCountryCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 2);
var lastPath = runtimeEntityType.AddProperty(
"LastPath",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("LastPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastPath>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var lastRegion = runtimeEntityType.AddProperty(
"LastRegion",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("LastRegion", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastRegion>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastStatusCode = runtimeEntityType.AddProperty(
"LastStatusCode",
typeof(int?),
propertyInfo: typeof(BlockEntry).GetProperty("LastStatusCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastStatusCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var lastUserAgent = runtimeEntityType.AddProperty(
"LastUserAgent",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("LastUserAgent", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<LastUserAgent>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 256);
var reason = runtimeEntityType.AddProperty(
"Reason",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("Reason", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<Reason>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 1024);
var redirectTo = runtimeEntityType.AddProperty(
"RedirectTo",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("RedirectTo", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<RedirectTo>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var source = runtimeEntityType.AddProperty(
"Source",
typeof(BlockSource),
propertyInfo: typeof(BlockEntry).GetProperty("Source", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<Source>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
providerPropertyType: typeof(int));
source.SetSentinelFromProviderValue(0);
var sourceKey = runtimeEntityType.AddProperty(
"SourceKey",
typeof(string),
propertyInfo: typeof(BlockEntry).GetProperty("SourceKey", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(BlockEntry).GetField("<SourceKey>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 128);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { expiresAt });
var index0 = runtimeEntityType.AddIndex(
new[] { sourceKey, source },
unique: true);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "block_entries");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,109 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class ConfigChangeEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.ConfigChange",
typeof(ConfigChange),
baseEntityType,
propertyCount: 7,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(ConfigChange).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var action = runtimeEntityType.AddProperty(
"Action",
typeof(string),
propertyInfo: typeof(ConfigChange).GetProperty("Action", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Action>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 16);
var actor = runtimeEntityType.AddProperty(
"Actor",
typeof(string),
propertyInfo: typeof(ConfigChange).GetProperty("Actor", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Actor>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 16);
var at = runtimeEntityType.AddProperty(
"At",
typeof(DateTimeOffset),
propertyInfo: typeof(ConfigChange).GetProperty("At", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<At>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
at.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
at.SetSentinelFromProviderValue(0L);
var detail = runtimeEntityType.AddProperty(
"Detail",
typeof(string),
propertyInfo: typeof(ConfigChange).GetProperty("Detail", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Detail>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var section = runtimeEntityType.AddProperty(
"Section",
typeof(string),
propertyInfo: typeof(ConfigChange).GetProperty("Section", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Section>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 16);
var target = runtimeEntityType.AddProperty(
"Target",
typeof(string),
propertyInfo: typeof(ConfigChange).GetProperty("Target", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(ConfigChange).GetField("<Target>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 128);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { at });
var index0 = runtimeEntityType.AddIndex(
new[] { section });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "config_changes");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,80 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Policy;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class CountryRuleEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Policy.CountryRule",
typeof(CountryRule),
baseEntityType,
propertyCount: 4,
keyCount: 1);
var code = runtimeEntityType.AddProperty(
"Code",
typeof(string),
propertyInfo: typeof(CountryRule).GetProperty("Code", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CountryRule).GetField("<Code>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
afterSaveBehavior: PropertySaveBehavior.Throw,
maxLength: 2);
var isAllowed = runtimeEntityType.AddProperty(
"IsAllowed",
typeof(bool),
propertyInfo: typeof(CountryRule).GetProperty("IsAllowed", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CountryRule).GetField("<IsAllowed>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: false);
var name = runtimeEntityType.AddProperty(
"Name",
typeof(string),
propertyInfo: typeof(CountryRule).GetProperty("Name", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CountryRule).GetField("<Name>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var updatedAt = runtimeEntityType.AddProperty(
"UpdatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(CountryRule).GetProperty("UpdatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(CountryRule).GetField("<UpdatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
updatedAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
updatedAt.SetSentinelFromProviderValue(0L);
var key = runtimeEntityType.AddKey(
new[] { code });
runtimeEntityType.SetPrimaryKey(key);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "country_rules");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,112 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class EdgeAlertEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.EdgeAlert",
typeof(EdgeAlert),
baseEntityType,
propertyCount: 8,
unnamedIndexCount: 1,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(EdgeAlert).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var count = runtimeEntityType.AddProperty(
"Count",
typeof(int),
propertyInfo: typeof(EdgeAlert).GetProperty("Count", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<Count>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(EdgeAlert).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var detail = runtimeEntityType.AddProperty(
"Detail",
typeof(string),
propertyInfo: typeof(EdgeAlert).GetProperty("Detail", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<Detail>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 1024);
var kind = runtimeEntityType.AddProperty(
"Kind",
typeof(string),
propertyInfo: typeof(EdgeAlert).GetProperty("Kind", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<Kind>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 64);
var lastPath = runtimeEntityType.AddProperty(
"LastPath",
typeof(string),
propertyInfo: typeof(EdgeAlert).GetProperty("LastPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<LastPath>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var lastStatusCode = runtimeEntityType.AddProperty(
"LastStatusCode",
typeof(int?),
propertyInfo: typeof(EdgeAlert).GetProperty("LastStatusCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<LastStatusCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var sourceKey = runtimeEntityType.AddProperty(
"SourceKey",
typeof(string),
propertyInfo: typeof(EdgeAlert).GetProperty("SourceKey", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(EdgeAlert).GetField("<SourceKey>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 128);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { createdAt });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "edge_alerts");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,107 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class NetworkBanEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.NetworkBan",
typeof(NetworkBan),
baseEntityType,
propertyCount: 6,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(NetworkBan).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(NetworkBan).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var expiresAt = runtimeEntityType.AddProperty(
"ExpiresAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(NetworkBan).GetProperty("ExpiresAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<ExpiresAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
expiresAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var match = runtimeEntityType.AddProperty(
"Match",
typeof(string),
propertyInfo: typeof(NetworkBan).GetProperty("Match", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<Match>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 64);
var reason = runtimeEntityType.AddProperty(
"Reason",
typeof(string),
propertyInfo: typeof(NetworkBan).GetProperty("Reason", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<Reason>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 1024);
var redirectTo = runtimeEntityType.AddProperty(
"RedirectTo",
typeof(string),
propertyInfo: typeof(NetworkBan).GetProperty("RedirectTo", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(NetworkBan).GetField("<RedirectTo>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { expiresAt });
var index0 = runtimeEntityType.AddIndex(
new[] { match },
unique: true);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "network_bans");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,9 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore.Infrastructure;
using OpenWaf.Infrastructure.Persistence;
using OpenWaf.Infrastructure.Persistence.CompiledModel;
#pragma warning disable 219, 612, 618
#nullable disable
[assembly: DbContextModel(typeof(OpenWafDbContext), typeof(OpenWafDbContextModel))]
@@ -0,0 +1,47 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[DbContext(typeof(OpenWafDbContext))]
public partial class OpenWafDbContextModel : RuntimeModel
{
private static readonly bool _useOldBehavior31751 =
System.AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue31751", out var enabled31751) && enabled31751;
static OpenWafDbContextModel()
{
var model = new OpenWafDbContextModel();
if (_useOldBehavior31751)
{
model.Initialize();
}
else
{
var thread = new System.Threading.Thread(RunInitialization, 10 * 1024 * 1024);
thread.Start();
thread.Join();
void RunInitialization()
{
model.Initialize();
}
}
model.Customize();
_instance = (OpenWafDbContextModel)model.FinalizeModel();
}
private static OpenWafDbContextModel _instance;
public static IModel Instance => _instance;
partial void Initialize();
partial void Customize();
}
}
@@ -0,0 +1,49 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
public partial class OpenWafDbContextModel
{
private OpenWafDbContextModel()
: base(skipDetectChanges: false, modelId: new Guid("e8adf9c5-38e5-4c16-8d3a-d7635b54b361"), entityTypeCount: 12)
{
}
partial void Initialize()
{
var countryRule = CountryRuleEntityType.Create(this);
var alertPush = AlertPushEntityType.Create(this);
var allowEntry = AllowEntryEntityType.Create(this);
var blockEntry = BlockEntryEntityType.Create(this);
var configChange = ConfigChangeEntityType.Create(this);
var edgeAlert = EdgeAlertEntityType.Create(this);
var networkBan = NetworkBanEntityType.Create(this);
var rateRule = RateRuleEntityType.Create(this);
var requestRule = RequestRuleEntityType.Create(this);
var sourceObservation = SourceObservationEntityType.Create(this);
var sourceStreak = SourceStreakEntityType.Create(this);
var policySetting = PolicySettingEntityType.Create(this);
CountryRuleEntityType.CreateAnnotations(countryRule);
AlertPushEntityType.CreateAnnotations(alertPush);
AllowEntryEntityType.CreateAnnotations(allowEntry);
BlockEntryEntityType.CreateAnnotations(blockEntry);
ConfigChangeEntityType.CreateAnnotations(configChange);
EdgeAlertEntityType.CreateAnnotations(edgeAlert);
NetworkBanEntityType.CreateAnnotations(networkBan);
RateRuleEntityType.CreateAnnotations(rateRule);
RequestRuleEntityType.CreateAnnotations(requestRule);
SourceObservationEntityType.CreateAnnotations(sourceObservation);
SourceStreakEntityType.CreateAnnotations(sourceStreak);
PolicySettingEntityType.CreateAnnotations(policySetting);
AddAnnotation("ProductVersion", "10.0.12");
}
}
}
@@ -0,0 +1,71 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class PolicySettingEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Infrastructure.Persistence.PolicySetting",
typeof(PolicySetting),
baseEntityType,
propertyCount: 3,
keyCount: 1);
var key = runtimeEntityType.AddProperty(
"Key",
typeof(string),
propertyInfo: typeof(PolicySetting).GetProperty("Key", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(PolicySetting).GetField("<Key>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
afterSaveBehavior: PropertySaveBehavior.Throw,
maxLength: 64);
var updatedAt = runtimeEntityType.AddProperty(
"UpdatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(PolicySetting).GetProperty("UpdatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(PolicySetting).GetField("<UpdatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
updatedAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
updatedAt.SetSentinelFromProviderValue(0L);
var value = runtimeEntityType.AddProperty(
"Value",
typeof(string),
propertyInfo: typeof(PolicySetting).GetProperty("Value", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(PolicySetting).GetField("<Value>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 256);
var key0 = runtimeEntityType.AddKey(
new[] { key });
runtimeEntityType.SetPrimaryKey(key0);
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "policy_settings");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,112 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class RateRuleEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.RateRule",
typeof(RateRule),
baseEntityType,
propertyCount: 7,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(RateRule).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(RateRule).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var expiresAt = runtimeEntityType.AddProperty(
"ExpiresAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(RateRule).GetProperty("ExpiresAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<ExpiresAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
expiresAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var limitPerWindow = runtimeEntityType.AddProperty(
"LimitPerWindow",
typeof(int),
propertyInfo: typeof(RateRule).GetProperty("LimitPerWindow", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<LimitPerWindow>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var note = runtimeEntityType.AddProperty(
"Note",
typeof(string),
propertyInfo: typeof(RateRule).GetProperty("Note", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<Note>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var pattern = runtimeEntityType.AddProperty(
"Pattern",
typeof(string),
propertyInfo: typeof(RateRule).GetProperty("Pattern", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<Pattern>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 256);
var windowSeconds = runtimeEntityType.AddProperty(
"WindowSeconds",
typeof(int),
propertyInfo: typeof(RateRule).GetProperty("WindowSeconds", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RateRule).GetField("<WindowSeconds>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { expiresAt });
var index0 = runtimeEntityType.AddIndex(
new[] { pattern });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "rate_rules");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,106 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class RequestRuleEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.RequestRule",
typeof(RequestRule),
baseEntityType,
propertyCount: 6,
unnamedIndexCount: 2,
keyCount: 1);
var id = runtimeEntityType.AddProperty(
"Id",
typeof(long),
propertyInfo: typeof(RequestRule).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<Id>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
valueGenerated: ValueGenerated.OnAdd,
afterSaveBehavior: PropertySaveBehavior.Throw,
sentinel: 0L);
var action = runtimeEntityType.AddProperty(
"Action",
typeof(RequestRuleAction),
propertyInfo: typeof(RequestRule).GetProperty("Action", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<Action>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
providerPropertyType: typeof(int));
action.SetSentinelFromProviderValue(0);
var createdAt = runtimeEntityType.AddProperty(
"CreatedAt",
typeof(DateTimeOffset),
propertyInfo: typeof(RequestRule).GetProperty("CreatedAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<CreatedAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
createdAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
createdAt.SetSentinelFromProviderValue(0L);
var expiresAt = runtimeEntityType.AddProperty(
"ExpiresAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(RequestRule).GetProperty("ExpiresAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<ExpiresAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
expiresAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var note = runtimeEntityType.AddProperty(
"Note",
typeof(string),
propertyInfo: typeof(RequestRule).GetProperty("Note", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<Note>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var pattern = runtimeEntityType.AddProperty(
"Pattern",
typeof(string),
propertyInfo: typeof(RequestRule).GetProperty("Pattern", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(RequestRule).GetField("<Pattern>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
maxLength: 256);
var key = runtimeEntityType.AddKey(
new[] { id });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { expiresAt });
var index0 = runtimeEntityType.AddIndex(
new[] { pattern });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "request_rules");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,147 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class SourceObservationEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.SourceObservation",
typeof(SourceObservation),
baseEntityType,
propertyCount: 12,
unnamedIndexCount: 1,
keyCount: 1);
var sourceKey = runtimeEntityType.AddProperty(
"SourceKey",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("SourceKey", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<SourceKey>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
afterSaveBehavior: PropertySaveBehavior.Throw,
maxLength: 128);
var firstSeenAt = runtimeEntityType.AddProperty(
"FirstSeenAt",
typeof(DateTimeOffset),
propertyInfo: typeof(SourceObservation).GetProperty("FirstSeenAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<FirstSeenAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
firstSeenAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
firstSeenAt.SetSentinelFromProviderValue(0L);
var lastCity = runtimeEntityType.AddProperty(
"LastCity",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("LastCity", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastCity>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastCountryCode = runtimeEntityType.AddProperty(
"LastCountryCode",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("LastCountryCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastCountryCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 2);
var lastPath = runtimeEntityType.AddProperty(
"LastPath",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("LastPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastPath>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var lastRegion = runtimeEntityType.AddProperty(
"LastRegion",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("LastRegion", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastRegion>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastSeenAt = runtimeEntityType.AddProperty(
"LastSeenAt",
typeof(DateTimeOffset),
propertyInfo: typeof(SourceObservation).GetProperty("LastSeenAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastSeenAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
lastSeenAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
lastSeenAt.SetSentinelFromProviderValue(0L);
var lastStatusCode = runtimeEntityType.AddProperty(
"LastStatusCode",
typeof(int?),
propertyInfo: typeof(SourceObservation).GetProperty("LastStatusCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastStatusCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var lastUserAgent = runtimeEntityType.AddProperty(
"LastUserAgent",
typeof(string),
propertyInfo: typeof(SourceObservation).GetProperty("LastUserAgent", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<LastUserAgent>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 256);
var maxConsecutiveRefusals = runtimeEntityType.AddProperty(
"MaxConsecutiveRefusals",
typeof(int),
propertyInfo: typeof(SourceObservation).GetProperty("MaxConsecutiveRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<MaxConsecutiveRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var totalRefusals = runtimeEntityType.AddProperty(
"TotalRefusals",
typeof(int),
propertyInfo: typeof(SourceObservation).GetProperty("TotalRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<TotalRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var totalServerErrorStreak = runtimeEntityType.AddProperty(
"TotalServerErrorStreak",
typeof(int),
propertyInfo: typeof(SourceObservation).GetProperty("TotalServerErrorStreak", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceObservation).GetField("<TotalServerErrorStreak>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var key = runtimeEntityType.AddKey(
new[] { sourceKey });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { lastSeenAt });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "source_observations");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -0,0 +1,183 @@
// <auto-generated />
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using OpenWaf.Domain.Security;
#pragma warning disable 219, 612, 618
#nullable disable
namespace OpenWaf.Infrastructure.Persistence.CompiledModel
{
[EntityFrameworkInternal]
public partial class SourceStreakEntityType
{
public static RuntimeEntityType Create(RuntimeModel model, RuntimeEntityType baseEntityType = null)
{
var runtimeEntityType = model.AddEntityType(
"OpenWaf.Domain.Security.SourceStreak",
typeof(SourceStreak),
baseEntityType,
propertyCount: 17,
unnamedIndexCount: 1,
keyCount: 1);
var sourceKey = runtimeEntityType.AddProperty(
"SourceKey",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("SourceKey", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<SourceKey>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
afterSaveBehavior: PropertySaveBehavior.Throw,
maxLength: 128);
var consecutiveRefusals = runtimeEntityType.AddProperty(
"ConsecutiveRefusals",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("ConsecutiveRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<ConsecutiveRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var consecutiveServerErrors = runtimeEntityType.AddProperty(
"ConsecutiveServerErrors",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("ConsecutiveServerErrors", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<ConsecutiveServerErrors>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var lastAlertedRefusals = runtimeEntityType.AddProperty(
"LastAlertedRefusals",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("LastAlertedRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastAlertedRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var lastAlertedServerErrors = runtimeEntityType.AddProperty(
"LastAlertedServerErrors",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("LastAlertedServerErrors", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastAlertedServerErrors>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var lastCity = runtimeEntityType.AddProperty(
"LastCity",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("LastCity", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastCity>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastCountryCode = runtimeEntityType.AddProperty(
"LastCountryCode",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("LastCountryCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastCountryCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 2);
var lastPath = runtimeEntityType.AddProperty(
"LastPath",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("LastPath", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastPath>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 512);
var lastRefusalAt = runtimeEntityType.AddProperty(
"LastRefusalAt",
typeof(DateTimeOffset?),
propertyInfo: typeof(SourceStreak).GetProperty("LastRefusalAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastRefusalAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
lastRefusalAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
var lastRegion = runtimeEntityType.AddProperty(
"LastRegion",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("LastRegion", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastRegion>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 128);
var lastSeenAt = runtimeEntityType.AddProperty(
"LastSeenAt",
typeof(DateTimeOffset),
propertyInfo: typeof(SourceStreak).GetProperty("LastSeenAt", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastSeenAt>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
lastSeenAt.SetValueConverter(new ValueConverter<DateTimeOffset, long>(
long (DateTimeOffset v) => DateTimeOffsetToBinaryConverter.ToLong(v),
DateTimeOffset (long v) => DateTimeOffsetToBinaryConverter.ToDateTimeOffset(v)));
lastSeenAt.SetSentinelFromProviderValue(0L);
var lastStatusCode = runtimeEntityType.AddProperty(
"LastStatusCode",
typeof(int?),
propertyInfo: typeof(SourceStreak).GetProperty("LastStatusCode", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastStatusCode>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true);
var lastUserAgent = runtimeEntityType.AddProperty(
"LastUserAgent",
typeof(string),
propertyInfo: typeof(SourceStreak).GetProperty("LastUserAgent", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<LastUserAgent>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
nullable: true,
maxLength: 256);
var maxConsecutiveRefusals = runtimeEntityType.AddProperty(
"MaxConsecutiveRefusals",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("MaxConsecutiveRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<MaxConsecutiveRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var maxConsecutiveServerErrors = runtimeEntityType.AddProperty(
"MaxConsecutiveServerErrors",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("MaxConsecutiveServerErrors", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<MaxConsecutiveServerErrors>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var totalRefusals = runtimeEntityType.AddProperty(
"TotalRefusals",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("TotalRefusals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<TotalRefusals>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
sentinel: 0);
var version = runtimeEntityType.AddProperty(
"Version",
typeof(int),
propertyInfo: typeof(SourceStreak).GetProperty("Version", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly),
fieldInfo: typeof(SourceStreak).GetField("<Version>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly),
concurrencyToken: true,
sentinel: 0);
var key = runtimeEntityType.AddKey(
new[] { sourceKey });
runtimeEntityType.SetPrimaryKey(key);
var index = runtimeEntityType.AddIndex(
new[] { lastSeenAt });
return runtimeEntityType;
}
public static void CreateAnnotations(RuntimeEntityType runtimeEntityType)
{
runtimeEntityType.AddAnnotation("Relational:FunctionName", null);
runtimeEntityType.AddAnnotation("Relational:Schema", null);
runtimeEntityType.AddAnnotation("Relational:SqlQuery", null);
runtimeEntityType.AddAnnotation("Relational:TableName", "source_streaks");
runtimeEntityType.AddAnnotation("Relational:ViewName", null);
runtimeEntityType.AddAnnotation("Relational:ViewSchema", null);
Customize(runtimeEntityType);
}
static partial void Customize(RuntimeEntityType runtimeEntityType);
}
}
@@ -62,7 +62,8 @@ public sealed class EdgePolicyProvider
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var rows = await db.PolicySettings.AsNoTracking().ToListAsync(ct);
var token = ct;
var rows = await db.PolicySettings.AsNoTracking().ToListAsync(token);
_current = ApplyOverrides(_current, rows);
Interlocked.Exchange(ref _reloadFailures, 0);
Volatile.Write(ref _lastReloadError, null);
@@ -83,14 +84,15 @@ public sealed class EdgePolicyProvider
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
foreach (var (key, value) in overrides)
{
if (value is null)
{
await db.PolicySettings.Where(p => p.Key == key).ExecuteDeleteAsync(ct);
await db.PolicySettings.Where(p => p.Key == key).ExecuteDeleteAsync(token);
continue;
}
var row = await db.PolicySettings.FindAsync([key], ct);
var row = await db.PolicySettings.FindAsync([key], token);
if (row is null) db.PolicySettings.Add(new PolicySetting { Key = key, Value = value, UpdatedAt = DateTimeOffset.UtcNow });
else { row.Value = value; row.UpdatedAt = DateTimeOffset.UtcNow; }
}
@@ -143,10 +143,11 @@ public sealed class EdgeStateStore
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var blocks = await db.Blocks.AsNoTracking().ToListAsync(ct);
var allow = await db.AllowEntries.AsNoTracking().ToListAsync(ct);
var countries = await db.CountryRules.AsNoTracking().ToListAsync(ct);
var blocks = await db.Blocks.AsNoTracking().ToListAsync(token);
var allow = await db.AllowEntries.AsNoTracking().ToListAsync(token);
var countries = await db.CountryRules.AsNoTracking().ToListAsync(token);
// The rules read stands alone, on purpose. `request_rules` is the
// newest table in the schema, and a database created before the
// feature has every other table — so reading it in the same block
@@ -161,7 +162,7 @@ public sealed class EdgeStateStore
// Ordered by id: the listing an operator reads and the order the
// engine evaluates are the same thing, so "which rule wins" has
// one answer that is visible on the page.
rules = await db.RequestRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(ct);
rules = await db.RequestRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token);
RulesAvailable = true;
Volatile.Write(ref _rulesError, null);
}
@@ -182,7 +183,7 @@ public sealed class EdgeStateStore
IReadOnlyList<RateRule> rateRules;
try
{
rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(ct);
rateRules = await db.RateRules.AsNoTracking().OrderBy(r => r.Id).ToListAsync(token);
RateRulesAvailable = true;
Volatile.Write(ref _rateRulesError, null);
}
@@ -210,7 +211,7 @@ public sealed class EdgeStateStore
NetworkBanIndex ranges;
try
{
ranges = new NetworkBanIndex(await db.NetworkBans.AsNoTracking().ToListAsync(ct));
ranges = new NetworkBanIndex(await db.NetworkBans.AsNoTracking().ToListAsync(token));
RangesAvailable = true;
Volatile.Write(ref _rangesError, null);
}
@@ -0,0 +1,53 @@
using System.Text;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// The schema DDL this build carries inside itself.
///
/// A NativeAOT binary cannot ask EF to build a model at run time — EF refuses it
/// outright — and both <c>EnsureCreated</c> and <c>GenerateCreateScript</c> go
/// through the design-time model, so the step that makes the first database in a
/// deployment has nowhere to get its SQL from. The answer here is to generate
/// that SQL from the model at build time, commit it, and embed it: the same
/// provider-shaped statements EF would have emitted, read from the binary rather
/// than re-derived from it.
///
/// The file is not hand-written and is not meant to be edited. The schema-script
/// gate regenerates it from the current model and fails when the committed copy
/// differs, which is what keeps "the same SQL" a checked claim rather than a
/// hope.
/// </summary>
public static class EmbeddedSchema
{
private const string SqliteResource = "OpenWaf.Infrastructure.Persistence.Schema.schema.sqlite.sql";
/// <summary>
/// The DDL for a provider, or null when this build carries none for it. The
/// caller decides what that means; it is never treated as "no schema".
/// </summary>
public static string? ScriptFor(string? providerName)
=> providerName switch
{
"Microsoft.EntityFrameworkCore.Sqlite" => Read(SqliteResource),
_ => null
};
/// <summary>
/// The resource names this build embeds, so the gate can enumerate them
/// instead of hard-coding the file list a second time.
/// </summary>
public static IReadOnlyList<string> ResourceNames
=> typeof(EmbeddedSchema).Assembly.GetManifestResourceNames();
private static string? Read(string resource)
{
using var stream = typeof(EmbeddedSchema).Assembly.GetManifestResourceStream(resource);
if (stream is null) return null;
using var reader = new StreamReader(stream, Encoding.UTF8);
// The generator writes a byte-order mark; sqlite parses it as the start of
// the first statement and reports a syntax error on the very first table.
return reader.ReadToEnd().TrimStart('\uFEFF');
}
}
@@ -109,17 +109,18 @@ public sealed class NetblockWatcher : BackgroundService
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var bans = await db.Blocks
.Where(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now))
.Select(b => new { b.SourceKey, b.CreatedAt })
.AsNoTracking()
.ToListAsync(ct);
.ToListAsync(token);
var ranges = await db.NetworkBans
.Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
.AsNoTracking()
.ToListAsync(ct);
.ToListAsync(token);
candidates = Netblocks.Candidates(
bans.Select(b => (b.SourceKey, b.CreatedAt)),
@@ -87,8 +87,9 @@ public sealed class ObservationWriter : BackgroundService
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
var keys = due.Select(d => d.SourceKey).ToList();
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(ct);
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(token);
var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal);
foreach (var s in due)
@@ -46,14 +46,24 @@ public sealed class RetentionWorker : BackgroundService
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var token = ct;
// The three cut-offs are computed here rather than inside the predicates.
// An arithmetic expression over a policy record is a query parameter the
// precompiler tries to evaluate while it is still reading the source, and
// it fails there ("An exception was thrown while attempting to evaluate a
// LINQ query parameter expression") — a local of the same value is a value
// it can capture.
var observationCutoff = now - policy.ObservationRetention;
var retentionCutoff = now - policy.BanRetention;
try
{
await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Observations.Where(o => o.LastSeenAt < observationCutoff).ExecuteDeleteAsync(token);
await db.Blocks
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct);
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < retentionCutoff)
.ExecuteDeleteAsync(token);
await db.Alerts.Where(a => a.CreatedAt < retentionCutoff).ExecuteDeleteAsync(token);
// The push queue keeps its rows after they resolve, so "how many were
// delivered" and "what did we give up on" are counts of rows rather
@@ -63,13 +73,13 @@ public sealed class RetentionWorker : BackgroundService
// delivery that is owed outlives the alert row it was copied from
// (OPEN-60), which is exactly why the payload is copied.
await db.AlertPushes
.Where(p => (p.PushedAt != null || p.GivenUpAt != null) && p.CreatedAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
.Where(p => (p.PushedAt != null || p.GivenUpAt != null) && p.CreatedAt < retentionCutoff)
.ExecuteDeleteAsync(token);
// The shared streak map (OPEN-52) is the one table this edge writes
// on the request path, so it is also the one that could grow without
// bound if nothing swept it. Same window as observations: a source
// key stops being kept after this long without traffic.
await db.Streaks.Where(t => t.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Streaks.Where(t => t.LastSeenAt < observationCutoff).ExecuteDeleteAsync(token);
// The change log (OPEN-64) is bounded twice, and the second bound is
// the one the age window cannot provide: an operator scripting a
@@ -77,14 +87,14 @@ public sealed class RetentionWorker : BackgroundService
// whose whole use is being readable. The oldest rows go first, so
// what survives is the recent history an operator actually asks for.
var changeAge = now - policy.ChangeRetention;
await db.ConfigChanges.Where(c => c.At < changeAge).ExecuteDeleteAsync(ct);
var held = await db.ConfigChanges.CountAsync(ct);
await db.ConfigChanges.Where(c => c.At < changeAge).ExecuteDeleteAsync(token);
var held = await db.ConfigChanges.CountAsync(token);
var excess = held - policy.ChangeLogMaxRows;
if (excess > 0)
{
var oldest = await db.ConfigChanges.OrderBy(c => c.Id).Select(c => c.Id)
.Take(excess).ToListAsync(ct);
await db.ConfigChanges.Where(c => oldest.Contains(c.Id)).ExecuteDeleteAsync(ct);
.Take(excess).ToListAsync(token);
await db.ConfigChanges.Where(c => oldest.Contains(c.Id)).ExecuteDeleteAsync(token);
}
_health.RecordSuccess(DurabilityHealth.Retention);
}
@@ -0,0 +1,202 @@
CREATE TABLE "alert_pushes" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_alert_pushes" PRIMARY KEY AUTOINCREMENT,
"AlertId" INTEGER NOT NULL,
"Kind" TEXT NOT NULL,
"SourceKey" TEXT NOT NULL,
"Count" INTEGER NOT NULL,
"LastStatusCode" INTEGER NULL,
"LastPath" TEXT NULL,
"Detail" TEXT NOT NULL,
"AlertCreatedAt" INTEGER NOT NULL,
"Attempts" INTEGER NOT NULL,
"CreatedAt" INTEGER NOT NULL,
"NextAttemptAt" INTEGER NULL,
"LastError" TEXT NULL,
"PushedAt" INTEGER NULL,
"GivenUpAt" INTEGER NULL,
"ClaimedBy" TEXT NULL,
"ClaimedAt" INTEGER NULL
);
CREATE TABLE "allow_entries" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_allow_entries" PRIMARY KEY AUTOINCREMENT,
"Match" TEXT NOT NULL,
"Note" TEXT NULL,
"CreatedAt" INTEGER NOT NULL,
"ExpiresAt" INTEGER NULL
);
CREATE TABLE "block_entries" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_block_entries" PRIMARY KEY AUTOINCREMENT,
"SourceKey" TEXT NOT NULL,
"Source" INTEGER NOT NULL,
"CreatedAt" INTEGER NOT NULL,
"ExpiresAt" INTEGER NULL,
"Reason" TEXT NULL,
"RedirectTo" TEXT NULL,
"LastStatusCode" INTEGER NULL,
"LastPath" TEXT NULL,
"LastUserAgent" TEXT NULL,
"LastCountryCode" TEXT NULL,
"LastCity" TEXT NULL,
"LastRegion" TEXT NULL,
"ConsecutiveRefusals" INTEGER NULL
);
CREATE TABLE "config_changes" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_config_changes" PRIMARY KEY AUTOINCREMENT,
"At" INTEGER NOT NULL,
"Section" TEXT NOT NULL,
"Action" TEXT NOT NULL,
"Target" TEXT NOT NULL,
"Detail" TEXT NULL,
"Actor" TEXT NOT NULL
);
CREATE TABLE "country_rules" (
"Code" TEXT NOT NULL CONSTRAINT "PK_country_rules" PRIMARY KEY,
"Name" TEXT NULL,
"IsAllowed" INTEGER NOT NULL,
"UpdatedAt" INTEGER NOT NULL
);
CREATE TABLE "edge_alerts" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_edge_alerts" PRIMARY KEY AUTOINCREMENT,
"SourceKey" TEXT NOT NULL,
"Kind" TEXT NOT NULL,
"Count" INTEGER NOT NULL,
"LastStatusCode" INTEGER NULL,
"LastPath" TEXT NULL,
"CreatedAt" INTEGER NOT NULL,
"Detail" TEXT NOT NULL
);
CREATE TABLE "network_bans" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_network_bans" PRIMARY KEY AUTOINCREMENT,
"Match" TEXT NOT NULL,
"CreatedAt" INTEGER NOT NULL,
"ExpiresAt" INTEGER NULL,
"Reason" TEXT NULL,
"RedirectTo" TEXT NULL
);
CREATE TABLE "policy_settings" (
"Key" TEXT NOT NULL CONSTRAINT "PK_policy_settings" PRIMARY KEY,
"Value" TEXT NOT NULL,
"UpdatedAt" INTEGER NOT NULL
);
CREATE TABLE "rate_rules" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_rate_rules" PRIMARY KEY AUTOINCREMENT,
"Pattern" TEXT NOT NULL,
"LimitPerWindow" INTEGER NOT NULL,
"WindowSeconds" INTEGER NOT NULL,
"Note" TEXT NULL,
"CreatedAt" INTEGER NOT NULL,
"ExpiresAt" INTEGER NULL
);
CREATE TABLE "request_rules" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_request_rules" PRIMARY KEY AUTOINCREMENT,
"Pattern" TEXT NOT NULL,
"Action" INTEGER NOT NULL,
"Note" TEXT NULL,
"CreatedAt" INTEGER NOT NULL,
"ExpiresAt" INTEGER NULL
);
CREATE TABLE "source_observations" (
"SourceKey" TEXT NOT NULL CONSTRAINT "PK_source_observations" PRIMARY KEY,
"FirstSeenAt" INTEGER NOT NULL,
"LastSeenAt" INTEGER NOT NULL,
"MaxConsecutiveRefusals" INTEGER NOT NULL,
"TotalRefusals" INTEGER NOT NULL,
"TotalServerErrorStreak" INTEGER NOT NULL,
"LastStatusCode" INTEGER NULL,
"LastPath" TEXT NULL,
"LastUserAgent" TEXT NULL,
"LastCountryCode" TEXT NULL,
"LastCity" TEXT NULL,
"LastRegion" TEXT NULL
);
CREATE TABLE "source_streaks" (
"SourceKey" TEXT NOT NULL CONSTRAINT "PK_source_streaks" PRIMARY KEY,
"ConsecutiveRefusals" INTEGER NOT NULL,
"MaxConsecutiveRefusals" INTEGER NOT NULL,
"TotalRefusals" INTEGER NOT NULL,
"ConsecutiveServerErrors" INTEGER NOT NULL,
"MaxConsecutiveServerErrors" INTEGER NOT NULL,
"LastAlertedRefusals" INTEGER NOT NULL,
"LastAlertedServerErrors" INTEGER NOT NULL,
"LastRefusalAt" INTEGER NULL,
"LastSeenAt" INTEGER NOT NULL,
"LastStatusCode" INTEGER NULL,
"LastPath" TEXT NULL,
"LastUserAgent" TEXT NULL,
"LastCountryCode" TEXT NULL,
"LastCity" TEXT NULL,
"LastRegion" TEXT NULL,
"Version" INTEGER NOT NULL
);
CREATE INDEX "IX_alert_pushes_AlertId" ON "alert_pushes" ("AlertId");
CREATE INDEX "IX_alert_pushes_PushedAt_GivenUpAt_NextAttemptAt" ON "alert_pushes" ("PushedAt", "GivenUpAt", "NextAttemptAt");
CREATE UNIQUE INDEX "IX_allow_entries_Match" ON "allow_entries" ("Match");
CREATE INDEX "IX_block_entries_ExpiresAt" ON "block_entries" ("ExpiresAt");
CREATE UNIQUE INDEX "IX_block_entries_SourceKey_Source" ON "block_entries" ("SourceKey", "Source");
CREATE INDEX "IX_config_changes_At" ON "config_changes" ("At");
CREATE INDEX "IX_config_changes_Section" ON "config_changes" ("Section");
CREATE INDEX "IX_edge_alerts_CreatedAt" ON "edge_alerts" ("CreatedAt");
CREATE INDEX "IX_network_bans_ExpiresAt" ON "network_bans" ("ExpiresAt");
CREATE UNIQUE INDEX "IX_network_bans_Match" ON "network_bans" ("Match");
CREATE INDEX "IX_rate_rules_ExpiresAt" ON "rate_rules" ("ExpiresAt");
CREATE INDEX "IX_rate_rules_Pattern" ON "rate_rules" ("Pattern");
CREATE INDEX "IX_request_rules_ExpiresAt" ON "request_rules" ("ExpiresAt");
CREATE INDEX "IX_request_rules_Pattern" ON "request_rules" ("Pattern");
CREATE INDEX "IX_source_observations_LastSeenAt" ON "source_observations" ("LastSeenAt");
CREATE INDEX "IX_source_streaks_LastSeenAt" ON "source_streaks" ("LastSeenAt");
@@ -55,14 +55,24 @@ public static class SchemaUpgrader
/// added — empty when there was nothing to add, which is every start after
/// the first one.
/// </summary>
public static async Task<IReadOnlyList<string>> AddMissingTablesAsync(
public static Task<IReadOnlyList<string>> AddMissingTablesAsync(
OpenWafDbContext db, ILogger log, CancellationToken ct = default)
=> AddMissingTablesAsync(db, log, db.Database.GenerateCreateScript(), ct);
/// <summary>
/// The same step for a caller that supplies the DDL rather than letting EF
/// generate it — which is what a build that cannot reach the design-time
/// model has to do. The script is still EF's own output for this provider;
/// it was produced at build time instead of at start-up.
/// </summary>
public static async Task<IReadOnlyList<string>> AddMissingTablesAsync(
OpenWafDbContext db, ILogger log, string script, CancellationToken ct = default)
{
var missing = await MissingTablesAsync(db, ct);
if (missing.Count == 0) return missing;
var statements = SchemaDdl.StatementsFor(
db.Database.GenerateCreateScript(),
script,
new HashSet<string>(missing, StringComparer.OrdinalIgnoreCase));
if (statements.Count == 0)
@@ -203,6 +213,85 @@ public static class SchemaUpgrader
return tables;
}
/// <summary>
/// The tables the model this process is running with describes.
///
/// Asked of the runtime model rather than the design-time one. The two answer
/// the same question for table names, and the design-time one is not merely
/// the more ceremonial choice: EF refuses it outright in a NativeAOT build
/// ("Design-time DbContext operations are not supported when publishing with
/// NativeAOT"), which made this one call the reason a compiled edge refused to
/// start at all. The runtime model is the one the process actually queries
/// with, so it is also the more honest thing to ask.
///
/// Asked per entity type rather than of the relational model, and that is not
/// style either: measured on a compiled model, <c>GetRelationalModel()</c> on
/// the runtime model threw <c>The annotation 'Relational:DefaultMappings'
/// cannot be added because an annotation with the same name already exists on
/// the object EntityType: CountryRule</c> — the relational model of a compiled
/// model already exists, and building it a second time collides with itself.
/// <c>GetTableName()</c> reads the mapping directly, and it is the same call
/// <see cref="BaselineIfUntrackedAsync"/> already makes on a migration's
/// target model.
/// </summary>
private static IReadOnlyList<string> ModelTables(OpenWafDbContext db)
=> db.GetService<IDesignTimeModel>().Model.GetRelationalModel().Tables.Select(table => table.Name).ToList();
=> db.Model.GetEntityTypes()
.Select(entity => entity.GetTableName())
.Where(name => name is not null)
.Select(name => name!)
.Distinct()
.ToList();
/// <summary>
/// The DDL this build carries for the provider in use. Null when it carries
/// none — the caller decides what that means, and it is never "no schema".
/// </summary>
public static string? EmbeddedScriptFor(OpenWafDbContext db)
=> EmbeddedSchema.ScriptFor(db.Database.ProviderName);
/// <summary>
/// Create the tables this database does not have from the DDL this build
/// carries, instead of from a model EF is asked to build at run time.
///
/// This is the <c>ensurecreated</c> step for a binary that cannot run
/// <c>ensurecreated</c>. What it does is the same thing: only what is absent
/// is created, from the provider-shaped statements the model generated at
/// build time, and a table that already holds the operator's lists is left
/// exactly as it is.
/// </summary>
public static async Task<IReadOnlyList<string>> ApplyScriptAsync(
OpenWafDbContext db, ILogger log, CancellationToken ct = default)
{
var script = EmbeddedScriptFor(db)
?? throw new NotSupportedException(
$"the schema script this build carries has no entry for {db.Database.ProviderName}; "
+ "the script strategy is only available for a provider whose DDL was generated at build time.");
var missing = await MissingTablesAsync(db, ct);
if (missing.Count == 0) return missing;
var statements = SchemaDdl.StatementsFor(
script,
new HashSet<string>(missing, StringComparer.OrdinalIgnoreCase));
if (statements.Count == 0)
{
log.LogError(
"edge: the database is missing {Tables} but the schema script this build carries has no "
+ "statement that creates them — the affected pillars will report themselves unavailable rather "
+ "than answer with nothing.",
string.Join(", ", missing));
return [];
}
foreach (var statement in statements)
await db.Database.ExecuteSqlRawAsync(statement, ct);
log.LogWarning(
"edge: the schema came from the DDL this build carries rather than from a model built at start-up — "
+ "created {Count} table(s): {Tables}. Nothing that was already in the database was touched.",
missing.Count, string.Join(", ", missing));
return missing;
}
}
@@ -49,13 +49,20 @@ public sealed class SharedStreakTracker : IStreakTracker
{
if (string.IsNullOrEmpty(sourceKey)) return StreakOutcome.None;
// Copied to a local on purpose. EF's query precompiler (the only way a
// NativeAOT build can run a LINQ query at all) fails on a captured method
// parameter — "IdentifierName of type ParameterSymbol: sourceKey" — while
// a local of the same value precompiles. dotnet/efcore#35887, fixed only
// in the 12.0-preview1 line.
var key = sourceKey;
for (var attempt = 0; ; attempt++)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
try
{
var row = db.Streaks.FirstOrDefault(t => t.SourceKey == sourceKey);
var row = db.Streaks.FirstOrDefault(t => t.SourceKey == key);
var isNew = row is null;
row ??= new SourceStreak { SourceKey = sourceKey, LastSeenAt = now };
@@ -88,7 +95,7 @@ public sealed class SharedStreakTracker : IStreakTracker
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
EvictIdle(db, now, policy);
EvictIdle(now, policy);
return db.Streaks.AsNoTracking()
.Where(t => t.TotalRefusals > 0 || t.MaxConsecutiveServerErrors > 0)
.ToList()
@@ -103,7 +110,8 @@ public sealed class SharedStreakTracker : IStreakTracker
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var t = db.Streaks.AsNoTracking().FirstOrDefault(x => x.SourceKey == sourceKey);
var key = sourceKey;
var t = db.Streaks.AsNoTracking().FirstOrDefault(x => x.SourceKey == key);
return t is null ? null : new StreakSnapshot(
t.SourceKey, t.MaxConsecutiveRefusals, t.TotalRefusals, t.MaxConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastUserAgent, t.LastCountryCode, t.LastCity, t.LastRegion,
@@ -128,14 +136,36 @@ public sealed class SharedStreakTracker : IStreakTracker
var skip = Math.Max(0, offset);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
EvictIdle(db, now, policy);
EvictIdle(now, policy);
var query = db.Streaks.AsNoTracking()
.Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0);
if (sourceKey is not null) query = query.Where(t => t.SourceKey == sourceKey);
// Two literal chains rather than one IQueryable assembled by an if. The
// precompiler reads the query from the source text, so a query that is
// composed across statements is "dynamic" to it however it is written at
// run time — and this listing has to work in a NativeAOT build too.
var key = sourceKey;
if (key is null)
{
standingTotal = db.Streaks.AsNoTracking()
.Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0)
.Count();
return db.Streaks.AsNoTracking()
.Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0)
.OrderByDescending(t => t.ConsecutiveRefusals)
.ThenByDescending(t => t.ConsecutiveServerErrors)
.ThenByDescending(t => t.LastSeenAt)
.Skip(skip).Take(take)
.ToList()
.Select(t => new LiveStreak(
t.SourceKey, t.ConsecutiveRefusals, t.ConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastCountryCode, t.LastSeenAt))
.ToList();
}
standingTotal = query.Count();
return query
standingTotal = db.Streaks.AsNoTracking()
.Where(t => (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0) && t.SourceKey == key)
.Count();
return db.Streaks.AsNoTracking()
.Where(t => (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0) && t.SourceKey == key)
.OrderByDescending(t => t.ConsecutiveRefusals)
.ThenByDescending(t => t.ConsecutiveServerErrors)
.ThenByDescending(t => t.LastSeenAt)
@@ -165,20 +195,25 @@ public sealed class SharedStreakTracker : IStreakTracker
if (string.IsNullOrEmpty(sourceKey)) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var key = sourceKey;
db.Streaks
.Where(t => t.SourceKey == sourceKey && (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0))
.Where(t => t.SourceKey == key && (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0))
// The values are lambda-valued rather than plain constants: the query
// precompiler's funcletizer throws a NullReferenceException on the
// conversion it inserts around a constant in a set-list.
.ExecuteUpdate(u => u
.SetProperty(t => t.ConsecutiveRefusals, 0)
.SetProperty(t => t.ConsecutiveServerErrors, 0)
.SetProperty(t => t.LastAlertedRefusals, 0)
.SetProperty(t => t.LastAlertedServerErrors, 0));
.SetProperty(t => t.ConsecutiveRefusals, r => 0)
.SetProperty(t => t.ConsecutiveServerErrors, r => 0)
.SetProperty(t => t.LastAlertedRefusals, r => 0)
.SetProperty(t => t.LastAlertedServerErrors, r => 0));
}
public void Forget(string sourceKey)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.Streaks.Where(t => t.SourceKey == sourceKey).ExecuteDelete();
var key = sourceKey;
db.Streaks.Where(t => t.SourceKey == key).ExecuteDelete();
}
/// <summary>No cap to carry: <see cref="EdgePolicy.MaxTrackedSources"/>
@@ -187,10 +222,18 @@ public sealed class SharedStreakTracker : IStreakTracker
/// the retention worker.</summary>
public void Configure(EdgePolicy policy) { }
private static void EvictIdle(OpenWafDbContext db, DateTimeOffset now, EdgePolicy policy)
/// <summary>Drop the rows no traffic has touched for longer than the idle
/// window. The context is resolved here rather than passed in: a query whose
/// root is a method parameter cannot be precompiled at all
/// (dotnet/efcore#38030), and precompiled queries are the only queries a
/// NativeAOT build can run.</summary>
private void EvictIdle(DateTimeOffset now, EdgePolicy policy)
{
if (policy.StateIdleTtl <= TimeSpan.Zero) return;
db.Streaks.Where(t => t.LastSeenAt < now - policy.StateIdleTtl).ExecuteDelete();
var idleBefore = now - policy.StateIdleTtl;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.Streaks.Where(t => t.LastSeenAt < idleBefore).ExecuteDelete();
}
private static StreakState Read(SourceStreak row) => new()
+1 -1
View File
@@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "10.0.0",
"version": "10.0.12",
"commands": [
"dotnet-ef"
],
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env bash
# What a NativeAOT edge actually does on this tree, measured rather than argued.
#
# This is not a gate. It is the reproduction of a verdict: the AOT build compiles,
# starts, and creates its own schema, and then every EF query it makes fails,
# because EF cannot compile a LINQ query at run time in a NativeAOT binary and the
# only alternative — precompiling them at build time — does not produce compilable
# code for this model. Run it when the EF version changes, before deciding again
# whether AOT is worth the price.
#
# scripts/aot-probe.sh # publish + start + curl
# scripts/aot-probe.sh --regen # regenerate the EF compiled model first
#
# Needs the NativeAOT toolchain (clang/lld) and takes a few minutes: the ILC step
# alone is over a minute. It is deliberately not in `ci-gates.sh all` — a machine
# without clang would then report a build failure as if the product were broken.
#
# The compiled model is generated for sqlite, the provider the shipped image uses,
# and is compiled into the binary only under -p:OpenWafCompiledModel=true; the
# framework-dependent build still builds its model at start-up and serves both
# providers. See dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj.
set -uo pipefail
cd "$(dirname "$0")/.." || exit 2
RUNTIME=$(dotnet --info 2>/dev/null | sed -n 's/^ *RID: *//p' | head -1)
[ -n "$RUNTIME" ] || { printf 'cannot work out this RID from the dotnet --info output\n' >&2; exit 2; }
PUBLISH=dotnet/OpenWaf.Edge/bin/Release/net10.0/$RUNTIME/publish
BIN=$PUBLISH/OpenWaf.Edge
if [ "${1:-}" = "--regen" ]; then
printf '\n=== regenerate the EF compiled model (sqlite) ===\n'
rm -rf dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel
# OPENWAF_MIGRATE_PROVIDER=sqlite: the design-time factory defaults to postgres,
# and a postgres compiled model in a sqlite image is a different kind of broken.
(cd dotnet && OPENWAF_MIGRATE_PROVIDER=sqlite dotnet ef dbcontext optimize \
--project OpenWaf.Infrastructure --startup-project OpenWaf.Infrastructure \
--context OpenWafDbContext --namespace OpenWaf.Infrastructure.Persistence.CompiledModel \
--output-dir Persistence/CompiledModel) || { printf 'compiled model generation failed\n' >&2; exit 1; }
fi
printf '\n=== publish NativeAOT (%s) ===\n' "$RUNTIME"
# IlcTreatWarningsAsErrors=false and the two NoWarn codes are what let the build
# finish at all: EF's assemblies produce IL2104/IL3053 trim warnings and the
# schema step still calls three design-time APIs. Those are recorded, not hidden —
# the counts are printed below from the same log.
AOT_LOG=/tmp/openwaf-aot-publish.log
(cd dotnet && dotnet publish OpenWaf.Edge/OpenWaf.Edge.csproj -c Release -r "$RUNTIME" \
-p:PublishAot=true -p:InvariantGlobalization=true -p:DebugType=none \
-p:OpenWafCompiledModel=true -p:NoWarn=IL2026%3BIL3050 \
-p:IlcTreatWarningsAsErrors=false) >"$AOT_LOG" 2>&1
publish_status=$?
# The warning count only means something if the ILC actually ran. An up-to-date
# publish skips "Generating native code" and would otherwise report zero warnings
# for a build that produced no output at all.
generated=no
grep -q 'Generating native code' "$AOT_LOG" && generated=yes
printf 'publish exit %s; native code generated: %s; IL warnings: %s; errors: %s\n' \
"$publish_status" "$generated" "$(grep -c ' warning IL[0-9]' "$AOT_LOG")" \
"$(grep -c ' error ' "$AOT_LOG")"
[ "$publish_status" -eq 0 ] || { tail -20 "$AOT_LOG"; exit 1; }
[ -x "$BIN" ] || { printf 'no native binary at %s\n' "$BIN" >&2; exit 1; }
# Absolute, because --contentRoot is resolved against the binary's own directory
# rather than the caller's: measured, a relative one came back doubled
# (…/publish/dotnet/OpenWaf.Edge/…/publish/) and the host died in
# DirectoryNotFoundException before it could say anything useful.
PUBLISH="$(cd "$PUBLISH" && pwd)"
printf 'native binary: %s bytes\n' "$(wc -c < "$BIN" | tr -d ' ')"
EDGE_PORT=${EDGE_PORT:-18077}
UP_PORT=${UP_PORT:-18078}
DB=/tmp/openwaf-aot-probe-$$.db
LOG=/tmp/openwaf-aot-probe-edge.log
TOKEN=aot-probe-token
rm -f "$DB" "$DB-shm" "$DB-wal"
cleanup() {
[ -n "${EDGE_PID:-}" ] && kill "$EDGE_PID" 2>/dev/null
[ -n "${UP_PID:-}" ] && kill "$UP_PID" 2>/dev/null
rm -f "$DB" "$DB-shm" "$DB-wal"
}
trap cleanup EXIT
mkdir -p /tmp/openwaf-upstream && printf 'aot probe upstream\n' > /tmp/openwaf-upstream/body.txt
python3 -m http.server "$UP_PORT" --bind 127.0.0.1 -d /tmp/openwaf-upstream >/dev/null 2>&1 &
UP_PID=$!
# OPENWAF_SCHEMA=script is the point of the exercise: EnsureCreated and
# GenerateCreateScript both go through EF's design-time model, which a NativeAOT
# build refuses outright, so the DDL is generated at build time and read out of
# the binary. The schema-script gate keeps that file equal to what the model
# generates.
ASPNETCORE_URLS="http://127.0.0.1:$EDGE_PORT" \
OPENWAF_ADMIN_TOKEN="$TOKEN" \
OPENWAF_SCHEMA=script \
ConnectionStrings__OpenWaf="Data Source=$DB" \
Database__Provider=sqlite \
OpenWaf__Policy__Mode=Enforce \
OpenWaf__Policy__TrustProxyHeaders=true \
OpenWaf__Policy__StreakThreshold=3 \
ReverseProxy__Clusters__upstream__Destinations__upstream1__Address="http://127.0.0.1:$UP_PORT/" \
"$BIN" --contentRoot "$PUBLISH" >"$LOG" 2>&1 &
EDGE_PID=$!
for _ in $(seq 1 60); do
curl -fsS "http://127.0.0.1:$EDGE_PORT/healthz" >/dev/null 2>&1 && break
sleep 0.25
done
pass=0; fail=0
check() {
if [ "$2" = "$3" ]; then pass=$((pass+1)); printf ' ok %-52s %s\n' "$1" "$3"
else fail=$((fail+1)); printf ' FAIL %-52s expected %s, got %s\n' "$1" "$2" "$3"; fi
}
code() { curl -s -o /dev/null -m 5 -w '%{http_code}' "$@"; }
printf '\n=== the schema step ===\n'
tables=$(python3 -c "import sqlite3;print(len([r for r in sqlite3.connect('$DB').execute(\"select name from sqlite_master where type='table' and name != 'sqlite_sequence'\")]))" 2>/dev/null || echo 0)
check 'tables the shipped DDL created' 12 "$tables"
printf '\n=== the curl assertions ===\n'
check 'healthz answers' 200 "$(code "http://127.0.0.1:$EDGE_PORT/healthz")"
check 'a request reaches the upstream' 200 "$(code "http://127.0.0.1:$EDGE_PORT/body.txt")"
check 'an operator block is accepted' 204 "$(code -X POST -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-d '{"ip":"198.51.100.7","reason":"aot probe","redirectTo":"https://honeypot.example.org/"}' \
"http://127.0.0.1:$EDGE_PORT/admin-api/blocks")"
check 'the blocked source is redirected' 301 "$(code -H 'X-Forwarded-For: 198.51.100.7' \
"http://127.0.0.1:$EDGE_PORT/body.txt")"
ban=""
for _ in 1 2 3 4; do ban="$ban $(code -H 'X-Forwarded-For: 203.0.113.66' "http://127.0.0.1:$EDGE_PORT/probe")"; done
check 'four probes draw the streak ban' " 403 403 403 403" "$ban"
check 'the state surface answers' 200 "$(code -H "Authorization: Bearer $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/state")"
HEALTHCHECK_PORT="$EDGE_PORT" "$BIN" --healthcheck >/dev/null 2>&1
check 'the healthcheck mode answers 0' 0 "$?"
printf '\npassed %s, failed %s\n' "$pass" "$fail"
printf '\n=== what the edge said about its own queries ===\n'
grep -c "Query wasn't precompiled and dynamic code isn't supported with NativeAOT" "$LOG" \
| sed 's/^/ queries refused at run time: /'
grep -c "Application startup exception" "$LOG" | sed 's/^/ startup exceptions: /'
printf ' full log: %s\n' "$LOG"
[ "$fail" -eq 0 ] || exit 1
+38 -3
View File
@@ -4,7 +4,7 @@
# the job log still names the gate that failed; `all` runs them in order and
# stops at the first failure.
#
# scripts/ci-gates.sh restore|build|unit|integration|smoke|image|compose-smoke|all
# scripts/ci-gates.sh restore|build|unit|integration|schema-script|smoke|image|compose-smoke|all
# scripts/ci-gates.sh console (needs a real Chromium; not part of `all`)
# scripts/ci-gates.sh readme-counts scripts/<gate> (compares the README's
# assertion count with what that gate printed
@@ -47,6 +47,40 @@ integration() { banner integration; dotnet test dotnet/OpenWaf.Tests.Integra
smoke() { banner smoke; ./scripts/smoke.sh; }
# The DDL the shipped binary carries (Persistence/Schema/schema.sqlite.sql) is
# generated from the EF model, not written by hand. This gate regenerates it and
# refuses the run when the committed copy is not what the current model produces,
# which is what keeps "the image creates the schema the model describes" a
# checked claim. It exists because the NativeAOT build cannot ask EF to build a
# model at run time at all, so for that build the file *is* the schema step.
schema_script() {
banner schema-script
local committed=dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql
local regenerated
regenerated="$(mktemp)"
if ! dotnet tool restore >/dev/null 2>&1; then
printf 'the pinned dotnet-ef tool could not be restored: cannot check the schema script\n' >&2
return 2
fi
# OPENWAF_MIGRATE_PROVIDER=sqlite: the design-time factory defaults to postgres,
# and a postgres DDL checked against a sqlite file would fail for the wrong
# reason.
if ! (cd dotnet && OPENWAF_MIGRATE_PROVIDER=sqlite dotnet ef dbcontext script \
-c OpenWafDbContext -p OpenWaf.Infrastructure -s OpenWaf.Infrastructure \
-o "$regenerated" >/dev/null); then
printf 'dotnet ef dbcontext script could not run: cannot check the schema script\n' >&2
return 2
fi
if cmp -s "$committed" "$regenerated"; then
printf ' ok the committed schema script is what the current model generates (%s bytes)\n' \
"$(wc -c < "$committed" | tr -d ' ')"
else
printf ' FAIL the committed schema script is not what the current model generates\n' >&2
diff -u "$committed" "$regenerated" | head -40 >&2
return 1
fi
}
# The plain build the README shows, plus its size: the compose path would hide a
# Dockerfile regression that this step catches.
image() { banner image; docker build -t openwaf:ci .; docker image ls openwaf:ci --format '{{.Repository}}:{{.Tag}} {{.Size}}'; }
@@ -191,6 +225,7 @@ case "${1:-all}" in
unit) unit ;;
integration) integration ;;
smoke) smoke ;;
schema-script) schema_script ;;
image) image ;;
compose-smoke) compose_smoke ;;
console) console ;;
@@ -201,7 +236,7 @@ case "${1:-all}" in
# if the gates that produced them and the check that reads them ran in the
# same invocation.
export GATE_TOTALS_DIR="${GATE_TOTALS_DIR:-$(mktemp -d)}"
restore; build; unit; integration; smoke; image; compose_smoke
restore; build; unit; integration; schema-script; smoke; image; compose_smoke
# The two gates `all` actually ran. console is not among them, so its README
# number is verified by the console job (or by an operator who ran it and
# then calls readme-counts with the same GATE_TOTALS_DIR).
@@ -214,7 +249,7 @@ case "${1:-all}" in
printf 'If a workflow or script changed, run: %s lint\n' "$0"
;;
*)
printf 'usage: %s restore|build|unit|integration|smoke|image|compose-smoke|console|lint|readme-counts|all\n' "$0" >&2
printf 'usage: %s restore|build|unit|integration|schema-script|smoke|image|compose-smoke|console|lint|readme-counts|all\n' "$0" >&2
exit 2
;;
esac
+24 -4
View File
@@ -153,6 +153,28 @@ print('' if v is None else (json.dumps(v) if isinstance(v,(bool,int,float)) else
# assertion, which is exactly the kind of gate that reports nothing.
alerts_for() { admin "$EDGE/admin-api/alerts?limit=500" | jcount "b['kind']=='$1' and b['sourceKey']=='$2'"; }
# Read the alert rows for a source once they have stopped moving. The alert is
# written after the response is, so a count taken the instant the last request
# returns undercounts — and a fixed pause is a coin toss on a loaded host: the
# same tree read 3 rows on one run and 1 on the next, and the assertion that
# follows is about a settled number either way. Three equal reads in a row is the
# definition of settled here, with a bounded wait so a queue that never settles
# fails the gate rather than hiding.
settle_alerts() {
local prev=-1 stable=0 now
for _ in $(seq 1 24); do
now=$(alerts_for "$1" "$2")
if [ "$now" = "$prev" ]; then
stable=$((stable + 1))
[ "$stable" -ge 3 ] && { printf '%s' "$now"; return; }
else
stable=0; prev=$now
fi
sleep 0.5
done
printf '%s' "${prev:-0}"
}
cleanup() {
admin -X PUT -H 'Content-Type: application/json' \
-d '{"mode":"Enforce","geo":"Off","streakThreshold":10,"trustProxyHeaders":false}' "$EDGE/admin-api/policy" >/dev/null
@@ -377,8 +399,7 @@ check 'a server_error_streak alert was written for that source' 'yes' "$([ "$ERR
# response is, so a count read the instant the last request returns undercounts
# — the first version of this line read 1 where the settled number was 2, and a
# number that is wrong by a race is worse than no number.
sleep 2
ERR_SETTLED=$(alerts_for server_error_streak "$ERR_SRC")
ERR_SETTLED=$(settle_alerts server_error_streak "$ERR_SRC")
ERR_ROWS=$(( ${ERR_SETTLED:-0} - ${BEFORE_ERR:-0} ))
printf ' info alert rows for 12 server errors at N=3: %s (expected 3: the crossing, then the doublings)\n' "$ERR_ROWS"
check 'a 5xx storm alerts per escalation, not per request' '3' "$ERR_ROWS"
@@ -404,8 +425,7 @@ check 'the dry run is visible as a candidate_ban alert' 'yes' "$OBS_ALERT"
# observed and the threshold stays "triggered" on all eight past N. A dry run
# that writes a row per request is the safest mode doubling as a way to grow the
# operator's tables.
sleep 2
OBS_ROWS=$(( $(alerts_for candidate_ban "$OBS_SRC") - ${BEFORE_OBS:-0} ))
OBS_ROWS=$(( $(settle_alerts candidate_ban "$OBS_SRC") - ${BEFORE_OBS:-0} ))
printf ' info candidate_ban rows for 10 refusals at N=3: %s (expected 2: at 3 and at 6)\n' "$OBS_ROWS"
check 'a dry run announces a candidate ban per escalation, not per request' '2' "$OBS_ROWS"
admin -X PUT -H 'Content-Type: application/json' \