aiwaf 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +93 -22
- package/NOTICE +58 -0
- package/README.md +629 -23
- package/index.js +3 -0
- package/lib/adonisMiddleware.js +7 -4
- package/lib/bodyParser.js +25 -0
- package/lib/fastifyPlugin.js +15 -0
- package/lib/hapiPlugin.js +22 -0
- package/lib/koaMiddleware.js +7 -4
- package/lib/nativePipeline.js +191 -0
- package/lib/nestMiddleware.js +3 -1
- package/lib/nextMiddleware.js +6 -4
- package/lib/rateLimiter.js +14 -3
- package/lib/settingsCompat.js +1 -0
- package/lib/wafMiddleware.js +27 -8
- package/lib/wasmAdapter.js +24 -1
- package/licenses/MIT.txt +22 -0
- package/package.json +31 -22
package/README.md
CHANGED
|
@@ -2,26 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
AIWAF is a multi-runtime web application firewall toolkit for Python, Node.js, WebAssembly, and Java applications. It combines deterministic request controls with route-aware policies, reputation tracking, request logging, training pipelines, and optional Isolation Forest anomaly detection.
|
|
4
4
|
|
|
5
|
-
This is the single authoritative README for the monorepo and every published AIWAF package. Release workflows stage this file
|
|
5
|
+
This is the single authoritative README for the monorepo and every published AIWAF package. Release workflows stage this file, the root `LICENSE`, `NOTICE`, and `licenses/` into package artifacts when a registry requires package-local copies.
|
|
6
6
|
|
|
7
7
|
AIWAF is a defense-in-depth component. It does not replace secure application code, authentication and authorization, dependency patching, TLS, a reverse proxy, or a managed edge WAF.
|
|
8
8
|
|
|
9
9
|
## Packages
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
The next local drafts add bounded Java SQL inspection, a JavaScript `bodyParser`
|
|
12
|
+
helper, and atomic Python Redis rate buckets. They have not been published.
|
|
13
|
+
|
|
14
|
+
For custom Node HTTP servers or middleware registered before a framework's
|
|
15
|
+
parser, call `aiwaf.bodyParser()` before AIWAF and before forwarding requests.
|
|
16
|
+
It parses JSON and URL-encoded bodies, retains the original forwarding bytes,
|
|
17
|
+
and rejects oversized bodies (default 64 KiB). Native Fastify/Hapi integrations
|
|
18
|
+
must run AIWAF after body parsing and before their proxy handler.
|
|
19
|
+
|
|
20
|
+
Java SQL inspection defaults to `security.sql_injection_mode: "block"`;
|
|
21
|
+
`monitor` records findings without denying requests and `off` disables it.
|
|
22
|
+
`AIWAF_SQL_INJECTION_MODE` provides the environment override. Inspection uses
|
|
23
|
+
the configured body byte limit and rejects over-budget inspection with 413.
|
|
24
|
+
Previously learned benign keywords no longer block ordinary Java routes.
|
|
25
|
+
|
|
26
|
+
Redis rate-cache failures now produce generic HTTP 503 responses in JavaScript
|
|
27
|
+
and Python rate-limit middleware. JavaScript defaults to
|
|
28
|
+
`AIWAF_RATE_CACHE_FAILURE_MODE: 'closed'`; explicitly setting `'open'` preserves
|
|
29
|
+
availability at the cost of enforcement when the cache fails. Flask rejects
|
|
30
|
+
invalid Redis configuration at initialization, and FastAPI rejects requests
|
|
31
|
+
instead of silently selecting a process-local cache. Python `rediss://` URLs
|
|
32
|
+
are delegated to redis-py for TLS support when that driver is installed.
|
|
33
|
+
Java uses Jackson 2.22.3 to address advisories affecting 2.22.2.
|
|
34
|
+
|
|
35
|
+
Python Flask/FastAPI Redis buckets now update atomically across workers.
|
|
36
|
+
Django's native `django.core.cache.backends.redis.RedisCache` uses Redis
|
|
37
|
+
transactions while preserving its existing serialized bucket values. Memory
|
|
38
|
+
and other custom cache backends serialize updates within one process; use
|
|
39
|
+
the supported Redis backends when sharing limits across workers.
|
|
12
40
|
|
|
13
41
|
Each package is versioned and released independently.
|
|
14
42
|
|
|
15
|
-
Python
|
|
16
|
-
[upgrade notes](docs/releases/2026-10-
|
|
43
|
+
Python 1.1.4, Rust/Python 0.2.3, Node.js 1.1.2, WASM 0.2.2, and Java 1.3.3 are local release candidates; see the
|
|
44
|
+
[upgrade notes](docs/releases/2026-10-elv2.md).
|
|
17
45
|
|
|
18
46
|
| Runtime | Package | Repository version | Primary use |
|
|
19
47
|
| --- | --- | ---: | --- |
|
|
20
|
-
| Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.1.
|
|
21
|
-
| Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.1.
|
|
22
|
-
| Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.
|
|
23
|
-
| WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.
|
|
24
|
-
| Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.
|
|
48
|
+
| Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.1.4` | Django, Flask, and FastAPI protection |
|
|
49
|
+
| Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.1.2` | Express and Node framework middleware |
|
|
50
|
+
| Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.3` | Native Python acceleration and JSON model inference |
|
|
51
|
+
| WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.2` | Rust detection and model primitives for JavaScript |
|
|
52
|
+
| Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.3` | Spring MVC and Jakarta Servlet protection |
|
|
25
53
|
|
|
26
54
|
Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
|
|
27
55
|
|
|
@@ -38,7 +66,7 @@ Supported framework integrations include Django, Flask, FastAPI, Express, Fastif
|
|
|
38
66
|
- Memory, file, CSV, SQLite, database, and cache-backed runtime state, depending on the runtime
|
|
39
67
|
- Structured request logging and offline training
|
|
40
68
|
- Six-feature anomaly models with Rust, JavaScript, and Java implementations
|
|
41
|
-
-
|
|
69
|
+
- Required Rust runtime for Python 1.1.4 and optional WebAssembly acceleration for Node.js
|
|
42
70
|
|
|
43
71
|
The runtimes share policy intent and training feature names, but their framework adapters and model implementations remain language-native. Model artifacts are not generally interchangeable across languages.
|
|
44
72
|
|
|
@@ -56,7 +84,7 @@ The runtimes share policy intent and training feature names, but their framework
|
|
|
56
84
|
├── examples/ Focused Python examples
|
|
57
85
|
├── .github/workflows/ Tests, security checks, and releases
|
|
58
86
|
├── README.md Canonical project documentation
|
|
59
|
-
└── LICENSE Canonical
|
|
87
|
+
└── LICENSE Canonical Elastic License 2.0 (see NOTICE)
|
|
60
88
|
```
|
|
61
89
|
|
|
62
90
|
## Quick installation
|
|
@@ -70,7 +98,7 @@ pip install "aiwaf[django]"
|
|
|
70
98
|
pip install "aiwaf[flask]"
|
|
71
99
|
pip install "aiwaf[fastapi]"
|
|
72
100
|
|
|
73
|
-
# Python
|
|
101
|
+
# Backward-compatible alias; Python 1.1.4 already installs aiwaf-rust
|
|
74
102
|
pip install "aiwaf[rust]"
|
|
75
103
|
|
|
76
104
|
# Node.js middleware
|
|
@@ -80,13 +108,13 @@ npm install aiwaf
|
|
|
80
108
|
npm install aiwaf-wasm
|
|
81
109
|
```
|
|
82
110
|
|
|
83
|
-
Java 1.3.
|
|
111
|
+
Java 1.3.3, after it is published to Maven Central:
|
|
84
112
|
|
|
85
113
|
```xml
|
|
86
114
|
<dependency>
|
|
87
115
|
<groupId>io.github.aiwaf-project</groupId>
|
|
88
116
|
<artifactId>aiwaf-java</artifactId>
|
|
89
|
-
<version>1.3.
|
|
117
|
+
<version>1.3.3</version>
|
|
90
118
|
</dependency>
|
|
91
119
|
```
|
|
92
120
|
|
|
@@ -94,6 +122,160 @@ Java 1.3.1, after it is published to Maven Central:
|
|
|
94
122
|
|
|
95
123
|
The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
|
|
96
124
|
|
|
125
|
+
Python 1.1.4 requires `aiwaf-rust>=0.2.3`; the `rust` extra remains an installation
|
|
126
|
+
alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
|
|
127
|
+
the Python release. The Rust release workflow builds Linux x86_64/aarch64,
|
|
128
|
+
musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
|
|
129
|
+
pipeline API. Windows and WSL builds are checked locally; the other wheel
|
|
130
|
+
targets must pass CI before publication.
|
|
131
|
+
|
|
132
|
+
### Rust-owned CSV pipeline
|
|
133
|
+
|
|
134
|
+
The complete CSV request pipeline is available through explicit adapters below.
|
|
135
|
+
Install it **instead of the existing eight-middleware chain**. The existing
|
|
136
|
+
`AIWAF` adapters remain available for compatibility with custom stores and hooks;
|
|
137
|
+
they do not switch automatically to this pipeline.
|
|
138
|
+
|
|
139
|
+
Rust owns the immutable configuration, enforcement order, SQL and keyword
|
|
140
|
+
inspection, geo and blacklist decisions, rate buckets, form timing state, UUID
|
|
141
|
+
scores, anomaly inference/history, keyword learning and CSV logging. Python
|
|
142
|
+
supplies framework routing/authentication facts, obtains GeoIP country data,
|
|
143
|
+
buffers a bounded body prefix and constructs responses. Each request crosses
|
|
144
|
+
into the engine once before the handler and once when its response is available.
|
|
145
|
+
The engine never calls Python policy callbacks or falls back to Python execution.
|
|
146
|
+
Missing native support, unsupported settings and invalid CSV schemas fail at
|
|
147
|
+
startup.
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
# Flask
|
|
151
|
+
from flask import Flask
|
|
152
|
+
from aiwaf.flask import NativeAIWAF
|
|
153
|
+
|
|
154
|
+
app = Flask(__name__)
|
|
155
|
+
NativeAIWAF(app, config={"data_dir": "aiwaf_data"})
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
# FastAPI / pure ASGI
|
|
160
|
+
from fastapi import FastAPI
|
|
161
|
+
from aiwaf.fast import NativeAIWAFMiddleware
|
|
162
|
+
|
|
163
|
+
app = FastAPI()
|
|
164
|
+
app.add_middleware(NativeAIWAFMiddleware, config={"data_dir": "aiwaf_data"})
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
# Django settings: replace the existing AIWAF middleware entries
|
|
169
|
+
AIWAF_CSV_PIPELINE = {"data_dir": "aiwaf_data"}
|
|
170
|
+
MIDDLEWARE = [
|
|
171
|
+
# Keep the application's other middleware in the required order.
|
|
172
|
+
"aiwaf.django.csv_pipeline.NativeAIWAFMiddleware",
|
|
173
|
+
]
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The configuration uses a dedicated lowercase profile; existing uppercase
|
|
177
|
+
framework settings, `AIWAFConfig` dictionaries, PATH_RULES, manifests, custom
|
|
178
|
+
stores and policy callbacks are not imported into it. Unknown keys are rejected.
|
|
179
|
+
Route decorators for full/partial exemptions and required middleware are read
|
|
180
|
+
once. Required decorators override decorator exemptions; profile-level path/IP
|
|
181
|
+
exemptions remain global. The profile is immutable: construct a new engine and
|
|
182
|
+
reload workers to change it.
|
|
183
|
+
|
|
184
|
+
Common profile keys and defaults:
|
|
185
|
+
|
|
186
|
+
| Setting | Default / meaning |
|
|
187
|
+
| --- | --- |
|
|
188
|
+
| `enabled` | All eight names: `geo_block`, `ip_keyword_block`, `rate_limit`, `ai_anomaly`, `honeypot`, `uuid_tamper`, `header_validation`, `logging` |
|
|
189
|
+
| `data_dir` | `aiwaf_data`; policy CSVs use the shared whitelist/blacklist/keyword/geo/path schemas |
|
|
190
|
+
| `exempt_paths`, `exempt_ips` | `/health`, `/robots.txt`, `/sitemap.xml`; empty IP list. Paths are literal, case-insensitive prefixes, not globs. Stored path exemptions use the same literal-prefix rule |
|
|
191
|
+
| `sql_mode`, `max_bytes` | `block`, `65536`; `off` supported, `monitor` rejected. Structured JSON/form bodies and nested escaped strings are inspected with bounded traversal |
|
|
192
|
+
| `learning`, `top_n` | `True`, `10`; presence keywords use a sorted, stable subset instead of Python set iteration order |
|
|
193
|
+
| `static_keywords`, `legitimate_keywords`, `exempt_keywords`, `safe_prefixes` | Native policy defaults or explicit arrays; set route-specific safe vocabulary in the profile |
|
|
194
|
+
| `geo_allow`, `geo_block` | Empty lists; includes stored blocked countries. Unknown country remains allowed |
|
|
195
|
+
| `rate_backend`, `rate_key_mode` | `memory`, `ip_path`; `csv` shares buckets across workers; `ip` aggregates paths. Redis is rejected |
|
|
196
|
+
| `rate_window`, `rate_max`, `rate_flood` | `10`, `20`, `40`; throttle at 429, flood at 403 with blacklist persistence |
|
|
197
|
+
| `soft_block_blacklist`, `ip_blocking`, `block_duration` | `False`, `True`, reputation-based duration; explicit seconds or nonpositive permanent duration |
|
|
198
|
+
| `honeypot_backend` | `csv`; shared, persistent form timestamps in `pipeline_state.csv`. Optional `memory` uses a Rust map local to one engine/worker |
|
|
199
|
+
| `min_form_time`, `max_page_time`, `skip_authenticated` | `1.0`, `240`, `True`; same timing policy for both honeypot backends |
|
|
200
|
+
| `uuid_score_enabled`, `uuid_window`, `uuid_threshold` | `True`, `60`, `5`; weights: `uuid_malformed_weight=5`, `uuid_not_found_weight=1`, `uuid_success_decay=2` |
|
|
201
|
+
| `required_headers`, `header_min_score` | `HTTP_USER_AGENT` and `HTTP_ACCEPT`, `3`; empty required list disables required-header/quality checks, retains safety caps |
|
|
202
|
+
| `anomaly_window`, `anomaly_keywords` | `60`, standard anomaly vocabulary; history/scoring is held in Rust per worker |
|
|
203
|
+
| `log_path`, `log_fsync` | `data_dir/requests.csv`, `False`; immediate CSV append, optional per-row fsync |
|
|
204
|
+
|
|
205
|
+
Pass a trained `aiwaf_rust.IsolationForest` as `model=` to Flask/FastAPI, or
|
|
206
|
+
set `AIWAF_CSV_PIPELINE_MODEL` in Django. Without a model, the anomaly stage
|
|
207
|
+
maintains history and learns suspicious 404 keywords but performs no model-based
|
|
208
|
+
blocking. `pipeline.native.set_model(model)` replaces the model with an owned
|
|
209
|
+
snapshot; `set_model(None)` disables inference. Training and management APIs
|
|
210
|
+
remain available through the existing Python interface.
|
|
211
|
+
|
|
212
|
+
For deployments that accept per-worker form timing, set
|
|
213
|
+
`"honeypot_backend": "memory"` in the native profile. Rust then holds GET
|
|
214
|
+
timestamps in an expiring map and evaluates/clears POST timing atomically,
|
|
215
|
+
avoiding a durable CSV rewrite on each GET. Timing state is isolated per engine,
|
|
216
|
+
is not shared across workers and resets on restart. Backend switches do not
|
|
217
|
+
transfer timestamps automatically. Keep `csv` for shared or persistent timing;
|
|
218
|
+
CSV writes remain immediately synced. Blacklist, keyword, geo and whitelist
|
|
219
|
+
policy files and immediate request logging keep their configured CSV behavior.
|
|
220
|
+
|
|
221
|
+
A second matched WSL benchmark compared these two timing backends with all
|
|
222
|
+
eight stages enabled. Three alternating runs of 300 requests per mode/framework
|
|
223
|
+
measured the following added overhead after subtracting framework-only latency:
|
|
224
|
+
|
|
225
|
+
| Framework | CSV timing, AI off | Memory timing, AI off | CSV timing, AI on | Memory timing, AI on |
|
|
226
|
+
| --- | ---: | ---: | ---: | ---: |
|
|
227
|
+
| Flask | 3.74 ms | 0.83 ms | 3.66 ms | 0.97 ms |
|
|
228
|
+
| Django | 3.67 ms | 0.91 ms | 4.02 ms | 0.83 ms |
|
|
229
|
+
| FastAPI | 3.78 ms | 0.78 ms | 3.70 ms | 0.92 ms |
|
|
230
|
+
|
|
231
|
+
All 13,500 measured requests returned 200 and both protected modes blocked the
|
|
232
|
+
SQL/PHP probes. These are medians of per-run mean server times for a synthetic
|
|
233
|
+
one-client workload with immediate logging, 80% GET / 20% JSON POST, 30 fields
|
|
234
|
+
and a seeded 100-tree Rust model when AI is enabled. The performance comparison
|
|
235
|
+
does not remove the persistence and cross-worker differences between backends.
|
|
236
|
+
Reproduce memory mode with `--pipeline --honeypot-backend memory` in the HTTP
|
|
237
|
+
benchmark harness; the default remains `--honeypot-backend csv`.
|
|
238
|
+
|
|
239
|
+
Flask/FastAPI accept synchronous `country_lookup(ip)` and
|
|
240
|
+
`authenticated(request)` callbacks for adapter facts. Default GeoIP uses the
|
|
241
|
+
bundled lookup. Configure authentication explicitly in these adapters when
|
|
242
|
+
authenticated requests should bypass honeypot timing; Django reads user/session
|
|
243
|
+
state, so place it after authentication/session middleware. Django function views
|
|
244
|
+
have no standard method declaration and are accepted conservatively; class-based
|
|
245
|
+
views supply their declared method facts. Anomaly history stores route eligibility
|
|
246
|
+
as observed at arrival; historical requests are not re-resolved after routes change.
|
|
247
|
+
|
|
248
|
+
The ASGI adapter preserves streaming bodies and finalizes enforcement/logging at
|
|
249
|
+
response start. Logged response time measures time to response headers rather
|
|
250
|
+
than stream completion. WSGI adapters finalize when the framework response is
|
|
251
|
+
available. Session/route handlers, response construction, GeoIP lookup and legacy
|
|
252
|
+
custom integrations still execute in Python; the whole Python package has not
|
|
253
|
+
been rewritten in Rust.
|
|
254
|
+
|
|
255
|
+
Measure this path with `scripts/benchmark_release_http.py --pipeline`, alongside
|
|
256
|
+
the existing chain and `--plain` framework baseline. Native execution and both
|
|
257
|
+
SQL/PHP protection probes are checked by the harness; the benchmark report
|
|
258
|
+
records workload details and subtracts the framework baseline for added overhead.
|
|
259
|
+
|
|
260
|
+
Matched WSL tests of the complete pipeline (three alternating runs of 300
|
|
261
|
+
requests per framework/mode, one client, all eight stages and immediate CSV
|
|
262
|
+
logging) measured the following **added overhead**, after subtracting the same
|
|
263
|
+
framework-only baseline. The comparison is against the current legacy chain.
|
|
264
|
+
|
|
265
|
+
| Framework | Current chain, AI off | Native pipeline, AI off | Current chain, AI on | Native pipeline, AI on |
|
|
266
|
+
| --- | ---: | ---: | ---: | ---: |
|
|
267
|
+
| Flask | 10.60 ms | 3.77 ms | 14.53 ms | 3.56 ms |
|
|
268
|
+
| Django | 14.18 ms | 3.52 ms | 18.98 ms | 3.66 ms |
|
|
269
|
+
| FastAPI | 11.83 ms | 3.52 ms | 12.21 ms | 3.67 ms |
|
|
270
|
+
|
|
271
|
+
These are medians of per-run mean server times. Native and legacy run ranges
|
|
272
|
+
were separated in all six protected comparisons. All 13,500 measured requests
|
|
273
|
+
returned 200 and both protected modes blocked SQL/PHP probes. The AI fixture
|
|
274
|
+
used a seeded 100-tree Rust forest and 200 initial history records per client.
|
|
275
|
+
The dedicated profile, storage layout and adapter semantics differ from some
|
|
276
|
+
legacy configurations; this is a synthetic comparison of the documented modes,
|
|
277
|
+
not a production latency guarantee or a drop-in migration result.
|
|
278
|
+
|
|
97
279
|
### Flask
|
|
98
280
|
|
|
99
281
|
```python
|
|
@@ -243,10 +425,204 @@ Python adapters use flat `AIWAF_*` settings or their equivalent constructor opti
|
|
|
243
425
|
|
|
244
426
|
When `aiwaf_rust` is importable, supported acceleration paths are selected automatically. Python remains the fallback when a native capability is unavailable. Persisted runtime models use JSON state; AIWAF does not load pickle, joblib, or other executable Python-object formats.
|
|
245
427
|
|
|
428
|
+
### Rust-backed CSV runtime and training
|
|
429
|
+
|
|
430
|
+
The Python 1.1.4 and `aiwaf-rust` 0.2.3 release candidates add native CSV storage,
|
|
431
|
+
shared policy evaluation, and training preparation for Django, Flask, and FastAPI.
|
|
432
|
+
Install matching Python and Rust builds and reload application workers to activate
|
|
433
|
+
the new capabilities. Older extensions retain the compatible Python fallback.
|
|
434
|
+
|
|
435
|
+
- **CSV storage:** bounded snapshot caches and indexed IP/key lookups avoid repeated
|
|
436
|
+
parsing and copying entire tables into Python. Native readers validate file
|
|
437
|
+
metadata and use shared OS locks; mutations use exclusive locks. Blacklist
|
|
438
|
+
reputation updates, keyword increments/removals, exemptions, audit entries, and
|
|
439
|
+
geo-list changes use atomic transactions. Unchanged policy rows skip rewriting
|
|
440
|
+
and disk synchronization. Changed policy writes still synchronize to disk.
|
|
441
|
+
- **Request policies:** native helpers handle keyword/probe decisions, ASCII SQL
|
|
442
|
+
signatures, geo decisions, rate-window filtering, form timing, UUID format
|
|
443
|
+
validation, reputation scoring, wildcard/CIDR exemptions, and longest-prefix
|
|
444
|
+
route plans. Flask CSV keyword retrieval, evaluation, and learning share one
|
|
445
|
+
native call. SQL checks and blacklist updates retain their existing order;
|
|
446
|
+
custom evaluators and unsupported Unicode behavior use the Python adapter.
|
|
447
|
+
- **Exemption reuse:** Flask reuses CSV exemption results within a request and
|
|
448
|
+
checks file identity, size, timestamps, and configuration before each reuse.
|
|
449
|
+
Changes invalidate the result; decorator checks still execute. Set
|
|
450
|
+
`AIWAF_CSV_REQUEST_CACHE=False` to disable this optimization.
|
|
451
|
+
- **Training ingestion:** plain and gzip CSV stream directly in bounded batches,
|
|
452
|
+
including quoted fields and embedded newlines. Seconds and millisecond response
|
|
453
|
+
fields are normalized. Apache logs use batched extraction and native timestamp
|
|
454
|
+
parsing for supported English/C-locale forms. Unsupported dates/locales and
|
|
455
|
+
Unicode keyword learning retain Python behavior. Route checks are reused for
|
|
456
|
+
distinct paths, and learned keywords are persisted in batches.
|
|
457
|
+
- **Native model preparation:** `NativeTrainingBatch` keeps features and numeric
|
|
458
|
+
matrices in Rust through Isolation Forest fitting, prediction, and per-IP anomaly
|
|
459
|
+
aggregation. `NativeTrainingBuilder` preserves Django's chunk/state behavior.
|
|
460
|
+
Supported native model paths train without a Pandas DataFrame; older APIs and
|
|
461
|
+
custom parsers retain compatibility paths.
|
|
462
|
+
- **Synchronous CSV logging:** a bounded cache of writer handles avoids repeated
|
|
463
|
+
opens. Every row is locked and flushed before returning. File identity checks
|
|
464
|
+
handle rotation/replacement, and truncation recreates the header. Rows are not
|
|
465
|
+
queued in an application-side batch.
|
|
466
|
+
|
|
467
|
+
Framework hooks, request/body extraction, route discovery, session/ORM access,
|
|
468
|
+
response construction, datetime object/epoch conversion, training orchestration,
|
|
469
|
+
and model artifact serialization still run in Python. The route plan selects
|
|
470
|
+
middleware; framework hooks continue to execute separately in their established
|
|
471
|
+
order. Database and Redis backends remain separate from the CSV implementation.
|
|
472
|
+
|
|
473
|
+
Flask and Django honor `AIWAF_USE_RUST=False` or `AIWAF_RUST_CSV=False` to disable
|
|
474
|
+
native CSV dispatch. Outside those application contexts, use the environment
|
|
475
|
+
variable `AIWAF_RUST_CSV=false`. FastAPI training also honors these application
|
|
476
|
+
options. ISO timestamps use Python's faster C parser by default;
|
|
477
|
+
`AIWAF_RUST_ISO_DATES=1` opts into native ISO parsing for measurement.
|
|
478
|
+
|
|
479
|
+
Flask can opt into shared, persistent CSV rate buckets:
|
|
480
|
+
|
|
481
|
+
```python
|
|
482
|
+
app.config["AIWAF_RATE_CACHE_BACKEND"] = "csv"
|
|
483
|
+
# Optional: otherwise stored under AIWAF_DATA_DIR.
|
|
484
|
+
app.config["AIWAF_RATE_CSV_PATH"] = "/absolute/path/to/rate_buckets.csv"
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
CSV rate decisions trim the window, consume the request, and persist the bucket
|
|
488
|
+
under one native lock. Missing or disabled native support returns HTTP 503.
|
|
489
|
+
Memory remains the default; CSV rewrites and synchronization can be slower than
|
|
490
|
+
memory or Redis. Workers sharing CSV state must use compatible schemas and a
|
|
491
|
+
filesystem with suitable locking. Legacy Python fallback writers on Windows only
|
|
492
|
+
have process-local thread locks, so mixed Python/native writers need particular
|
|
493
|
+
care. Explicit whole-file replacements are not concurrent incremental updates.
|
|
494
|
+
|
|
495
|
+
`AIWAF_CSV_LOG_FSYNC=True` adds a disk sync per log row; the default is `False`,
|
|
496
|
+
matching previous Python logging durability. Without per-row sync, a system crash
|
|
497
|
+
can lose recently flushed OS-buffered entries. Cached handles close at process
|
|
498
|
+
shutdown. After requests stop, call the Flask logger's `close()` or
|
|
499
|
+
`aiwaf.core.native_runtime.close_csv_logs()` before deleting temporary log
|
|
500
|
+
directories, especially on Windows.
|
|
501
|
+
|
|
502
|
+
Check the installed extension without touching application data:
|
|
503
|
+
|
|
504
|
+
```bash
|
|
505
|
+
python scripts/check_native_csv_runtime.py
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
Development request batching adds `policy_sql_signatures` and
|
|
509
|
+
`csv_geo_policy` capabilities. Shared SQL inspection checks the first
|
|
510
|
+
eight ASCII strings immediately for prompt denial, then checks subsequent strings
|
|
511
|
+
in batches of at most 128. Unicode boundaries and inspection-limit exits flush
|
|
512
|
+
pending checks first, preserving first-finding order. Django, Flask, and FastAPI
|
|
513
|
+
use the shared path; older extensions retain single-string checks.
|
|
514
|
+
|
|
515
|
+
Flask with CSV geo state and an explicit allow/block list can read dynamic countries
|
|
516
|
+
and evaluate the geo policy in one native call. Django CSV and FastAPI CSV use
|
|
517
|
+
`csv_runtime_geo_policy` for their key/value geo state. Django additionally retains
|
|
518
|
+
its existing ORM country blocks; the combined call includes those countries as
|
|
519
|
+
extra policy input. ORM-only Django operation remains separate. FastAPI geo
|
|
520
|
+
middleware honors its `use_rust` option, passed from the application's Rust flags.
|
|
521
|
+
Dynamic-only FastAPI policy and custom getters/evaluators retain their fallback
|
|
522
|
+
path. Native reads respect TTLs and observe updates/removals; disabled native geo
|
|
523
|
+
reads refresh the Python CSV snapshot. Exemptions and blacklist writes still run
|
|
524
|
+
at their original stages. Rebuild the extension from this checkout to test these
|
|
525
|
+
unpublished capabilities.
|
|
526
|
+
|
|
527
|
+
Run `python scripts/benchmark_native_request_batches.py` for the focused comparison.
|
|
528
|
+
Three alternating Windows runs of 500 checks measured 100-field SQL inspection at
|
|
529
|
+
0.650 ms combined versus 0.989 ms previous, and the CSV geo binding at 0.286 ms
|
|
530
|
+
versus 0.367 ms. Early SQL rejection measured 0.067 ms versus 0.066 ms. These
|
|
531
|
+
isolated, warmed checks exclude the complete middleware chain, networking, model
|
|
532
|
+
scoring, and concurrent load.
|
|
533
|
+
|
|
534
|
+
### Request-time anomaly acceleration (development)
|
|
535
|
+
|
|
536
|
+
With a matching rebuilt extension and a real Rust Isolation Forest, Flask and
|
|
537
|
+
FastAPI retain request histories as immutable `NativeAnomalyHistory` snapshots.
|
|
538
|
+
Native code trims the time window, builds the six current features, and predicts
|
|
539
|
+
without exporting the numeric matrix. Records are shared between snapshots;
|
|
540
|
+
evaluating a response does not mutate another request's history. Existing
|
|
541
|
+
per-worker cache ownership and response/keyword/blocking order remain unchanged.
|
|
542
|
+
|
|
543
|
+
If the forest predicts an anomaly, Python still resolves the current route and
|
|
544
|
+
exemptions for each historical path. Rust then analyzes the retained records.
|
|
545
|
+
Dynamic route/exemption changes remain visible. Unicode paths/keywords, non-finite
|
|
546
|
+
current inputs, disabled native settings, older extensions, and other model types
|
|
547
|
+
retain the established Python-history path. Set
|
|
548
|
+
`AIWAF_RUST_ANOMALY_HISTORY=False` in Flask config or the FastAPI `AIWAFConfig`
|
|
549
|
+
object to disable native history retention; existing snapshots convert back to
|
|
550
|
+
tuple lists. Disabling or replacing a model also retains compatibility.
|
|
551
|
+
|
|
552
|
+
Django continues to cache serializable tuple lists, including with shared cache
|
|
553
|
+
backends. The shared recent-behavior bridge uses `analyze_recent_tuples` to avoid
|
|
554
|
+
building a dictionary per historical record. No native process-local object is
|
|
555
|
+
stored in Django's cache. These changes do not introduce model auto-reload or
|
|
556
|
+
shared histories for Flask/FastAPI.
|
|
557
|
+
|
|
558
|
+
Run `python scripts/benchmark_anomaly_runtime.py` to compare the previous bridge,
|
|
559
|
+
tuple analysis, and native histories with a real seeded forest. Five alternating
|
|
560
|
+
Windows runs of 300 evaluations, a 100-tree forest, and 200 prior requests measured
|
|
561
|
+
anomalous evaluation at 0.175 ms versus 0.486 ms (2.78x) and benign evaluation at
|
|
562
|
+
0.040 ms versus 0.146 ms (3.61x). The same WSL benchmark measured anomalous
|
|
563
|
+
evaluation at 0.178 ms versus 0.533 ms (2.99x) and benign evaluation at
|
|
564
|
+
0.036 ms versus 0.126 ms (3.46x). These isolated engine timings exclude networking,
|
|
565
|
+
CSV writes, real route-resolution costs, the full middleware chain, and concurrent
|
|
566
|
+
load. They are not deployed-site speedup claims.
|
|
567
|
+
|
|
568
|
+
Further request-path refinements use the existing native CSV log writer for
|
|
569
|
+
Flask/FastAPI anomaly training logs when supported. Each row is flushed before
|
|
570
|
+
returning; there is no background queue. `AIWAF_CSV_LOG_FSYNC=True` additionally
|
|
571
|
+
requests an OS sync for these logs, including in the Python fallback. Rust-disable
|
|
572
|
+
settings and older extensions retain the Python writer.
|
|
573
|
+
|
|
574
|
+
Flask reuses its routing adapter within a request while continuing to match each
|
|
575
|
+
path and evaluate exemptions. Route-map replacement and additions remain visible;
|
|
576
|
+
the `MethodNotAllowed` import was corrected so existing routes with another HTTP
|
|
577
|
+
method are recognized. Flask/FastAPI sweep inactive histories at most every 30
|
|
578
|
+
seconds during response processing, removing only histories with no entries in
|
|
579
|
+
the configured scoring window. Active histories remain uncapped, and a quiet
|
|
580
|
+
worker performs no background cleanup. Django continues to use cache timeouts.
|
|
581
|
+
|
|
582
|
+
Rust recent-behavior analysis now counts symmetric ten-second bursts with a
|
|
583
|
+
linear sweep after sorting finite timestamps, replacing two binary searches per
|
|
584
|
+
record. Non-finite timestamps retain the established search path. This shared-core
|
|
585
|
+
change also applies to the WASM recent-behavior API. Run
|
|
586
|
+
`python scripts/benchmark_request_refinements.py` for isolated logging, route, and
|
|
587
|
+
burst-analysis timings; these do not measure deployed-site throughput.
|
|
588
|
+
With five runs of 300 operations in WSL, immediate CSV writes measured 0.030 ms
|
|
589
|
+
versus 0.173 ms, repeated route checks 0.0175 ms versus 0.0266 ms, and analysis of
|
|
590
|
+
1,000 history records 0.663 ms versus 0.787 ms. The route comparison uses the
|
|
591
|
+
previous implementation with its exception import corrected; burst timings
|
|
592
|
+
include Python-to-Rust tuple conversion. These benchmarks use local files and
|
|
593
|
+
synthetic inputs, without concurrent load.
|
|
594
|
+
|
|
246
595
|
### Python operations
|
|
247
596
|
|
|
597
|
+
#### Experimental compiled request stage
|
|
598
|
+
|
|
599
|
+
`AIWAF_RUST_REQUEST_ENGINE=True` opts into `NativeRequestEngine` with a matching
|
|
600
|
+
rebuilt Rust extension. Set it in Flask/Django settings or the FastAPI `AIWAFConfig`.
|
|
601
|
+
It is **off by default**. This first stage combines bounded ASCII query SQL
|
|
602
|
+
inspection, default keyword-context evaluation, dynamic CSV keyword reads, and
|
|
603
|
+
keyword learning writes behind a compiled policy profile. Static policy changes
|
|
604
|
+
rebuild the profile; CSV state remains live. Flask/FastAPI can use one native call
|
|
605
|
+
for supported query requests. Django keeps SQL inspection before route resolution,
|
|
606
|
+
then uses the compiled keyword/CSV stage with the resolved route facts.
|
|
607
|
+
|
|
608
|
+
Framework extraction, body buffering/replay, exemptions, blacklist enforcement,
|
|
609
|
+
rate limits, honeypot/UUID hooks, header enforcement, and response processing keep
|
|
610
|
+
their existing positions. Structured SQL bodies, Unicode paths/decoding, monitor
|
|
611
|
+
mode, custom policy/storage hooks, custom Django converters, older extensions,
|
|
612
|
+
and dynamic-keyword subsets whose ranking requires Python retain the established
|
|
613
|
+
path. The engine does not replace the whole eight-middleware chain.
|
|
614
|
+
|
|
615
|
+
Three alternating WSL runs of 300 requests through the full chain, at concurrency
|
|
616
|
+
one with AI scoring off, observed server-time medians of 12.88 to 12.46 ms for
|
|
617
|
+
Flask, 16.09 to 15.60 ms for Django, and 13.41 to 13.17 ms for FastAPI. Run ranges
|
|
618
|
+
overlapped; these do not establish a dependable speedup. The opt-in default avoids
|
|
619
|
+
assuming that fewer boundaries alone remove the remaining request cost. Compare
|
|
620
|
+
`scripts/benchmark_release_http.py` with and without `--engine` using identical
|
|
621
|
+
dependencies and traffic. `--plain` measures an endpoint without AIWAF, and the
|
|
622
|
+
harness reports server processing time separately from HTTP latency.
|
|
623
|
+
|
|
248
624
|
```bash
|
|
249
|
-
#
|
|
625
|
+
# Auto-detected CLI (one supported framework installed)
|
|
250
626
|
aiwaf --help
|
|
251
627
|
aiwaf blacklist migrate
|
|
252
628
|
aiwaf status
|
|
@@ -262,8 +638,53 @@ python manage.py geo_block_country list
|
|
|
262
638
|
aiwaf django aiwaf_list --all
|
|
263
639
|
aiwaf flask --help
|
|
264
640
|
aiwaf fast --help
|
|
641
|
+
aiwaf fastapi --help
|
|
642
|
+
|
|
643
|
+
# FastAPI route-aware training using the application's runtime storage
|
|
644
|
+
aiwaf fast train --app app:app --log-dir aiwaf_logs --disable-ai
|
|
645
|
+
aiwaf fast train --app app:app --log-dir aiwaf_logs --model-path model.json
|
|
265
646
|
```
|
|
266
647
|
|
|
648
|
+
Bare CLI commands select the single installed supported framework. If multiple
|
|
649
|
+
frameworks are installed, specify `aiwaf flask ...`, `aiwaf fastapi ...`, or
|
|
650
|
+
`aiwaf django <management-command> ...`. The `fast` alias remains supported.
|
|
651
|
+
Django uses its management command names, such as `aiwaf_list`.
|
|
652
|
+
|
|
653
|
+
The Flask CSV management CLI reuses existing policy files in the current project's
|
|
654
|
+
`aiwaf_data` (preferred) or `.aiwaf/data` before searching user and package data
|
|
655
|
+
directories. `AIWAF_DATA_DIR` or `aiwaf flask --data-dir /absolute/path status`
|
|
656
|
+
overrides discovery, including for a new directory. Set the same absolute
|
|
657
|
+
`AIWAF_DATA_DIR` for the Flask app and CLI when running them from different
|
|
658
|
+
working directories.
|
|
659
|
+
|
|
660
|
+
Flask, FastAPI, Django CSV mode, and the native Rust pipeline now use the same
|
|
661
|
+
policy files: `blacklist.csv`, `whitelist.csv`, `keywords.csv`,
|
|
662
|
+
`geo_blocked_countries.csv`, and `path_exemptions.csv`. For FastAPI, configure
|
|
663
|
+
`storage.backend = "csv"` and `storage.data_dir = "/absolute/path/aiwaf_data"`;
|
|
664
|
+
`AIWAF_DATA_DIR` also supplies the directory. Memory, JSON-file, database, and
|
|
665
|
+
Django ORM modes retain their existing storage behavior.
|
|
666
|
+
|
|
667
|
+
Startup imports a legacy `runtime_store.csv` in the chosen directory, or the
|
|
668
|
+
old default `aiwaf_data.csv` beside the project's `aiwaf_data` directory.
|
|
669
|
+
Existing custom `storage.file_path` settings remain accepted as migration
|
|
670
|
+
sources: `/path/custom.csv` maps to `/path/custom/`, while `runtime_store.csv`
|
|
671
|
+
maps to its parent. Prefer an explicit `data_dir` for the application and CLI.
|
|
672
|
+
Original legacy files remain intact, pre-import canonical files are backed up,
|
|
673
|
+
and a completion marker prevents replay after blocks or keywords are removed.
|
|
674
|
+
Existing canonical policy wins conflicts. Invalid legacy input stops startup
|
|
675
|
+
with an error; repair it and restart to retry an incomplete import. Stop old
|
|
676
|
+
workers before upgrading: subsequent writes to a legacy source are not reimported.
|
|
677
|
+
|
|
678
|
+
Keyword frequencies and non-policy runtime history are retained in
|
|
679
|
+
`runtime_metadata.csv`; policy enforcement reads the shared policy files.
|
|
680
|
+
The low-level `CSVStorage` key/value class remains available for explicit use,
|
|
681
|
+
but framework CSV initialization selects `PolicyCSVStorage`.
|
|
682
|
+
|
|
683
|
+
FastAPI also exposes `aiwaf.fast.trainer.train_from_logs(app, ...)`. Training
|
|
684
|
+
refreshes learned keywords and can write a Rust JSON model artifact. Existing
|
|
685
|
+
anomaly middleware instances require an explicit model reload or application
|
|
686
|
+
restart to use the newly trained model.
|
|
687
|
+
|
|
267
688
|
## JavaScript package
|
|
268
689
|
|
|
269
690
|
The npm package uses CommonJS and exports the Express middleware as its default function plus adapters for the other supported Node frameworks.
|
|
@@ -351,6 +772,138 @@ npm run aiwaf -- manifest --framework express --routes routes.json --output .aiw
|
|
|
351
772
|
|
|
352
773
|
AIWAF loads `aiwaf-wasm` when available and falls back to the JavaScript implementation when WASM initialization or conversion is not worthwhile. Small, object-heavy operations can be faster in JavaScript because crossing the JS/WASM boundary and serializing objects has a fixed cost. WASM is most useful for sufficiently large feature batches and model scoring workloads.
|
|
353
774
|
|
|
775
|
+
The Python filesystem CSV transactions and retained training bindings remain
|
|
776
|
+
PyO3-specific. Node now also has an **explicit stateful WASM request pipeline**;
|
|
777
|
+
its transport and filesystem I/O remain in JavaScript.
|
|
778
|
+
|
|
779
|
+
### Rust-owned Node request pipeline
|
|
780
|
+
|
|
781
|
+
Node 1.1.2 now requires `aiwaf-wasm>=0.2.2,<0.3`. From the current source checkout, build the companion package with
|
|
782
|
+
`NativeRequestPipeline` support before using this adapter. Registry packages may
|
|
783
|
+
not yet contain this new API. Publish the WASM 0.2.2 companion first; refresh the
|
|
784
|
+
npm lockfile's registry integrity after publication, then run Node release gates
|
|
785
|
+
and publish the Node package. The existing `aiwaf(options)` integration remains
|
|
786
|
+
the legacy path; it does not switch automatically.
|
|
787
|
+
|
|
788
|
+
```javascript
|
|
789
|
+
const express = require('express');
|
|
790
|
+
const aiwaf = require('aiwaf');
|
|
791
|
+
|
|
792
|
+
async function main() {
|
|
793
|
+
const app = express();
|
|
794
|
+
// Configure trust proxy for your actual deployment; the native adapter uses req.ip.
|
|
795
|
+
app.use(express.json({ limit: '64kb' }));
|
|
796
|
+
app.use(express.urlencoded({ extended: false, limit: '64kb' }));
|
|
797
|
+
const firewall = await aiwaf.native({
|
|
798
|
+
dataDir: 'aiwaf_native_data',
|
|
799
|
+
profile: { rate_key_mode: 'ip_path', min_form_time: 1.0 },
|
|
800
|
+
// Optional synchronous adapter facts; use your application's authentication.
|
|
801
|
+
authenticated: req => Boolean(req.user),
|
|
802
|
+
routeExists: req => req.path === '/api/ok'
|
|
803
|
+
});
|
|
804
|
+
app.use(firewall);
|
|
805
|
+
app.get('/api/ok', (_req, res) => res.json({ ok: true }));
|
|
806
|
+
app.listen(3000);
|
|
807
|
+
}
|
|
808
|
+
main().catch(error => { console.error(error); process.exitCode = 1; });
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
Configuration and native API checks happen once at startup. Rust runs geo,
|
|
812
|
+
IP/keyword/structured SQL inspection, rate/flood, anomaly block state, honeypot,
|
|
813
|
+
UUID and header checks in one `begin` call. A single `finish` call owns response
|
|
814
|
+
observations, UUID scores, anomaly features/history/inference, bounded keyword
|
|
815
|
+
learning, and escaped CSV row formatting. Node normalizes framework facts,
|
|
816
|
+
serializes the request envelope, emits responses, and appends the returned rows
|
|
817
|
+
using cached file descriptors. Logging is immediate, not queued or batched.
|
|
818
|
+
|
|
819
|
+
The dedicated lowercase `profile` rejects unknown keys. It does not import legacy
|
|
820
|
+
settings, PATH_RULES/manifests, Redis, custom stores, UUID resolver callbacks or
|
|
821
|
+
ORM state. Missing native support fails startup with no JavaScript policy fallback.
|
|
822
|
+
Install this adapter instead of the existing chain, not alongside it. Bounded body
|
|
823
|
+
parsers must run first; an unparsed body with a declared length/chunked encoding
|
|
824
|
+
is rejected with 413 when inspection is enabled. Upload streams require another
|
|
825
|
+
integration path. `countryLookup(req)`, `authenticated(req)` and `routeExists(req)`
|
|
826
|
+
are optional synchronous fact callbacks; country defaults to unknown and route
|
|
827
|
+
existence to `Boolean(req.route)`. Supply accurate facts when the firewall runs
|
|
828
|
+
before Express resolves routes. Country headers are not implicitly trusted.
|
|
829
|
+
|
|
830
|
+
All eight stages are enabled by default. Native defaults include:
|
|
831
|
+
|
|
832
|
+
| Profile setting | Default / scope |
|
|
833
|
+
| --- | --- |
|
|
834
|
+
| `exempt_paths`, `exempt_ips` | `/health`, `/robots.txt`, `/sitemap.xml`; no IPs; literal case-insensitive path prefixes |
|
|
835
|
+
| `sql_mode`, `max_bytes` | `block`, `65536`; `off` supported, monitor rejected; bounded nested JSON/form values and double URL decoding |
|
|
836
|
+
| `static_keywords`, `dynamic_keywords`, `legitimate_keywords`, `learning` | Native vocabulary, empty dynamic set, legitimate exact route names, `true`; learned probe segments capped at 4096 |
|
|
837
|
+
| `geo_allow`, `geo_block`, `blacklist` | Empty; blacklist maps IP to Unix expiry seconds (`0` permanent) |
|
|
838
|
+
| `rate_window`, `rate_max`, `rate_flood`, `rate_key_mode` | `10` seconds, `20`, `40`, `ip_path`; `ip` also supported |
|
|
839
|
+
| `min_form_time`, `max_page_time`, `skip_authenticated`, `honeypot_field` | `1.0`, `240` seconds, `true`, empty field; local Rust timing state |
|
|
840
|
+
| `allowed_methods`, `uuid_prefix`, `uuid_window`, `uuid_threshold` | Empty method restriction, `/user/`, `60` seconds, `5` repeated UUID 404s; malformed UUID denied immediately |
|
|
841
|
+
| `required_headers`, `header_min_score` | `HTTP_USER_AGENT`, `HTTP_ACCEPT`; score `3`, plus header safety caps |
|
|
842
|
+
| `anomaly_window`, `max_history`, `max_clients`, `max_pending` | `60` seconds, `1000`, `100000`, `10000`; periodic cleanup and bounded state |
|
|
843
|
+
| `block_duration` | `86400` seconds for newly generated blocks |
|
|
844
|
+
|
|
845
|
+
Rate counters, honeypot timestamps, UUID scores, anomaly history and loaded policy
|
|
846
|
+
snapshots are local to each engine/worker and reset on restart. Blocks and learned
|
|
847
|
+
keywords append to dedicated `native_blocks.csv`/`native_keywords.csv`, synced
|
|
848
|
+
immediately, and replay at startup (`persistBlocks: false` disables this disk
|
|
849
|
+
history). Policy files are **not live synchronized across workers**; do not share
|
|
850
|
+
the native state/log files across worker processes. These schemas and block rules
|
|
851
|
+
are separate from legacy reputation/CLI stores. Restart/reconstruct to apply
|
|
852
|
+
changed policies; no backend migration or automatic legacy CSV import occurs.
|
|
853
|
+
|
|
854
|
+
`native_requests.csv` is written immediately; `logFsync` defaults to false and
|
|
855
|
+
optionally syncs every log row. `logPath` overrides its location. CSV formatting
|
|
856
|
+
and policy decisions run in Rust; Node necessarily owns actual filesystem calls.
|
|
857
|
+
Finalization runs on response `finish` (or `close`, recorded as 499), uses a Node
|
|
858
|
+
monotonic elapsed clock, and executes once per engine-owned context. Stop requests,
|
|
859
|
+
wait for responses, then call `firewall.close()` to release writers/WASM state.
|
|
860
|
+
Logging/persistence errors invoke `onError(error)` or report to stderr; an already
|
|
861
|
+
completed response cannot be retracted.
|
|
862
|
+
After rotating native log files, reload workers to reopen the cached writers;
|
|
863
|
+
ordinary appends do not check file metadata or reopen descriptors per request.
|
|
864
|
+
|
|
865
|
+
Pass a fitted six-feature Rust/WASM forest as `model` (from
|
|
866
|
+
`aiwaf.wasm.createIsolationForest` with `__aiwafWasm === true`). The engine copies
|
|
867
|
+
its snapshot; `firewall.setModel(model)` replaces it and `setModel(null)` disables
|
|
868
|
+
inference. Node's feature order remains `[pathLen, kwHits, statusIdx, responseTime,
|
|
869
|
+
burst, total404]`, with response time in **milliseconds**, distinct from Python's
|
|
870
|
+
contract. Model scoring/behavior gates at response finalization can update block
|
|
871
|
+
state for later requests. No model means history/learning without model blocking.
|
|
872
|
+
`firewall.diagnostics()` reports native activation, actual inference count and
|
|
873
|
+
state sizes. There are no historical request-log database reads per request.
|
|
874
|
+
|
|
875
|
+
Fastify/Hapi/Koa/Nest/Next/Adonis/Sails can select the same engine with the sole
|
|
876
|
+
outer option `AIWAF_NATIVE_PIPELINE: { profile: {...}, dataDir: '...' }`. Do not mix
|
|
877
|
+
legacy options. Fastify initializes during registration and executes at
|
|
878
|
+
`preValidation`; Hapi initializes during registration, begins enforcement on
|
|
879
|
+
`onRequest` (including unknown routes), then makes an additional native call at
|
|
880
|
+
`onPreHandler` for parsed-body inspection and authenticated form timing.
|
|
881
|
+
Koa/Adonis wrappers and Next API handlers expose `.ready`;
|
|
882
|
+
Nest's middleware class exposes static `.ready`; await those promises before
|
|
883
|
+
starting the application. Fastify/Hapi close the engine on shutdown; use the
|
|
884
|
+
resolved native handle's `close()` for the other wrappers. Route metadata must be
|
|
885
|
+
installed before enforcement; required middleware overrides decorator exemptions,
|
|
886
|
+
while profile-level exemptions remain global. Next integration is Node API routes,
|
|
887
|
+
not Edge/Fetch middleware.
|
|
888
|
+
|
|
889
|
+
Run `npm run test:native` in `js/` against the built WASM package and
|
|
890
|
+
`node scripts/benchmark_js_pipeline.js` for full HTTP comparisons. The benchmark
|
|
891
|
+
subtracts bare Express server processing latency and includes synchronous response
|
|
892
|
+
finalization/logging. Its legacy comparison uses SQLite policy lookups and JSONL
|
|
893
|
+
logging, while native uses Rust state and CSV output; this is an integration
|
|
894
|
+
comparison with different persistence/policy semantics, not a pure language test.
|
|
895
|
+
|
|
896
|
+
The matched Windows HTTP benchmark (Node v22.18.0, Express 4.22.1) measured:
|
|
897
|
+
|
|
898
|
+
| Mode | Server processing | Added overhead |
|
|
899
|
+
| --- | ---: | ---: |
|
|
900
|
+
| Express only | 0.37 ms | 0.00 ms |
|
|
901
|
+
| Legacy, AI off | 3.86 ms | 3.48 ms |
|
|
902
|
+
| Native, AI off | 0.60 ms | 0.22 ms |
|
|
903
|
+
| Native, AI on | 0.64 ms | 0.27 ms |
|
|
904
|
+
|
|
905
|
+
Server samples include synchronous finalization and immediate logging. Overhead subtracts the matched bare Express baseline; figures are medians of per-run means. Legacy uses SQLite policy lookups and one immediate JSONL append; native uses Rust state and one immediate CSV append. These stores/policies have different persistence semantics, so this is an integration comparison, not a pure Rust-versus-JavaScript equivalence test. GeoIP is an unknown-country fixture, not a real database lookup. Synthetic local latency does not establish production throughput or latency.
|
|
906
|
+
|
|
354
907
|
### JavaScript training and operations
|
|
355
908
|
|
|
356
909
|
```bash
|
|
@@ -384,6 +937,11 @@ The module provides:
|
|
|
384
937
|
- incremental feature extraction with explicit state
|
|
385
938
|
- recent-behavior analysis
|
|
386
939
|
- `IsolationForest` training, scoring, prediction, retraining, and JSON state
|
|
940
|
+
- locked CSV storage, indexed snapshot lookups, atomic policy mutations, and
|
|
941
|
+
synchronous cached log writers
|
|
942
|
+
- shared request policies, combined route plans, and exemption matching
|
|
943
|
+
- batched log/timestamp preparation, `TrainingCSVReader`,
|
|
944
|
+
`NativeTrainingBatch`, and `NativeTrainingBuilder`
|
|
387
945
|
|
|
388
946
|
```python
|
|
389
947
|
import aiwaf_rust
|
|
@@ -413,6 +971,8 @@ For a local native build, stage the two canonical repository assets and run matu
|
|
|
413
971
|
```bash
|
|
414
972
|
cp README.md rust/README.md
|
|
415
973
|
cp LICENSE rust/LICENSE
|
|
974
|
+
cp NOTICE rust/NOTICE
|
|
975
|
+
cp -R licenses rust/
|
|
416
976
|
python -m pip install maturin
|
|
417
977
|
cd rust
|
|
418
978
|
maturin develop
|
|
@@ -463,11 +1023,13 @@ wasm-pack build --release --target bundler
|
|
|
463
1023
|
cd ../..
|
|
464
1024
|
python scripts/patch_wasm_pkg.py
|
|
465
1025
|
cp ../LICENSE crates/aiwaf_wasm/pkg/LICENSE
|
|
1026
|
+
cp ../NOTICE crates/aiwaf_wasm/pkg/NOTICE
|
|
1027
|
+
cp -R ../licenses crates/aiwaf_wasm/pkg/
|
|
466
1028
|
```
|
|
467
1029
|
|
|
468
1030
|
## Java package
|
|
469
1031
|
|
|
470
|
-
AIWAF Java 1.3.
|
|
1032
|
+
AIWAF Java 1.3.3 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
|
|
471
1033
|
|
|
472
1034
|
### Core engine
|
|
473
1035
|
|
|
@@ -556,7 +1118,7 @@ UUID protection uses Python-compatible weighted signals: malformed input, valid
|
|
|
556
1118
|
Generate a route manifest from the live Spring application rather than supplying controller methods manually:
|
|
557
1119
|
|
|
558
1120
|
```bash
|
|
559
|
-
java -cp "your-app.jar:aiwaf-java-1.3.
|
|
1121
|
+
java -cp "your-app.jar:aiwaf-java-1.3.3.jar" \
|
|
560
1122
|
com.aiwaf.cli.AiwafConsole init \
|
|
561
1123
|
--app com.example.Application \
|
|
562
1124
|
--output .aiwaf/paths.json
|
|
@@ -723,17 +1285,55 @@ python -m benchmarks.benchmark_auto_middleware --requests 200 --rounds 3 --warmu
|
|
|
723
1285
|
|
|
724
1286
|
Use the same machine, environment, request count, and background load when comparing results. These measurements exclude network and production-server overhead.
|
|
725
1287
|
|
|
1288
|
+
The latest native optimization measurements used three alternating runs. Timestamp
|
|
1289
|
+
and feature/model tests used 10,000 synthetic records; the model test used a
|
|
1290
|
+
20-tree forest and compared the previous Rust-feature/Python-matrix path with
|
|
1291
|
+
retained native features.
|
|
1292
|
+
|
|
1293
|
+
| Scoped workload | Windows speedup | WSL Linux speedup |
|
|
1294
|
+
| --- | ---: | ---: |
|
|
1295
|
+
| Unique Apache timestamp parsing | 4.57× | 3.65× |
|
|
1296
|
+
| Feature extraction + Rust fit/predict boundary | 1.55× | 1.35× |
|
|
1297
|
+
|
|
1298
|
+
Native ISO parsing was slower on both platforms, so it remains optional. An
|
|
1299
|
+
offline Windows Flask test-client workload with IP/keyword enforcement and CSV
|
|
1300
|
+
logging measured 5.95 ms/request native versus 9.18 ms/request Python (1.54×),
|
|
1301
|
+
using 100 initial blacklist rows and 20 requests per trial. These measurements
|
|
1302
|
+
exclude networking, production-server overhead, and concurrent request load;
|
|
1303
|
+
they do not establish a complete training or deployed-site speedup.
|
|
1304
|
+
|
|
1305
|
+
Reproduce the focused measurements and concurrency smoke check locally:
|
|
1306
|
+
|
|
1307
|
+
```bash
|
|
1308
|
+
python scripts/benchmark_native_training_boundary.py
|
|
1309
|
+
python scripts/benchmark_native_csv_training.py
|
|
1310
|
+
python scripts/benchmark_native_csv_workloads.py
|
|
1311
|
+
python scripts/benchmark_csv_request_reuse.py
|
|
1312
|
+
python scripts/profile_csv_logging.py
|
|
1313
|
+
python scripts/check_csv_release_concurrency.py
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
Validation of the development changes passed 282 Django tests, 134 FastAPI tests
|
|
1317
|
+
(one skipped), and 247 Flask/core optimization tests in separate processes.
|
|
1318
|
+
Coverage includes timestamp fallbacks, gzip/quoted CSV, seeded model parity,
|
|
1319
|
+
chunk equivalence, concurrent mutations, no-op writes, and log rotation/reopening.
|
|
1320
|
+
An installed-wheel Linux smoke check with four processes retained all 160 access
|
|
1321
|
+
rows and 80 blacklist entries. Local wheels were checked on Windows Python 3.13
|
|
1322
|
+
and WSL Python 3.10; the locally built Linux wheel requires glibc 2.34 or newer.
|
|
1323
|
+
The complete supported platform/version matrix and production load validation
|
|
1324
|
+
remain release checks.
|
|
1325
|
+
|
|
726
1326
|
## Release automation
|
|
727
1327
|
|
|
728
1328
|
Release versions and tags must match the relevant manifest.
|
|
729
1329
|
|
|
730
1330
|
| Package | Manifest | Tag | Workflow |
|
|
731
1331
|
| --- | --- | --- | --- |
|
|
732
|
-
| Python `aiwaf` | `pyproject.toml` | `python-v1.1.
|
|
733
|
-
| npm `aiwaf` | `js/package.json` | `js-v1.1.
|
|
734
|
-
| PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.
|
|
735
|
-
| npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.
|
|
736
|
-
| Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.
|
|
1332
|
+
| Python `aiwaf` | `pyproject.toml` | `python-v1.1.4` | `python-publish.yml` |
|
|
1333
|
+
| npm `aiwaf` | `js/package.json` | `js-v1.1.2` | `npm-publish.yml` |
|
|
1334
|
+
| PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.3` | `rust-publish.yml` |
|
|
1335
|
+
| npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.2` | `wasm-publish.yml` |
|
|
1336
|
+
| Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.3` | `java-publish.yml` |
|
|
737
1337
|
|
|
738
1338
|
Python and Rust publish to PyPI with trusted publishing. The npm workflows use npm trusted publishing and stage packages for approval. Configure the trusted publisher with organization `aiwaf-project`, repository `aiwaf`, the exact workflow filename, and the environment used by that workflow.
|
|
739
1339
|
|
|
@@ -759,4 +1359,10 @@ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for contributor setup and expectations,
|
|
|
759
1359
|
|
|
760
1360
|
## License
|
|
761
1361
|
|
|
762
|
-
AIWAF
|
|
1362
|
+
Original AIWAF project code in this checkout uses the unmodified [Elastic License 2.0](LICENSE), with separately licensed material identified in [NOTICE](NOTICE). AIWAF is the business offering these terms. ELv2 permits commercial use, modification, redistribution, and consulting, subject to its conditions. It restricts providing substantial AIWAF functionality as a hosted or managed service, bypassing license-key functionality, and removing required notices. ELv2-covered code is source available.
|
|
1363
|
+
|
|
1364
|
+
This migration applies to this checkout and future releases expressly distributed under ELv2. Previously distributed MIT copies retain their permissions; version numbers do not retroactively change their license. Do not republish an existing version with new licensing terms. Independently versioned packages record their license in their release artifacts.
|
|
1365
|
+
|
|
1366
|
+
Retained MIT contributions keep their rights and notices in [licenses/MIT.txt](licenses/MIT.txt). The bundled IPinfo Lite database is provided by [IPinfo](https://ipinfo.io/) under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/); ELv2 restrictions do not apply to that data. Package metadata uses an `AND` expression where separately licensed components are included; this does not offer a choice to license the entire package under MIT. Dependencies retain their respective terms.
|
|
1367
|
+
|
|
1368
|
+
Redistributions must include the applicable LICENSE, NOTICE, and licenses/ files. See [NOTICE](NOTICE) for historical rights, contributor notices, and attribution.
|