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