aiwaf 1.0.2 → 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/README.md CHANGED
@@ -1,348 +1,344 @@
1
1
  # AIWAF
2
2
 
3
- > A self-learning Web Application Firewall for Python and JavaScript applications.
4
- > Framework adapters for Django, Flask, FastAPI, Express, Fastify, Hapi, Koa,
5
- > Next.js, NestJS, AdonisJS, and Sails.
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
+
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
+
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
+
9
+ ## Packages
10
+
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.
40
+
41
+ Each package is versioned and released independently.
42
+
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).
45
+
46
+ | Runtime | Package | Repository version | Primary use |
47
+ | --- | --- | ---: | --- |
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 |
53
+
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.
55
+
56
+ ## What AIWAF provides
57
+
58
+ - IP blacklist, exemption, reputation, expiry, and progressive-block handling
59
+ - Sliding-window rate limiting and flood detection
60
+ - Header, method, request-size, content-type, and parameter validation
61
+ - Static and learned malicious keyword detection
62
+ - Honeypot field and form-timing checks
63
+ - UUID probing and tamper detection
64
+ - GeoIP allow/block policies using the bundled MMDB data
65
+ - Route manifests, path-specific overrides, and decorator/annotation exemptions
66
+ - Memory, file, CSV, SQLite, database, and cache-backed runtime state, depending on the runtime
67
+ - Structured request logging and offline training
68
+ - Six-feature anomaly models with Rust, JavaScript, and Java implementations
69
+ - Required Rust runtime for Python 1.1.4 and optional WebAssembly acceleration for Node.js
70
+
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.
72
+
73
+ ## Repository layout
6
74
 
7
- AIWAF provides context-aware protection across Python and JavaScript runtimes,
8
- with rate limiting, anomaly detection, honeypots, UUID tamper protection, smart
9
- keyword learning, file-extension probing detection, exempt path/IP awareness,
10
- and scheduled retraining.
11
-
12
- This monorepo contains three independently published packages:
13
-
14
- - `py/aiwaf/` and the root Python packaging files publish `aiwaf` to PyPI.
15
- - `js/` publishes `aiwaf` to npm and supports Express, Fastify, Hapi, Koa, Next.js, NestJS, AdonisJS, and Sails.
16
- - `rust/` publishes `aiwaf-rust` to PyPI as a separate package.
17
-
18
- Install the JavaScript package with `npm install aiwaf`. Its usage, configuration, framework adapters, and operational commands are documented in [JavaScript Package](#javascript-package-aiwaf).
19
-
20
- For local JavaScript development, run `npm ci` and `npm test` from `js/`. Releases are independent: push a `python-v*` tag (for example, `python-v1.0.8`) to publish the Python package to PyPI, a `js-v*` tag (for example, `js-v1.0.1`) to publish `aiwaf` to npm, or a `rust-v*` tag (for example, `rust-v0.2.1`) to publish `aiwaf-rust` to PyPI. The publish workflows can also be started manually from GitHub Actions.
21
-
22
- Run the Python and JavaScript test suites with `python aiwaf_test.py`. Use `--python-only` or `--js-only` when working on one package. For the Rust core, run `cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core`.
23
-
24
- ## Latest Enhancements
25
-
26
- - Reputation-based IP blocking with weighted offenses and progressive block durations
27
- - Automatic migration of legacy blacklist CSV formats with CLI tools to inspect, convert, or clear imported entries
28
- - Request payload-field inference for generated route manifests
29
- - Smart keyword filtering to avoid blocking legitimate paths like `/profile/`
30
- - Granular reset controls for blacklist, keywords, and exemptions
31
- - Context-aware learning that prioritizes suspicious traffic over normal routes
32
- - Enhanced keyword controls via `AIWAF_ALLOWED_PATH_KEYWORDS` and `AIWAF_EXEMPT_KEYWORDS`
33
- - Comprehensive HTTP method validation in honeypot logic
34
- - Enhanced honeypot timing with page expiry/reload flow
35
- - Header validation with quality scoring and bot-pattern detection
36
-
37
- ---
38
-
39
- ## Quick Installation
40
-
41
- Python:
42
-
43
- ```bash
44
- pip install aiwaf
75
+ ```text
76
+ .
77
+ ├── py/aiwaf/ Python package and adapters
78
+ ├── js/ Node.js package and adapters
79
+ ├── rust/ Rust core and Python bindings
80
+ │ └── crates/aiwaf_wasm/ WebAssembly bindings
81
+ ├── java/ Java 17 package
82
+ ├── tests/ Python integration and parity tests
83
+ ├── benchmarks/ Python middleware benchmarks
84
+ ├── examples/ Focused Python examples
85
+ ├── .github/workflows/ Tests, security checks, and releases
86
+ ├── README.md Canonical project documentation
87
+ └── LICENSE Canonical Elastic License 2.0 (see NOTICE)
45
88
  ```
46
89
 
47
- JavaScript:
48
-
49
- ```bash
50
- npm install aiwaf
51
- ```
90
+ ## Quick installation
52
91
 
53
- Optional framework extras:
92
+ Choose the package for the application runtime:
54
93
 
55
94
  ```bash
95
+ # Python core or a framework extra
96
+ pip install aiwaf
56
97
  pip install "aiwaf[django]"
57
98
  pip install "aiwaf[flask]"
58
99
  pip install "aiwaf[fastapi]"
100
+
101
+ # Backward-compatible alias; Python 1.1.4 already installs aiwaf-rust
59
102
  pip install "aiwaf[rust]"
60
- ```
61
103
 
62
- Rust extra installs `aiwaf-rust`, which accelerates selected paths and is required
63
- for persisted AI model inference from JSON `IsolationForest` artifacts.
104
+ # Node.js middleware
105
+ npm install aiwaf
64
106
 
65
- Important:
66
- - Use the adapter package for your framework (`aiwaf.django`, `aiwaf.flask`, or `aiwaf.fast`).
67
- - For Django setup and command details, see `INSTALLATION.md` and `REPO_GUIDE_DJANGO.md`.
107
+ # Standalone WebAssembly bindings
108
+ npm install aiwaf-wasm
109
+ ```
68
110
 
69
- ---
111
+ Java 1.3.3, after it is published to Maven Central:
70
112
 
71
- ## System Requirements
113
+ ```xml
114
+ <dependency>
115
+ <groupId>io.github.aiwaf-project</groupId>
116
+ <artifactId>aiwaf-java</artifactId>
117
+ <version>1.3.3</version>
118
+ </dependency>
119
+ ```
72
120
 
73
- - Python 3.8+
74
- - CPU-only operation (no GPU required)
75
- - Small deployments: ~1 vCPU and ~512 MB RAM
76
- - Moderate deployments: 2 to 4 vCPU and 2 to 4 GB RAM recommended
77
- - For production, schedule detect/train jobs and rotate logs
121
+ ## Python package
78
122
 
79
- ---
123
+ The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
80
124
 
81
- ## Package Structure
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.
82
131
 
83
- ```text
84
- py/
85
- aiwaf/ # Python package (import name remains `aiwaf`)
86
- core/ # framework-agnostic helpers and storage
87
- django/ # Django adapter
88
- flask/ # Flask adapter
89
- fast/ # FastAPI adapter
90
- js/ # JavaScript package, tests, and framework adapters
91
- tests/ # Python test suites
92
- examples/ # Python examples and sandbox tooling
93
- ```
132
+ ### Rust-owned CSV pipeline
94
133
 
95
- Contributor setup, test commands, and release conventions are documented in [`CONTRIBUTING.md`](CONTRIBUTING.md).
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.
96
138
 
97
- Framework entry points:
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.
98
148
 
99
149
  ```python
100
- # Django
101
- import aiwaf.django as aiwaf
102
-
103
150
  # Flask
104
- import aiwaf.flask as aiwaf
151
+ from flask import Flask
152
+ from aiwaf.flask import NativeAIWAF
105
153
 
106
- # FastAPI
107
- import aiwaf.fast as aiwaf
154
+ app = Flask(__name__)
155
+ NativeAIWAF(app, config={"data_dir": "aiwaf_data"})
108
156
  ```
109
157
 
110
- ---
111
-
112
- ## Features
113
-
114
- - **IP blocklist**
115
- - blocks known suspicious sources quickly
116
- - supports runtime updates through adapter storage
117
- - tracks reason history, reputation score, offense count, and expiration metadata
118
- - uses progressive temporary blocks while retaining explicit permanent-block support
119
- - automatically removes expired entries during blacklist checks
120
-
121
- - **Rate limiting**
122
- - sliding-window request control (`AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`)
123
- - flood threshold support (`AIWAF_RATE_FLOOD`) for aggressive abuse
124
-
125
- - **AI anomaly detection**
126
- - IsolationForest-based behavioral detection
127
- - model training updates as traffic grows
128
- - persisted runtime models use JSON-only artifacts; Rust `IsolationForest` is required for saved-model inference
129
-
130
- - **Dynamic keyword learning**
131
- - learns suspicious path terms from attack-like traffic
132
- - excludes exempt/allowed terms to reduce false positives
133
-
134
- - **File-extension probing detection**
135
- - detects repeated probes for extensions like `.php`, `.asp`, `.jsp`
136
-
137
- - **Header validation**
138
- - missing required-header detection
139
- - suspicious user-agent and header-combination checks
140
- - header quality scoring
141
- - static-asset exemption support
142
-
143
- - **Enhanced honeypot timing**
144
- - GET to POST timing checks via `AIWAF_MIN_FORM_TIME`
145
- - page-age validation via `AIWAF_MAX_PAGE_TIME`
146
- - method-misuse checks (for example POST to read-only endpoints)
147
-
148
- - **UUID tamper protection**
149
- - score-based UUID abuse detection
150
- - malformed UUIDs add high score and can block immediately
151
- - valid UUID requests that repeatedly end in `404` increase score
152
- - score decays on successful UUID requests
153
- - blocks when per-IP UUID score crosses threshold
154
-
155
- - **GeoIP support**
156
- - optional country-level allow/block behavior
157
- - local bundled MMDB support by default
158
-
159
- - **Built-in logging path**
160
- - adapter-level request logging can feed training when primary access logs are unavailable
161
-
162
- - **Blocked-request debug logging**
163
- - captures reason, IP, method, path, and user-agent in debug mode
164
-
165
- ---
166
-
167
- ## Header Validation Details
168
-
169
- What it detects:
170
- - missing core browser-like headers
171
- - low-diversity header sets typical of simple bots
172
- - suspicious or automation-focused user agents
173
- - unrealistic header combinations
174
-
175
- What it allows:
176
- - normal browser traffic with complete headers
177
- - well-identified clients and known legitimate bots
178
- - static file requests when exempt patterns are configured
179
-
180
- Useful test pattern:
181
-
182
- ```bash
183
- # often low-quality header profile
184
- curl http://your-app.example/
158
+ ```python
159
+ # FastAPI / pure ASGI
160
+ from fastapi import FastAPI
161
+ from aiwaf.fast import NativeAIWAFMiddleware
185
162
 
186
- # compare against normal browser traffic
163
+ app = FastAPI()
164
+ app.add_middleware(NativeAIWAFMiddleware, config={"data_dir": "aiwaf_data"})
187
165
  ```
188
166
 
189
- ---
190
-
191
- ## Exemptions and Safe Routing
192
-
193
- AIWAF supports:
194
- - exempt paths (`AIWAF_EXEMPT_PATHS`)
195
- - exempt IPs (adapter-managed allowlists)
196
- - exempt keywords (`AIWAF_EXEMPT_KEYWORDS`)
197
- - allowed route keywords (`AIWAF_ALLOWED_PATH_KEYWORDS`)
198
-
199
- Effects of exemption:
200
- - excluded from keyword learning
201
- - bypass of selected blocking paths
202
- - reduced false positives on trusted operational routes (webhooks, health, static assets)
203
-
204
- Decorator-based exemptions:
205
- - Django adapter and Flask adapter both expose exemption decorators in their adapter modules.
206
-
207
- ---
208
-
209
- ## Training and Retraining
210
-
211
- Training pipeline:
212
- 1. Read configured access logs or adapter logger output
213
- 2. Detect suspicious patterns (including heavy 404 probe behavior)
214
- 3. Train/update IsolationForest when AI thresholds are met
215
- 4. Refresh dynamic keywords from suspicious traffic
216
- 5. Remove exempt/allowed noise from learned keyword set
217
-
218
- Thresholds:
219
- - `AIWAF_MIN_AI_LOGS` default 10,000 for full AI training
220
- - `AIWAF_MIN_TRAIN_LOGS` default 50 for keyword-focused fallback
221
- - `AIWAF_FORCE_AI_TRAINING` can override AI threshold gating
222
-
223
- Daily retraining is recommended for active internet-facing workloads.
224
-
225
- Model persistence is intentionally JSON-only. AIWAF does not load Python object
226
- model artifacts (`pickle`, `joblib`, or `skops`) because those formats can
227
- execute code during deserialization. Scikit-learn models may be used during a
228
- training run for immediate analysis, but they are not persisted. To persist and
229
- reload runtime AI models, install the Rust package so
230
- `aiwaf_rust.IsolationForest` can save/load JSON state. The old bundled
231
- `model.pkl` artifacts have been
232
- removed; retrain to generate a `model.json` artifact.
233
-
234
- ---
235
-
236
- ## Configuration (`AIWAF_*`)
237
-
238
- AIWAF uses flat `AIWAF_*` settings/config keys.
239
- Some knobs are adapter-specific; core controls are shared.
240
-
241
- Required in most deployments:
242
-
243
167
  ```python
244
- AIWAF_ACCESS_LOG = "/var/log/nginx/access.log"
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
+ ]
245
174
  ```
246
175
 
247
- Core defaults (examples):
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
+
279
+ ### Flask
248
280
 
249
281
  ```python
250
- AIWAF_DISABLE_AI = False
251
- AIWAF_MIN_AI_LOGS = 10000
252
- AIWAF_MIN_TRAIN_LOGS = 50
253
- AIWAF_FORCE_AI_TRAINING = False
254
- AIWAF_AI_CONTAMINATION = 0.05
255
-
256
- AIWAF_RATE_WINDOW = 10
257
- AIWAF_RATE_MAX = 20
258
- AIWAF_RATE_FLOOD = 10
259
- AIWAF_WINDOW_SECONDS = 60
260
-
261
- AIWAF_MIN_FORM_TIME = 1.0
262
- AIWAF_MAX_PAGE_TIME = 240
263
- AIWAF_FILE_EXTENSIONS = [".php", ".asp", ".jsp"]
264
-
265
- AIWAF_UUID_SCORE_ENABLED = True
266
- AIWAF_UUID_SCORE_WINDOW_SECONDS = 60
267
- AIWAF_UUID_SCORE_BLOCK_THRESHOLD = 5
268
- AIWAF_UUID_SCORE_MALFORMED_WEIGHT = 5
269
- AIWAF_UUID_SCORE_NOT_FOUND_WEIGHT = 1
270
- AIWAF_UUID_SCORE_SUCCESS_DECAY = 2
271
-
272
- AIWAF_ALLOWED_PATH_KEYWORDS = ["profile", "user", "account", "dashboard"]
273
- AIWAF_EXEMPT_KEYWORDS = ["api", "webhook", "health", "static", "media"]
274
- AIWAF_EXEMPT_PATHS = ["/favicon.ico", "/robots.txt", "/static/", "/health/"]
275
- ```
282
+ from flask import Flask
283
+ from aiwaf.flask import AIWAF
276
284
 
277
- Model storage:
285
+ app = Flask(__name__)
286
+ AIWAF(
287
+ app,
288
+ middlewares=["auto"],
289
+ )
278
290
 
279
- ```python
280
- AIWAF_MODEL_PATH = "aiwaf/resources/model.json"
281
- AIWAF_MODEL_STORAGE = "file" # file | db | cache
282
- AIWAF_MODEL_CACHE_KEY = "aiwaf:model"
283
- AIWAF_MODEL_CACHE_TIMEOUT = None
284
- AIWAF_MODEL_STORAGE_FALLBACK = True
291
+ @app.get("/")
292
+ def home():
293
+ return {"protected": True}
285
294
  ```
286
295
 
287
- Only JSON-serializable model artifacts are saved. Python object model artifacts
288
- are rejected by design.
296
+ `middlewares=["all"]` enables the canonical middleware set. `auto` starts from the same set and omits checks that are not useful for the detected application signals.
289
297
 
290
- Header controls:
298
+ ### FastAPI
291
299
 
292
300
  ```python
293
- AIWAF_REQUIRED_HEADERS = None # list or method->list mapping
294
- AIWAF_HEADER_QUALITY_MIN_SCORE = 3
295
- ```
296
-
297
- GeoIP:
301
+ from fastapi import FastAPI
302
+ from aiwaf.fast import AIWAF
298
303
 
299
- ```python
300
- AIWAF_GEO_BLOCK_ENABLED = False
301
- AIWAF_GEOIP_DB_PATH = "py/aiwaf/core/geolock/ipinfo_lite.mmdb"
302
- AIWAF_GEO_BLOCK_COUNTRIES = ["CN", "RU"]
303
- AIWAF_GEO_ALLOW_COUNTRIES = []
304
- AIWAF_GEO_CACHE_SECONDS = 3600
305
- AIWAF_GEO_CACHE_PREFIX = "aiwaf:geo:"
306
- ```
304
+ app = FastAPI()
307
305
 
308
- Rust acceleration:
306
+ AIWAF(
307
+ app,
308
+ middlewares=["auto"],
309
+ storage={"backend": "memory"},
310
+ header_validation={"enabled": True, "quality_threshold": 3},
311
+ rate_limiting={"enabled": True, "window_seconds": 10, "max_requests": 20},
312
+ logging_middleware={
313
+ "enabled": True,
314
+ "log_dir": "aiwaf_logs",
315
+ "log_format": "json",
316
+ },
317
+ )
309
318
 
310
- ```python
311
- AIWAF_RUST_ISOLATION_FOREST = True
319
+ @app.get("/")
320
+ async def home():
321
+ return {"protected": True}
312
322
  ```
313
323
 
314
- When `aiwaf_rust` is importable, AIWAF automatically uses its supported
315
- accelerators. No `AIWAF_USE_RUST` setting is required. Python fallback remains
316
- automatic when the package or a particular Rust capability is unavailable.
317
- Persisted AI model loading requires a JSON artifact; the Rust `IsolationForest`
318
- backend provides the supported JSON model state. Pickle-based `model.pkl`
319
- artifacts are no longer shipped or loaded.
320
-
321
- Legacy compatibility:
322
- - if you still use nested `AIWAF_SETTINGS`, AIWAF maps common keys into flat `AIWAF_*` values at startup.
323
-
324
- ---
324
+ ### Django
325
325
 
326
- ## Middleware Setup
326
+ Add the app and the unified middleware alias in `settings.py`:
327
327
 
328
- Order matters in all adapters. Put protection middleware early and logging middleware near the end.
329
-
330
- ### Unified `all` / `auto` Selection
331
-
332
- AIWAF now supports a centralized "enable everything with smart defaults" mode across adapters.
333
-
334
- - FastAPI and Flask: pass `middlewares=["all"]` (or `["auto"]`)
335
- - Django: use `"aiwaf.django.middleware.all"` in `MIDDLEWARE`
328
+ ```python
329
+ INSTALLED_APPS = [
330
+ # ...
331
+ "aiwaf.django",
332
+ ]
336
333
 
337
- Auto behavior:
338
- - logging middleware is enabled when `AIWAF_ACCESS_LOG` is missing/empty
339
- - logging middleware is disabled when `AIWAF_ACCESS_LOG` is configured
340
- - geo middleware is enabled when any of these are true:
341
- - explicit geo enable flag is on
342
- - static geo block list has countries
343
- - dynamic geo block store/table has countries
334
+ MIDDLEWARE = [
335
+ "django.middleware.security.SecurityMiddleware",
336
+ "aiwaf.django.middleware.all",
337
+ # ...
338
+ ]
339
+ ```
344
340
 
345
- Django example order:
341
+ For explicit ordering, replace the alias with the individual middleware classes:
346
342
 
347
343
  ```python
348
344
  MIDDLEWARE = [
@@ -358,1532 +354,1015 @@ MIDDLEWARE = [
358
354
  ]
359
355
  ```
360
356
 
361
- If JSON API clients need JSON 403 bodies, keep `JsonExceptionMiddleware` near the top.
357
+ Protection middleware should run early. Logging should run late enough to observe the application response.
362
358
 
363
- Django alias example:
359
+ ### Route manifests
364
360
 
365
- ```python
366
- MIDDLEWARE = [
367
- "django.middleware.security.SecurityMiddleware",
368
- "aiwaf.django.middleware.all",
369
- ]
370
- ```
361
+ `aiwaf init` imports the live application and records all registered routes in `.aiwaf/paths.json`. The `--app` value must be `module:object`, not only a module name.
371
362
 
372
- FastAPI quick integration:
363
+ ```bash
364
+ # Flask application object
365
+ aiwaf init --framework flask --app app:app
373
366
 
374
- ```python
375
- from fastapi import FastAPI
376
- from aiwaf.fast import AIWAF
367
+ # Flask application factory
368
+ aiwaf init --framework flask --app app:create_app
377
369
 
378
- app = FastAPI()
370
+ # FastAPI
371
+ aiwaf init --framework fastapi --app app:app
379
372
 
380
- aiwaf = AIWAF(
381
- app,
382
- middlewares=["all"],
383
- storage={"backend": "memory"},
384
- header_validation={"enabled": True, "quality_threshold": 3},
385
- rate_limiting={"enabled": True, "window_seconds": 10, "max_requests": 20},
386
- logging_middleware={"enabled": True, "log_dir": "aiwaf_logs", "log_format": "json"},
387
- )
388
- ```
373
+ # Django
374
+ aiwaf init --framework django --settings project.settings
389
375
 
390
- Flask quick integration:
376
+ # Custom output
377
+ aiwaf init --framework flask --app app:app --output .aiwaf/paths.json
378
+ ```
391
379
 
392
- ```python
393
- from flask import Flask
394
- from aiwaf.flask import AIWAF
380
+ Run the command in the same environment and checkout used to start the application. If it discovers only `/` and Flask's static route, verify the imported file and live route table:
395
381
 
396
- app = Flask(__name__)
397
- aiwaf = AIWAF(app, middlewares=["all"])
382
+ ```bash
383
+ python -c "import app; print(app.__file__); print(*sorted(r.rule for r in app.app.url_map.iter_rules()), sep='\n')"
398
384
  ```
399
385
 
400
- ---
386
+ ### Python route exemptions
387
+
388
+ Django, Flask, and FastAPI expose equivalent route helpers:
401
389
 
402
- ## Operations
390
+ ```python
391
+ from aiwaf.flask import (
392
+ aiwaf_exempt,
393
+ aiwaf_exempt_from,
394
+ aiwaf_only,
395
+ aiwaf_require_protection,
396
+ )
403
397
 
404
- Django adapter examples:
398
+ @app.get("/health")
399
+ @aiwaf_exempt
400
+ def health():
401
+ return {"ok": True}
402
+
403
+ @app.post("/webhook")
404
+ @aiwaf_only("header_validation")
405
+ def webhook():
406
+ return {"accepted": True}
407
+ ```
408
+
409
+ Canonical middleware names include `header_validation`, `rate_limit`, `ip_keyword_block`, `honeypot`, `geo_block`, `uuid_tamper`, `ai_anomaly`, and `logging`.
410
+
411
+ ### Python configuration
412
+
413
+ Python adapters use flat `AIWAF_*` settings or their equivalent constructor options.
414
+
415
+ | Area | Important settings |
416
+ | --- | --- |
417
+ | Training | `AIWAF_ACCESS_LOG`, `AIWAF_MIN_TRAIN_LOGS`, `AIWAF_MIN_AI_LOGS`, `AIWAF_FORCE_AI_TRAINING` |
418
+ | Rate limiting | `AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`, `AIWAF_RATE_FLOOD` |
419
+ | Headers | `AIWAF_REQUIRED_HEADERS`, `AIWAF_HEADER_QUALITY_MIN_SCORE` |
420
+ | Honeypot | `AIWAF_MIN_FORM_TIME`, `AIWAF_MAX_PAGE_TIME` |
421
+ | UUID checks | `AIWAF_UUID_SCORE_ENABLED`, `AIWAF_UUID_SCORE_BLOCK_THRESHOLD` |
422
+ | GeoIP | `AIWAF_GEO_BLOCK_ENABLED`, `AIWAF_GEO_BLOCK_COUNTRIES`, `AIWAF_GEO_ALLOW_COUNTRIES` |
423
+ | Exemptions | `AIWAF_EXEMPT_PATHS`, `AIWAF_EXEMPT_KEYWORDS`, `AIWAF_ALLOWED_PATH_KEYWORDS` |
424
+ | Models | `AIWAF_MODEL_PATH`, `AIWAF_MODEL_STORAGE`, `AIWAF_MODEL_STORAGE_FALLBACK` |
425
+
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.
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:
405
480
 
406
- ```bash
407
- python manage.py detect_and_train
408
- python manage.py regenerate_model
409
- python manage.py aiwaf_reset --keywords --confirm
410
- python manage.py add_ipexemption 203.0.113.10 --reason "trusted integration"
411
- python manage.py add_pathexemption /api/webhooks/ --reason "partner callbacks"
412
- python manage.py aiwaf_logging --status
413
- python manage.py geo_block_country list
414
- python manage.py geo_block_country add US
415
- python manage.py geo_block_country remove US
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"
416
485
  ```
417
486
 
418
- Flask adapter:
419
- - use `aiwaf.flask.AIWAF` for middleware registration
420
- - use `aiwaf.flask.cli.AIWAFManager` for CSV-backed operational tasks
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.
421
494
 
422
- FastAPI adapter:
423
- - use `aiwaf.fast.AIWAF` for middleware registration
424
- - use `aiwaf fast ...` or `aiwaf-fast ...` for CLI operations
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.
425
501
 
426
- ### Django Command Reference
502
+ Check the installed extension without touching application data:
427
503
 
428
- Common management commands:
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
+
595
+ ### Python operations
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.
429
623
 
430
624
  ```bash
625
+ # Auto-detected CLI (one supported framework installed)
626
+ aiwaf --help
627
+ aiwaf blacklist migrate
628
+ aiwaf status
629
+
630
+ # Django management commands
431
631
  python manage.py detect_and_train
432
632
  python manage.py regenerate_model
433
- python manage.py aiwaf_reset --confirm
434
- python manage.py aiwaf_reset --blacklist --confirm
435
633
  python manage.py aiwaf_reset --keywords --confirm
436
- python manage.py aiwaf_reset --exemptions --confirm
437
- python manage.py add_ipexemption <ip> --reason "optional reason"
438
- python manage.py add_pathexemption /path/prefix/ --reason "optional reason"
439
- python manage.py aiwaf_pathshell
440
634
  python manage.py aiwaf_logging --status
441
635
  python manage.py geo_block_country list
442
- python manage.py geo_block_country add US
443
- python manage.py geo_block_country remove US
444
- python manage.py aiwaf_diagnose
445
- ```
446
636
 
447
- `aiwaf_pathshell` helpers:
448
-
449
- ```text
450
- ls # list path tree at current node
451
- cd <index|name> # enter child path node
452
- up / cd .. # move up
453
- pwd # current path prefix
454
- exempt <index|name|.> # add exemption for selected/current path
455
- exit # quit shell
456
- ```
457
-
458
- ### Flask Adapter Reference
459
-
460
- Programmatic integration:
461
-
462
- ```python
463
- from flask import Flask
464
- from aiwaf.flask import AIWAF
465
-
466
- app = Flask(__name__)
467
- app.config["AIWAF_GEO_BLOCK_ENABLED"] = False
468
- app.config["AIWAF_MIN_AI_LOGS"] = 10000
469
-
470
- aiwaf = AIWAF(
471
- app,
472
- middlewares=[
473
- "logging",
474
- "header_validation",
475
- "ip_keyword_block",
476
- "rate_limit",
477
- "geo_block",
478
- "ai_anomaly",
479
- "uuid_tamper",
480
- ],
481
- )
482
- ```
483
-
484
- Optional Flask CLI manager:
485
-
486
- ```bash
487
- python -m aiwaf.flask.cli list all
488
- python -m aiwaf.flask.cli add whitelist 203.0.113.10
489
- python -m aiwaf.flask.cli add blacklist 203.0.113.99 --reason "manual test"
490
- python -m aiwaf.flask.cli add keyword ../etc/passwd
491
- python -m aiwaf.flask.cli status
492
- python -m aiwaf.flask.cli blocked
493
- python -m aiwaf.flask.cli unblock 203.0.113.99
494
- python -m aiwaf.flask.cli clear
495
- ```
496
-
497
- Blacklist migration commands:
498
-
499
- ```bash
500
- # Detect the configured backend and upgrade legacy rows
501
- aiwaf flask blacklist migrate --app myapp:app
502
- aiwaf fast blacklist migrate --app myapp:app
503
- aiwaf django blacklist migrate
637
+ # Explicit adapter dispatch
638
+ aiwaf django aiwaf_list --all
639
+ aiwaf flask --help
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
646
+ ```
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
+
688
+ ## JavaScript package
689
+
690
+ The npm package uses CommonJS and exports the Express middleware as its default function plus adapters for the other supported Node frameworks.
691
+
692
+ ### Express
693
+
694
+ ```javascript
695
+ const express = require('express');
696
+ const aiwaf = require('aiwaf');
504
697
 
505
- # Inspect all entries or only legacy imports
506
- python -m aiwaf.flask.cli blacklist list
507
- python -m aiwaf.flask.cli blacklist list --legacy
698
+ const app = express();
699
+ app.use(express.json());
508
700
 
509
- # Convert legacy permanent entries to temporary blocks (default: 24h)
510
- python -m aiwaf.flask.cli blacklist convert-legacy
511
- python -m aiwaf.flask.cli blacklist convert-legacy --duration 1d
701
+ app.use(aiwaf({
702
+ AIWAF_MIDDLEWARES: ['auto'],
703
+ staticKeywords: ['.php', '.env', '.git'],
704
+ WINDOW_SEC: 10,
705
+ MAX_REQ: 20,
706
+ FLOOD_REQ: 40,
707
+ AIWAF_HEADER_VALIDATION: true,
708
+ AIWAF_METHOD_POLICY_ENABLED: true,
709
+ AIWAF_ALLOWED_METHODS: ['GET', 'POST', 'HEAD', 'OPTIONS']
710
+ }));
512
711
 
513
- # Remove only legacy-imported entries
514
- python -m aiwaf.flask.cli blacklist clear-legacy
712
+ app.get('/', (req, res) => res.json({ protected: true }));
713
+ app.listen(3000);
515
714
  ```
516
715
 
517
- Durations accept seconds or an `s`, `m`, `h`, or `d` suffix, such as `900`,
518
- `15m`, `24h`, or `1d`. Old headered and headerless blacklist CSV layouts are
519
- upgraded automatically. Imported legacy rows remain permanent until explicitly
520
- converted or cleared.
521
-
522
- #### Upgrading an Existing Blocklist
716
+ Attach AIWAF after the body parser when honeypot rules inspect parsed form or JSON fields.
523
717
 
524
- Back up the database or AIWAF data directory before upgrading. Existing entries
525
- should be preserved as permanent blocks unless you deliberately convert them to
526
- temporary blocks.
718
+ ### Node framework adapters
527
719
 
528
- | Framework/storage | Schema update | Existing entries |
529
- |---|---|---|
530
- | Django ORM | Run Django migrations, then `aiwaf django blacklist migrate` | Command backfills the new reputation fields |
531
- | Flask SQLAlchemy | Run the application's Alembic/Flask-Migrate migration, then `aiwaf flask blacklist migrate --app ...` | Command backfills the new fields |
532
- | Flask `blacklist.csv` | `aiwaf flask blacklist migrate --app ...` | Imported as permanent; use `convert-legacy` to make them temporary |
533
- | Django/FastAPI shared `csv`, `file`, or `db` runtime backend | `aiwaf django blacklist migrate` or `aiwaf fast blacklist migrate --app ...` | Command upgrades legacy key/value records in place |
720
+ | Framework | Entry point |
721
+ | --- | --- |
722
+ | Express | `aiwaf(options)` |
723
+ | Fastify | `fastify.register(aiwaf.fastify, options)` |
724
+ | Hapi | `server.register({ plugin: aiwaf.hapi, options })` |
725
+ | Koa | `app.use(aiwaf.koa(options))` |
726
+ | NestJS/Express | `aiwaf.nest(options)` or the Express middleware |
727
+ | NestJS/Fastify | `app.register(aiwaf.fastify, options)` |
728
+ | Next.js API routes | `aiwaf.next(handler, options)` |
729
+ | AdonisJS | `aiwaf.adonis(options)` |
730
+ | Sails.js | `aiwaf.sails(options)` |
534
731
 
535
- Django ORM:
536
-
537
- ```bash
538
- # Generate and apply the model-column migration in the Django project.
539
- python manage.py makemigrations aiwaf
540
- python manage.py migrate aiwaf
732
+ ### JavaScript path policies
541
733
 
542
- aiwaf django blacklist migrate
543
- # Equivalent:
544
- python manage.py aiwaf_migrate_blacklist
734
+ ```javascript
735
+ app.use(aiwaf({
736
+ AIWAF_PATH_RULES: [
737
+ { PREFIX: '/health/', DISABLE: ['header_validation', 'rate_limit'] },
738
+ { PREFIX: '/api/public/', RATE_LIMIT: { WINDOW: 60, MAX: 300 } }
739
+ ]
740
+ }));
545
741
  ```
546
742
 
547
- The command detects `AIWAF_STORAGE_MODE`. In ORM mode it verifies that the new
548
- columns exist and backfills legacy rows. In CSV mode it upgrades the configured
549
- runtime store. It stops with the exact schema-migration instruction if ORM
550
- columns are still missing.
743
+ Applications can also use `aiwaf.exempt`, `aiwaf.exemptFrom`, `aiwaf.only`, and `aiwaf.requireProtection` to build route policies.
551
744
 
552
- Flask SQLAlchemy ORM:
745
+ Generate an Express route manifest after routes are registered:
553
746
 
554
- ```bash
555
- # db.create_all() does not alter an existing table.
556
- flask db migrate -m "add AIWAF blacklist reputation fields"
557
- flask db upgrade
558
- aiwaf flask blacklist migrate --app myapp:app
747
+ ```javascript
748
+ aiwaf.generateExpressManifest(app, '.aiwaf/paths.json');
559
749
  ```
560
750
 
561
- The Flask command loads the application so it can inspect `AIWAF_USE_CSV` and
562
- the initialized SQLAlchemy extension. It migrates CSV directly, or verifies and
563
- backfills the ORM table. If ORM columns are missing, it stops and asks for the
564
- application-owned Alembic/Flask-Migrate migration; AIWAF does not silently alter
565
- an application's relational schema.
566
-
567
- Migration is optional for runtime compatibility. Until it is run, Django and
568
- Flask ORM adapters detect the deployed table columns and continue using the
569
- legacy `ip`/`reason` behavior. FastAPI and the shared runtime backends continue
570
- to recognize old reason-only `blocked:*` values as permanent blocks. New
571
- reputation metadata takes effect after migration or when a legacy runtime value
572
- is updated. This fallback prevents a package upgrade from silently unblocking
573
- existing IPs.
574
-
575
- For Flask CSV storage, set `AIWAF_DATA_DIR` (or Flask
576
- `AIWAF_DATA_DIR`) to the directory containing the current `blacklist.csv`
577
- before running the migration commands. Reading the file rewrites old layouts
578
- to the current columns. The migration recognizes old headered layouts such as
579
- `ip,reason,added_date,extended_request_info` and `ip,timestamp,reason`, plus
580
- headerless `ip[,reason]` rows.
581
-
582
- For Django CSV and FastAPI, the shared runtime backends use key/value storage
583
- (`runtime_store.csv`, JSON/file storage, or the `kv_store` SQLite table), so
584
- there are no ORM columns to add. Keep the configured data path unchanged and
585
- run the matching migration command. For FastAPI without an importable app, pass
586
- the backend explicitly, for example:
751
+ Or generate one from a route list with the CLI:
587
752
 
588
753
  ```bash
589
- aiwaf fast blacklist migrate --backend csv --storage-path aiwaf_data/runtime_store.csv
590
- aiwaf fast blacklist migrate --backend db --storage-path aiwaf_data/aiwaf_data.db
754
+ cd js
755
+ npm run aiwaf -- manifest --framework express --routes routes.json --output .aiwaf/paths.json
591
756
  ```
592
757
 
593
- ### FastAPI Adapter Reference
758
+ ### JavaScript configuration
594
759
 
595
- Programmatic integration:
760
+ | Area | Important options |
761
+ | --- | --- |
762
+ | Middleware | `AIWAF_MIDDLEWARES`, `AIWAF_DISABLE_MIDDLEWARES`, `AIWAF_PATH_RULES` |
763
+ | Rate limiting | `WINDOW_SEC`, `MAX_REQ`, `FLOOD_REQ`, `cache` |
764
+ | Headers | `AIWAF_HEADER_VALIDATION`, `AIWAF_REQUIRED_HEADERS`, `AIWAF_HEADER_QUALITY_MIN_SCORE` |
765
+ | Methods | `AIWAF_METHOD_POLICY_ENABLED`, `AIWAF_ALLOWED_METHODS` |
766
+ | Keywords | `staticKeywords`, `AIWAF_ENABLE_KEYWORD_LEARNING`, `AIWAF_DYNAMIC_TOP_N` |
767
+ | Honeypot | `HONEYPOT_FIELD`, timing settings |
768
+ | GeoIP | `AIWAF_GEO_BLOCK_ENABLED`, `AIWAF_GEO_BLOCK_COUNTRIES`, `AIWAF_GEO_ALLOW_COUNTRIES` |
769
+ | Models | `AIWAF_MODEL_STORAGE`, `AIWAF_MODEL_PATH`, `AIWAF_MODEL_CACHE_KEY` |
770
+ | Logging | `AIWAF_MIDDLEWARE_LOGGING`, `AIWAF_MIDDLEWARE_LOG_PATH`, DB/CSV options |
771
+ | WASM | `AIWAF_WASM_VALIDATION`, `AIWAF_WASM_VALIDATE_RECENT` |
596
772
 
597
- ```python
598
- from fastapi import FastAPI
599
- from aiwaf.fast import AIWAF
600
-
601
- app = FastAPI()
602
- AIWAF(app)
603
- ```
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.
604
774
 
605
- CLI usage:
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.
606
778
 
607
- ```bash
608
- aiwaf fast --help
609
- aiwaf-fast --help
610
- ```
779
+ ### Rust-owned Node request pipeline
611
780
 
612
- ### Path-Specific Rules
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.
613
787
 
614
- AIWAF can generate a route manifest at `.aiwaf/paths.json` and compile it into
615
- runtime path rules. This is the preferred 1.0 workflow because framework-specific
616
- route extraction happens once during init, not on every request.
788
+ ```javascript
789
+ const express = require('express');
790
+ const aiwaf = require('aiwaf');
617
791
 
618
- Generate a manifest:
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
+
907
+ ### JavaScript training and operations
619
908
 
620
909
  ```bash
621
- # Django
622
- python manage.py aiwaf init
623
-
624
- # Flask
625
- aiwaf flask init --app myapp:app
626
-
627
- # FastAPI
628
- aiwaf fast init --app myapp:app
910
+ cd js
629
911
 
630
- # Unified entrypoint
631
- aiwaf init
632
- aiwaf init --app myapp:app
633
- aiwaf init --framework flask --app myapp:app
634
- aiwaf init --framework django --settings myproject.settings
912
+ AIWAF_ACCESS_LOG=/path/to/access.log npm run train
913
+ npm run aiwaf -- status
914
+ npm run aiwaf -- list blacklist
915
+ npm run aiwaf -- add blacklist 203.0.113.9 "manual block"
916
+ npm run aiwaf -- add ip-exemption 203.0.113.10 "trusted monitor"
917
+ npm run aiwaf -- geo summary
918
+ npm run aiwaf -- model info
919
+ npm run aiwaf -- export aiwaf-export.json
635
920
  ```
636
921
 
637
- `aiwaf init` auto-detects the framework when exactly one supported framework is
638
- installed. If multiple supported frameworks are installed, pass `--app` for
639
- Flask/FastAPI projects or `--framework` to choose the adapter explicitly.
640
- For Django, run from the project root containing `manage.py`, set
641
- `DJANGO_SETTINGS_MODULE`, or pass `--settings`.
642
-
643
- During init, AIWAF uses framework metadata first and then bounded static source
644
- analysis when metadata is missing. It can infer:
645
-
646
- - route methods from Flask/FastAPI routers, DRF actions, Django CBVs, decorators, and view source
647
- - auth endpoints from signals such as `authenticate`, `login`, `login_user`, `OAuth2PasswordRequestForm`, and helper calls
648
- - API endpoints from combined signals such as `/api/` paths, DRF `APIView`/`ViewSet`, Flask JSON endpoints, FastAPI route metadata, Pydantic/body models, `request.body`, `request.data`, `request.json`, and JSON content-type expectations
649
- - form endpoints from `request.POST`, `request.form`, Django `Form`/`ModelForm`, `render`, `render_template`, `redirect`, and mixed HTML/JSON response flows
650
- - literal payload field names from form/JSON access such as `payload.get("email")`, `request.form["password"]`, and equivalent aliases
651
- - upload/static/app routes from path and source signals
652
-
653
- Detector output is explainable: generated routes can include confidence scores
654
- and the exact signals used for auth/API/form classification. Response type alone
655
- does not force API classification; payload type is preferred. For example, a
656
- contact form that redirects on success and returns `JsonResponse` on validation
657
- failure is classified as `category: "form"`, `response_type: "mixed"`, and
658
- `payload_type: "form"`.
659
-
660
- Manifest shape:
661
-
662
- ```json
663
- {
664
- "schema_version": "1.0",
665
- "framework": "flask",
666
- "context_hash": "sha256...",
667
- "routes": {
668
- "/api/users/": {
669
- "methods": ["GET", "POST"],
670
- "view": "myapp.users",
671
- "category": "api",
672
- "response_type": "json",
673
- "payload_type": "json",
674
- "payload_fields": ["email", "message"],
675
- "auth_required": false,
676
- "api_confidence": 0.94,
677
- "api_signals": ["path:/api", "JsonResponse", "request.body"],
678
- "request_body": true,
679
- "protections": {
680
- "rate_limit": {"requests": 120, "window_seconds": 60},
681
- "api_rate_limit": {"requests": 120, "window_seconds": 60},
682
- "payload_validation": {"max_body_bytes": 1048576, "max_json_depth": 8},
683
- "content_type_validation": {"require_valid_content_type": true},
684
- "honeypot": {"enabled": false}
685
- }
686
- },
687
- "/contact/": {
688
- "methods": ["GET", "POST"],
689
- "view": "myapp.contact",
690
- "category": "form",
691
- "response_type": "mixed",
692
- "payload_type": "form",
693
- "auth_required": false,
694
- "form_confidence": 0.75,
695
- "form_signals": ["request.POST", "render", "redirect"],
696
- "request_body": true,
697
- "protections": {
698
- "rate_limit": {"requests": 30, "window_seconds": 60},
699
- "payload_validation": {"max_body_bytes": 1048576},
700
- "honeypot": {"enabled": true}
701
- }
702
- },
703
- "/login/": {
704
- "methods": ["GET", "POST"],
705
- "view": "accounts.views.login_view",
706
- "category": "auth",
707
- "response_type": "html",
708
- "auth_required": false,
709
- "auth_action": "login",
710
- "auth_confidence": 0.9,
711
- "auth_signals": ["django.contrib.auth.authenticate", "django.contrib.auth.login", "POST"],
712
- "protections": {
713
- "rate_limit": {"requests": 30, "window_seconds": 60},
714
- "honeypot": {"enabled": true}
715
- }
716
- }
717
- }
718
- }
719
- ```
922
+ Use Redis or another shared cache for consistent rate limiting across multiple Node processes. Without shared state, the in-memory fallback is process-local.
720
923
 
721
- Method and category detection is deterministic but still best-effort for highly
722
- dynamic code. For maximum accuracy, use framework method decorators such as
723
- Django `@require_http_methods`, explicit Flask route methods, and FastAPI
724
- `@app.get` / `@app.post` decorators.
924
+ ## Rust accelerator for Python
725
925
 
726
- You can still define manual path rules to selectively disable middleware or
727
- override rate limits without globally weakening protection:
926
+ `aiwaf-rust` exposes the shared Rust core through PyO3 and ABI3 wheels for Python 3.8 and newer.
728
927
 
729
- ```python
730
- AIWAF_SETTINGS = {
731
- "PATH_RULES": [
732
- {
733
- "PREFIX": "/api/webhooks/",
734
- "DISABLE": ["HeaderValidationMiddleware"],
735
- "RATE_LIMIT": {"WINDOW": 60, "MAX": 2000},
736
- },
737
- {
738
- "PREFIX": "/api/public/",
739
- "RATE_LIMIT": {"WINDOW": 60, "MAX": 500},
740
- },
741
- ]
742
- }
928
+ ```bash
929
+ pip install aiwaf-rust
743
930
  ```
744
931
 
745
- Rules are matched by path prefix, and the most specific matching rule applies.
746
- Manual rules are applied before generated manifest rules. Path rules are compiled
747
- and cached. If a running application mutates its rules in place, increment
748
- `AIWAF_ROUTE_PLAN_VERSION` (Flask/Django) or `route_plan_version` (FastAPI) so
749
- cached plans are rebuilt. Replacing the rules list with a new object recompiles
750
- it automatically.
751
-
752
- ### Blocking Behavior
753
-
754
- - Default behavior: blocked requests raise `PermissionDenied("blocked")` and return `403`.
755
- - For JSON APIs (Django): `JsonExceptionMiddleware` converts blocked JSON requests into JSON `403` payloads.
756
- - Rate limiting can emit `429` for soft throttling paths while still escalating repeated abuse to blacklist flow.
757
- - Reputation scores accumulate by reason (for example SQL injection, XSS, scanner, brute-force, rate-limit, honeypot, UUID, header, geo, and keyword events).
758
- - The default reputation threshold is 60. Qualifying blocks progress from 15 minutes to 1 hour and then 24 hours for repeated or high-score abuse.
759
- - Storage backends persist score, offenses, reason history, block/expiry timestamps, duration, permanence, and extended request details.
760
- - Passing a positive duration creates a temporary block; the runtime storage API treats a non-positive duration as an explicit permanent block.
932
+ The module provides:
761
933
 
762
- ### Rate Limiting Cache (Multi-worker)
763
-
764
- By default, Flask and FastAPI rate limiting uses an in-process cache (per worker). For multi-worker / multi-instance
765
- deployments, configure the rate limiter to use Redis so all workers share the same counters.
766
-
767
- **Flask**
934
+ - `validate_headers` and `validate_headers_with_config`
935
+ - `KeywordMatcher` and `RouteMatcher`
936
+ - request-record construction and six-feature extraction
937
+ - incremental feature extraction with explicit state
938
+ - recent-behavior analysis
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`
768
945
 
769
946
  ```python
770
- app.config["AIWAF_RATE_CACHE_BACKEND"] = "redis"
771
- app.config["AIWAF_REDIS_URL"] = "redis://localhost:6379/0"
772
- # Optional (defaults to "aiwaf:rate:")
773
- app.config["AIWAF_RATE_CACHE_KEY_PREFIX"] = "aiwaf:rate:"
774
- ```
775
-
776
- **FastAPI**
777
-
778
- ```python
779
- from aiwaf.fast import AIWAF
780
-
781
- AIWAF(
782
- app,
783
- rate_limiting={
784
- "enabled": True,
785
- "cache_backend": "redis",
786
- "redis_url": "redis://localhost:6379/0",
787
- "cache_key_prefix": "aiwaf:rate:", # optional
788
- },
947
+ import aiwaf_rust
948
+
949
+ reason = aiwaf_rust.validate_headers({
950
+ "HTTP_USER_AGENT": "Mozilla/5.0",
951
+ "HTTP_ACCEPT": "text/html",
952
+ })
953
+
954
+ forest = aiwaf_rust.IsolationForest(
955
+ n_estimators=100,
956
+ max_samples="auto",
957
+ contamination="auto",
958
+ max_features=1.0,
959
+ bootstrap=False,
960
+ random_state=42,
961
+ warm_start=False,
789
962
  )
963
+ forest.fit([[0.1, 1.0], [0.2, 1.1], [9.0, 9.0]])
964
+ score = forest.anomaly_score([9.0, 9.0])
965
+ state = forest.to_json()
966
+ restored = aiwaf_rust.IsolationForest.from_json(state)
790
967
  ```
791
968
 
792
- Environment variables (both adapters):
793
-
794
- ```bash
795
- set AIWAF_RATE_CACHE_BACKEND=redis
796
- set AIWAF_REDIS_URL=redis://localhost:6379/0
797
- set AIWAF_RATE_CACHE_KEY_PREFIX=aiwaf:rate:
798
- ```
799
-
800
- ### Logging and Training Data Sources
801
-
802
- AIWAF trainer can pull from:
803
-
804
- 1. `AIWAF_ACCESS_LOG` (primary, supports rotated/gzipped parsing where applicable)
805
- 2. middleware-captured logs (CSV/DB depending on adapter settings)
806
-
807
- This enables training even when reverse proxy logs are unavailable.
808
-
809
- ---
810
-
811
- ## Sandbox and Benchmarking
812
-
813
- The sandbox in `examples/sandbox/` provides:
814
-
815
- - `direct` (no AIWAF)
816
- - `protected_django`
817
- - `protected_flask`
818
- - `protected_fastapi`
819
-
820
- Run full benchmark:
969
+ For a local native build, stage the two canonical repository assets and run maturin:
821
970
 
822
971
  ```bash
823
- cd examples/sandbox
824
- python run-and-compare.py -n 5
972
+ cp README.md rust/README.md
973
+ cp LICENSE rust/LICENSE
974
+ cp NOTICE rust/NOTICE
975
+ cp -R licenses rust/
976
+ python -m pip install maturin
977
+ cd rust
978
+ maturin develop
825
979
  ```
826
980
 
827
- Generated outputs:
828
-
829
- - `results_direct_*.json`
830
- - `results_protected_django_*.json`
831
- - `results_protected_flask_*.json`
832
- - `comparison_modes_*.json`
833
- - `comparison_aggregate_*.json`
834
-
835
- Interpretation guidance:
981
+ The staged files are ignored by Git. Release automation performs the same staging before building wheels and the source distribution.
836
982
 
837
- - `direct` should show low/zero block rate for attacks (baseline)
838
- - protected targets should keep normal traffic blocking near `0%`
839
- - compare attack blocked% and median latency across iterations, not single-run averages
983
+ ## WebAssembly package
840
984
 
841
- ---
985
+ `aiwaf-wasm` exposes the shared Rust core to browsers and Node-compatible bundlers.
842
986
 
843
- ## Publish Checklist
987
+ ```javascript
988
+ import init, {
989
+ IsolationForest,
990
+ KeywordMatcher,
991
+ RouteMatcher,
992
+ analyze_recent_behavior,
993
+ extract_features,
994
+ validate_headers,
995
+ } from 'aiwaf-wasm';
844
996
 
845
- Before publishing a new package version:
997
+ await init();
846
998
 
847
- 1. run the Python and JavaScript test suites
848
- 2. validate sandbox comparison (`run-and-compare.py -n 3` minimum)
849
- 3. bump the Python version in both `pyproject.toml` and `setup.py`, or the JavaScript version in `js/package.json`
850
- 4. build artifacts (`python -m build`)
851
- 5. smoke-test wheel install in clean virtualenv
852
- 6. verify the README and package metadata match actual behavior
853
-
854
- ---
855
-
856
- ## Reset and Recovery
857
-
858
- Granular reset (Django adapter):
999
+ const reason = validate_headers({
1000
+ 'user-agent': 'Mozilla/5.0',
1001
+ accept: 'text/html'
1002
+ });
859
1003
 
860
- ```bash
861
- python manage.py aiwaf_reset --blacklist
862
- python manage.py aiwaf_reset --keywords
863
- python manage.py aiwaf_reset --exemptions
864
- python manage.py aiwaf_reset --blacklist --keywords
865
- python manage.py aiwaf_reset --confirm
1004
+ const forest = new IsolationForest({
1005
+ n_estimators: 100,
1006
+ max_samples: 'auto',
1007
+ contamination: 'auto',
1008
+ random_state: 42
1009
+ });
1010
+ forest.fit([[0.1, 1.0], [0.2, 1.1], [9.0, 9.0]]);
1011
+ const score = forest.anomaly_score([9.0, 9.0]);
866
1012
  ```
867
1013
 
868
- Common recovery path for false positives:
869
- 1. clear learned keywords
870
- 2. add legitimate route terms to `AIWAF_ALLOWED_PATH_KEYWORDS`
871
- 3. add never-block terms to `AIWAF_EXEMPT_KEYWORDS`
872
- 4. retrain
873
-
874
- ---
875
-
876
- ## Troubleshooting
1014
+ The WASM API includes header, URL, and content validation; keyword and route matchers; record conversion; batched feature extraction; recent-behavior analysis; and Isolation Forest lifecycle methods. Browser use requires a bundler that understands WebAssembly assets.
877
1015
 
878
- ### Legitimate pages blocked
879
-
880
- Cause:
881
- - learned keywords included legitimate app vocabulary
882
-
883
- Fix:
1016
+ Build and test it locally:
884
1017
 
885
1018
  ```bash
886
- python manage.py aiwaf_reset --keywords --confirm
887
- python manage.py detect_and_train
888
- ```
889
-
890
- Then tune:
891
- - `AIWAF_ALLOWED_PATH_KEYWORDS`
892
- - `AIWAF_EXEMPT_KEYWORDS`
893
-
894
- ### AI model not training
895
-
896
- - verify log path and permissions
897
- - check volume vs `AIWAF_MIN_AI_LOGS` / `AIWAF_MIN_TRAIN_LOGS`
898
- - use `AIWAF_FORCE_AI_TRAINING=True` only when appropriate
899
- - install `aiwaf-rust` for persisted runtime ML inference and JSON model artifacts
900
-
901
- ### Geo-blocking not active
902
-
903
- - verify `AIWAF_GEO_BLOCK_ENABLED=True`
904
- - verify `AIWAF_GEOIP_DB_PATH`
905
- - confirm geo middleware is enabled in your adapter chain
906
-
907
- ### Rust mode appears inactive
908
-
909
- - verify environment can import Rust extension
910
- - fallback to Python is expected on Rust import/runtime failure
911
-
912
- ---
913
-
914
- ## How It Works
915
-
916
- | Layer | Purpose |
917
- |---|---|
918
- | Geo blocking | Country-level allow/block filtering |
919
- | IP/keyword block | Known-bad source and keyword defense |
920
- | Rate limiting | Burst/flood control in sliding windows |
921
- | AI anomaly | ML-based behavior outlier detection |
922
- | Honeypot timing | Automation/timing/method misuse checks |
923
- | UUID tamper | Score-based malformed UUID + repeated UUID-404 abuse detection |
924
- | Header validation | Bot-like header profile detection |
925
- | Request logger | Optional telemetry capture for analysis/training |
926
-
927
- ---
928
-
929
- ## Request Lifecycle (Detailed)
930
-
931
- For a typical protected request:
932
-
933
- 1. Request enters adapter middleware chain.
934
- 2. Path/view/IP exemption checks run first.
935
- 3. Header validation evaluates required headers and quality score.
936
- 4. IP/keyword checks apply static + learned rules.
937
- 5. Rate limit checks apply window/flood logic.
938
- 6. Geo checks apply country allow/block rules (if enabled).
939
- 7. AI anomaly evaluates extracted behavior features (if enabled and model available).
940
- 8. Honeypot timing/method checks evaluate form timing and method misuse.
941
- 9. UUID tamper checks validate UUID format and apply score-based repeated-miss detection.
942
- 10. Optional logger records request/response metadata.
943
-
944
- If any blocking stage denies request:
945
- - status is typically `403` (`PermissionDenied("blocked")`)
946
- - JSON APIs can receive JSON-formatted `403` via JSON exception middleware
947
- - some throttle paths may return `429`
948
-
949
- ---
950
-
951
- ## Middleware Notes
952
-
953
- `IPAndKeywordBlockMiddleware`:
954
- - blocks already-blacklisted IPs quickly
955
- - checks static suspicious keywords and learned dynamic keywords
956
- - supports exempt keywords and allowed-path keyword logic
957
-
958
- `RateLimitMiddleware`:
959
- - enforces short-window max request budgets
960
- - can blacklist persistent flooders
961
- - supports path rule overrides
962
-
963
- `GeoBlockMiddleware`:
964
- - resolves country from source IP via MMDB
965
- - supports block-list mode and optional allow-list mode
966
- - can cache lookups for performance
967
-
968
- `AIAnomalyMiddleware`:
969
- - uses a persisted JSON model when available, otherwise falls back to heuristic/keyword anomaly behavior
970
- - gracefully disables itself when model/deps are unavailable
971
- - persisted ML inference requires the Rust JSON model backend; scikit-learn is training-time only and `model.pkl` is not supported
972
-
973
- `HoneypotTimingMiddleware`:
974
- - enforces minimum submit timing
975
- - enforces max page age semantics where enabled
976
- - includes method misuse detection logic
977
-
978
- `UUIDTamperMiddleware`:
979
- - guards UUID access patterns
980
- - usually no-op where no UUID model rules apply
981
-
982
- `HeaderValidationMiddleware`:
983
- - checks required headers by method
984
- - scores request realism and can block low-quality profiles
985
- - commonly tuned for API/webhook/socket endpoints via `PATH_RULES`
986
-
987
- ---
988
-
989
- ## Advanced Configuration Matrix
990
-
991
- Traffic controls:
992
-
993
- ```python
994
- AIWAF_RATE_WINDOW = 10
995
- AIWAF_RATE_MAX = 20
996
- AIWAF_RATE_FLOOD = 10
997
- AIWAF_WINDOW_SECONDS = 60
1019
+ cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core
1020
+ cd rust/crates/aiwaf_wasm
1021
+ wasm-pack test --node
1022
+ wasm-pack build --release --target bundler
1023
+ cd ../..
1024
+ python scripts/patch_wasm_pkg.py
1025
+ cp ../LICENSE crates/aiwaf_wasm/pkg/LICENSE
1026
+ cp ../NOTICE crates/aiwaf_wasm/pkg/NOTICE
1027
+ cp -R ../licenses crates/aiwaf_wasm/pkg/
1028
+ ```
1029
+
1030
+ ## Java package
1031
+
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.
1033
+
1034
+ ### Core engine
1035
+
1036
+ Use the two-stage API when the integration can observe the handler response. Deterministic controls run before the application; anomaly scoring then receives the actual status and elapsed time.
1037
+
1038
+ ```java
1039
+ import com.aiwaf.core.AiwafConfig;
1040
+ import com.aiwaf.core.AiwafDecision;
1041
+ import com.aiwaf.core.AiwafEngine;
1042
+ import com.aiwaf.core.AiwafRequest;
1043
+
1044
+ import java.util.Map;
1045
+ import java.util.Set;
1046
+
1047
+ AiwafConfig config = new AiwafConfig();
1048
+ config.rateLimitEnabled = true;
1049
+ config.rateLimitMax = 20;
1050
+ config.rateLimitWindowSeconds = 10;
1051
+
1052
+ AiwafEngine engine = new AiwafEngine(config);
1053
+ AiwafRequest request = new AiwafRequest(
1054
+ "GET",
1055
+ "/api/profile",
1056
+ "203.0.113.10",
1057
+ "US",
1058
+ Map.of("User-Agent", "Mozilla/5.0", "Accept", "application/json"),
1059
+ Map.of(),
1060
+ System.currentTimeMillis(),
1061
+ Set.of()
1062
+ );
1063
+
1064
+ long started = System.currentTimeMillis();
1065
+ AiwafDecision decision = engine.evaluateBeforeResponse(request);
1066
+ if (decision.allowed()) {
1067
+ decision = engine.evaluateAfterResponse(
1068
+ request,
1069
+ 200,
1070
+ System.currentTimeMillis() - started
1071
+ );
1072
+ }
998
1073
  ```
999
1074
 
1000
- Header validation:
1075
+ `evaluate(request)` remains available for request-only integrations and uses provisional response values for AI features.
1001
1076
 
1002
- ```python
1003
- AIWAF_REQUIRED_HEADERS = None
1004
- AIWAF_HEADER_QUALITY_MIN_SCORE = 3
1005
- AIWAF_MAX_ACCEPT_LENGTH = 4096
1006
- ```
1077
+ ### Spring MVC
1007
1078
 
1008
- AI/model behavior:
1079
+ Spring Boot applications are protected automatically. Adding `aiwaf-java` creates `AiwafConfig`, `AiwafEngine`, and the ordered `AiwafFilter`; discovers live MVC routes, route annotations, and JPA UUID fields; and applies request controls before the controller plus post-response scoring with the real status and timing. Set `aiwaf.enabled=false` to disable auto-configuration.
1009
1080
 
1010
- ```python
1011
- AIWAF_DISABLE_AI = False
1012
- AIWAF_MIN_AI_LOGS = 10000
1013
- AIWAF_MIN_TRAIN_LOGS = 50
1014
- AIWAF_FORCE_AI_TRAINING = False
1015
- AIWAF_AI_CONTAMINATION = 0.05
1081
+ ```properties
1082
+ aiwaf.rate-limit.max=60
1083
+ aiwaf.rate-limit.window-seconds=60
1084
+ aiwaf.geo.enabled=true
1085
+ aiwaf.geo.blocked-countries=CN,RU
1086
+ aiwaf.path-manifest.path=.aiwaf/paths.json
1087
+ # Use one namespace and shared enforcement state across application instances.
1088
+ aiwaf.storage.backend=redis
1089
+ aiwaf.storage.redis-url=redis://localhost:6379/0
1090
+ aiwaf.storage.key-prefix=my-service
1091
+ # Redis is fail-closed by default. Every wait is bounded.
1092
+ aiwaf.storage.redis-failure-mode=fail_closed
1093
+ aiwaf.storage.redis-connection-timeout-millis=1000
1094
+ aiwaf.storage.redis-socket-timeout-millis=2000
1095
+ aiwaf.storage.redis-pool-max-total=32
1096
+ aiwaf.storage.redis-pool-max-idle=16
1097
+ aiwaf.storage.redis-pool-min-idle=0
1098
+ aiwaf.storage.redis-pool-max-wait-millis=250
1016
1099
  ```
1017
1100
 
1018
- Model storage:
1101
+ Set `aiwaf.config-file=/etc/aiwaf/config.json` (or `AIWAF_CONFIG_FILE`) to load the same nested JSON configuration used by the Python runtime. Environment variables and Spring properties override file values. `AiwafConfigFileCore` also exposes load, save, deep-merge, and validation APIs for non-Spring applications.
1019
1102
 
1020
- ```python
1021
- AIWAF_MODEL_STORAGE = "file" # file | db | cache
1022
- AIWAF_MODEL_PATH = "aiwaf/resources/model.json"
1023
- AIWAF_MODEL_CACHE_KEY = "aiwaf:model"
1024
- AIWAF_MODEL_CACHE_TIMEOUT = None
1025
- AIWAF_MODEL_STORAGE_FALLBACK = True
1026
- ```
1103
+ Define an `AiwafConfig`, `AiwafEngine`, or `AiwafFilter` bean only when the application needs a custom replacement. For plain Spring MVC without Boot, register the filter directly; passing the application context enables the same live route discovery:
1027
1104
 
1028
- Do not point `AIWAF_MODEL_PATH` at `pickle`, `joblib`, or `skops` artifacts.
1029
- AIWAF loads JSON artifacts only. Fresh installs do not include `model.pkl`;
1030
- run training with Rust enabled to create `model.json`.
1031
-
1032
- Keyword and false-positive controls:
1033
-
1034
- ```python
1035
- AIWAF_ALLOWED_PATH_KEYWORDS = ["profile", "user", "dashboard"]
1036
- AIWAF_EXEMPT_KEYWORDS = ["api", "health", "static", "webhook"]
1037
- AIWAF_DYNAMIC_TOP_N = 10
1038
- ```
1039
-
1040
- Exemptions:
1041
-
1042
- ```python
1043
- AIWAF_EXEMPT_PATHS = ["/health/", "/static/", "/favicon.ico"]
1044
- AIWAF_EXEMPT_IPS = ["127.0.0.1", "::1"]
1105
+ ```java
1106
+ @Bean
1107
+ AiwafFilter aiwafFilter(AiwafEngine engine, ApplicationContext context) {
1108
+ return new AiwafFilter(engine, context);
1109
+ }
1045
1110
  ```
1046
1111
 
1047
- ---
1048
-
1049
- ## Tuning Playbooks
1050
-
1051
- Reduce false positives without globally weakening protection:
1052
- 1. reset learned keywords (`--keywords`)
1053
- 2. add legitimate domain terms to `AIWAF_ALLOWED_PATH_KEYWORDS`
1054
- 3. add operational terms to `AIWAF_EXEMPT_KEYWORDS`
1055
- 4. add route-level `PATH_RULES` for webhook/socket endpoints
1056
- 5. retrain and benchmark again
1057
-
1058
- Harden for sustained attack traffic:
1059
- 1. tune `AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`, `AIWAF_RATE_FLOOD`
1060
- 2. keep header validation enabled for public paths
1061
- 3. keep geo rules explicit and minimal
1062
- 4. enable middleware logging + regular retraining
1063
- 5. review block reasons before adding broad keyword rules
1064
-
1065
- Stabilize real-time paths:
1066
- 1. keep global protections enabled
1067
- 2. disable only strict checks on `/socket.io/` or equivalent via `PATH_RULES`
1068
- 3. keep blacklist logic for non-realtime paths
1069
- 4. whitelist trusted internal integration IPs when needed
1070
-
1071
- ---
1072
-
1073
- ## Rust Verification
1074
-
1075
- Runtime behavior:
1076
- - Rust extension available: selected paths use Rust acceleration
1077
- - Rust extension unavailable: automatic fallback to Python
1078
-
1079
- Verification checklist:
1080
- 1. verify `python -c "import aiwaf_rust"` succeeds
1081
- 2. confirm startup/runtime logs show Rust availability or fallback path
1082
- 3. benchmark with multiple iterations and compare medians (`run-and-compare.py -n 5`)
1083
-
1084
- ---
1085
-
1086
- ## Troubleshooting Decision Tree
1087
-
1088
- Blank page but `/` is `200`:
1089
- - inspect JS/CSS/API requests for `403`/`4xx`
1090
- - check whether client IP was blacklisted
1091
- - confirm `PATH_RULES` for socket/static/API paths
1092
-
1093
- Many `403` immediately after one blocked request:
1094
- - likely blacklist cascade
1095
- - clear blacklist and add targeted exemption/path rule
1096
- - avoid disabling all middleware globally
1097
-
1098
- AI anomaly not active:
1099
- - verify model is a JSON artifact
1100
- - verify AI deps are installed
1101
- - verify `AIWAF_DISABLE_AI=False`
1102
- - verify thresholds (`AIWAF_MIN_AI_LOGS`, `AIWAF_MIN_TRAIN_LOGS`)
1103
- - install `aiwaf-rust` if you need a persisted runtime ML model
1112
+ The live mapping integration honors `@AiwafExempt`, `@AiwafExemptFrom`, `@AiwafOnly`, and `@AiwafRequireProtection` without a controller list. Do not register `AiwafInterceptor` and `AiwafFilter` as independent enforcement layers for the same request.
1104
1113
 
1105
- Geo-blocking appears inactive:
1106
- - confirm middleware enabled
1107
- - confirm MMDB path valid
1108
- - confirm allow/block lists are configured as intended
1114
+ Committed, streaming, and asynchronous responses are recorded but are not replaced after bytes have been sent.
1109
1115
 
1110
- ---
1116
+ UUID protection uses Python-compatible weighted signals: malformed input, valid UUID requests that resolve to `404`, and successful requests that decay the score. UUID-valued query parameters and `{uuid}` route variables are supported. `SpringUuidModelLookup` optionally discovers UUID primary keys and unique UUID properties through the JPA metamodel; omit it when the application does not use JPA.
1111
1117
 
1112
- ## Deployment Patterns
1113
-
1114
- ### Reverse Proxy + App Server
1115
-
1116
- Typical production path:
1117
- 1. internet -> CDN/WAF edge (optional)
1118
- 2. reverse proxy (Nginx/Traefik/Caddy)
1119
- 3. application server (Django/Flask with AIWAF middleware)
1120
- 4. app database/cache + model/log storage
1121
-
1122
- Recommended:
1123
- - preserve client IP forwarding correctly (`X-Forwarded-For`)
1124
- - keep clock synchronization (NTP) for reliable log timing features
1125
- - rotate logs and enforce retention limits
1126
- - run periodic retraining as a scheduled job
1127
-
1128
- ### Multi-Instance Deployments
1129
-
1130
- When running multiple app instances:
1131
- - prefer shared storage mode for model artifacts (`db` or centralized cache)
1132
- - ensure blacklist/exemption updates propagate consistently
1133
- - avoid host-local-only model paths if instances autoscale
1134
-
1135
- ### Blue/Green or Rolling Updates
1136
-
1137
- For safer rollout:
1138
- 1. deploy with conservative thresholds
1139
- 2. verify block metrics and false-positive ratio
1140
- 3. gradually tighten controls
1141
- 4. promote only after stable benchmark + production canary behavior
1142
-
1143
- ---
1144
-
1145
- ## Observability and KPIs
1146
-
1147
- Track these indicators per adapter:
1148
-
1149
- - **Normal traffic block rate**: target near `0%`
1150
- - **Attack traffic block rate**: target high and stable under replay suite
1151
- - **P95/P99 response latency**: compare before/after tuning
1152
- - **Blacklist churn**: sudden spikes may indicate noisy rules
1153
- - **Top block reasons**: helps tune headers/keywords/rate limits
1154
- - **Retraining success/failure counts**: detect model pipeline regressions
1155
-
1156
- Minimum dashboard slices:
1157
- - by endpoint family (`/api`, `/socket.io`, static assets)
1158
- - by source ASN/country (if geo enabled)
1159
- - by middleware reason code
1160
- - by deployment version
1161
-
1162
- ---
1163
-
1164
- ## Security Boundaries and Caveats
1165
-
1166
- AIWAF improves application-layer protection but is not a complete security boundary.
1167
-
1168
- Important caveats:
1169
- - does not replace secure coding, authz, secrets management, patching, or network controls
1170
- - ML anomaly detection is probabilistic and can drift with traffic profile changes
1171
- - aggressive keyword/rate settings can cause self-inflicted outages if not staged
1172
- - websocket/realtime paths often require explicit path-rule tuning
1173
- - allowlists/exemptions should be tightly scoped and periodically reviewed
1174
-
1175
- ---
1176
-
1177
- ## Contributor Test Strategy
1178
-
1179
- Recommended local validation flow for changes:
1180
-
1181
- 1. unit and adapter tests
1182
- 2. sandbox startup validation (direct + protected targets)
1183
- 3. replay benchmark with multiple iterations
1184
- 4. review aggregate detection and latency medians
1185
- 5. inspect a sample of blocked and allowed requests for regressions
1186
-
1187
- Suggested benchmark command:
1118
+ Generate a route manifest from the live Spring application rather than supplying controller methods manually:
1188
1119
 
1189
1120
  ```bash
1190
- cd examples/sandbox
1191
- python run-and-compare.py -n 5
1121
+ java -cp "your-app.jar:aiwaf-java-1.3.3.jar" \
1122
+ com.aiwaf.cli.AiwafConsole init \
1123
+ --app com.example.Application \
1124
+ --output .aiwaf/paths.json
1192
1125
  ```
1193
1126
 
1194
- Regression gates (example policy):
1195
- - no increase in normal-traffic blocking
1196
- - no meaningful drop in attack blocked%
1197
- - no unexplained latency regressions beyond agreed budget
1127
+ The command starts the application, reads every registered `RequestMappingHandlerMapping`, writes the shared `schema_version/framework/context_hash/routes` document, and then closes the temporary application context. At runtime, `AiwafEngine` loads this file automatically and appends its disabled middleware and rate-limit overrides after explicit `pathRules`, so explicit equal-prefix rules retain precedence. Set `pathManifestEnabled=false` or `aiwaf.path-manifest.enabled=false` to opt out.
1198
1128
 
1199
- ---
1129
+ ### Jakarta Servlet
1200
1130
 
1201
- ## FAQ
1131
+ ```java
1132
+ AiwafConfig config = new AiwafConfig();
1133
+ AiwafEngine engine = new AiwafEngine(config);
1202
1134
 
1203
- **Why do I see `403` on `curl` but browser works?**
1204
- Header validation can classify low-quality client headers as automated traffic.
1135
+ servletContext
1136
+ .addFilter("aiwaf", new AiwafServletFilter(engine))
1137
+ .addMappingForUrlPatterns(null, false, "/*");
1138
+ ```
1205
1139
 
1206
- **Why did everything start returning `403` suddenly?**
1207
- Likely blacklist cascade after an initial block event; clear blacklist and add targeted path/IP tuning.
1140
+ The generic servlet filter uses request-time evaluation. Spring applications should prefer `AiwafFilter` for handler metadata and post-response scoring.
1208
1141
 
1209
- **Can I disable one middleware for a single route?**
1210
- Yes, use `AIWAF_SETTINGS["PATH_RULES"]` with `DISABLE` for that prefix.
1142
+ ### Java configuration and models
1211
1143
 
1212
- **Does Rust mode change detection outcomes?**
1213
- It should preserve behavior while improving some execution paths; verify with A/B multi-iteration benchmarks.
1144
+ | Area | Main `AiwafConfig` fields |
1145
+ | --- | --- |
1146
+ | Rate limiting | `rateLimitEnabled`, `rateLimitScope`, `rateLimitWindowSeconds`, `rateLimitMax`, `rateLimitFloodThreshold` |
1147
+ | Headers | `headerValidationEnabled`, `requiredHeadersByMethod`, `minHeaderQualityScore`, size/count limits |
1148
+ | Request | body, parameter, method, and content-type limits |
1149
+ | Proxies | `trustedProxyCidrs`, `maxForwardedForEntries` |
1150
+ | Exemptions | `exemptIps`, `exemptPaths`, `autoExemptPathPrefixes` |
1151
+ | GeoIP | `geoBlockEnabled`, `geoAllowedCountries`, `geoBlockedCountries`, `geoIpDatabasePath`, cache limits |
1152
+ | Route manifest | `pathManifestEnabled`, `pathManifestPath`, `pathRules` |
1153
+ | UUID checks | `uuidTamperEnabled`, `uuidScoreWindowSeconds`, `uuidScoreBlockThreshold`, signal weights, `uuidParameterNames` |
1154
+ | AI | `aiEnabled`, `aiModelPath`, `aiAnomalyScoreThreshold` |
1155
+ | Storage | `storageBackend`, `storageFilePath`, `storageRedisUrl`, `storageKeyPrefix`, `storageRedisFailureMode`, Redis timeout and pool limits |
1156
+ | Telemetry | `observabilityEnabled` |
1214
1157
 
1215
- **Why is model persistence JSON-only?**
1216
- AIWAF is security middleware, so it avoids Python object deserialization formats
1217
- such as `pickle`, `joblib`, and `skops`. Persisted AI models should use the Rust
1218
- `IsolationForest` JSON state path. Legacy `model.pkl` files are not loaded and
1219
- are no longer bundled.
1158
+ GeoIP uses the bundled MMDB through the native Java reader; it does not require the external `mmdblookup` executable. A valid `X-Country` value is accepted only from a peer in `trustedProxyCidrs`; otherwise AIWAF resolves the client address itself. Default blacklist calls use Python-compatible reputation scoring and temporary escalation (15 minutes, 1 hour, then 24 hours). Use `BlacklistManager.blockPermanent(ip, reason)` for an explicit permanent administrative block.
1220
1159
 
1221
- **Do I need Django to use AIWAF?**
1222
- No. Core supports both Django and Flask adapters, but some operational commands are Django-specific.
1160
+ `storageBackend="redis"` makes rate-limit buckets, honeypot timing, weighted UUID scores, recent-request anomaly state, blacklist data, exemptions, geo policy, and learned keywords visible to every application instance using the same key prefix. Redis enforcement updates use atomic server-side scripts. Memory, file, CSV, and SQLite engines keep request state isolated per `AiwafEngine`; constructing another engine no longer replaces an existing engine's stores. The static `RuntimeStorage` and `BlacklistManager` methods remain compatibility facades for command-line and administrative code.
1223
1161
 
1224
- ---
1162
+ The Java 1.3 Redis backend supports **standalone Redis only**. Sentinel and Cluster configurations are rejected during validation instead of silently operating with incomplete semantics. `fail_closed` is the default: an unavailable Redis instance prevents startup or raises a request-path storage failure, which results in the application denying availability rather than bypassing protection. `fail_open` permits startup and returns non-blocking enforcement fallbacks while Redis is unavailable; failed mutations return `false` at the `StorageBackend` boundary. Connection, socket, pool size, and pool wait limits are bounded and configurable. `RedisStorage.diagnostics()` reports operation/failure counts, latency, and live pool utilization.
1225
1163
 
1226
- ## CLI Entry Point
1164
+ Redis keys include a state-schema version, and each base key prefix has an atomic compatibility marker. Releases using the same schema can share state during a rolling upgrade. A runtime with an incompatible schema refuses the namespace—even in `fail_open` mode. Use a unique key prefix per application and environment; deploy an incompatible schema with a new prefix, migrate deliberately, then retire the old namespace. Serialized persistent values remain JSON within a schema version.
1227
1165
 
1228
- ```bash
1229
- aiwaf-detect
1230
- ```
1166
+ New Java models use the Python-aligned six-feature schema and are written as safe JSON containing the Python `aiwaf_rust.IsolationForest` state. Python can restore Java-generated forest state, and Java can load Python Rust-model artifacts. Existing signed Java binary artifacts, including nine-feature models, remain readable through the restricted legacy loader. Scikit-learn object artifacts are intentionally unsupported.
1231
1167
 
1232
- Current behavior:
1233
- - dispatches to Django trainer (`aiwaf.django.trainer.train`)
1234
- - requires Django adapter availability
1235
-
1236
- ---
1237
-
1238
- ## JavaScript Package (`aiwaf`)
1239
-
1240
- The JavaScript package lives in `js/`. Unless a command explicitly installs the
1241
- published package, run commands in this section after `cd js`.
1242
-
1243
- AIWAF-JS is a Node.js/Express Web Application Firewall that combines deterministic protections with anomaly detection and continuous learning. It ships as middleware, a CLI for ops workflows, and an offline trainer for IsolationForest models.
1244
- Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fastify wrappers), Next.js (API route wrapper), AdonisJS, and Sails.js.
1245
-
1246
- ### What It Does
1247
-
1248
- - Blocks known bad traffic with static keyword rules and IP blacklisting
1249
- - Enforces rate limits with flood detection
1250
- - Detects bot-like form abuse using honeypot field checks and timing gates
1251
- - Enforces optional method policies (405) and suspicious method usage
1252
- - Blocks suspicious UUID probing on route prefixes (with optional existence resolver)
1253
- - Learns high-frequency malicious segments as dynamic suspicious keywords
1254
- - Runs IsolationForest anomaly checks with recent-behavior analysis
1255
- - Supports Redis/custom cache backends with memory fallback
1256
- - Optional GeoIP blocking (MMDB) with allow/block lists and dynamic blocklist
1257
- - CSV fallback storage when DB is unavailable
1258
- - Operational CLI for blacklist, exemptions, geo, request logs, training and diagnostics
1259
-
1260
- ### Repository Layout
1261
-
1262
- - `index.js`: package entrypoint
1263
- - `lib/wafMiddleware.js`: main middleware orchestration
1264
- - `lib/rateLimiter.js`: rate-window and flood logic
1265
- - `lib/blacklistManager.js`: blocked IP persistence and operations
1266
- - `lib/keywordDetector.js`: static keyword checks
1267
- - `lib/dynamicKeyword.js`: in-memory dynamic keyword learning/checking
1268
- - `lib/uuidDetector.js`: UUID tamper detection
1269
- - `lib/honeypotDetector.js`: honeypot trap detection
1270
- - `lib/anomalyDetector.js`: pretrained model loading and anomaly scoring
1271
- - `lib/featureUtils.js`: request feature extraction and short-lived caching
1272
- - `lib/isolationForest.js`: IsolationForest implementation
1273
- - `lib/redisClient.js`: optional Redis client lifecycle
1274
- - `lib/headerValidation.js`: header caps, suspicious UA, and header quality scoring
1275
- - `lib/geoBlocker.js`: GeoIP allow/block checks + MMDB lookup + cache
1276
- - `lib/middlewareLogger.js`: JSONL/CSV/DB request logging
1277
- - `lib/*Store.js`: DB/CSV storage adapters (blacklist, exemptions, geo, logs, keywords, models)
1278
- - `train.js`: offline model training from access logs
1279
- - `resources/model.json`: pretrained anomaly model artifact
1280
- - `utils/db.js`: SQLite connection (memory DB in test)
1281
- - `test/`: Jest test suite
1282
-
1283
- ### Request Processing Flow
1284
-
1285
- 1. Initialize module options for rate limiter, keyword detectors, honeypot, UUID checks, and anomaly detector.
1286
- 2. Resolve client IP (`x-forwarded-for` first, then `req.ip`) and normalized path.
1287
- 3. Enforce optional method policy (405) if enabled.
1288
- 4. Block immediately if IP is already in blacklist.
1289
- 5. Header validation (required headers, suspicious UA, header caps, quality score).
1290
- 6. Geo checks (allow/block lists + DB-backed blocklist).
1291
- 7. Honeypot field + timing checks.
1292
- 8. Rate-limit + flood handling.
1293
- 9. Static keyword blocking.
1294
- 10. Dynamic keyword blocking.
1295
- 11. UUID tamper checks (optional existence resolver).
1296
- 12. Anomaly detection for unknown routes with recent-behavior analysis.
1297
- 13. Request logging (JSONL/CSV/DB) and optional dynamic keyword learning on 404s.
1298
- 14. Allow request through `next()` when no rule triggers.
1299
-
1300
- ### Installation
1168
+ Java operational commands mirror the common Python workflow:
1301
1169
 
1302
1170
  ```bash
1303
- npm install aiwaf
1171
+ aiwaf-cli status
1172
+ aiwaf-cli diagnose --model model.json
1173
+ aiwaf-cli blocked
1174
+ aiwaf-cli unblock 203.0.113.10
1175
+ aiwaf-cli clear
1176
+ aiwaf-cli train --events events.json --out model.json --backend java
1177
+ aiwaf-cli replay --cases replay.json
1178
+ aiwaf-cli model status --path model.json
1179
+ aiwaf-cli logs --dir aiwaf_logs
1304
1180
  ```
1305
1181
 
1306
- #### Optional WASM Acceleration
1307
-
1308
- AIWAF can use the `aiwaf-wasm` optional dependency for faster IsolationForest scoring and deterministic feature validation.
1309
- If the WASM module fails to load, it automatically falls back to the JS implementation.
1182
+ Build Java from the repository root:
1310
1183
 
1311
1184
  ```bash
1312
- npm install aiwaf-wasm
1185
+ cd java
1186
+ mvn test
1187
+ mvn -Dgpg.skip=true package
1313
1188
  ```
1314
1189
 
1315
- ### Quick Start
1316
-
1317
- ```js
1318
- const express = require('express');
1319
- const aiwaf = require('aiwaf');
1190
+ The build produces the main, source, and Javadoc JARs under `java/target/`. The main JAR embeds the root license as `META-INF/LICENSE`. FastR training is optional and falls back to the Java trainer when R or `jsonlite` is unavailable.
1320
1191
 
1321
- const app = express();
1322
- app.use(express.json());
1192
+ ## Shared training schema
1323
1193
 
1324
- app.use(aiwaf({
1325
- staticKeywords: ['.php', '.env', '.git'],
1326
- dynamicTopN: 10,
1327
- WINDOW_SEC: 10,
1328
- MAX_REQ: 20,
1329
- FLOOD_REQ: 40,
1330
- HONEYPOT_FIELD: 'hp_field',
1331
- uuidRoutePrefix: '/user',
1332
- AIWAF_HEADER_VALIDATION: true,
1333
- AIWAF_METHOD_POLICY_ENABLED: true,
1334
- AIWAF_ALLOWED_METHODS: ['GET', 'POST', 'HEAD', 'OPTIONS']
1335
- }));
1194
+ New training paths use these six features in this order:
1336
1195
 
1337
- app.get('/', (req, res) => res.send('Protected'));
1338
- app.listen(3000);
1339
- ```
1196
+ 1. `path_len`
1197
+ 2. `kw_hits`
1198
+ 3. `resp_time`
1199
+ 4. `status_idx`
1200
+ 5. `burst_count`
1201
+ 6. `total_404`
1340
1202
 
1341
- ### Path Rules and Auto Middleware
1203
+ `resp_time` is expressed in seconds in feature vectors. Artifact summary fields explicitly named with `_ms` remain milliseconds.
1342
1204
 
1343
- Use path rules to disable selected AIWAF checks or override rate limits for a route prefix:
1205
+ The training lifecycle is:
1344
1206
 
1345
- ```js
1346
- app.use(aiwaf({
1347
- AIWAF_PATH_RULES: [
1348
- { PREFIX: '/health/', DISABLE: ['header_validation', 'rate_limit'] },
1349
- { PREFIX: '/api/public/', RATE_LIMIT: { WINDOW: 60, MAX: 300 } }
1350
- ]
1351
- }));
1352
- ```
1207
+ 1. Parse configured access logs or middleware-generated request logs.
1208
+ 2. Normalize request paths, status, timing, and per-IP state.
1209
+ 3. Extract the six features and suspicious route segments.
1210
+ 4. Train or update the Isolation Forest after configured volume thresholds are met.
1211
+ 5. Refresh learned keywords while excluding known legitimate and exempt routes.
1212
+ 6. Persist portable JSON forest state and runtime metadata; legacy language-specific artifacts remain read-only compatibility inputs.
1353
1213
 
1354
- `DISABLE` accepts canonical names such as `ip_keyword_block`, `rate_limit`, `honeypot`, `header_validation`, `geo_block`, `ai_anomaly`, `uuid_tamper`, and `logging`. Class-style names like `HeaderValidationMiddleware` are also accepted.
1214
+ Do not train directly on unreviewed sensitive request bodies or authentication headers. Treat models, logs, exported state, and MMDB files as deployment artifacts with controlled access.
1355
1215
 
1356
- AIWAF can also read a generated route manifest from `.aiwaf/paths.json` and compile route protections into path rules. For Express apps, generate one after routes are registered. Route extraction uses a Babel-backed JavaScript AST parser, with a conservative string heuristic fallback, to infer API/form/auth signals from handlers:
1216
+ ## Deployment guidance
1357
1217
 
1358
- ```js
1359
- const manifest = aiwaf.generateExpressManifest(app, '.aiwaf/paths.json');
1360
- ```
1218
+ - Configure the application to trust forwarding headers only from known proxy CIDRs.
1219
+ - Configure the outermost proxy to overwrite client-supplied forwarding headers.
1220
+ - Use Redis, a database, or another shared backend when multiple workers must share rate-limit, blacklist, or exemption state.
1221
+ - Keep health checks, static assets, and trusted webhook routes explicitly scoped instead of disabling protection globally.
1222
+ - Start anomaly detection in observe-only or conservative mode and tune it with representative normal traffic.
1223
+ - Rotate logs and exclude secrets, authorization headers, cookies, and personal data.
1224
+ - Sign model/configuration artifacts where the runtime supports HMAC verification.
1225
+ - Run AIWAF alongside normal secure-development controls and an edge/reverse-proxy layer.
1361
1226
 
1362
- Other frameworks can use `generateFrameworkManifest(framework, app, output, { routes })`. Express/Sails can be introspected from the app, Hapi can be introspected from `server.table()`, and Fastify/Koa/Next/Nest can also accept explicit route lists:
1227
+ ## Development and tests
1363
1228
 
1364
- ```js
1365
- aiwaf.generateFrameworkManifest('fastify', null, '.aiwaf/paths.json', {
1366
- routes: [
1367
- { method: 'GET', path: '/api/users', handler: usersHandler },
1368
- { method: 'POST', path: '/contact', handler: contactHandler }
1369
- ]
1370
- });
1371
- ```
1229
+ ### Whole monorepo
1372
1230
 
1373
- The CLI can generate a manifest from a JSON route list:
1231
+ Create a Python environment, install all adapters, then install Node dependencies:
1374
1232
 
1375
1233
  ```bash
1376
- npm run aiwaf -- manifest --framework express --routes routes.json --output .aiwaf/paths.json
1234
+ python -m pip install -e ".[django,flask,fastapi,rust]"
1235
+ python -m pip install pytest pytest-cov coverage httpx
1236
+ npm ci --prefix js
1237
+ python aiwaf_test.py --coverage
1377
1238
  ```
1378
1239
 
1379
- The Rust/WASM helper surface is available under `aiwaf.wasm` for advanced integrations:
1380
-
1381
- ```js
1382
- const aiwaf = require('aiwaf');
1383
-
1384
- const model = await aiwaf.wasm.createIsolationForest({ nTrees: 100 });
1385
- const features = await aiwaf.wasm.extractWasmFeatures(records, ['.php', '.env']);
1386
- const recent = await aiwaf.wasm.analyzeRecentBehavior(entries, ['.php']);
1387
- ```
1388
-
1389
- Python-parity helper modules are exposed for advanced integrations:
1390
-
1391
- ```js
1392
- aiwaf.runtimeUtils.isStaticFile('/assets/app.css');
1393
- aiwaf.trainingLogic.isScanningPath('/wp-admin/install.php');
1394
- aiwaf.geoPolicy.evaluateGeoPolicy({ country: 'US', allowCountries: ['US'] });
1395
- aiwaf.blockResponses.blockedPayload('blocked by AIWAF');
1396
- ```
1397
-
1398
- Use `auto`/`all` middleware selection to enable the canonical protection set while skipping middleware that is not useful for the current app signals:
1399
-
1400
- ```js
1401
- app.use(aiwaf.auto({
1402
- AIWAF_DISABLE_MIDDLEWARES: ['geo_block']
1403
- }));
1404
- // Equivalent:
1405
- app.use(aiwaf({ AIWAF_MIDDLEWARES: ['auto'] }));
1406
- ```
1407
-
1408
- ### Fastify Usage
1409
-
1410
- ```js
1411
- const fastify = require('fastify')({ logger: true });
1412
- const aiwaf = require('aiwaf');
1413
-
1414
- fastify.register(aiwaf.fastify, {
1415
- staticKeywords: ['.php', '.env', '.git'],
1416
- dynamicTopN: 10,
1417
- WINDOW_SEC: 10,
1418
- MAX_REQ: 20,
1419
- FLOOD_REQ: 40,
1420
- HONEYPOT_FIELD: 'hp_field'
1421
- });
1422
-
1423
- fastify.get('/', async () => 'Protected');
1424
- fastify.listen({ port: 3000 });
1425
- ```
1426
-
1427
- ### Hapi Usage
1428
-
1429
- ```js
1430
- const Hapi = require('@hapi/hapi');
1431
- const aiwaf = require('aiwaf');
1432
-
1433
- const server = Hapi.server({ port: 3000 });
1434
- await server.register({
1435
- plugin: aiwaf.hapi,
1436
- options: {
1437
- staticKeywords: ['.php', '.env', '.git'],
1438
- dynamicTopN: 10,
1439
- WINDOW_SEC: 10,
1440
- MAX_REQ: 20,
1441
- FLOOD_REQ: 40,
1442
- HONEYPOT_FIELD: 'hp_field'
1443
- }
1444
- });
1445
-
1446
- server.route({ method: 'GET', path: '/', handler: () => 'Protected' });
1447
- await server.start();
1448
- ```
1449
-
1450
- ### Koa Usage
1451
-
1452
- ```js
1453
- const Koa = require('koa');
1454
- const bodyParser = require('koa-bodyparser');
1455
- const aiwaf = require('aiwaf');
1456
-
1457
- const app = new Koa();
1458
- app.use(bodyParser());
1240
+ Focused suites:
1459
1241
 
1460
- app.use(aiwaf.koa({
1461
- staticKeywords: ['.php', '.env', '.git'],
1462
- dynamicTopN: 10,
1463
- WINDOW_SEC: 10,
1464
- MAX_REQ: 20,
1465
- FLOOD_REQ: 40,
1466
- HONEYPOT_FIELD: 'hp_field'
1467
- }));
1468
-
1469
- app.use(ctx => {
1470
- ctx.body = 'Protected';
1471
- });
1472
-
1473
- app.listen(3000);
1474
- ```
1475
-
1476
- ### NestJS (Express) Usage
1477
-
1478
- ```ts
1479
- import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
1480
- import aiwaf from 'aiwaf';
1481
-
1482
- @Module({})
1483
- export class AppModule implements NestModule {
1484
- configure(consumer: MiddlewareConsumer) {
1485
- consumer
1486
- .apply(aiwaf.nest({
1487
- staticKeywords: ['.php', '.env', '.git'],
1488
- dynamicTopN: 10,
1489
- WINDOW_SEC: 10,
1490
- MAX_REQ: 20,
1491
- FLOOD_REQ: 40,
1492
- HONEYPOT_FIELD: 'hp_field'
1493
- }))
1494
- .forRoutes('*');
1495
- }
1496
- }
1242
+ ```bash
1243
+ python aiwaf_test.py --python-only
1244
+ python aiwaf_test.py --rust-only
1245
+ python aiwaf_test.py --js-only
1246
+ python aiwaf_test.py --wasm-only
1497
1247
  ```
1498
1248
 
1499
- If you need to guarantee ordering before other middleware/proxies, you can also attach the Express middleware directly in `main.ts`:
1500
-
1501
- ```ts
1502
- import { NestFactory } from '@nestjs/core';
1503
- import aiwaf from 'aiwaf';
1504
- import { AppModule } from './app.module';
1505
-
1506
- async function bootstrap() {
1507
- const app = await NestFactory.create(AppModule);
1508
- app.use(aiwaf({
1509
- staticKeywords: ['.php', '.env', '.git'],
1510
- dynamicTopN: 10,
1511
- WINDOW_SEC: 10,
1512
- MAX_REQ: 20,
1513
- FLOOD_REQ: 40,
1514
- HONEYPOT_FIELD: 'hp_field'
1515
- }));
1516
- await app.listen(3000);
1517
- }
1518
- bootstrap();
1519
- ```
1249
+ Java is tested separately:
1520
1250
 
1521
- ### NestJS (Fastify) Usage
1522
-
1523
- Use the Fastify plugin when running Nest with `FastifyAdapter`:
1524
-
1525
- ```ts
1526
- import { NestFactory } from '@nestjs/core';
1527
- import { FastifyAdapter } from '@nestjs/platform-fastify';
1528
- import aiwaf from 'aiwaf';
1529
- import { AppModule } from './app.module';
1530
-
1531
- async function bootstrap() {
1532
- const app = await NestFactory.create(AppModule, new FastifyAdapter());
1533
- await app.register(aiwaf.fastify, {
1534
- staticKeywords: ['.php', '.env', '.git'],
1535
- dynamicTopN: 10,
1536
- WINDOW_SEC: 10,
1537
- MAX_REQ: 20,
1538
- FLOOD_REQ: 40,
1539
- HONEYPOT_FIELD: 'hp_field'
1540
- });
1541
- await app.listen(3000, '0.0.0.0');
1542
- }
1543
- bootstrap();
1251
+ ```bash
1252
+ cd java
1253
+ mvn test
1544
1254
  ```
1545
1255
 
1546
- ### Next.js (API Routes) Usage
1547
-
1548
- Use the `aiwaf.next` helper to wrap a Next.js API route handler.
1549
-
1550
- ```ts
1551
- import aiwaf from 'aiwaf';
1552
-
1553
- function handler(req, res) {
1554
- res.status(200).json({ ok: true });
1555
- }
1256
+ ### Direct package commands
1556
1257
 
1557
- export default aiwaf.next(handler, {
1558
- staticKeywords: ['.php', '.env', '.git'],
1559
- dynamicTopN: 10,
1560
- WINDOW_SEC: 10,
1561
- MAX_REQ: 20,
1562
- FLOOD_REQ: 40,
1563
- HONEYPOT_FIELD: 'hp_field'
1564
- });
1565
- ```
1258
+ ```bash
1259
+ # Python
1260
+ pytest
1566
1261
 
1567
- ### AdonisJS Usage
1262
+ # Node.js
1263
+ npm ci --prefix js
1264
+ npm test --prefix js
1568
1265
 
1569
- Register the middleware in your Adonis middleware stack:
1266
+ # Rust core
1267
+ cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core
1570
1268
 
1571
- ```ts
1572
- import aiwaf from 'aiwaf';
1269
+ # Rust Python API, after installing the local wheel
1270
+ pytest -q rust/tests/test_python_api.py
1573
1271
 
1574
- export const middleware = [
1575
- () => aiwaf.adonis({
1576
- staticKeywords: ['.php', '.env', '.git'],
1577
- dynamicTopN: 10,
1578
- WINDOW_SEC: 10,
1579
- MAX_REQ: 20,
1580
- FLOOD_REQ: 40,
1581
- HONEYPOT_FIELD: 'hp_field'
1582
- })
1583
- ];
1272
+ # Java
1273
+ mvn -f java/pom.xml test
1584
1274
  ```
1585
1275
 
1586
- ### Sails.js Usage
1276
+ ### Benchmark
1587
1277
 
1588
- Use the Express-compatible middleware in your Sails `config/http.js`:
1589
-
1590
- ```js
1591
- const aiwaf = require('aiwaf');
1592
-
1593
- module.exports.http = {
1594
- middleware: {
1595
- aiwaf: aiwaf.sails({
1596
- staticKeywords: ['.php', '.env', '.git'],
1597
- dynamicTopN: 10,
1598
- WINDOW_SEC: 10,
1599
- MAX_REQ: 20,
1600
- FLOOD_REQ: 40,
1601
- HONEYPOT_FIELD: 'hp_field'
1602
- })
1603
- }
1604
- };
1605
- ```
1606
-
1607
- ### Configuration
1608
-
1609
- #### Core Controls
1610
-
1611
- | Option | Default | Description |
1612
- |---|---|---|
1613
- | `staticKeywords` | `[]` | Substrings that trigger immediate block + blacklist |
1614
- | `dynamicTopN` or `DYNAMIC_TOP_N` | `10` | Frequency threshold for dynamic segment blocking |
1615
- | `WINDOW_SEC` | `60` | Time window for rate limiting |
1616
- | `MAX_REQ` | `100` | Max allowed requests in window before rate block |
1617
- | `FLOOD_REQ` | `200` | Hard threshold that blacklists IP |
1618
- | `HONEYPOT_FIELD` | `undefined` | Body field name used as bot trap |
1619
- | `uuidRoutePrefix` | `"/user"` | Path prefix monitored for UUID tamper attempts |
1620
- | `uuidResolver` | `undefined` | Optional async resolver `(uuid, req) => boolean` for existence checks |
1621
- | `cache` | fallback memory cache | Custom cache backend used by limiter/features |
1622
- | `nTrees` | `100` | IsolationForest trees when model is initialized in-process |
1623
- | `sampleSize` | `256` | IsolationForest sample size |
1624
- | `AIWAF_WASM_VALIDATION` | `true` | Enable WASM validation when available (headers, URL, content, recent) |
1625
- | `AIWAF_WASM_VALIDATE_RECENT` | `false` | Run WASM recent-behavior validation on recent request logs |
1626
-
1627
- #### Header Validation
1628
-
1629
- | Option | Default | Description |
1630
- |---|---|---|
1631
- | `AIWAF_HEADER_VALIDATION` | `false` | Enable header validation pipeline |
1632
- | `AIWAF_REQUIRED_HEADERS` | `[]` | Required headers array, or `{ DEFAULT, GET, POST }` mapping |
1633
- | `AIWAF_HEADER_QUALITY_MIN_SCORE` | `3` | Minimum header quality score |
1634
- | `AIWAF_MAX_HEADER_BYTES` | `32768` | Max header bytes before blocking |
1635
- | `AIWAF_MAX_HEADER_COUNT` | `100` | Max header count before blocking |
1636
- | `AIWAF_MAX_USER_AGENT_LENGTH` | `500` | Max User-Agent length |
1637
- | `AIWAF_MAX_ACCEPT_LENGTH` | `4096` | Max Accept header length |
1638
- | `AIWAF_BLOCKED_USER_AGENTS` | list | Substring deny list |
1639
- | `AIWAF_SUSPICIOUS_USER_AGENTS` | regex list | Regex list for suspicious UA detection |
1640
- | `AIWAF_LEGITIMATE_BOTS` | regex list | Regex allow list for legitimate crawlers |
1641
-
1642
- #### Method Policy
1643
-
1644
- | Option | Default | Description |
1645
- |---|---|---|
1646
- | `AIWAF_METHOD_POLICY_ENABLED` | `false` | Enforce method allowlist (returns 405) |
1647
- | `AIWAF_ALLOWED_METHODS` | `['GET','POST','HEAD','OPTIONS']` | Allowed methods when policy enabled |
1648
- | `AIWAF_POST_ONLY_SUFFIXES` | `['/create/','/submit/','/upload/','/delete/','/process/']` | GET to these triggers 405 when policy enabled |
1649
- | `AIWAF_LOGIN_PATH_PREFIXES` | common login paths | Shorten min form time for login |
1650
-
1651
- #### Middleware Selection / Path Rules
1652
-
1653
- | Option | Default | Description |
1654
- |---|---|---|
1655
- | `AIWAF_MIDDLEWARES` | all compatible checks | Explicit middleware list, or `['auto']` / `['all']` |
1656
- | `AIWAF_DISABLE_MIDDLEWARES` | `[]` | Middleware names to disable after selection |
1657
- | `AIWAF_PATH_RULES` | `[]` | Prefix rules with `PREFIX`, `DISABLE`, and optional section overrides |
1658
- | `AIWAF_PATH_MANIFEST` | `.aiwaf/paths.json` | Route manifest compiled into additional path rules |
1659
- | `AIWAF_ROUTE_PLAN_VERSION` | `0` | User-controlled version marker for route policy changes |
1660
-
1661
- #### Keyword Learning
1662
-
1663
- | Option | Default | Description |
1664
- |---|---|---|
1665
- | `AIWAF_ENABLE_KEYWORD_LEARNING` | `true` | Enable dynamic keyword learning |
1666
- | `AIWAF_DYNAMIC_TOP_N` | `10` | Dynamic keyword learning threshold |
1667
- | `AIWAF_EXEMPT_KEYWORDS` | `[]` | Skip these keywords |
1668
- | `AIWAF_ALLOWED_PATH_KEYWORDS` | `[]` | Allowlist of path fragments |
1669
-
1670
- #### Model / Training
1671
-
1672
- | Option | Default | Description |
1673
- |---|---|---|
1674
- | `AIWAF_MIN_TRAIN_LOGS` | `50` | Minimum logs to run training |
1675
- | `AIWAF_MIN_AI_LOGS` | `10000` | Minimum logs to train AI model |
1676
- | `AIWAF_CLEAR_STATE_ON_START` | `false` | Clear blacklist, request logs, and dynamic keywords on startup |
1677
- | `AIWAF_FORCE_AI_TRAINING` | `false` | Force AI training below minimum logs |
1678
- | `AIWAF_MODEL_STORAGE` | `file` | `file`, `db`, or `cache` |
1679
- | `AIWAF_MODEL_PATH` | `resources/model.json` | Model file path (file backend) |
1680
- | `AIWAF_MODEL_STORAGE_FALLBACK` | `file` | Fallback model backend |
1681
- | `AIWAF_MODEL_CACHE_KEY` | `aiwaf:model` | Cache key when using cache backend |
1682
- | `AIWAF_MODEL_CACHE_TTL` | `0` | Cache TTL in seconds |
1683
-
1684
- #### Geo Blocking
1685
-
1686
- | Option | Default | Description |
1687
- |---|---|---|
1688
- | `AIWAF_GEO_BLOCK_ENABLED` | `false` | Enable geo blocking |
1689
- | `AIWAF_GEO_BLOCK_COUNTRIES` | `[]` | Block list (country codes) |
1690
- | `AIWAF_GEO_ALLOW_COUNTRIES` | `[]` | Allow list (country codes) |
1691
- | `AIWAF_GEO_MMDB_PATH` | `geolock/ipinfo_lite.mmdb` | MMDB path |
1692
- | `AIWAF_GEO_CACHE_SECONDS` | `3600` | Geo cache TTL |
1693
- | `AIWAF_GEO_CACHE_PREFIX` | `aiwaf:geo:` | Geo cache key prefix |
1694
-
1695
- #### Logging / Storage
1696
-
1697
- | Option | Default | Description |
1698
- |---|---|---|
1699
- | `AIWAF_MIDDLEWARE_LOGGING` | `false` | Enable JSONL logging |
1700
- | `AIWAF_MIDDLEWARE_LOG_PATH` | `logs/aiwaf-requests.jsonl` | JSONL log path |
1701
- | `AIWAF_MIDDLEWARE_LOG_DB` | `false` | Store logs in DB |
1702
- | `AIWAF_MIDDLEWARE_LOG_CSV` | `false` | Store logs in CSV |
1703
- | `AIWAF_MIDDLEWARE_LOG_CSV_PATH` | `logs/aiwaf-requests.csv` | CSV log path |
1704
- | `AIWAF_BLOCKED_IPS_CSV_PATH` | `logs/storage/blocked_ips.csv` | CSV fallback for blocked IPs |
1705
- | `AIWAF_IP_EXEMPTIONS_CSV_PATH` | `logs/storage/ip_exemptions.csv` | CSV fallback for IP exemptions |
1706
- | `AIWAF_PATH_EXEMPTIONS_CSV_PATH` | `logs/storage/path_exemptions.csv` | CSV fallback for path exemptions |
1707
- | `AIWAF_GEO_BLOCKED_COUNTRIES_CSV_PATH` | `logs/storage/geo_blocked_countries.csv` | CSV fallback for geo blocklist |
1708
- | `AIWAF_REQUEST_LOGS_CSV_PATH` | `logs/storage/request_logs.csv` | CSV fallback for request logs |
1709
- | `AIWAF_DYNAMIC_KEYWORDS_CSV_PATH` | `logs/storage/dynamic_keywords.csv` | CSV fallback for dynamic keywords |
1710
-
1711
- #### Redis / Cache
1712
- ### Redis and Cache Behavior
1713
-
1714
- - Set `REDIS_URL` (or `AIWAF_REDIS_URL`) to enable Redis connectivity (`lib/redisClient.js`).
1715
- - If Redis is unavailable, runtime falls back to in-memory behavior.
1716
- - You can inject a custom cache object.
1717
-
1718
- Rate limiter custom cache must implement:
1719
-
1720
- - `lPush(key, value)`
1721
- - `expire(key, ttl)`
1722
- - `lLen(key)`
1723
- - `lRange(key, start, end)`
1724
-
1725
- Feature cache custom backend supports:
1726
-
1727
- - `get(key)`
1728
- - `set(key, value, ttl)`
1729
-
1730
- ### Geo Blocking (MMDB)
1731
-
1732
- - Put your DB at `geolock/ipinfo_lite.mmdb` (default) or set `AIWAF_GEO_MMDB_PATH`.
1733
- - Enable with `AIWAF_GEO_BLOCK_ENABLED: true`.
1734
- - Configure `AIWAF_GEO_BLOCK_COUNTRIES` and/or `AIWAF_GEO_ALLOW_COUNTRIES`.
1735
- - Install MMDB reader dependency in your app:
1736
- - `npm install maxmind`
1737
- - If MMDB is unavailable, the middleware falls back to `x-country-code` header.
1738
-
1739
- ### Offline Training
1740
-
1741
- Train a model using access logs:
1278
+ The in-process Flask benchmark compares a baseline app, `auto` middleware selection, and the full middleware chain:
1742
1279
 
1743
1280
  ```bash
1744
- AIWAF_ACCESS_LOG=/path/to/access.log npm run train
1281
+ python -m benchmarks.benchmark_auto_middleware
1282
+ python -m benchmarks.benchmark_auto_middleware --path-rules 250
1283
+ python -m benchmarks.benchmark_auto_middleware --requests 200 --rounds 3 --warmup 50
1745
1284
  ```
1746
1285
 
1747
- Optional rotated/gz support:
1286
+ Use the same machine, environment, request count, and background load when comparing results. These measurements exclude network and production-server overhead.
1748
1287
 
1749
- ```bash
1750
- NODE_LOG_GLOB='/path/to/access.log.*' npm run train
1751
- ```
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.
1752
1292
 
1753
- Training pipeline in `train.js`:
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× |
1754
1297
 
1755
- - Reads raw and rotated (including `.gz`) access logs
1756
- - Parses request fields (IP, URI, status, response time, timestamp)
1757
- - Builds feature vectors: `[pathLen, kwHits, statusIdx, responseTime, burst, total404]`
1758
- - Enforces `AIWAF_MIN_TRAIN_LOGS` and `AIWAF_MIN_AI_LOGS`
1759
- - Trains IsolationForest when log volume is sufficient
1760
- - Learns dynamic keywords from suspicious 4xx/5xx traffic
1761
- - Removes exempt keywords and unblocks exempt IPs
1762
- - Writes model artifact to `resources/model.json` with metadata
1763
- - Model storage backends:
1764
- - `AIWAF_MODEL_STORAGE`: `file` (default), `db`, `cache`
1765
- - `AIWAF_MODEL_PATH` (file backend)
1766
- - `AIWAF_MODEL_STORAGE_FALLBACK` (fallback backend)
1767
- - `AIWAF_MODEL_CACHE_KEY`, `AIWAF_MODEL_CACHE_TTL` (cache backend)
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.
1768
1304
 
1769
- ### Testing
1305
+ Reproduce the focused measurements and concurrency smoke check locally:
1770
1306
 
1771
1307
  ```bash
1772
- npm test
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
1773
1314
  ```
1774
1315
 
1775
- Current tests cover:
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.
1776
1325
 
1777
- - Header validation (caps, suspicious UA, quality scoring)
1778
- - Method policy enforcement
1779
- - Geo blocking and MMDB lookup
1780
- - Honeypot timing policies
1781
- - UUID tamper detection (with resolver)
1782
- - Anomaly detection and recent-behavior analysis
1783
- - Dynamic keyword learning and trainer behaviors
1784
- - CSV/DB fallback storage
1785
- - CLI and settings compatibility
1326
+ ## Release automation
1786
1327
 
1787
- ### Data and Persistence
1328
+ Release versions and tags must match the relevant manifest.
1788
1329
 
1789
- #### Reputation-aware blacklist
1330
+ | Package | Manifest | Tag | Workflow |
1331
+ | --- | --- | --- | --- |
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` |
1790
1337
 
1791
- Blacklist records use the same reputation lifecycle as the Python package. Each
1792
- record stores the original reason, accumulated reasons, score, offense count,
1793
- block timestamp, expiry, duration, permanent status, and optional redacted
1794
- request metadata. Repeated offenses progress from 15-minute blocks to one-hour
1795
- and 24-hour blocks. Expired entries are ignored and can be removed explicitly:
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.
1796
1339
 
1797
- ```bash
1798
- npm run aiwaf -- blacklist cleanup
1799
- npm run aiwaf -- blacklist migrate
1800
- npm run aiwaf -- blacklist migrate --duration 24h
1801
- ```
1340
+ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE_KEY`, `GPG_PASSPHRASE`, `CENTRAL_TOKEN_USERNAME`, and `CENTRAL_TOKEN_PASSWORD`. The workflow verifies the tag, runs tests, signs the POM and all three JARs, uploads the deployment bundle, and waits for Maven Central publication.
1802
1341
 
1803
- Set `AIWAF_CAPTURE_EXTENDED_REQUEST_INFO=true` to retain redacted request
1804
- headers and fingerprints with blacklist decisions. Authorization and cookie
1805
- headers are redacted by default.
1806
-
1807
- - Runtime blacklist storage uses SQLite through `utils/db.js`.
1808
- - Production DB file defaults to `./aiwaf.sqlite`.
1809
- - Test environment uses in-memory SQLite (`NODE_ENV=test`).
1810
- - Primary blocked IP table: `blocked_ips`.
1811
- - Middleware logging supports JSONL, optional SQLite, and CSV fallback.
1812
- - CSV settings:
1813
- - `AIWAF_MIDDLEWARE_LOG_CSV`
1814
- - `AIWAF_MIDDLEWARE_LOG_CSV_PATH`
1815
- - Table storage CSV fallbacks are enabled automatically when DB operations fail:
1816
- - `blocked_ips` -> `logs/storage/blocked_ips.csv` (`AIWAF_BLOCKED_IPS_CSV_PATH`)
1817
- - `ip_exemptions` -> `logs/storage/ip_exemptions.csv` (`AIWAF_IP_EXEMPTIONS_CSV_PATH`)
1818
- - `path_exemptions` -> `logs/storage/path_exemptions.csv` (`AIWAF_PATH_EXEMPTIONS_CSV_PATH`)
1819
- - `geo_blocked_countries` -> `logs/storage/geo_blocked_countries.csv` (`AIWAF_GEO_BLOCKED_COUNTRIES_CSV_PATH`)
1820
- - `request_logs` -> `logs/storage/request_logs.csv` (`AIWAF_REQUEST_LOGS_CSV_PATH`)
1821
- - `dynamic_keywords` -> `logs/storage/dynamic_keywords.csv` (`AIWAF_DYNAMIC_KEYWORDS_CSV_PATH`)
1822
-
1823
- ### Operational Notes
1824
-
1825
- - Middleware order matters; place AIWAF after body parsers if honeypot checks depend on parsed JSON/form body.
1826
- - If no trained model exists or loading fails, anomaly detector fails open.
1827
- - Dynamic keyword learning persists to DB/CSV via `dynamicKeywordStore`.
1828
- - Multi-instance deployments should use Redis/custom shared cache for limiter consistency.
1829
-
1830
- ### Development
1342
+ Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1831
1343
 
1832
- ```bash
1833
- npm install
1834
- npm test
1835
- npm run train
1836
- npm run aiwaf -- help
1837
- ```
1344
+ ## Security and limitations
1838
1345
 
1839
- ### Operations CLI
1346
+ - Deterministic controls can produce false positives when legitimate routes resemble common probes; use narrow route exemptions and regression tests.
1347
+ - Language-native Isolation Forest implementations can produce different scores for identical feature rows.
1348
+ - WASM object conversion has overhead and is not automatically faster than JavaScript for small calls.
1349
+ - In-memory rate limits and runtime stores are local to one process.
1350
+ - GeoIP data can be missing, stale, or imprecise and should not be the sole authorization control.
1351
+ - Post-response blocking cannot replace data already committed or streamed to a client.
1352
+ - No WAF can compensate for broken authorization or unsafe application logic.
1840
1353
 
1841
- ```bash
1842
- npm run aiwaf -- list blacklist
1843
- npm run aiwaf -- list exemptions
1844
- npm run aiwaf -- add blacklist 203.0.113.9 "manual block"
1845
- npm run aiwaf -- remove blacklist 203.0.113.9
1846
- npm run aiwaf -- add ip-exemption 203.0.113.10 "trusted monitor"
1847
- npm run aiwaf -- add path-exemption /health "health probes"
1848
- npm run aiwaf -- add dynamic-keyword scanner 5
1849
- npm run aiwaf -- remove dynamic-keyword scanner
1850
- npm run aiwaf -- geo block CN "manual block"
1851
- npm run aiwaf -- geo summary
1852
- npm run aiwaf -- whois example.com
1853
- npm run aiwaf -- diagnose 203.0.113.10
1854
- npm run aiwaf -- reset --all --confirm
1855
- npm run aiwaf -- pathshell
1856
- npm run aiwaf -- status
1857
- npm run aiwaf -- stats 5000
1858
- npm run aiwaf -- logs analyze 5000
1859
- npm run aiwaf -- export aiwaf-export.json
1860
- npm run aiwaf -- import aiwaf-export.json
1861
- npm run aiwaf -- model info
1862
- npm run aiwaf -- model export aiwaf-model.json
1863
- npm run aiwaf -- model import aiwaf-model.json
1864
- npm run aiwaf -- model clear
1865
- ```
1866
-
1867
- ### Sandbox (OWASP Juice Shop)
1354
+ Report vulnerabilities privately to the maintainers rather than opening a public exploit issue.
1868
1355
 
1869
- The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF.
1356
+ ## Contributing
1870
1357
 
1871
- ```bash
1872
- docker compose -f examples/sandbox/docker-compose.yml up --build
1873
- ```
1874
-
1875
- Fastify proxy is also available on `http://localhost:3002`.
1876
-
1877
- ---
1358
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for contributor setup and expectations, [`CHANGELOG.md`](CHANGELOG.md) for release history, and [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md) for community standards.
1878
1359
 
1879
- ## Acknowledgements
1880
-
1881
- GeoIP support uses the bundled IPinfo MMDB format for country mapping.
1360
+ ## License
1882
1361
 
1883
- [DigitalOcean](https://www.digitalocean.com/) provides the cloud infrastructure that powers AIWAF development.
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.
1884
1363
 
1885
- ---
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.
1886
1365
 
1887
- ## License
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.
1888
1367
 
1889
- MIT. See `LICENSE`.
1368
+ Redistributions must include the applicable LICENSE, NOTICE, and licenses/ files. See [NOTICE](NOTICE) for historical rights, contributor notices, and attribution.