diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e21ee2..02d1972 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/Dockerfile b/Dockerfile index 7166849..c231c90 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/README.md b/README.md index a13dc86..4a0dd21 100644 --- a/README.md +++ b/README.md @@ -345,8 +345,13 @@ dotnet ef migrations add --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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1980572..9793ce0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs index cfd57c5..00bbf7e 100644 --- a/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs +++ b/dotnet/OpenWaf.Edge/Startup/EdgeStateWarmer.cs @@ -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( } } + /// + /// The script strategy's share of the race for the schema. + /// + /// Same rule as : 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. + /// + 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; } diff --git a/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj index 0fbae39..5342c78 100644 --- a/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj +++ b/dotnet/OpenWaf.Infrastructure/OpenWaf.Infrastructure.csproj @@ -8,31 +8,52 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + - + + + false net10.0 enable enable + + + + + + + + + diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs b/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs index d45f2df..d532df2 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs @@ -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(); 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(); + 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; } /// For the surfaces and the tests: the queue as the database holds /// it, not as this process last cached it. - public async Task ReadCountsAsync(CancellationToken ct = default) + public Task ReadCountsAsync(CancellationToken ct = default) + => _url is null + ? Task.FromResult(new PushQueueCounts(0, 0, 0, null, null, 0)) + : QueryCountsAsync(ct); + + /// The queue's numbers, each one a literal chain from the DbSet. + /// + /// 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. + /// + private async Task 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(), ct); + var db = scope.ServiceProvider.GetRequiredService(); + 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)); } /// 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. public sealed record PushQueueCounts( int Pending, int Delivered, int GivenUp, string? LastError, DateTimeOffset? OldestPendingAt, + int Attempts); + +/// 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. +internal sealed record AlertPushPayload( + string Kind, + string SourceKey, + int Count, + int? LastStatusCode, + string? LastPath, + DateTimeOffset CreatedAt, + string Detail, int Attempts) { - public static async Task 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; diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs index 9258b73..c819348 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -172,8 +172,10 @@ public sealed class BlockStore { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + 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(); + // 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(); - 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(); - 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(); + 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(); + 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(); + 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(); - 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(); - 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 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; - } - - /// Ranges are always the operator's, so the provenance filter has - /// one answer for them: an engine filter matches nothing. - private static IQueryable 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; - } } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AlertPushEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AlertPushEntityType.cs new file mode 100644 index 0000000..0cc0426 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AlertPushEntityType.cs @@ -0,0 +1,195 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + alertCreatedAt.SetValueConverter(new ValueConverter( + 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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + claimedAt.SetValueConverter(new ValueConverter( + 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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + givenUpAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + nextAttemptAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + pushedAt.SetValueConverter(new ValueConverter( + 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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AllowEntryEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AllowEntryEntityType.cs new file mode 100644 index 0000000..f81db67 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/AllowEntryEntityType.cs @@ -0,0 +1,96 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + expiresAt.SetValueConverter(new ValueConverter( + 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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/BlockEntryEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/BlockEntryEntityType.cs new file mode 100644 index 0000000..bda75a1 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/BlockEntryEntityType.cs @@ -0,0 +1,169 @@ +// +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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + expiresAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("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("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("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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/ConfigChangeEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/ConfigChangeEntityType.cs new file mode 100644 index 0000000..01fa38a --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/ConfigChangeEntityType.cs @@ -0,0 +1,109 @@ +// +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("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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + at.SetValueConverter(new ValueConverter( + 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("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("
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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/CountryRuleEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/CountryRuleEntityType.cs new file mode 100644 index 0000000..725c813 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/CountryRuleEntityType.cs @@ -0,0 +1,80 @@ +// +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("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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + updatedAt.SetValueConverter(new ValueConverter( + 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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/EdgeAlertEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/EdgeAlertEntityType.cs new file mode 100644 index 0000000..a5737c8 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/EdgeAlertEntityType.cs @@ -0,0 +1,112 @@ +// +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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/NetworkBanEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/NetworkBanEntityType.cs new file mode 100644 index 0000000..9bebaad --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/NetworkBanEntityType.cs @@ -0,0 +1,107 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + expiresAt.SetValueConverter(new ValueConverter( + 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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextAssemblyAttributes.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextAssemblyAttributes.cs new file mode 100644 index 0000000..0932100 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextAssemblyAttributes.cs @@ -0,0 +1,9 @@ +// +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))] diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModel.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModel.cs new file mode 100644 index 0000000..dddbe08 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModel.cs @@ -0,0 +1,47 @@ +// +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(); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModelBuilder.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModelBuilder.cs new file mode 100644 index 0000000..6f23b82 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/OpenWafDbContextModelBuilder.cs @@ -0,0 +1,49 @@ +// +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"); + } + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/PolicySettingEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/PolicySettingEntityType.cs new file mode 100644 index 0000000..8ba0e4f --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/PolicySettingEntityType.cs @@ -0,0 +1,71 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + updatedAt.SetValueConverter(new ValueConverter( + 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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RateRuleEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RateRuleEntityType.cs new file mode 100644 index 0000000..90ddeb2 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RateRuleEntityType.cs @@ -0,0 +1,112 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + expiresAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RequestRuleEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RequestRuleEntityType.cs new file mode 100644 index 0000000..47796da --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/RequestRuleEntityType.cs @@ -0,0 +1,106 @@ +// +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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + createdAt.SetValueConverter(new ValueConverter( + 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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + expiresAt.SetValueConverter(new ValueConverter( + 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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceObservationEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceObservationEntityType.cs new file mode 100644 index 0000000..cb768b5 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceObservationEntityType.cs @@ -0,0 +1,147 @@ +// +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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + firstSeenAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + lastSeenAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceStreakEntityType.cs b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceStreakEntityType.cs new file mode 100644 index 0000000..4f0f575 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/CompiledModel/SourceStreakEntityType.cs @@ -0,0 +1,183 @@ +// +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("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("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("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("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("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("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("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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), + nullable: true); + lastRefusalAt.SetValueConverter(new ValueConverter( + 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("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("k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + lastSeenAt.SetValueConverter(new ValueConverter( + 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("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("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("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("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("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("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); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs index ae54d21..4c993d2 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgePolicyProvider.cs @@ -62,7 +62,8 @@ public sealed class EdgePolicyProvider { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); - 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(); + 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; } } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs index 8a5647c..7ef562d 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EdgeStateStore.cs @@ -143,10 +143,11 @@ public sealed class EdgeStateStore using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + 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 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); } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/EmbeddedSchema.cs b/dotnet/OpenWaf.Infrastructure/Persistence/EmbeddedSchema.cs new file mode 100644 index 0000000..900a9f4 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/EmbeddedSchema.cs @@ -0,0 +1,53 @@ +using System.Text; + +namespace OpenWaf.Infrastructure.Persistence; + +/// +/// 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 EnsureCreated and GenerateCreateScript 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. +/// +public static class EmbeddedSchema +{ + private const string SqliteResource = "OpenWaf.Infrastructure.Persistence.Schema.schema.sqlite.sql"; + + /// + /// 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". + /// + public static string? ScriptFor(string? providerName) + => providerName switch + { + "Microsoft.EntityFrameworkCore.Sqlite" => Read(SqliteResource), + _ => null + }; + + /// + /// The resource names this build embeds, so the gate can enumerate them + /// instead of hard-coding the file list a second time. + /// + public static IReadOnlyList 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'); + } +} diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs b/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs index 6e3bb96..4231925 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/NetblockWatcher.cs @@ -109,17 +109,18 @@ public sealed class NetblockWatcher : BackgroundService { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + 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)), diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs index c5d129c..51a0a15 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs @@ -87,8 +87,9 @@ public sealed class ObservationWriter : BackgroundService { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + 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) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs index 6a7fe38..192c610 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs @@ -46,14 +46,24 @@ public sealed class RetentionWorker : BackgroundService using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); + 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); } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql b/dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql new file mode 100644 index 0000000..9720e76 --- /dev/null +++ b/dotnet/OpenWaf.Infrastructure/Persistence/Schema/schema.sqlite.sql @@ -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"); + + diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs index 9b7c47f..6abc5df 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SchemaUpgrader.cs @@ -55,14 +55,24 @@ public static class SchemaUpgrader /// added — empty when there was nothing to add, which is every start after /// the first one. /// - public static async Task> AddMissingTablesAsync( + public static Task> AddMissingTablesAsync( OpenWafDbContext db, ILogger log, CancellationToken ct = default) + => AddMissingTablesAsync(db, log, db.Database.GenerateCreateScript(), ct); + + /// + /// 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. + /// + public static async Task> 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(missing, StringComparer.OrdinalIgnoreCase)); if (statements.Count == 0) @@ -203,6 +213,85 @@ public static class SchemaUpgrader return tables; } + /// + /// 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, GetRelationalModel() on + /// the runtime model threw The annotation 'Relational:DefaultMappings' + /// cannot be added because an annotation with the same name already exists on + /// the object EntityType: CountryRule — the relational model of a compiled + /// model already exists, and building it a second time collides with itself. + /// GetTableName() reads the mapping directly, and it is the same call + /// already makes on a migration's + /// target model. + /// private static IReadOnlyList ModelTables(OpenWafDbContext db) - => db.GetService().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(); + + /// + /// 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". + /// + public static string? EmbeddedScriptFor(OpenWafDbContext db) + => EmbeddedSchema.ScriptFor(db.Database.ProviderName); + + /// + /// 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 ensurecreated step for a binary that cannot run + /// ensurecreated. 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. + /// + public static async Task> 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(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; + } } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs b/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs index f7aef76..e246729 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/SharedStreakTracker.cs @@ -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(); 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(); - 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(); - 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(); - 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(); + 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(); - db.Streaks.Where(t => t.SourceKey == sourceKey).ExecuteDelete(); + var key = sourceKey; + db.Streaks.Where(t => t.SourceKey == key).ExecuteDelete(); } /// No cap to carry: @@ -187,10 +222,18 @@ public sealed class SharedStreakTracker : IStreakTracker /// the retention worker. public void Configure(EdgePolicy policy) { } - private static void EvictIdle(OpenWafDbContext db, DateTimeOffset now, EdgePolicy policy) + /// 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. + 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(); + db.Streaks.Where(t => t.LastSeenAt < idleBefore).ExecuteDelete(); } private static StreakState Read(SourceStreak row) => new() diff --git a/dotnet/dotnet-tools.json b/dotnet/dotnet-tools.json index 0d6d304..5c1165b 100644 --- a/dotnet/dotnet-tools.json +++ b/dotnet/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "dotnet-ef": { - "version": "10.0.0", + "version": "10.0.12", "commands": [ "dotnet-ef" ], diff --git a/scripts/aot-probe.sh b/scripts/aot-probe.sh new file mode 100755 index 0000000..a1fdcd2 --- /dev/null +++ b/scripts/aot-probe.sh @@ -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 diff --git a/scripts/ci-gates.sh b/scripts/ci-gates.sh index 2e425d2..3d95875 100755 --- a/scripts/ci-gates.sh +++ b/scripts/ci-gates.sh @@ -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/ (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 diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index ceb5de5..295a73e 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -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' \