aiwaf 1.0.2 → 1.1.0

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,162 @@
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.
6
4
 
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.
5
+ This is the single authoritative README for the monorepo and every published AIWAF package. Release workflows stage this file and the root `LICENSE` into package artifacts when a registry requires package-local copies.
11
6
 
12
- This monorepo contains three independently published packages:
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.
13
8
 
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.
9
+ ## Packages
17
10
 
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).
11
+ New request controls: [Python/JavaScript SQL injection inspection and Java keyword learning safety](docs/request-inspection.md).
19
12
 
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.
13
+ Each package is versioned and released independently.
21
14
 
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`.
15
+ Python and Node.js 1.1.0 and Java 1.3.1 are local release candidates; see the
16
+ [upgrade notes](docs/releases/2026-10-request-inspection.md).
23
17
 
24
- ## Latest Enhancements
18
+ | Runtime | Package | Repository version | Primary use |
19
+ | --- | --- | ---: | --- |
20
+ | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.1.0` | Django, Flask, and FastAPI protection |
21
+ | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.1.0` | Express and Node framework middleware |
22
+ | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.1` | Native Python acceleration and JSON model inference |
23
+ | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.1` | Rust detection and model primitives for JavaScript |
24
+ | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.1` | Spring MVC and Jakarta Servlet protection |
25
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
26
+ Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
36
27
 
37
- ---
28
+ ## What AIWAF provides
38
29
 
39
- ## Quick Installation
30
+ - IP blacklist, exemption, reputation, expiry, and progressive-block handling
31
+ - Sliding-window rate limiting and flood detection
32
+ - Header, method, request-size, content-type, and parameter validation
33
+ - Static and learned malicious keyword detection
34
+ - Honeypot field and form-timing checks
35
+ - UUID probing and tamper detection
36
+ - GeoIP allow/block policies using the bundled MMDB data
37
+ - Route manifests, path-specific overrides, and decorator/annotation exemptions
38
+ - Memory, file, CSV, SQLite, database, and cache-backed runtime state, depending on the runtime
39
+ - Structured request logging and offline training
40
+ - Six-feature anomaly models with Rust, JavaScript, and Java implementations
41
+ - Optional Rust acceleration for Python and optional WebAssembly acceleration for Node.js
40
42
 
41
- Python:
43
+ 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.
42
44
 
43
- ```bash
44
- pip install aiwaf
45
- ```
46
-
47
- JavaScript:
45
+ ## Repository layout
48
46
 
49
- ```bash
50
- npm install aiwaf
47
+ ```text
48
+ .
49
+ ├── py/aiwaf/ Python package and adapters
50
+ ├── js/ Node.js package and adapters
51
+ ├── rust/ Rust core and Python bindings
52
+ │ └── crates/aiwaf_wasm/ WebAssembly bindings
53
+ ├── java/ Java 17 package
54
+ ├── tests/ Python integration and parity tests
55
+ ├── benchmarks/ Python middleware benchmarks
56
+ ├── examples/ Focused Python examples
57
+ ├── .github/workflows/ Tests, security checks, and releases
58
+ ├── README.md Canonical project documentation
59
+ └── LICENSE Canonical MIT license
51
60
  ```
52
61
 
53
- Optional framework extras:
62
+ ## Quick installation
63
+
64
+ Choose the package for the application runtime:
54
65
 
55
66
  ```bash
67
+ # Python core or a framework extra
68
+ pip install aiwaf
56
69
  pip install "aiwaf[django]"
57
70
  pip install "aiwaf[flask]"
58
71
  pip install "aiwaf[fastapi]"
59
- pip install "aiwaf[rust]"
60
- ```
61
-
62
- Rust extra installs `aiwaf-rust`, which accelerates selected paths and is required
63
- for persisted AI model inference from JSON `IsolationForest` artifacts.
64
-
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`.
68
-
69
- ---
70
-
71
- ## System Requirements
72
72
 
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
78
-
79
- ---
73
+ # Python with the optional Rust accelerator
74
+ pip install "aiwaf[rust]"
80
75
 
81
- ## Package Structure
76
+ # Node.js middleware
77
+ npm install aiwaf
82
78
 
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
79
+ # Standalone WebAssembly bindings
80
+ npm install aiwaf-wasm
93
81
  ```
94
82
 
95
- Contributor setup, test commands, and release conventions are documented in [`CONTRIBUTING.md`](CONTRIBUTING.md).
96
-
97
- Framework entry points:
98
-
99
- ```python
100
- # Django
101
- import aiwaf.django as aiwaf
83
+ Java 1.3.1, after it is published to Maven Central:
102
84
 
103
- # Flask
104
- import aiwaf.flask as aiwaf
105
-
106
- # FastAPI
107
- import aiwaf.fast as aiwaf
85
+ ```xml
86
+ <dependency>
87
+ <groupId>io.github.aiwaf-project</groupId>
88
+ <artifactId>aiwaf-java</artifactId>
89
+ <version>1.3.1</version>
90
+ </dependency>
108
91
  ```
109
92
 
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
93
+ ## Python package
124
94
 
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
95
+ The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
129
96
 
130
- - **Dynamic keyword learning**
131
- - learns suspicious path terms from attack-like traffic
132
- - excludes exempt/allowed terms to reduce false positives
97
+ ### Flask
133
98
 
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:
99
+ ```python
100
+ from flask import Flask
101
+ from aiwaf.flask import AIWAF
181
102
 
182
- ```bash
183
- # often low-quality header profile
184
- curl http://your-app.example/
103
+ app = Flask(__name__)
104
+ AIWAF(
105
+ app,
106
+ middlewares=["auto"],
107
+ )
185
108
 
186
- # compare against normal browser traffic
109
+ @app.get("/")
110
+ def home():
111
+ return {"protected": True}
187
112
  ```
188
113
 
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.
114
+ `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.
224
115
 
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:
116
+ ### FastAPI
242
117
 
243
118
  ```python
244
- AIWAF_ACCESS_LOG = "/var/log/nginx/access.log"
245
- ```
246
-
247
- Core defaults (examples):
119
+ from fastapi import FastAPI
120
+ from aiwaf.fast import AIWAF
248
121
 
249
- ```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
- ```
122
+ app = FastAPI()
276
123
 
277
- Model storage:
124
+ AIWAF(
125
+ app,
126
+ middlewares=["auto"],
127
+ storage={"backend": "memory"},
128
+ header_validation={"enabled": True, "quality_threshold": 3},
129
+ rate_limiting={"enabled": True, "window_seconds": 10, "max_requests": 20},
130
+ logging_middleware={
131
+ "enabled": True,
132
+ "log_dir": "aiwaf_logs",
133
+ "log_format": "json",
134
+ },
135
+ )
278
136
 
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
137
+ @app.get("/")
138
+ async def home():
139
+ return {"protected": True}
285
140
  ```
286
141
 
287
- Only JSON-serializable model artifacts are saved. Python object model artifacts
288
- are rejected by design.
289
-
290
- Header controls:
291
-
292
- ```python
293
- AIWAF_REQUIRED_HEADERS = None # list or method->list mapping
294
- AIWAF_HEADER_QUALITY_MIN_SCORE = 3
295
- ```
142
+ ### Django
296
143
 
297
- GeoIP:
144
+ Add the app and the unified middleware alias in `settings.py`:
298
145
 
299
146
  ```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
- ```
307
-
308
- Rust acceleration:
147
+ INSTALLED_APPS = [
148
+ # ...
149
+ "aiwaf.django",
150
+ ]
309
151
 
310
- ```python
311
- AIWAF_RUST_ISOLATION_FOREST = True
152
+ MIDDLEWARE = [
153
+ "django.middleware.security.SecurityMiddleware",
154
+ "aiwaf.django.middleware.all",
155
+ # ...
156
+ ]
312
157
  ```
313
158
 
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
- ---
325
-
326
- ## Middleware Setup
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`
336
-
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
344
-
345
- Django example order:
159
+ For explicit ordering, replace the alias with the individual middleware classes:
346
160
 
347
161
  ```python
348
162
  MIDDLEWARE = [
@@ -358,1532 +172,591 @@ MIDDLEWARE = [
358
172
  ]
359
173
  ```
360
174
 
361
- If JSON API clients need JSON 403 bodies, keep `JsonExceptionMiddleware` near the top.
362
-
363
- Django alias example:
364
-
365
- ```python
366
- MIDDLEWARE = [
367
- "django.middleware.security.SecurityMiddleware",
368
- "aiwaf.django.middleware.all",
369
- ]
370
- ```
371
-
372
- FastAPI quick integration:
373
-
374
- ```python
375
- from fastapi import FastAPI
376
- from aiwaf.fast import AIWAF
377
-
378
- app = FastAPI()
379
-
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
- ```
389
-
390
- Flask quick integration:
391
-
392
- ```python
393
- from flask import Flask
394
- from aiwaf.flask import AIWAF
395
-
396
- app = Flask(__name__)
397
- aiwaf = AIWAF(app, middlewares=["all"])
398
- ```
399
-
400
- ---
175
+ Protection middleware should run early. Logging should run late enough to observe the application response.
401
176
 
402
- ## Operations
177
+ ### Route manifests
403
178
 
404
- Django adapter examples:
179
+ `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.
405
180
 
406
181
  ```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
416
- ```
417
-
418
- Flask adapter:
419
- - use `aiwaf.flask.AIWAF` for middleware registration
420
- - use `aiwaf.flask.cli.AIWAFManager` for CSV-backed operational tasks
182
+ # Flask application object
183
+ aiwaf init --framework flask --app app:app
421
184
 
422
- FastAPI adapter:
423
- - use `aiwaf.fast.AIWAF` for middleware registration
424
- - use `aiwaf fast ...` or `aiwaf-fast ...` for CLI operations
185
+ # Flask application factory
186
+ aiwaf init --framework flask --app app:create_app
425
187
 
426
- ### Django Command Reference
188
+ # FastAPI
189
+ aiwaf init --framework fastapi --app app:app
427
190
 
428
- Common management commands:
191
+ # Django
192
+ aiwaf init --framework django --settings project.settings
429
193
 
430
- ```bash
431
- python manage.py detect_and_train
432
- python manage.py regenerate_model
433
- python manage.py aiwaf_reset --confirm
434
- python manage.py aiwaf_reset --blacklist --confirm
435
- 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
- python manage.py aiwaf_logging --status
441
- 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
194
+ # Custom output
195
+ aiwaf init --framework flask --app app:app --output .aiwaf/paths.json
445
196
  ```
446
197
 
447
- `aiwaf_pathshell` helpers:
198
+ 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:
448
199
 
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
200
+ ```bash
201
+ python -c "import app; print(app.__file__); print(*sorted(r.rule for r in app.app.url_map.iter_rules()), sep='\n')"
456
202
  ```
457
203
 
458
- ### Flask Adapter Reference
204
+ ### Python route exemptions
459
205
 
460
- Programmatic integration:
206
+ Django, Flask, and FastAPI expose equivalent route helpers:
461
207
 
462
208
  ```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
- ],
209
+ from aiwaf.flask import (
210
+ aiwaf_exempt,
211
+ aiwaf_exempt_from,
212
+ aiwaf_only,
213
+ aiwaf_require_protection,
481
214
  )
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
215
 
497
- Blacklist migration commands:
216
+ @app.get("/health")
217
+ @aiwaf_exempt
218
+ def health():
219
+ return {"ok": True}
498
220
 
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
504
-
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
508
-
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
512
-
513
- # Remove only legacy-imported entries
514
- python -m aiwaf.flask.cli blacklist clear-legacy
221
+ @app.post("/webhook")
222
+ @aiwaf_only("header_validation")
223
+ def webhook():
224
+ return {"accepted": True}
515
225
  ```
516
226
 
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
523
-
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.
527
-
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 |
227
+ Canonical middleware names include `header_validation`, `rate_limit`, `ip_keyword_block`, `honeypot`, `geo_block`, `uuid_tamper`, `ai_anomaly`, and `logging`.
534
228
 
535
- Django ORM:
229
+ ### Python configuration
536
230
 
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
231
+ Python adapters use flat `AIWAF_*` settings or their equivalent constructor options.
541
232
 
542
- aiwaf django blacklist migrate
543
- # Equivalent:
544
- python manage.py aiwaf_migrate_blacklist
545
- ```
233
+ | Area | Important settings |
234
+ | --- | --- |
235
+ | Training | `AIWAF_ACCESS_LOG`, `AIWAF_MIN_TRAIN_LOGS`, `AIWAF_MIN_AI_LOGS`, `AIWAF_FORCE_AI_TRAINING` |
236
+ | Rate limiting | `AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`, `AIWAF_RATE_FLOOD` |
237
+ | Headers | `AIWAF_REQUIRED_HEADERS`, `AIWAF_HEADER_QUALITY_MIN_SCORE` |
238
+ | Honeypot | `AIWAF_MIN_FORM_TIME`, `AIWAF_MAX_PAGE_TIME` |
239
+ | UUID checks | `AIWAF_UUID_SCORE_ENABLED`, `AIWAF_UUID_SCORE_BLOCK_THRESHOLD` |
240
+ | GeoIP | `AIWAF_GEO_BLOCK_ENABLED`, `AIWAF_GEO_BLOCK_COUNTRIES`, `AIWAF_GEO_ALLOW_COUNTRIES` |
241
+ | Exemptions | `AIWAF_EXEMPT_PATHS`, `AIWAF_EXEMPT_KEYWORDS`, `AIWAF_ALLOWED_PATH_KEYWORDS` |
242
+ | Models | `AIWAF_MODEL_PATH`, `AIWAF_MODEL_STORAGE`, `AIWAF_MODEL_STORAGE_FALLBACK` |
546
243
 
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.
244
+ 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.
551
245
 
552
- Flask SQLAlchemy ORM:
246
+ ### Python operations
553
247
 
554
248
  ```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
559
- ```
560
-
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:
587
-
588
- ```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
591
- ```
249
+ # Unified CLI
250
+ aiwaf --help
251
+ aiwaf blacklist migrate
252
+ aiwaf status
592
253
 
593
- ### FastAPI Adapter Reference
594
-
595
- Programmatic integration:
596
-
597
- ```python
598
- from fastapi import FastAPI
599
- from aiwaf.fast import AIWAF
600
-
601
- app = FastAPI()
602
- AIWAF(app)
603
- ```
604
-
605
- CLI usage:
254
+ # Django management commands
255
+ python manage.py detect_and_train
256
+ python manage.py regenerate_model
257
+ python manage.py aiwaf_reset --keywords --confirm
258
+ python manage.py aiwaf_logging --status
259
+ python manage.py geo_block_country list
606
260
 
607
- ```bash
261
+ # Explicit adapter dispatch
262
+ aiwaf django aiwaf_list --all
263
+ aiwaf flask --help
608
264
  aiwaf fast --help
609
- aiwaf-fast --help
610
265
  ```
611
266
 
612
- ### Path-Specific Rules
267
+ ## JavaScript package
613
268
 
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.
269
+ The npm package uses CommonJS and exports the Express middleware as its default function plus adapters for the other supported Node frameworks.
617
270
 
618
- Generate a manifest:
271
+ ### Express
619
272
 
620
- ```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
629
-
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
635
- ```
636
-
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
- ```
273
+ ```javascript
274
+ const express = require('express');
275
+ const aiwaf = require('aiwaf');
720
276
 
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.
277
+ const app = express();
278
+ app.use(express.json());
725
279
 
726
- You can still define manual path rules to selectively disable middleware or
727
- override rate limits without globally weakening protection:
280
+ app.use(aiwaf({
281
+ AIWAF_MIDDLEWARES: ['auto'],
282
+ staticKeywords: ['.php', '.env', '.git'],
283
+ WINDOW_SEC: 10,
284
+ MAX_REQ: 20,
285
+ FLOOD_REQ: 40,
286
+ AIWAF_HEADER_VALIDATION: true,
287
+ AIWAF_METHOD_POLICY_ENABLED: true,
288
+ AIWAF_ALLOWED_METHODS: ['GET', 'POST', 'HEAD', 'OPTIONS']
289
+ }));
728
290
 
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
- }
291
+ app.get('/', (req, res) => res.json({ protected: true }));
292
+ app.listen(3000);
743
293
  ```
744
294
 
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.
295
+ Attach AIWAF after the body parser when honeypot rules inspect parsed form or JSON fields.
751
296
 
752
- ### Blocking Behavior
297
+ ### Node framework adapters
753
298
 
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.
299
+ | Framework | Entry point |
300
+ | --- | --- |
301
+ | Express | `aiwaf(options)` |
302
+ | Fastify | `fastify.register(aiwaf.fastify, options)` |
303
+ | Hapi | `server.register({ plugin: aiwaf.hapi, options })` |
304
+ | Koa | `app.use(aiwaf.koa(options))` |
305
+ | NestJS/Express | `aiwaf.nest(options)` or the Express middleware |
306
+ | NestJS/Fastify | `app.register(aiwaf.fastify, options)` |
307
+ | Next.js API routes | `aiwaf.next(handler, options)` |
308
+ | AdonisJS | `aiwaf.adonis(options)` |
309
+ | Sails.js | `aiwaf.sails(options)` |
761
310
 
762
- ### Rate Limiting Cache (Multi-worker)
311
+ ### JavaScript path policies
763
312
 
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**
768
-
769
- ```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:"
313
+ ```javascript
314
+ app.use(aiwaf({
315
+ AIWAF_PATH_RULES: [
316
+ { PREFIX: '/health/', DISABLE: ['header_validation', 'rate_limit'] },
317
+ { PREFIX: '/api/public/', RATE_LIMIT: { WINDOW: 60, MAX: 300 } }
318
+ ]
319
+ }));
774
320
  ```
775
321
 
776
- **FastAPI**
322
+ Applications can also use `aiwaf.exempt`, `aiwaf.exemptFrom`, `aiwaf.only`, and `aiwaf.requireProtection` to build route policies.
777
323
 
778
- ```python
779
- from aiwaf.fast import AIWAF
324
+ Generate an Express route manifest after routes are registered:
780
325
 
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
- },
789
- )
326
+ ```javascript
327
+ aiwaf.generateExpressManifest(app, '.aiwaf/paths.json');
790
328
  ```
791
329
 
792
- Environment variables (both adapters):
330
+ Or generate one from a route list with the CLI:
793
331
 
794
332
  ```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:
333
+ cd js
334
+ npm run aiwaf -- manifest --framework express --routes routes.json --output .aiwaf/paths.json
798
335
  ```
799
336
 
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
337
+ ### JavaScript configuration
812
338
 
813
- The sandbox in `examples/sandbox/` provides:
339
+ | Area | Important options |
340
+ | --- | --- |
341
+ | Middleware | `AIWAF_MIDDLEWARES`, `AIWAF_DISABLE_MIDDLEWARES`, `AIWAF_PATH_RULES` |
342
+ | Rate limiting | `WINDOW_SEC`, `MAX_REQ`, `FLOOD_REQ`, `cache` |
343
+ | Headers | `AIWAF_HEADER_VALIDATION`, `AIWAF_REQUIRED_HEADERS`, `AIWAF_HEADER_QUALITY_MIN_SCORE` |
344
+ | Methods | `AIWAF_METHOD_POLICY_ENABLED`, `AIWAF_ALLOWED_METHODS` |
345
+ | Keywords | `staticKeywords`, `AIWAF_ENABLE_KEYWORD_LEARNING`, `AIWAF_DYNAMIC_TOP_N` |
346
+ | Honeypot | `HONEYPOT_FIELD`, timing settings |
347
+ | GeoIP | `AIWAF_GEO_BLOCK_ENABLED`, `AIWAF_GEO_BLOCK_COUNTRIES`, `AIWAF_GEO_ALLOW_COUNTRIES` |
348
+ | Models | `AIWAF_MODEL_STORAGE`, `AIWAF_MODEL_PATH`, `AIWAF_MODEL_CACHE_KEY` |
349
+ | Logging | `AIWAF_MIDDLEWARE_LOGGING`, `AIWAF_MIDDLEWARE_LOG_PATH`, DB/CSV options |
350
+ | WASM | `AIWAF_WASM_VALIDATION`, `AIWAF_WASM_VALIDATE_RECENT` |
814
351
 
815
- - `direct` (no AIWAF)
816
- - `protected_django`
817
- - `protected_flask`
818
- - `protected_fastapi`
352
+ 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.
819
353
 
820
- Run full benchmark:
354
+ ### JavaScript training and operations
821
355
 
822
356
  ```bash
823
- cd examples/sandbox
824
- python run-and-compare.py -n 5
825
- ```
826
-
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:
836
-
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
840
-
841
- ---
842
-
843
- ## Publish Checklist
357
+ cd js
844
358
 
845
- Before publishing a new package version:
846
-
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):
859
-
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
359
+ AIWAF_ACCESS_LOG=/path/to/access.log npm run train
360
+ npm run aiwaf -- status
361
+ npm run aiwaf -- list blacklist
362
+ npm run aiwaf -- add blacklist 203.0.113.9 "manual block"
363
+ npm run aiwaf -- add ip-exemption 203.0.113.10 "trusted monitor"
364
+ npm run aiwaf -- geo summary
365
+ npm run aiwaf -- model info
366
+ npm run aiwaf -- export aiwaf-export.json
866
367
  ```
867
368
 
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
369
+ Use Redis or another shared cache for consistent rate limiting across multiple Node processes. Without shared state, the in-memory fallback is process-local.
873
370
 
874
- ---
371
+ ## Rust accelerator for Python
875
372
 
876
- ## Troubleshooting
877
-
878
- ### Legitimate pages blocked
879
-
880
- Cause:
881
- - learned keywords included legitimate app vocabulary
882
-
883
- Fix:
373
+ `aiwaf-rust` exposes the shared Rust core through PyO3 and ABI3 wheels for Python 3.8 and newer.
884
374
 
885
375
  ```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
376
+ pip install aiwaf-rust
998
377
  ```
999
378
 
1000
- Header validation:
379
+ The module provides:
1001
380
 
1002
- ```python
1003
- AIWAF_REQUIRED_HEADERS = None
1004
- AIWAF_HEADER_QUALITY_MIN_SCORE = 3
1005
- AIWAF_MAX_ACCEPT_LENGTH = 4096
1006
- ```
1007
-
1008
- AI/model behavior:
381
+ - `validate_headers` and `validate_headers_with_config`
382
+ - `KeywordMatcher` and `RouteMatcher`
383
+ - request-record construction and six-feature extraction
384
+ - incremental feature extraction with explicit state
385
+ - recent-behavior analysis
386
+ - `IsolationForest` training, scoring, prediction, retraining, and JSON state
1009
387
 
1010
388
  ```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
1016
- ```
1017
-
1018
- Model storage:
1019
-
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
- ```
1027
-
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"]
389
+ import aiwaf_rust
390
+
391
+ reason = aiwaf_rust.validate_headers({
392
+ "HTTP_USER_AGENT": "Mozilla/5.0",
393
+ "HTTP_ACCEPT": "text/html",
394
+ })
395
+
396
+ forest = aiwaf_rust.IsolationForest(
397
+ n_estimators=100,
398
+ max_samples="auto",
399
+ contamination="auto",
400
+ max_features=1.0,
401
+ bootstrap=False,
402
+ random_state=42,
403
+ warm_start=False,
404
+ )
405
+ forest.fit([[0.1, 1.0], [0.2, 1.1], [9.0, 9.0]])
406
+ score = forest.anomaly_score([9.0, 9.0])
407
+ state = forest.to_json()
408
+ restored = aiwaf_rust.IsolationForest.from_json(state)
1045
409
  ```
1046
410
 
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
1104
-
1105
- Geo-blocking appears inactive:
1106
- - confirm middleware enabled
1107
- - confirm MMDB path valid
1108
- - confirm allow/block lists are configured as intended
1109
-
1110
- ---
1111
-
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:
411
+ For a local native build, stage the two canonical repository assets and run maturin:
1188
412
 
1189
413
  ```bash
1190
- cd examples/sandbox
1191
- python run-and-compare.py -n 5
414
+ cp README.md rust/README.md
415
+ cp LICENSE rust/LICENSE
416
+ python -m pip install maturin
417
+ cd rust
418
+ maturin develop
1192
419
  ```
1193
420
 
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
1198
-
1199
- ---
1200
-
1201
- ## FAQ
1202
-
1203
- **Why do I see `403` on `curl` but browser works?**
1204
- Header validation can classify low-quality client headers as automated traffic.
1205
-
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.
421
+ The staged files are ignored by Git. Release automation performs the same staging before building wheels and the source distribution.
1208
422
 
1209
- **Can I disable one middleware for a single route?**
1210
- Yes, use `AIWAF_SETTINGS["PATH_RULES"]` with `DISABLE` for that prefix.
423
+ ## WebAssembly package
1211
424
 
1212
- **Does Rust mode change detection outcomes?**
1213
- It should preserve behavior while improving some execution paths; verify with A/B multi-iteration benchmarks.
425
+ `aiwaf-wasm` exposes the shared Rust core to browsers and Node-compatible bundlers.
1214
426
 
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.
427
+ ```javascript
428
+ import init, {
429
+ IsolationForest,
430
+ KeywordMatcher,
431
+ RouteMatcher,
432
+ analyze_recent_behavior,
433
+ extract_features,
434
+ validate_headers,
435
+ } from 'aiwaf-wasm';
1220
436
 
1221
- **Do I need Django to use AIWAF?**
1222
- No. Core supports both Django and Flask adapters, but some operational commands are Django-specific.
437
+ await init();
1223
438
 
1224
- ---
1225
-
1226
- ## CLI Entry Point
1227
-
1228
- ```bash
1229
- aiwaf-detect
1230
- ```
1231
-
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
439
+ const reason = validate_headers({
440
+ 'user-agent': 'Mozilla/5.0',
441
+ accept: 'text/html'
442
+ });
1301
443
 
1302
- ```bash
1303
- npm install aiwaf
444
+ const forest = new IsolationForest({
445
+ n_estimators: 100,
446
+ max_samples: 'auto',
447
+ contamination: 'auto',
448
+ random_state: 42
449
+ });
450
+ forest.fit([[0.1, 1.0], [0.2, 1.1], [9.0, 9.0]]);
451
+ const score = forest.anomaly_score([9.0, 9.0]);
1304
452
  ```
1305
453
 
1306
- #### Optional WASM Acceleration
454
+ 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.
1307
455
 
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.
456
+ Build and test it locally:
1310
457
 
1311
458
  ```bash
1312
- npm install aiwaf-wasm
459
+ cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core
460
+ cd rust/crates/aiwaf_wasm
461
+ wasm-pack test --node
462
+ wasm-pack build --release --target bundler
463
+ cd ../..
464
+ python scripts/patch_wasm_pkg.py
465
+ cp ../LICENSE crates/aiwaf_wasm/pkg/LICENSE
466
+ ```
467
+
468
+ ## Java package
469
+
470
+ AIWAF Java 1.3.1 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
471
+
472
+ ### Core engine
473
+
474
+ 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.
475
+
476
+ ```java
477
+ import com.aiwaf.core.AiwafConfig;
478
+ import com.aiwaf.core.AiwafDecision;
479
+ import com.aiwaf.core.AiwafEngine;
480
+ import com.aiwaf.core.AiwafRequest;
481
+
482
+ import java.util.Map;
483
+ import java.util.Set;
484
+
485
+ AiwafConfig config = new AiwafConfig();
486
+ config.rateLimitEnabled = true;
487
+ config.rateLimitMax = 20;
488
+ config.rateLimitWindowSeconds = 10;
489
+
490
+ AiwafEngine engine = new AiwafEngine(config);
491
+ AiwafRequest request = new AiwafRequest(
492
+ "GET",
493
+ "/api/profile",
494
+ "203.0.113.10",
495
+ "US",
496
+ Map.of("User-Agent", "Mozilla/5.0", "Accept", "application/json"),
497
+ Map.of(),
498
+ System.currentTimeMillis(),
499
+ Set.of()
500
+ );
501
+
502
+ long started = System.currentTimeMillis();
503
+ AiwafDecision decision = engine.evaluateBeforeResponse(request);
504
+ if (decision.allowed()) {
505
+ decision = engine.evaluateAfterResponse(
506
+ request,
507
+ 200,
508
+ System.currentTimeMillis() - started
509
+ );
510
+ }
1313
511
  ```
1314
512
 
1315
- ### Quick Start
513
+ `evaluate(request)` remains available for request-only integrations and uses provisional response values for AI features.
1316
514
 
1317
- ```js
1318
- const express = require('express');
1319
- const aiwaf = require('aiwaf');
515
+ ### Spring MVC
1320
516
 
1321
- const app = express();
1322
- app.use(express.json());
517
+ 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.
1323
518
 
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
- }));
1336
-
1337
- app.get('/', (req, res) => res.send('Protected'));
1338
- app.listen(3000);
519
+ ```properties
520
+ aiwaf.rate-limit.max=60
521
+ aiwaf.rate-limit.window-seconds=60
522
+ aiwaf.geo.enabled=true
523
+ aiwaf.geo.blocked-countries=CN,RU
524
+ aiwaf.path-manifest.path=.aiwaf/paths.json
525
+ # Use one namespace and shared enforcement state across application instances.
526
+ aiwaf.storage.backend=redis
527
+ aiwaf.storage.redis-url=redis://localhost:6379/0
528
+ aiwaf.storage.key-prefix=my-service
529
+ # Redis is fail-closed by default. Every wait is bounded.
530
+ aiwaf.storage.redis-failure-mode=fail_closed
531
+ aiwaf.storage.redis-connection-timeout-millis=1000
532
+ aiwaf.storage.redis-socket-timeout-millis=2000
533
+ aiwaf.storage.redis-pool-max-total=32
534
+ aiwaf.storage.redis-pool-max-idle=16
535
+ aiwaf.storage.redis-pool-min-idle=0
536
+ aiwaf.storage.redis-pool-max-wait-millis=250
1339
537
  ```
1340
538
 
1341
- ### Path Rules and Auto Middleware
539
+ 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.
1342
540
 
1343
- Use path rules to disable selected AIWAF checks or override rate limits for a route prefix:
541
+ 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:
1344
542
 
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
- }));
543
+ ```java
544
+ @Bean
545
+ AiwafFilter aiwafFilter(AiwafEngine engine, ApplicationContext context) {
546
+ return new AiwafFilter(engine, context);
547
+ }
1352
548
  ```
1353
549
 
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.
1355
-
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:
1357
-
1358
- ```js
1359
- const manifest = aiwaf.generateExpressManifest(app, '.aiwaf/paths.json');
1360
- ```
550
+ 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.
1361
551
 
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:
552
+ Committed, streaming, and asynchronous responses are recorded but are not replaced after bytes have been sent.
1363
553
 
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
- ```
554
+ 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.
1372
555
 
1373
- The CLI can generate a manifest from a JSON route list:
556
+ Generate a route manifest from the live Spring application rather than supplying controller methods manually:
1374
557
 
1375
558
  ```bash
1376
- npm run aiwaf -- manifest --framework express --routes routes.json --output .aiwaf/paths.json
1377
- ```
1378
-
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'] }));
559
+ java -cp "your-app.jar:aiwaf-java-1.3.1.jar" \
560
+ com.aiwaf.cli.AiwafConsole init \
561
+ --app com.example.Application \
562
+ --output .aiwaf/paths.json
1406
563
  ```
1407
564
 
1408
- ### Fastify Usage
565
+ 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.
1409
566
 
1410
- ```js
1411
- const fastify = require('fastify')({ logger: true });
1412
- const aiwaf = require('aiwaf');
567
+ ### Jakarta Servlet
1413
568
 
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
- });
569
+ ```java
570
+ AiwafConfig config = new AiwafConfig();
571
+ AiwafEngine engine = new AiwafEngine(config);
1422
572
 
1423
- fastify.get('/', async () => 'Protected');
1424
- fastify.listen({ port: 3000 });
573
+ servletContext
574
+ .addFilter("aiwaf", new AiwafServletFilter(engine))
575
+ .addMappingForUrlPatterns(null, false, "/*");
1425
576
  ```
1426
577
 
1427
- ### Hapi Usage
578
+ The generic servlet filter uses request-time evaluation. Spring applications should prefer `AiwafFilter` for handler metadata and post-response scoring.
1428
579
 
1429
- ```js
1430
- const Hapi = require('@hapi/hapi');
1431
- const aiwaf = require('aiwaf');
580
+ ### Java configuration and models
1432
581
 
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
- });
582
+ | Area | Main `AiwafConfig` fields |
583
+ | --- | --- |
584
+ | Rate limiting | `rateLimitEnabled`, `rateLimitScope`, `rateLimitWindowSeconds`, `rateLimitMax`, `rateLimitFloodThreshold` |
585
+ | Headers | `headerValidationEnabled`, `requiredHeadersByMethod`, `minHeaderQualityScore`, size/count limits |
586
+ | Request | body, parameter, method, and content-type limits |
587
+ | Proxies | `trustedProxyCidrs`, `maxForwardedForEntries` |
588
+ | Exemptions | `exemptIps`, `exemptPaths`, `autoExemptPathPrefixes` |
589
+ | GeoIP | `geoBlockEnabled`, `geoAllowedCountries`, `geoBlockedCountries`, `geoIpDatabasePath`, cache limits |
590
+ | Route manifest | `pathManifestEnabled`, `pathManifestPath`, `pathRules` |
591
+ | UUID checks | `uuidTamperEnabled`, `uuidScoreWindowSeconds`, `uuidScoreBlockThreshold`, signal weights, `uuidParameterNames` |
592
+ | AI | `aiEnabled`, `aiModelPath`, `aiAnomalyScoreThreshold` |
593
+ | Storage | `storageBackend`, `storageFilePath`, `storageRedisUrl`, `storageKeyPrefix`, `storageRedisFailureMode`, Redis timeout and pool limits |
594
+ | Telemetry | `observabilityEnabled` |
1445
595
 
1446
- server.route({ method: 'GET', path: '/', handler: () => 'Protected' });
1447
- await server.start();
1448
- ```
596
+ 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.
1449
597
 
1450
- ### Koa Usage
598
+ `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.
1451
599
 
1452
- ```js
1453
- const Koa = require('koa');
1454
- const bodyParser = require('koa-bodyparser');
1455
- const aiwaf = require('aiwaf');
600
+ 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.
1456
601
 
1457
- const app = new Koa();
1458
- app.use(bodyParser());
602
+ 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.
1459
603
 
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
- }));
604
+ 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.
1468
605
 
1469
- app.use(ctx => {
1470
- ctx.body = 'Protected';
1471
- });
606
+ Java operational commands mirror the common Python workflow:
1472
607
 
1473
- app.listen(3000);
608
+ ```bash
609
+ aiwaf-cli status
610
+ aiwaf-cli diagnose --model model.json
611
+ aiwaf-cli blocked
612
+ aiwaf-cli unblock 203.0.113.10
613
+ aiwaf-cli clear
614
+ aiwaf-cli train --events events.json --out model.json --backend java
615
+ aiwaf-cli replay --cases replay.json
616
+ aiwaf-cli model status --path model.json
617
+ aiwaf-cli logs --dir aiwaf_logs
1474
618
  ```
1475
619
 
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
- }
1497
- ```
620
+ Build Java from the repository root:
1498
621
 
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();
622
+ ```bash
623
+ cd java
624
+ mvn test
625
+ mvn -Dgpg.skip=true package
1519
626
  ```
1520
627
 
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();
1544
- ```
628
+ 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.
1545
629
 
1546
- ### Next.js (API Routes) Usage
630
+ ## Shared training schema
1547
631
 
1548
- Use the `aiwaf.next` helper to wrap a Next.js API route handler.
632
+ New training paths use these six features in this order:
1549
633
 
1550
- ```ts
1551
- import aiwaf from 'aiwaf';
634
+ 1. `path_len`
635
+ 2. `kw_hits`
636
+ 3. `resp_time`
637
+ 4. `status_idx`
638
+ 5. `burst_count`
639
+ 6. `total_404`
1552
640
 
1553
- function handler(req, res) {
1554
- res.status(200).json({ ok: true });
1555
- }
641
+ `resp_time` is expressed in seconds in feature vectors. Artifact summary fields explicitly named with `_ms` remain milliseconds.
1556
642
 
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
- ```
1566
-
1567
- ### AdonisJS Usage
1568
-
1569
- Register the middleware in your Adonis middleware stack:
643
+ The training lifecycle is:
1570
644
 
1571
- ```ts
1572
- import aiwaf from 'aiwaf';
645
+ 1. Parse configured access logs or middleware-generated request logs.
646
+ 2. Normalize request paths, status, timing, and per-IP state.
647
+ 3. Extract the six features and suspicious route segments.
648
+ 4. Train or update the Isolation Forest after configured volume thresholds are met.
649
+ 5. Refresh learned keywords while excluding known legitimate and exempt routes.
650
+ 6. Persist portable JSON forest state and runtime metadata; legacy language-specific artifacts remain read-only compatibility inputs.
1573
651
 
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
- ];
1584
- ```
652
+ 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.
1585
653
 
1586
- ### Sails.js Usage
654
+ ## Deployment guidance
1587
655
 
1588
- Use the Express-compatible middleware in your Sails `config/http.js`:
656
+ - Configure the application to trust forwarding headers only from known proxy CIDRs.
657
+ - Configure the outermost proxy to overwrite client-supplied forwarding headers.
658
+ - Use Redis, a database, or another shared backend when multiple workers must share rate-limit, blacklist, or exemption state.
659
+ - Keep health checks, static assets, and trusted webhook routes explicitly scoped instead of disabling protection globally.
660
+ - Start anomaly detection in observe-only or conservative mode and tune it with representative normal traffic.
661
+ - Rotate logs and exclude secrets, authorization headers, cookies, and personal data.
662
+ - Sign model/configuration artifacts where the runtime supports HMAC verification.
663
+ - Run AIWAF alongside normal secure-development controls and an edge/reverse-proxy layer.
1589
664
 
1590
- ```js
1591
- const aiwaf = require('aiwaf');
665
+ ## Development and tests
1592
666
 
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
- ```
667
+ ### Whole monorepo
1606
668
 
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:
669
+ Create a Python environment, install all adapters, then install Node dependencies:
1742
670
 
1743
671
  ```bash
1744
- AIWAF_ACCESS_LOG=/path/to/access.log npm run train
672
+ python -m pip install -e ".[django,flask,fastapi,rust]"
673
+ python -m pip install pytest pytest-cov coverage httpx
674
+ npm ci --prefix js
675
+ python aiwaf_test.py --coverage
1745
676
  ```
1746
677
 
1747
- Optional rotated/gz support:
678
+ Focused suites:
1748
679
 
1749
680
  ```bash
1750
- NODE_LOG_GLOB='/path/to/access.log.*' npm run train
681
+ python aiwaf_test.py --python-only
682
+ python aiwaf_test.py --rust-only
683
+ python aiwaf_test.py --js-only
684
+ python aiwaf_test.py --wasm-only
1751
685
  ```
1752
686
 
1753
- Training pipeline in `train.js`:
1754
-
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)
1768
-
1769
- ### Testing
687
+ Java is tested separately:
1770
688
 
1771
689
  ```bash
1772
- npm test
690
+ cd java
691
+ mvn test
1773
692
  ```
1774
693
 
1775
- Current tests cover:
694
+ ### Direct package commands
1776
695
 
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
696
+ ```bash
697
+ # Python
698
+ pytest
1786
699
 
1787
- ### Data and Persistence
700
+ # Node.js
701
+ npm ci --prefix js
702
+ npm test --prefix js
1788
703
 
1789
- #### Reputation-aware blacklist
704
+ # Rust core
705
+ cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core
1790
706
 
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:
707
+ # Rust Python API, after installing the local wheel
708
+ pytest -q rust/tests/test_python_api.py
1796
709
 
1797
- ```bash
1798
- npm run aiwaf -- blacklist cleanup
1799
- npm run aiwaf -- blacklist migrate
1800
- npm run aiwaf -- blacklist migrate --duration 24h
710
+ # Java
711
+ mvn -f java/pom.xml test
1801
712
  ```
1802
713
 
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
714
+ ### Benchmark
715
+
716
+ The in-process Flask benchmark compares a baseline app, `auto` middleware selection, and the full middleware chain:
1831
717
 
1832
718
  ```bash
1833
- npm install
1834
- npm test
1835
- npm run train
1836
- npm run aiwaf -- help
719
+ python -m benchmarks.benchmark_auto_middleware
720
+ python -m benchmarks.benchmark_auto_middleware --path-rules 250
721
+ python -m benchmarks.benchmark_auto_middleware --requests 200 --rounds 3 --warmup 50
1837
722
  ```
1838
723
 
1839
- ### Operations CLI
724
+ Use the same machine, environment, request count, and background load when comparing results. These measurements exclude network and production-server overhead.
1840
725
 
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
- ```
726
+ ## Release automation
1866
727
 
1867
- ### Sandbox (OWASP Juice Shop)
728
+ Release versions and tags must match the relevant manifest.
1868
729
 
1869
- The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF.
730
+ | Package | Manifest | Tag | Workflow |
731
+ | --- | --- | --- | --- |
732
+ | Python `aiwaf` | `pyproject.toml` | `python-v1.1.0` | `python-publish.yml` |
733
+ | npm `aiwaf` | `js/package.json` | `js-v1.1.0` | `npm-publish.yml` |
734
+ | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.1` | `rust-publish.yml` |
735
+ | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.1` | `wasm-publish.yml` |
736
+ | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.1` | `java-publish.yml` |
1870
737
 
1871
- ```bash
1872
- docker compose -f examples/sandbox/docker-compose.yml up --build
1873
- ```
738
+ Python and Rust publish to PyPI with trusted publishing. The npm workflows use npm trusted publishing and stage packages for approval. Configure the trusted publisher with organization `aiwaf-project`, repository `aiwaf`, the exact workflow filename, and the environment used by that workflow.
739
+
740
+ 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.
1874
741
 
1875
- Fastify proxy is also available on `http://localhost:3002`.
742
+ Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1876
743
 
1877
- ---
744
+ ## Security and limitations
1878
745
 
1879
- ## Acknowledgements
746
+ - Deterministic controls can produce false positives when legitimate routes resemble common probes; use narrow route exemptions and regression tests.
747
+ - Language-native Isolation Forest implementations can produce different scores for identical feature rows.
748
+ - WASM object conversion has overhead and is not automatically faster than JavaScript for small calls.
749
+ - In-memory rate limits and runtime stores are local to one process.
750
+ - GeoIP data can be missing, stale, or imprecise and should not be the sole authorization control.
751
+ - Post-response blocking cannot replace data already committed or streamed to a client.
752
+ - No WAF can compensate for broken authorization or unsafe application logic.
1880
753
 
1881
- GeoIP support uses the bundled IPinfo MMDB format for country mapping.
754
+ Report vulnerabilities privately to the maintainers rather than opening a public exploit issue.
1882
755
 
1883
- [DigitalOcean](https://www.digitalocean.com/) provides the cloud infrastructure that powers AIWAF development.
756
+ ## Contributing
1884
757
 
1885
- ---
758
+ 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.
1886
759
 
1887
760
  ## License
1888
761
 
1889
- MIT. See `LICENSE`.
762
+ AIWAF is distributed under the repository's single [`MIT License`](LICENSE). Published artifacts may contain a generated copy of this canonical file as required by their package registry.