aiwaf 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,1249 @@
1
- # aiwaf
1
+ # AIWAF
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.
6
+
7
+ AIWAF provides context-aware protection across Python and JavaScript runtimes,
8
+ with rate limiting, anomaly detection, honeypots, UUID tamper protection, smart
9
+ keyword learning, file-extension probing detection, exempt path/IP awareness,
10
+ and scheduled retraining.
11
+
12
+ This monorepo contains three independently published packages:
13
+
14
+ - `py/aiwaf/` and the root Python packaging files publish `aiwaf` to PyPI.
15
+ - `js/` publishes `aiwaf` to npm and supports Express, Fastify, Hapi, Koa, Next.js, NestJS, AdonisJS, and Sails.
16
+ - `rust/` publishes `aiwaf-rust` to PyPI as a separate package.
17
+
18
+ Install the JavaScript package with `npm install aiwaf`. Its usage, configuration, framework adapters, and operational commands are documented in [JavaScript Package](#javascript-package-aiwaf).
19
+
20
+ For local JavaScript development, run `npm ci` and `npm test` from `js/`. Releases are independent: push a `python-v*` tag (for example, `python-v1.0.8`) to publish the Python package to PyPI, a `js-v*` tag (for example, `js-v1.0.1`) to publish `aiwaf` to npm, or a `rust-v*` tag (for example, `rust-v0.2.1`) to publish `aiwaf-rust` to PyPI. The publish workflows can also be started manually from GitHub Actions.
21
+
22
+ Run the Python and JavaScript test suites with `python aiwaf_test.py`. Use `--python-only` or `--js-only` when working on one package. For the Rust core, run `cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core`.
23
+
24
+ ## Latest Enhancements
25
+
26
+ - Reputation-based IP blocking with weighted offenses and progressive block durations
27
+ - Automatic migration of legacy blacklist CSV formats with CLI tools to inspect, convert, or clear imported entries
28
+ - Request payload-field inference for generated route manifests
29
+ - Smart keyword filtering to avoid blocking legitimate paths like `/profile/`
30
+ - Granular reset controls for blacklist, keywords, and exemptions
31
+ - Context-aware learning that prioritizes suspicious traffic over normal routes
32
+ - Enhanced keyword controls via `AIWAF_ALLOWED_PATH_KEYWORDS` and `AIWAF_EXEMPT_KEYWORDS`
33
+ - Comprehensive HTTP method validation in honeypot logic
34
+ - Enhanced honeypot timing with page expiry/reload flow
35
+ - Header validation with quality scoring and bot-pattern detection
36
+
37
+ ---
38
+
39
+ ## Quick Installation
40
+
41
+ Python:
42
+
43
+ ```bash
44
+ pip install aiwaf
45
+ ```
46
+
47
+ JavaScript:
48
+
49
+ ```bash
50
+ npm install aiwaf
51
+ ```
52
+
53
+ Optional framework extras:
54
+
55
+ ```bash
56
+ pip install "aiwaf[django]"
57
+ pip install "aiwaf[flask]"
58
+ pip install "aiwaf[fastapi]"
59
+ pip install "aiwaf[rust]"
60
+ ```
61
+
62
+ Rust extra installs `aiwaf-rust`, which accelerates selected paths and is required
63
+ for persisted AI model inference from JSON `IsolationForest` artifacts.
64
+
65
+ Important:
66
+ - Use the adapter package for your framework (`aiwaf.django`, `aiwaf.flask`, or `aiwaf.fast`).
67
+ - For Django setup and command details, see `INSTALLATION.md` and `REPO_GUIDE_DJANGO.md`.
68
+
69
+ ---
70
+
71
+ ## System Requirements
72
+
73
+ - Python 3.8+
74
+ - CPU-only operation (no GPU required)
75
+ - Small deployments: ~1 vCPU and ~512 MB RAM
76
+ - Moderate deployments: 2 to 4 vCPU and 2 to 4 GB RAM recommended
77
+ - For production, schedule detect/train jobs and rotate logs
78
+
79
+ ---
80
+
81
+ ## Package Structure
82
+
83
+ ```text
84
+ py/
85
+ aiwaf/ # Python package (import name remains `aiwaf`)
86
+ core/ # framework-agnostic helpers and storage
87
+ django/ # Django adapter
88
+ flask/ # Flask adapter
89
+ fast/ # FastAPI adapter
90
+ js/ # JavaScript package, tests, and framework adapters
91
+ tests/ # Python test suites
92
+ examples/ # Python examples and sandbox tooling
93
+ ```
94
+
95
+ Contributor setup, test commands, and release conventions are documented in [`CONTRIBUTING.md`](CONTRIBUTING.md).
96
+
97
+ Framework entry points:
98
+
99
+ ```python
100
+ # Django
101
+ import aiwaf.django as aiwaf
102
+
103
+ # Flask
104
+ import aiwaf.flask as aiwaf
105
+
106
+ # FastAPI
107
+ import aiwaf.fast as aiwaf
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Features
113
+
114
+ - **IP blocklist**
115
+ - blocks known suspicious sources quickly
116
+ - supports runtime updates through adapter storage
117
+ - tracks reason history, reputation score, offense count, and expiration metadata
118
+ - uses progressive temporary blocks while retaining explicit permanent-block support
119
+ - automatically removes expired entries during blacklist checks
120
+
121
+ - **Rate limiting**
122
+ - sliding-window request control (`AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`)
123
+ - flood threshold support (`AIWAF_RATE_FLOOD`) for aggressive abuse
124
+
125
+ - **AI anomaly detection**
126
+ - IsolationForest-based behavioral detection
127
+ - model training updates as traffic grows
128
+ - persisted runtime models use JSON-only artifacts; Rust `IsolationForest` is required for saved-model inference
129
+
130
+ - **Dynamic keyword learning**
131
+ - learns suspicious path terms from attack-like traffic
132
+ - excludes exempt/allowed terms to reduce false positives
133
+
134
+ - **File-extension probing detection**
135
+ - detects repeated probes for extensions like `.php`, `.asp`, `.jsp`
136
+
137
+ - **Header validation**
138
+ - missing required-header detection
139
+ - suspicious user-agent and header-combination checks
140
+ - header quality scoring
141
+ - static-asset exemption support
142
+
143
+ - **Enhanced honeypot timing**
144
+ - GET to POST timing checks via `AIWAF_MIN_FORM_TIME`
145
+ - page-age validation via `AIWAF_MAX_PAGE_TIME`
146
+ - method-misuse checks (for example POST to read-only endpoints)
147
+
148
+ - **UUID tamper protection**
149
+ - score-based UUID abuse detection
150
+ - malformed UUIDs add high score and can block immediately
151
+ - valid UUID requests that repeatedly end in `404` increase score
152
+ - score decays on successful UUID requests
153
+ - blocks when per-IP UUID score crosses threshold
154
+
155
+ - **GeoIP support**
156
+ - optional country-level allow/block behavior
157
+ - local bundled MMDB support by default
158
+
159
+ - **Built-in logging path**
160
+ - adapter-level request logging can feed training when primary access logs are unavailable
161
+
162
+ - **Blocked-request debug logging**
163
+ - captures reason, IP, method, path, and user-agent in debug mode
164
+
165
+ ---
166
+
167
+ ## Header Validation Details
168
+
169
+ What it detects:
170
+ - missing core browser-like headers
171
+ - low-diversity header sets typical of simple bots
172
+ - suspicious or automation-focused user agents
173
+ - unrealistic header combinations
174
+
175
+ What it allows:
176
+ - normal browser traffic with complete headers
177
+ - well-identified clients and known legitimate bots
178
+ - static file requests when exempt patterns are configured
179
+
180
+ Useful test pattern:
181
+
182
+ ```bash
183
+ # often low-quality header profile
184
+ curl http://your-app.example/
185
+
186
+ # compare against normal browser traffic
187
+ ```
188
+
189
+ ---
190
+
191
+ ## Exemptions and Safe Routing
192
+
193
+ AIWAF supports:
194
+ - exempt paths (`AIWAF_EXEMPT_PATHS`)
195
+ - exempt IPs (adapter-managed allowlists)
196
+ - exempt keywords (`AIWAF_EXEMPT_KEYWORDS`)
197
+ - allowed route keywords (`AIWAF_ALLOWED_PATH_KEYWORDS`)
198
+
199
+ Effects of exemption:
200
+ - excluded from keyword learning
201
+ - bypass of selected blocking paths
202
+ - reduced false positives on trusted operational routes (webhooks, health, static assets)
203
+
204
+ Decorator-based exemptions:
205
+ - Django adapter and Flask adapter both expose exemption decorators in their adapter modules.
206
+
207
+ ---
208
+
209
+ ## Training and Retraining
210
+
211
+ Training pipeline:
212
+ 1. Read configured access logs or adapter logger output
213
+ 2. Detect suspicious patterns (including heavy 404 probe behavior)
214
+ 3. Train/update IsolationForest when AI thresholds are met
215
+ 4. Refresh dynamic keywords from suspicious traffic
216
+ 5. Remove exempt/allowed noise from learned keyword set
217
+
218
+ Thresholds:
219
+ - `AIWAF_MIN_AI_LOGS` default 10,000 for full AI training
220
+ - `AIWAF_MIN_TRAIN_LOGS` default 50 for keyword-focused fallback
221
+ - `AIWAF_FORCE_AI_TRAINING` can override AI threshold gating
222
+
223
+ Daily retraining is recommended for active internet-facing workloads.
224
+
225
+ Model persistence is intentionally JSON-only. AIWAF does not load Python object
226
+ model artifacts (`pickle`, `joblib`, or `skops`) because those formats can
227
+ execute code during deserialization. Scikit-learn models may be used during a
228
+ training run for immediate analysis, but they are not persisted. To persist and
229
+ reload runtime AI models, install the Rust package so
230
+ `aiwaf_rust.IsolationForest` can save/load JSON state. The old bundled
231
+ `model.pkl` artifacts have been
232
+ removed; retrain to generate a `model.json` artifact.
233
+
234
+ ---
235
+
236
+ ## Configuration (`AIWAF_*`)
237
+
238
+ AIWAF uses flat `AIWAF_*` settings/config keys.
239
+ Some knobs are adapter-specific; core controls are shared.
240
+
241
+ Required in most deployments:
242
+
243
+ ```python
244
+ AIWAF_ACCESS_LOG = "/var/log/nginx/access.log"
245
+ ```
246
+
247
+ Core defaults (examples):
248
+
249
+ ```python
250
+ AIWAF_DISABLE_AI = False
251
+ AIWAF_MIN_AI_LOGS = 10000
252
+ AIWAF_MIN_TRAIN_LOGS = 50
253
+ AIWAF_FORCE_AI_TRAINING = False
254
+ AIWAF_AI_CONTAMINATION = 0.05
255
+
256
+ AIWAF_RATE_WINDOW = 10
257
+ AIWAF_RATE_MAX = 20
258
+ AIWAF_RATE_FLOOD = 10
259
+ AIWAF_WINDOW_SECONDS = 60
260
+
261
+ AIWAF_MIN_FORM_TIME = 1.0
262
+ AIWAF_MAX_PAGE_TIME = 240
263
+ AIWAF_FILE_EXTENSIONS = [".php", ".asp", ".jsp"]
264
+
265
+ AIWAF_UUID_SCORE_ENABLED = True
266
+ AIWAF_UUID_SCORE_WINDOW_SECONDS = 60
267
+ AIWAF_UUID_SCORE_BLOCK_THRESHOLD = 5
268
+ AIWAF_UUID_SCORE_MALFORMED_WEIGHT = 5
269
+ AIWAF_UUID_SCORE_NOT_FOUND_WEIGHT = 1
270
+ AIWAF_UUID_SCORE_SUCCESS_DECAY = 2
271
+
272
+ AIWAF_ALLOWED_PATH_KEYWORDS = ["profile", "user", "account", "dashboard"]
273
+ AIWAF_EXEMPT_KEYWORDS = ["api", "webhook", "health", "static", "media"]
274
+ AIWAF_EXEMPT_PATHS = ["/favicon.ico", "/robots.txt", "/static/", "/health/"]
275
+ ```
276
+
277
+ Model storage:
278
+
279
+ ```python
280
+ AIWAF_MODEL_PATH = "aiwaf/resources/model.json"
281
+ AIWAF_MODEL_STORAGE = "file" # file | db | cache
282
+ AIWAF_MODEL_CACHE_KEY = "aiwaf:model"
283
+ AIWAF_MODEL_CACHE_TIMEOUT = None
284
+ AIWAF_MODEL_STORAGE_FALLBACK = True
285
+ ```
286
+
287
+ Only JSON-serializable model artifacts are saved. Python object model artifacts
288
+ are rejected by design.
289
+
290
+ Header controls:
291
+
292
+ ```python
293
+ AIWAF_REQUIRED_HEADERS = None # list or method->list mapping
294
+ AIWAF_HEADER_QUALITY_MIN_SCORE = 3
295
+ ```
296
+
297
+ GeoIP:
298
+
299
+ ```python
300
+ AIWAF_GEO_BLOCK_ENABLED = False
301
+ AIWAF_GEOIP_DB_PATH = "py/aiwaf/core/geolock/ipinfo_lite.mmdb"
302
+ AIWAF_GEO_BLOCK_COUNTRIES = ["CN", "RU"]
303
+ AIWAF_GEO_ALLOW_COUNTRIES = []
304
+ AIWAF_GEO_CACHE_SECONDS = 3600
305
+ AIWAF_GEO_CACHE_PREFIX = "aiwaf:geo:"
306
+ ```
307
+
308
+ Rust acceleration:
309
+
310
+ ```python
311
+ AIWAF_RUST_ISOLATION_FOREST = True
312
+ ```
313
+
314
+ When `aiwaf_rust` is importable, AIWAF automatically uses its supported
315
+ accelerators. No `AIWAF_USE_RUST` setting is required. Python fallback remains
316
+ automatic when the package or a particular Rust capability is unavailable.
317
+ Persisted AI model loading requires a JSON artifact; the Rust `IsolationForest`
318
+ backend provides the supported JSON model state. Pickle-based `model.pkl`
319
+ artifacts are no longer shipped or loaded.
320
+
321
+ Legacy compatibility:
322
+ - if you still use nested `AIWAF_SETTINGS`, AIWAF maps common keys into flat `AIWAF_*` values at startup.
323
+
324
+ ---
325
+
326
+ ## Middleware Setup
327
+
328
+ Order matters in all adapters. Put protection middleware early and logging middleware near the end.
329
+
330
+ ### Unified `all` / `auto` Selection
331
+
332
+ AIWAF now supports a centralized "enable everything with smart defaults" mode across adapters.
333
+
334
+ - FastAPI and Flask: pass `middlewares=["all"]` (or `["auto"]`)
335
+ - Django: use `"aiwaf.django.middleware.all"` in `MIDDLEWARE`
336
+
337
+ Auto behavior:
338
+ - logging middleware is enabled when `AIWAF_ACCESS_LOG` is missing/empty
339
+ - logging middleware is disabled when `AIWAF_ACCESS_LOG` is configured
340
+ - geo middleware is enabled when any of these are true:
341
+ - explicit geo enable flag is on
342
+ - static geo block list has countries
343
+ - dynamic geo block store/table has countries
344
+
345
+ Django example order:
346
+
347
+ ```python
348
+ MIDDLEWARE = [
349
+ "aiwaf.django.middleware.JsonExceptionMiddleware",
350
+ "aiwaf.django.middleware.GeoBlockMiddleware",
351
+ "aiwaf.django.middleware.IPAndKeywordBlockMiddleware",
352
+ "aiwaf.django.middleware.RateLimitMiddleware",
353
+ "aiwaf.django.middleware.AIAnomalyMiddleware",
354
+ "aiwaf.django.middleware.HoneypotTimingMiddleware",
355
+ "aiwaf.django.middleware.UUIDTamperMiddleware",
356
+ "aiwaf.django.middleware.HeaderValidationMiddleware",
357
+ "aiwaf.django.middleware_logger.AIWAFLoggerMiddleware",
358
+ ]
359
+ ```
360
+
361
+ If JSON API clients need JSON 403 bodies, keep `JsonExceptionMiddleware` near the top.
362
+
363
+ Django alias example:
364
+
365
+ ```python
366
+ MIDDLEWARE = [
367
+ "django.middleware.security.SecurityMiddleware",
368
+ "aiwaf.django.middleware.all",
369
+ ]
370
+ ```
371
+
372
+ FastAPI quick integration:
373
+
374
+ ```python
375
+ from fastapi import FastAPI
376
+ from aiwaf.fast import AIWAF
377
+
378
+ app = FastAPI()
379
+
380
+ aiwaf = AIWAF(
381
+ app,
382
+ middlewares=["all"],
383
+ storage={"backend": "memory"},
384
+ header_validation={"enabled": True, "quality_threshold": 3},
385
+ rate_limiting={"enabled": True, "window_seconds": 10, "max_requests": 20},
386
+ logging_middleware={"enabled": True, "log_dir": "aiwaf_logs", "log_format": "json"},
387
+ )
388
+ ```
389
+
390
+ Flask quick integration:
391
+
392
+ ```python
393
+ from flask import Flask
394
+ from aiwaf.flask import AIWAF
395
+
396
+ app = Flask(__name__)
397
+ aiwaf = AIWAF(app, middlewares=["all"])
398
+ ```
399
+
400
+ ---
401
+
402
+ ## Operations
403
+
404
+ Django adapter examples:
405
+
406
+ ```bash
407
+ python manage.py detect_and_train
408
+ python manage.py regenerate_model
409
+ python manage.py aiwaf_reset --keywords --confirm
410
+ python manage.py add_ipexemption 203.0.113.10 --reason "trusted integration"
411
+ python manage.py add_pathexemption /api/webhooks/ --reason "partner callbacks"
412
+ python manage.py aiwaf_logging --status
413
+ python manage.py geo_block_country list
414
+ python manage.py geo_block_country add US
415
+ python manage.py geo_block_country remove US
416
+ ```
417
+
418
+ Flask adapter:
419
+ - use `aiwaf.flask.AIWAF` for middleware registration
420
+ - use `aiwaf.flask.cli.AIWAFManager` for CSV-backed operational tasks
421
+
422
+ FastAPI adapter:
423
+ - use `aiwaf.fast.AIWAF` for middleware registration
424
+ - use `aiwaf fast ...` or `aiwaf-fast ...` for CLI operations
425
+
426
+ ### Django Command Reference
427
+
428
+ Common management commands:
429
+
430
+ ```bash
431
+ python manage.py detect_and_train
432
+ python manage.py regenerate_model
433
+ python manage.py aiwaf_reset --confirm
434
+ python manage.py aiwaf_reset --blacklist --confirm
435
+ python manage.py aiwaf_reset --keywords --confirm
436
+ python manage.py aiwaf_reset --exemptions --confirm
437
+ python manage.py add_ipexemption <ip> --reason "optional reason"
438
+ python manage.py add_pathexemption /path/prefix/ --reason "optional reason"
439
+ python manage.py aiwaf_pathshell
440
+ python manage.py aiwaf_logging --status
441
+ python manage.py geo_block_country list
442
+ python manage.py geo_block_country add US
443
+ python manage.py geo_block_country remove US
444
+ python manage.py aiwaf_diagnose
445
+ ```
446
+
447
+ `aiwaf_pathshell` helpers:
448
+
449
+ ```text
450
+ ls # list path tree at current node
451
+ cd <index|name> # enter child path node
452
+ up / cd .. # move up
453
+ pwd # current path prefix
454
+ exempt <index|name|.> # add exemption for selected/current path
455
+ exit # quit shell
456
+ ```
457
+
458
+ ### Flask Adapter Reference
459
+
460
+ Programmatic integration:
461
+
462
+ ```python
463
+ from flask import Flask
464
+ from aiwaf.flask import AIWAF
465
+
466
+ app = Flask(__name__)
467
+ app.config["AIWAF_GEO_BLOCK_ENABLED"] = False
468
+ app.config["AIWAF_MIN_AI_LOGS"] = 10000
469
+
470
+ aiwaf = AIWAF(
471
+ app,
472
+ middlewares=[
473
+ "logging",
474
+ "header_validation",
475
+ "ip_keyword_block",
476
+ "rate_limit",
477
+ "geo_block",
478
+ "ai_anomaly",
479
+ "uuid_tamper",
480
+ ],
481
+ )
482
+ ```
483
+
484
+ Optional Flask CLI manager:
485
+
486
+ ```bash
487
+ python -m aiwaf.flask.cli list all
488
+ python -m aiwaf.flask.cli add whitelist 203.0.113.10
489
+ python -m aiwaf.flask.cli add blacklist 203.0.113.99 --reason "manual test"
490
+ python -m aiwaf.flask.cli add keyword ../etc/passwd
491
+ python -m aiwaf.flask.cli status
492
+ python -m aiwaf.flask.cli blocked
493
+ python -m aiwaf.flask.cli unblock 203.0.113.99
494
+ python -m aiwaf.flask.cli clear
495
+ ```
496
+
497
+ Blacklist migration commands:
498
+
499
+ ```bash
500
+ # Detect the configured backend and upgrade legacy rows
501
+ aiwaf flask blacklist migrate --app myapp:app
502
+ aiwaf fast blacklist migrate --app myapp:app
503
+ aiwaf django blacklist migrate
504
+
505
+ # Inspect all entries or only legacy imports
506
+ python -m aiwaf.flask.cli blacklist list
507
+ python -m aiwaf.flask.cli blacklist list --legacy
508
+
509
+ # Convert legacy permanent entries to temporary blocks (default: 24h)
510
+ python -m aiwaf.flask.cli blacklist convert-legacy
511
+ python -m aiwaf.flask.cli blacklist convert-legacy --duration 1d
512
+
513
+ # Remove only legacy-imported entries
514
+ python -m aiwaf.flask.cli blacklist clear-legacy
515
+ ```
516
+
517
+ Durations accept seconds or an `s`, `m`, `h`, or `d` suffix, such as `900`,
518
+ `15m`, `24h`, or `1d`. Old headered and headerless blacklist CSV layouts are
519
+ upgraded automatically. Imported legacy rows remain permanent until explicitly
520
+ converted or cleared.
521
+
522
+ #### Upgrading an Existing Blocklist
523
+
524
+ Back up the database or AIWAF data directory before upgrading. Existing entries
525
+ should be preserved as permanent blocks unless you deliberately convert them to
526
+ temporary blocks.
527
+
528
+ | Framework/storage | Schema update | Existing entries |
529
+ |---|---|---|
530
+ | Django ORM | Run Django migrations, then `aiwaf django blacklist migrate` | Command backfills the new reputation fields |
531
+ | Flask SQLAlchemy | Run the application's Alembic/Flask-Migrate migration, then `aiwaf flask blacklist migrate --app ...` | Command backfills the new fields |
532
+ | Flask `blacklist.csv` | `aiwaf flask blacklist migrate --app ...` | Imported as permanent; use `convert-legacy` to make them temporary |
533
+ | Django/FastAPI shared `csv`, `file`, or `db` runtime backend | `aiwaf django blacklist migrate` or `aiwaf fast blacklist migrate --app ...` | Command upgrades legacy key/value records in place |
534
+
535
+ Django ORM:
536
+
537
+ ```bash
538
+ # Generate and apply the model-column migration in the Django project.
539
+ python manage.py makemigrations aiwaf
540
+ python manage.py migrate aiwaf
541
+
542
+ aiwaf django blacklist migrate
543
+ # Equivalent:
544
+ python manage.py aiwaf_migrate_blacklist
545
+ ```
546
+
547
+ The command detects `AIWAF_STORAGE_MODE`. In ORM mode it verifies that the new
548
+ columns exist and backfills legacy rows. In CSV mode it upgrades the configured
549
+ runtime store. It stops with the exact schema-migration instruction if ORM
550
+ columns are still missing.
551
+
552
+ Flask SQLAlchemy ORM:
553
+
554
+ ```bash
555
+ # db.create_all() does not alter an existing table.
556
+ flask db migrate -m "add AIWAF blacklist reputation fields"
557
+ flask db upgrade
558
+ aiwaf flask blacklist migrate --app myapp:app
559
+ ```
560
+
561
+ The Flask command loads the application so it can inspect `AIWAF_USE_CSV` and
562
+ the initialized SQLAlchemy extension. It migrates CSV directly, or verifies and
563
+ backfills the ORM table. If ORM columns are missing, it stops and asks for the
564
+ application-owned Alembic/Flask-Migrate migration; AIWAF does not silently alter
565
+ an application's relational schema.
566
+
567
+ Migration is optional for runtime compatibility. Until it is run, Django and
568
+ Flask ORM adapters detect the deployed table columns and continue using the
569
+ legacy `ip`/`reason` behavior. FastAPI and the shared runtime backends continue
570
+ to recognize old reason-only `blocked:*` values as permanent blocks. New
571
+ reputation metadata takes effect after migration or when a legacy runtime value
572
+ is updated. This fallback prevents a package upgrade from silently unblocking
573
+ existing IPs.
574
+
575
+ For Flask CSV storage, set `AIWAF_DATA_DIR` (or Flask
576
+ `AIWAF_DATA_DIR`) to the directory containing the current `blacklist.csv`
577
+ before running the migration commands. Reading the file rewrites old layouts
578
+ to the current columns. The migration recognizes old headered layouts such as
579
+ `ip,reason,added_date,extended_request_info` and `ip,timestamp,reason`, plus
580
+ headerless `ip[,reason]` rows.
581
+
582
+ For Django CSV and FastAPI, the shared runtime backends use key/value storage
583
+ (`runtime_store.csv`, JSON/file storage, or the `kv_store` SQLite table), so
584
+ there are no ORM columns to add. Keep the configured data path unchanged and
585
+ run the matching migration command. For FastAPI without an importable app, pass
586
+ the backend explicitly, for example:
587
+
588
+ ```bash
589
+ aiwaf fast blacklist migrate --backend csv --storage-path aiwaf_data/runtime_store.csv
590
+ aiwaf fast blacklist migrate --backend db --storage-path aiwaf_data/aiwaf_data.db
591
+ ```
592
+
593
+ ### FastAPI Adapter Reference
594
+
595
+ Programmatic integration:
596
+
597
+ ```python
598
+ from fastapi import FastAPI
599
+ from aiwaf.fast import AIWAF
600
+
601
+ app = FastAPI()
602
+ AIWAF(app)
603
+ ```
604
+
605
+ CLI usage:
606
+
607
+ ```bash
608
+ aiwaf fast --help
609
+ aiwaf-fast --help
610
+ ```
611
+
612
+ ### Path-Specific Rules
613
+
614
+ AIWAF can generate a route manifest at `.aiwaf/paths.json` and compile it into
615
+ runtime path rules. This is the preferred 1.0 workflow because framework-specific
616
+ route extraction happens once during init, not on every request.
617
+
618
+ Generate a manifest:
619
+
620
+ ```bash
621
+ # Django
622
+ python manage.py aiwaf init
623
+
624
+ # Flask
625
+ aiwaf flask init --app myapp:app
626
+
627
+ # FastAPI
628
+ aiwaf fast init --app myapp:app
629
+
630
+ # Unified entrypoint
631
+ aiwaf init
632
+ aiwaf init --app myapp:app
633
+ aiwaf init --framework flask --app myapp:app
634
+ aiwaf init --framework django --settings myproject.settings
635
+ ```
636
+
637
+ `aiwaf init` auto-detects the framework when exactly one supported framework is
638
+ installed. If multiple supported frameworks are installed, pass `--app` for
639
+ Flask/FastAPI projects or `--framework` to choose the adapter explicitly.
640
+ For Django, run from the project root containing `manage.py`, set
641
+ `DJANGO_SETTINGS_MODULE`, or pass `--settings`.
642
+
643
+ During init, AIWAF uses framework metadata first and then bounded static source
644
+ analysis when metadata is missing. It can infer:
645
+
646
+ - route methods from Flask/FastAPI routers, DRF actions, Django CBVs, decorators, and view source
647
+ - auth endpoints from signals such as `authenticate`, `login`, `login_user`, `OAuth2PasswordRequestForm`, and helper calls
648
+ - API endpoints from combined signals such as `/api/` paths, DRF `APIView`/`ViewSet`, Flask JSON endpoints, FastAPI route metadata, Pydantic/body models, `request.body`, `request.data`, `request.json`, and JSON content-type expectations
649
+ - form endpoints from `request.POST`, `request.form`, Django `Form`/`ModelForm`, `render`, `render_template`, `redirect`, and mixed HTML/JSON response flows
650
+ - literal payload field names from form/JSON access such as `payload.get("email")`, `request.form["password"]`, and equivalent aliases
651
+ - upload/static/app routes from path and source signals
652
+
653
+ Detector output is explainable: generated routes can include confidence scores
654
+ and the exact signals used for auth/API/form classification. Response type alone
655
+ does not force API classification; payload type is preferred. For example, a
656
+ contact form that redirects on success and returns `JsonResponse` on validation
657
+ failure is classified as `category: "form"`, `response_type: "mixed"`, and
658
+ `payload_type: "form"`.
659
+
660
+ Manifest shape:
661
+
662
+ ```json
663
+ {
664
+ "schema_version": "1.0",
665
+ "framework": "flask",
666
+ "context_hash": "sha256...",
667
+ "routes": {
668
+ "/api/users/": {
669
+ "methods": ["GET", "POST"],
670
+ "view": "myapp.users",
671
+ "category": "api",
672
+ "response_type": "json",
673
+ "payload_type": "json",
674
+ "payload_fields": ["email", "message"],
675
+ "auth_required": false,
676
+ "api_confidence": 0.94,
677
+ "api_signals": ["path:/api", "JsonResponse", "request.body"],
678
+ "request_body": true,
679
+ "protections": {
680
+ "rate_limit": {"requests": 120, "window_seconds": 60},
681
+ "api_rate_limit": {"requests": 120, "window_seconds": 60},
682
+ "payload_validation": {"max_body_bytes": 1048576, "max_json_depth": 8},
683
+ "content_type_validation": {"require_valid_content_type": true},
684
+ "honeypot": {"enabled": false}
685
+ }
686
+ },
687
+ "/contact/": {
688
+ "methods": ["GET", "POST"],
689
+ "view": "myapp.contact",
690
+ "category": "form",
691
+ "response_type": "mixed",
692
+ "payload_type": "form",
693
+ "auth_required": false,
694
+ "form_confidence": 0.75,
695
+ "form_signals": ["request.POST", "render", "redirect"],
696
+ "request_body": true,
697
+ "protections": {
698
+ "rate_limit": {"requests": 30, "window_seconds": 60},
699
+ "payload_validation": {"max_body_bytes": 1048576},
700
+ "honeypot": {"enabled": true}
701
+ }
702
+ },
703
+ "/login/": {
704
+ "methods": ["GET", "POST"],
705
+ "view": "accounts.views.login_view",
706
+ "category": "auth",
707
+ "response_type": "html",
708
+ "auth_required": false,
709
+ "auth_action": "login",
710
+ "auth_confidence": 0.9,
711
+ "auth_signals": ["django.contrib.auth.authenticate", "django.contrib.auth.login", "POST"],
712
+ "protections": {
713
+ "rate_limit": {"requests": 30, "window_seconds": 60},
714
+ "honeypot": {"enabled": true}
715
+ }
716
+ }
717
+ }
718
+ }
719
+ ```
720
+
721
+ Method and category detection is deterministic but still best-effort for highly
722
+ dynamic code. For maximum accuracy, use framework method decorators such as
723
+ Django `@require_http_methods`, explicit Flask route methods, and FastAPI
724
+ `@app.get` / `@app.post` decorators.
725
+
726
+ You can still define manual path rules to selectively disable middleware or
727
+ override rate limits without globally weakening protection:
728
+
729
+ ```python
730
+ AIWAF_SETTINGS = {
731
+ "PATH_RULES": [
732
+ {
733
+ "PREFIX": "/api/webhooks/",
734
+ "DISABLE": ["HeaderValidationMiddleware"],
735
+ "RATE_LIMIT": {"WINDOW": 60, "MAX": 2000},
736
+ },
737
+ {
738
+ "PREFIX": "/api/public/",
739
+ "RATE_LIMIT": {"WINDOW": 60, "MAX": 500},
740
+ },
741
+ ]
742
+ }
743
+ ```
744
+
745
+ Rules are matched by path prefix, and the most specific matching rule applies.
746
+ Manual rules are applied before generated manifest rules. Path rules are compiled
747
+ and cached. If a running application mutates its rules in place, increment
748
+ `AIWAF_ROUTE_PLAN_VERSION` (Flask/Django) or `route_plan_version` (FastAPI) so
749
+ cached plans are rebuilt. Replacing the rules list with a new object recompiles
750
+ it automatically.
751
+
752
+ ### Blocking Behavior
753
+
754
+ - Default behavior: blocked requests raise `PermissionDenied("blocked")` and return `403`.
755
+ - For JSON APIs (Django): `JsonExceptionMiddleware` converts blocked JSON requests into JSON `403` payloads.
756
+ - Rate limiting can emit `429` for soft throttling paths while still escalating repeated abuse to blacklist flow.
757
+ - Reputation scores accumulate by reason (for example SQL injection, XSS, scanner, brute-force, rate-limit, honeypot, UUID, header, geo, and keyword events).
758
+ - The default reputation threshold is 60. Qualifying blocks progress from 15 minutes to 1 hour and then 24 hours for repeated or high-score abuse.
759
+ - Storage backends persist score, offenses, reason history, block/expiry timestamps, duration, permanence, and extended request details.
760
+ - Passing a positive duration creates a temporary block; the runtime storage API treats a non-positive duration as an explicit permanent block.
761
+
762
+ ### Rate Limiting Cache (Multi-worker)
763
+
764
+ By default, Flask and FastAPI rate limiting uses an in-process cache (per worker). For multi-worker / multi-instance
765
+ deployments, configure the rate limiter to use Redis so all workers share the same counters.
766
+
767
+ **Flask**
768
+
769
+ ```python
770
+ app.config["AIWAF_RATE_CACHE_BACKEND"] = "redis"
771
+ app.config["AIWAF_REDIS_URL"] = "redis://localhost:6379/0"
772
+ # Optional (defaults to "aiwaf:rate:")
773
+ app.config["AIWAF_RATE_CACHE_KEY_PREFIX"] = "aiwaf:rate:"
774
+ ```
775
+
776
+ **FastAPI**
777
+
778
+ ```python
779
+ from aiwaf.fast import AIWAF
780
+
781
+ AIWAF(
782
+ app,
783
+ rate_limiting={
784
+ "enabled": True,
785
+ "cache_backend": "redis",
786
+ "redis_url": "redis://localhost:6379/0",
787
+ "cache_key_prefix": "aiwaf:rate:", # optional
788
+ },
789
+ )
790
+ ```
791
+
792
+ Environment variables (both adapters):
793
+
794
+ ```bash
795
+ set AIWAF_RATE_CACHE_BACKEND=redis
796
+ set AIWAF_REDIS_URL=redis://localhost:6379/0
797
+ set AIWAF_RATE_CACHE_KEY_PREFIX=aiwaf:rate:
798
+ ```
799
+
800
+ ### Logging and Training Data Sources
801
+
802
+ AIWAF trainer can pull from:
803
+
804
+ 1. `AIWAF_ACCESS_LOG` (primary, supports rotated/gzipped parsing where applicable)
805
+ 2. middleware-captured logs (CSV/DB depending on adapter settings)
806
+
807
+ This enables training even when reverse proxy logs are unavailable.
808
+
809
+ ---
810
+
811
+ ## Sandbox and Benchmarking
812
+
813
+ The sandbox in `examples/sandbox/` provides:
814
+
815
+ - `direct` (no AIWAF)
816
+ - `protected_django`
817
+ - `protected_flask`
818
+ - `protected_fastapi`
819
+
820
+ Run full benchmark:
821
+
822
+ ```bash
823
+ cd examples/sandbox
824
+ python run-and-compare.py -n 5
825
+ ```
826
+
827
+ Generated outputs:
828
+
829
+ - `results_direct_*.json`
830
+ - `results_protected_django_*.json`
831
+ - `results_protected_flask_*.json`
832
+ - `comparison_modes_*.json`
833
+ - `comparison_aggregate_*.json`
834
+
835
+ Interpretation guidance:
836
+
837
+ - `direct` should show low/zero block rate for attacks (baseline)
838
+ - protected targets should keep normal traffic blocking near `0%`
839
+ - compare attack blocked% and median latency across iterations, not single-run averages
840
+
841
+ ---
842
+
843
+ ## Publish Checklist
844
+
845
+ Before publishing a new package version:
846
+
847
+ 1. run the Python and JavaScript test suites
848
+ 2. validate sandbox comparison (`run-and-compare.py -n 3` minimum)
849
+ 3. bump the Python version in both `pyproject.toml` and `setup.py`, or the JavaScript version in `js/package.json`
850
+ 4. build artifacts (`python -m build`)
851
+ 5. smoke-test wheel install in clean virtualenv
852
+ 6. verify the README and package metadata match actual behavior
853
+
854
+ ---
855
+
856
+ ## Reset and Recovery
857
+
858
+ Granular reset (Django adapter):
859
+
860
+ ```bash
861
+ python manage.py aiwaf_reset --blacklist
862
+ python manage.py aiwaf_reset --keywords
863
+ python manage.py aiwaf_reset --exemptions
864
+ python manage.py aiwaf_reset --blacklist --keywords
865
+ python manage.py aiwaf_reset --confirm
866
+ ```
867
+
868
+ Common recovery path for false positives:
869
+ 1. clear learned keywords
870
+ 2. add legitimate route terms to `AIWAF_ALLOWED_PATH_KEYWORDS`
871
+ 3. add never-block terms to `AIWAF_EXEMPT_KEYWORDS`
872
+ 4. retrain
873
+
874
+ ---
875
+
876
+ ## Troubleshooting
877
+
878
+ ### Legitimate pages blocked
879
+
880
+ Cause:
881
+ - learned keywords included legitimate app vocabulary
882
+
883
+ Fix:
884
+
885
+ ```bash
886
+ python manage.py aiwaf_reset --keywords --confirm
887
+ python manage.py detect_and_train
888
+ ```
889
+
890
+ Then tune:
891
+ - `AIWAF_ALLOWED_PATH_KEYWORDS`
892
+ - `AIWAF_EXEMPT_KEYWORDS`
893
+
894
+ ### AI model not training
895
+
896
+ - verify log path and permissions
897
+ - check volume vs `AIWAF_MIN_AI_LOGS` / `AIWAF_MIN_TRAIN_LOGS`
898
+ - use `AIWAF_FORCE_AI_TRAINING=True` only when appropriate
899
+ - install `aiwaf-rust` for persisted runtime ML inference and JSON model artifacts
900
+
901
+ ### Geo-blocking not active
902
+
903
+ - verify `AIWAF_GEO_BLOCK_ENABLED=True`
904
+ - verify `AIWAF_GEOIP_DB_PATH`
905
+ - confirm geo middleware is enabled in your adapter chain
906
+
907
+ ### Rust mode appears inactive
908
+
909
+ - verify environment can import Rust extension
910
+ - fallback to Python is expected on Rust import/runtime failure
911
+
912
+ ---
913
+
914
+ ## How It Works
915
+
916
+ | Layer | Purpose |
917
+ |---|---|
918
+ | Geo blocking | Country-level allow/block filtering |
919
+ | IP/keyword block | Known-bad source and keyword defense |
920
+ | Rate limiting | Burst/flood control in sliding windows |
921
+ | AI anomaly | ML-based behavior outlier detection |
922
+ | Honeypot timing | Automation/timing/method misuse checks |
923
+ | UUID tamper | Score-based malformed UUID + repeated UUID-404 abuse detection |
924
+ | Header validation | Bot-like header profile detection |
925
+ | Request logger | Optional telemetry capture for analysis/training |
926
+
927
+ ---
928
+
929
+ ## Request Lifecycle (Detailed)
930
+
931
+ For a typical protected request:
932
+
933
+ 1. Request enters adapter middleware chain.
934
+ 2. Path/view/IP exemption checks run first.
935
+ 3. Header validation evaluates required headers and quality score.
936
+ 4. IP/keyword checks apply static + learned rules.
937
+ 5. Rate limit checks apply window/flood logic.
938
+ 6. Geo checks apply country allow/block rules (if enabled).
939
+ 7. AI anomaly evaluates extracted behavior features (if enabled and model available).
940
+ 8. Honeypot timing/method checks evaluate form timing and method misuse.
941
+ 9. UUID tamper checks validate UUID format and apply score-based repeated-miss detection.
942
+ 10. Optional logger records request/response metadata.
943
+
944
+ If any blocking stage denies request:
945
+ - status is typically `403` (`PermissionDenied("blocked")`)
946
+ - JSON APIs can receive JSON-formatted `403` via JSON exception middleware
947
+ - some throttle paths may return `429`
948
+
949
+ ---
950
+
951
+ ## Middleware Notes
952
+
953
+ `IPAndKeywordBlockMiddleware`:
954
+ - blocks already-blacklisted IPs quickly
955
+ - checks static suspicious keywords and learned dynamic keywords
956
+ - supports exempt keywords and allowed-path keyword logic
957
+
958
+ `RateLimitMiddleware`:
959
+ - enforces short-window max request budgets
960
+ - can blacklist persistent flooders
961
+ - supports path rule overrides
962
+
963
+ `GeoBlockMiddleware`:
964
+ - resolves country from source IP via MMDB
965
+ - supports block-list mode and optional allow-list mode
966
+ - can cache lookups for performance
967
+
968
+ `AIAnomalyMiddleware`:
969
+ - uses a persisted JSON model when available, otherwise falls back to heuristic/keyword anomaly behavior
970
+ - gracefully disables itself when model/deps are unavailable
971
+ - persisted ML inference requires the Rust JSON model backend; scikit-learn is training-time only and `model.pkl` is not supported
972
+
973
+ `HoneypotTimingMiddleware`:
974
+ - enforces minimum submit timing
975
+ - enforces max page age semantics where enabled
976
+ - includes method misuse detection logic
977
+
978
+ `UUIDTamperMiddleware`:
979
+ - guards UUID access patterns
980
+ - usually no-op where no UUID model rules apply
981
+
982
+ `HeaderValidationMiddleware`:
983
+ - checks required headers by method
984
+ - scores request realism and can block low-quality profiles
985
+ - commonly tuned for API/webhook/socket endpoints via `PATH_RULES`
986
+
987
+ ---
988
+
989
+ ## Advanced Configuration Matrix
990
+
991
+ Traffic controls:
992
+
993
+ ```python
994
+ AIWAF_RATE_WINDOW = 10
995
+ AIWAF_RATE_MAX = 20
996
+ AIWAF_RATE_FLOOD = 10
997
+ AIWAF_WINDOW_SECONDS = 60
998
+ ```
999
+
1000
+ Header validation:
1001
+
1002
+ ```python
1003
+ AIWAF_REQUIRED_HEADERS = None
1004
+ AIWAF_HEADER_QUALITY_MIN_SCORE = 3
1005
+ AIWAF_MAX_ACCEPT_LENGTH = 4096
1006
+ ```
1007
+
1008
+ AI/model behavior:
1009
+
1010
+ ```python
1011
+ AIWAF_DISABLE_AI = False
1012
+ AIWAF_MIN_AI_LOGS = 10000
1013
+ AIWAF_MIN_TRAIN_LOGS = 50
1014
+ AIWAF_FORCE_AI_TRAINING = False
1015
+ AIWAF_AI_CONTAMINATION = 0.05
1016
+ ```
1017
+
1018
+ Model storage:
1019
+
1020
+ ```python
1021
+ AIWAF_MODEL_STORAGE = "file" # file | db | cache
1022
+ AIWAF_MODEL_PATH = "aiwaf/resources/model.json"
1023
+ AIWAF_MODEL_CACHE_KEY = "aiwaf:model"
1024
+ AIWAF_MODEL_CACHE_TIMEOUT = None
1025
+ AIWAF_MODEL_STORAGE_FALLBACK = True
1026
+ ```
1027
+
1028
+ Do not point `AIWAF_MODEL_PATH` at `pickle`, `joblib`, or `skops` artifacts.
1029
+ AIWAF loads JSON artifacts only. Fresh installs do not include `model.pkl`;
1030
+ run training with Rust enabled to create `model.json`.
1031
+
1032
+ Keyword and false-positive controls:
1033
+
1034
+ ```python
1035
+ AIWAF_ALLOWED_PATH_KEYWORDS = ["profile", "user", "dashboard"]
1036
+ AIWAF_EXEMPT_KEYWORDS = ["api", "health", "static", "webhook"]
1037
+ AIWAF_DYNAMIC_TOP_N = 10
1038
+ ```
1039
+
1040
+ Exemptions:
1041
+
1042
+ ```python
1043
+ AIWAF_EXEMPT_PATHS = ["/health/", "/static/", "/favicon.ico"]
1044
+ AIWAF_EXEMPT_IPS = ["127.0.0.1", "::1"]
1045
+ ```
1046
+
1047
+ ---
1048
+
1049
+ ## Tuning Playbooks
1050
+
1051
+ Reduce false positives without globally weakening protection:
1052
+ 1. reset learned keywords (`--keywords`)
1053
+ 2. add legitimate domain terms to `AIWAF_ALLOWED_PATH_KEYWORDS`
1054
+ 3. add operational terms to `AIWAF_EXEMPT_KEYWORDS`
1055
+ 4. add route-level `PATH_RULES` for webhook/socket endpoints
1056
+ 5. retrain and benchmark again
1057
+
1058
+ Harden for sustained attack traffic:
1059
+ 1. tune `AIWAF_RATE_WINDOW`, `AIWAF_RATE_MAX`, `AIWAF_RATE_FLOOD`
1060
+ 2. keep header validation enabled for public paths
1061
+ 3. keep geo rules explicit and minimal
1062
+ 4. enable middleware logging + regular retraining
1063
+ 5. review block reasons before adding broad keyword rules
1064
+
1065
+ Stabilize real-time paths:
1066
+ 1. keep global protections enabled
1067
+ 2. disable only strict checks on `/socket.io/` or equivalent via `PATH_RULES`
1068
+ 3. keep blacklist logic for non-realtime paths
1069
+ 4. whitelist trusted internal integration IPs when needed
1070
+
1071
+ ---
1072
+
1073
+ ## Rust Verification
1074
+
1075
+ Runtime behavior:
1076
+ - Rust extension available: selected paths use Rust acceleration
1077
+ - Rust extension unavailable: automatic fallback to Python
1078
+
1079
+ Verification checklist:
1080
+ 1. verify `python -c "import aiwaf_rust"` succeeds
1081
+ 2. confirm startup/runtime logs show Rust availability or fallback path
1082
+ 3. benchmark with multiple iterations and compare medians (`run-and-compare.py -n 5`)
1083
+
1084
+ ---
1085
+
1086
+ ## Troubleshooting Decision Tree
1087
+
1088
+ Blank page but `/` is `200`:
1089
+ - inspect JS/CSS/API requests for `403`/`4xx`
1090
+ - check whether client IP was blacklisted
1091
+ - confirm `PATH_RULES` for socket/static/API paths
1092
+
1093
+ Many `403` immediately after one blocked request:
1094
+ - likely blacklist cascade
1095
+ - clear blacklist and add targeted exemption/path rule
1096
+ - avoid disabling all middleware globally
1097
+
1098
+ AI anomaly not active:
1099
+ - verify model is a JSON artifact
1100
+ - verify AI deps are installed
1101
+ - verify `AIWAF_DISABLE_AI=False`
1102
+ - verify thresholds (`AIWAF_MIN_AI_LOGS`, `AIWAF_MIN_TRAIN_LOGS`)
1103
+ - install `aiwaf-rust` if you need a persisted runtime ML model
1104
+
1105
+ Geo-blocking appears inactive:
1106
+ - confirm middleware enabled
1107
+ - confirm MMDB path valid
1108
+ - confirm allow/block lists are configured as intended
1109
+
1110
+ ---
1111
+
1112
+ ## Deployment Patterns
1113
+
1114
+ ### Reverse Proxy + App Server
1115
+
1116
+ Typical production path:
1117
+ 1. internet -> CDN/WAF edge (optional)
1118
+ 2. reverse proxy (Nginx/Traefik/Caddy)
1119
+ 3. application server (Django/Flask with AIWAF middleware)
1120
+ 4. app database/cache + model/log storage
1121
+
1122
+ Recommended:
1123
+ - preserve client IP forwarding correctly (`X-Forwarded-For`)
1124
+ - keep clock synchronization (NTP) for reliable log timing features
1125
+ - rotate logs and enforce retention limits
1126
+ - run periodic retraining as a scheduled job
1127
+
1128
+ ### Multi-Instance Deployments
1129
+
1130
+ When running multiple app instances:
1131
+ - prefer shared storage mode for model artifacts (`db` or centralized cache)
1132
+ - ensure blacklist/exemption updates propagate consistently
1133
+ - avoid host-local-only model paths if instances autoscale
1134
+
1135
+ ### Blue/Green or Rolling Updates
1136
+
1137
+ For safer rollout:
1138
+ 1. deploy with conservative thresholds
1139
+ 2. verify block metrics and false-positive ratio
1140
+ 3. gradually tighten controls
1141
+ 4. promote only after stable benchmark + production canary behavior
1142
+
1143
+ ---
1144
+
1145
+ ## Observability and KPIs
1146
+
1147
+ Track these indicators per adapter:
1148
+
1149
+ - **Normal traffic block rate**: target near `0%`
1150
+ - **Attack traffic block rate**: target high and stable under replay suite
1151
+ - **P95/P99 response latency**: compare before/after tuning
1152
+ - **Blacklist churn**: sudden spikes may indicate noisy rules
1153
+ - **Top block reasons**: helps tune headers/keywords/rate limits
1154
+ - **Retraining success/failure counts**: detect model pipeline regressions
1155
+
1156
+ Minimum dashboard slices:
1157
+ - by endpoint family (`/api`, `/socket.io`, static assets)
1158
+ - by source ASN/country (if geo enabled)
1159
+ - by middleware reason code
1160
+ - by deployment version
1161
+
1162
+ ---
1163
+
1164
+ ## Security Boundaries and Caveats
1165
+
1166
+ AIWAF improves application-layer protection but is not a complete security boundary.
1167
+
1168
+ Important caveats:
1169
+ - does not replace secure coding, authz, secrets management, patching, or network controls
1170
+ - ML anomaly detection is probabilistic and can drift with traffic profile changes
1171
+ - aggressive keyword/rate settings can cause self-inflicted outages if not staged
1172
+ - websocket/realtime paths often require explicit path-rule tuning
1173
+ - allowlists/exemptions should be tightly scoped and periodically reviewed
1174
+
1175
+ ---
1176
+
1177
+ ## Contributor Test Strategy
1178
+
1179
+ Recommended local validation flow for changes:
1180
+
1181
+ 1. unit and adapter tests
1182
+ 2. sandbox startup validation (direct + protected targets)
1183
+ 3. replay benchmark with multiple iterations
1184
+ 4. review aggregate detection and latency medians
1185
+ 5. inspect a sample of blocked and allowed requests for regressions
1186
+
1187
+ Suggested benchmark command:
1188
+
1189
+ ```bash
1190
+ cd examples/sandbox
1191
+ python run-and-compare.py -n 5
1192
+ ```
1193
+
1194
+ Regression gates (example policy):
1195
+ - no increase in normal-traffic blocking
1196
+ - no meaningful drop in attack blocked%
1197
+ - no unexplained latency regressions beyond agreed budget
1198
+
1199
+ ---
1200
+
1201
+ ## FAQ
1202
+
1203
+ **Why do I see `403` on `curl` but browser works?**
1204
+ Header validation can classify low-quality client headers as automated traffic.
1205
+
1206
+ **Why did everything start returning `403` suddenly?**
1207
+ Likely blacklist cascade after an initial block event; clear blacklist and add targeted path/IP tuning.
1208
+
1209
+ **Can I disable one middleware for a single route?**
1210
+ Yes, use `AIWAF_SETTINGS["PATH_RULES"]` with `DISABLE` for that prefix.
1211
+
1212
+ **Does Rust mode change detection outcomes?**
1213
+ It should preserve behavior while improving some execution paths; verify with A/B multi-iteration benchmarks.
1214
+
1215
+ **Why is model persistence JSON-only?**
1216
+ AIWAF is security middleware, so it avoids Python object deserialization formats
1217
+ such as `pickle`, `joblib`, and `skops`. Persisted AI models should use the Rust
1218
+ `IsolationForest` JSON state path. Legacy `model.pkl` files are not loaded and
1219
+ are no longer bundled.
1220
+
1221
+ **Do I need Django to use AIWAF?**
1222
+ No. Core supports both Django and Flask adapters, but some operational commands are Django-specific.
1223
+
1224
+ ---
1225
+
1226
+ ## CLI Entry Point
1227
+
1228
+ ```bash
1229
+ aiwaf-detect
1230
+ ```
1231
+
1232
+ Current behavior:
1233
+ - dispatches to Django trainer (`aiwaf.django.trainer.train`)
1234
+ - requires Django adapter availability
1235
+
1236
+ ---
1237
+
1238
+ ## JavaScript Package (`aiwaf`)
1239
+
1240
+ The JavaScript package lives in `js/`. Unless a command explicitly installs the
1241
+ published package, run commands in this section after `cd js`.
2
1242
 
3
1243
  AIWAF-JS is a Node.js/Express Web Application Firewall that combines deterministic protections with anomaly detection and continuous learning. It ships as middleware, a CLI for ops workflows, and an offline trainer for IsolationForest models.
4
1244
  Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fastify wrappers), Next.js (API route wrapper), AdonisJS, and Sails.js.
5
1245
 
6
- ## What It Does
1246
+ ### What It Does
7
1247
 
8
1248
  - Blocks known bad traffic with static keyword rules and IP blacklisting
9
1249
  - Enforces rate limits with flood detection
@@ -17,7 +1257,7 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
17
1257
  - CSV fallback storage when DB is unavailable
18
1258
  - Operational CLI for blacklist, exemptions, geo, request logs, training and diagnostics
19
1259
 
20
- ## Repository Layout
1260
+ ### Repository Layout
21
1261
 
22
1262
  - `index.js`: package entrypoint
23
1263
  - `lib/wafMiddleware.js`: main middleware orchestration
@@ -40,7 +1280,7 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
40
1280
  - `utils/db.js`: SQLite connection (memory DB in test)
41
1281
  - `test/`: Jest test suite
42
1282
 
43
- ## Request Processing Flow
1283
+ ### Request Processing Flow
44
1284
 
45
1285
  1. Initialize module options for rate limiter, keyword detectors, honeypot, UUID checks, and anomaly detector.
46
1286
  2. Resolve client IP (`x-forwarded-for` first, then `req.ip`) and normalized path.
@@ -57,13 +1297,13 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
57
1297
  13. Request logging (JSONL/CSV/DB) and optional dynamic keyword learning on 404s.
58
1298
  14. Allow request through `next()` when no rule triggers.
59
1299
 
60
- ## Installation
1300
+ ### Installation
61
1301
 
62
1302
  ```bash
63
1303
  npm install aiwaf
64
1304
  ```
65
1305
 
66
- ### Optional WASM Acceleration
1306
+ #### Optional WASM Acceleration
67
1307
 
68
1308
  AIWAF can use the `aiwaf-wasm` optional dependency for faster IsolationForest scoring and deterministic feature validation.
69
1309
  If the WASM module fails to load, it automatically falls back to the JS implementation.
@@ -72,7 +1312,7 @@ If the WASM module fails to load, it automatically falls back to the JS implemen
72
1312
  npm install aiwaf-wasm
73
1313
  ```
74
1314
 
75
- ## Quick Start
1315
+ ### Quick Start
76
1316
 
77
1317
  ```js
78
1318
  const express = require('express');
@@ -98,7 +1338,7 @@ app.get('/', (req, res) => res.send('Protected'));
98
1338
  app.listen(3000);
99
1339
  ```
100
1340
 
101
- ## Path Rules and Auto Middleware
1341
+ ### Path Rules and Auto Middleware
102
1342
 
103
1343
  Use path rules to disable selected AIWAF checks or override rate limits for a route prefix:
104
1344
 
@@ -165,7 +1405,7 @@ app.use(aiwaf.auto({
165
1405
  app.use(aiwaf({ AIWAF_MIDDLEWARES: ['auto'] }));
166
1406
  ```
167
1407
 
168
- ## Fastify Usage
1408
+ ### Fastify Usage
169
1409
 
170
1410
  ```js
171
1411
  const fastify = require('fastify')({ logger: true });
@@ -184,7 +1424,7 @@ fastify.get('/', async () => 'Protected');
184
1424
  fastify.listen({ port: 3000 });
185
1425
  ```
186
1426
 
187
- ## Hapi Usage
1427
+ ### Hapi Usage
188
1428
 
189
1429
  ```js
190
1430
  const Hapi = require('@hapi/hapi');
@@ -207,7 +1447,7 @@ server.route({ method: 'GET', path: '/', handler: () => 'Protected' });
207
1447
  await server.start();
208
1448
  ```
209
1449
 
210
- ## Koa Usage
1450
+ ### Koa Usage
211
1451
 
212
1452
  ```js
213
1453
  const Koa = require('koa');
@@ -233,7 +1473,7 @@ app.use(ctx => {
233
1473
  app.listen(3000);
234
1474
  ```
235
1475
 
236
- ## NestJS (Express) Usage
1476
+ ### NestJS (Express) Usage
237
1477
 
238
1478
  ```ts
239
1479
  import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
@@ -278,7 +1518,7 @@ async function bootstrap() {
278
1518
  bootstrap();
279
1519
  ```
280
1520
 
281
- ## NestJS (Fastify) Usage
1521
+ ### NestJS (Fastify) Usage
282
1522
 
283
1523
  Use the Fastify plugin when running Nest with `FastifyAdapter`:
284
1524
 
@@ -303,7 +1543,7 @@ async function bootstrap() {
303
1543
  bootstrap();
304
1544
  ```
305
1545
 
306
- ## Next.js (API Routes) Usage
1546
+ ### Next.js (API Routes) Usage
307
1547
 
308
1548
  Use the `aiwaf.next` helper to wrap a Next.js API route handler.
309
1549
 
@@ -324,7 +1564,7 @@ export default aiwaf.next(handler, {
324
1564
  });
325
1565
  ```
326
1566
 
327
- ## AdonisJS Usage
1567
+ ### AdonisJS Usage
328
1568
 
329
1569
  Register the middleware in your Adonis middleware stack:
330
1570
 
@@ -343,7 +1583,7 @@ export const middleware = [
343
1583
  ];
344
1584
  ```
345
1585
 
346
- ## Sails.js Usage
1586
+ ### Sails.js Usage
347
1587
 
348
1588
  Use the Express-compatible middleware in your Sails `config/http.js`:
349
1589
 
@@ -364,9 +1604,9 @@ module.exports.http = {
364
1604
  };
365
1605
  ```
366
1606
 
367
- ## Configuration
1607
+ ### Configuration
368
1608
 
369
- ### Core Controls
1609
+ #### Core Controls
370
1610
 
371
1611
  | Option | Default | Description |
372
1612
  |---|---|---|
@@ -384,7 +1624,7 @@ module.exports.http = {
384
1624
  | `AIWAF_WASM_VALIDATION` | `true` | Enable WASM validation when available (headers, URL, content, recent) |
385
1625
  | `AIWAF_WASM_VALIDATE_RECENT` | `false` | Run WASM recent-behavior validation on recent request logs |
386
1626
 
387
- ### Header Validation
1627
+ #### Header Validation
388
1628
 
389
1629
  | Option | Default | Description |
390
1630
  |---|---|---|
@@ -399,7 +1639,7 @@ module.exports.http = {
399
1639
  | `AIWAF_SUSPICIOUS_USER_AGENTS` | regex list | Regex list for suspicious UA detection |
400
1640
  | `AIWAF_LEGITIMATE_BOTS` | regex list | Regex allow list for legitimate crawlers |
401
1641
 
402
- ### Method Policy
1642
+ #### Method Policy
403
1643
 
404
1644
  | Option | Default | Description |
405
1645
  |---|---|---|
@@ -408,7 +1648,7 @@ module.exports.http = {
408
1648
  | `AIWAF_POST_ONLY_SUFFIXES` | `['/create/','/submit/','/upload/','/delete/','/process/']` | GET to these triggers 405 when policy enabled |
409
1649
  | `AIWAF_LOGIN_PATH_PREFIXES` | common login paths | Shorten min form time for login |
410
1650
 
411
- ### Middleware Selection / Path Rules
1651
+ #### Middleware Selection / Path Rules
412
1652
 
413
1653
  | Option | Default | Description |
414
1654
  |---|---|---|
@@ -418,7 +1658,7 @@ module.exports.http = {
418
1658
  | `AIWAF_PATH_MANIFEST` | `.aiwaf/paths.json` | Route manifest compiled into additional path rules |
419
1659
  | `AIWAF_ROUTE_PLAN_VERSION` | `0` | User-controlled version marker for route policy changes |
420
1660
 
421
- ### Keyword Learning
1661
+ #### Keyword Learning
422
1662
 
423
1663
  | Option | Default | Description |
424
1664
  |---|---|---|
@@ -427,7 +1667,7 @@ module.exports.http = {
427
1667
  | `AIWAF_EXEMPT_KEYWORDS` | `[]` | Skip these keywords |
428
1668
  | `AIWAF_ALLOWED_PATH_KEYWORDS` | `[]` | Allowlist of path fragments |
429
1669
 
430
- ### Model / Training
1670
+ #### Model / Training
431
1671
 
432
1672
  | Option | Default | Description |
433
1673
  |---|---|---|
@@ -441,7 +1681,7 @@ module.exports.http = {
441
1681
  | `AIWAF_MODEL_CACHE_KEY` | `aiwaf:model` | Cache key when using cache backend |
442
1682
  | `AIWAF_MODEL_CACHE_TTL` | `0` | Cache TTL in seconds |
443
1683
 
444
- ### Geo Blocking
1684
+ #### Geo Blocking
445
1685
 
446
1686
  | Option | Default | Description |
447
1687
  |---|---|---|
@@ -452,7 +1692,7 @@ module.exports.http = {
452
1692
  | `AIWAF_GEO_CACHE_SECONDS` | `3600` | Geo cache TTL |
453
1693
  | `AIWAF_GEO_CACHE_PREFIX` | `aiwaf:geo:` | Geo cache key prefix |
454
1694
 
455
- ### Logging / Storage
1695
+ #### Logging / Storage
456
1696
 
457
1697
  | Option | Default | Description |
458
1698
  |---|---|---|
@@ -468,8 +1708,8 @@ module.exports.http = {
468
1708
  | `AIWAF_REQUEST_LOGS_CSV_PATH` | `logs/storage/request_logs.csv` | CSV fallback for request logs |
469
1709
  | `AIWAF_DYNAMIC_KEYWORDS_CSV_PATH` | `logs/storage/dynamic_keywords.csv` | CSV fallback for dynamic keywords |
470
1710
 
471
- ### Redis / Cache
472
- ## Redis and Cache Behavior
1711
+ #### Redis / Cache
1712
+ ### Redis and Cache Behavior
473
1713
 
474
1714
  - Set `REDIS_URL` (or `AIWAF_REDIS_URL`) to enable Redis connectivity (`lib/redisClient.js`).
475
1715
  - If Redis is unavailable, runtime falls back to in-memory behavior.
@@ -487,7 +1727,7 @@ Feature cache custom backend supports:
487
1727
  - `get(key)`
488
1728
  - `set(key, value, ttl)`
489
1729
 
490
- ## Geo Blocking (MMDB)
1730
+ ### Geo Blocking (MMDB)
491
1731
 
492
1732
  - Put your DB at `geolock/ipinfo_lite.mmdb` (default) or set `AIWAF_GEO_MMDB_PATH`.
493
1733
  - Enable with `AIWAF_GEO_BLOCK_ENABLED: true`.
@@ -496,7 +1736,7 @@ Feature cache custom backend supports:
496
1736
  - `npm install maxmind`
497
1737
  - If MMDB is unavailable, the middleware falls back to `x-country-code` header.
498
1738
 
499
- ## Offline Training
1739
+ ### Offline Training
500
1740
 
501
1741
  Train a model using access logs:
502
1742
 
@@ -526,7 +1766,7 @@ Training pipeline in `train.js`:
526
1766
  - `AIWAF_MODEL_STORAGE_FALLBACK` (fallback backend)
527
1767
  - `AIWAF_MODEL_CACHE_KEY`, `AIWAF_MODEL_CACHE_TTL` (cache backend)
528
1768
 
529
- ## Testing
1769
+ ### Testing
530
1770
 
531
1771
  ```bash
532
1772
  npm test
@@ -544,7 +1784,25 @@ Current tests cover:
544
1784
  - CSV/DB fallback storage
545
1785
  - CLI and settings compatibility
546
1786
 
547
- ## Data and Persistence
1787
+ ### Data and Persistence
1788
+
1789
+ #### Reputation-aware blacklist
1790
+
1791
+ Blacklist records use the same reputation lifecycle as the Python package. Each
1792
+ record stores the original reason, accumulated reasons, score, offense count,
1793
+ block timestamp, expiry, duration, permanent status, and optional redacted
1794
+ request metadata. Repeated offenses progress from 15-minute blocks to one-hour
1795
+ and 24-hour blocks. Expired entries are ignored and can be removed explicitly:
1796
+
1797
+ ```bash
1798
+ npm run aiwaf -- blacklist cleanup
1799
+ npm run aiwaf -- blacklist migrate
1800
+ npm run aiwaf -- blacklist migrate --duration 24h
1801
+ ```
1802
+
1803
+ Set `AIWAF_CAPTURE_EXTENDED_REQUEST_INFO=true` to retain redacted request
1804
+ headers and fingerprints with blacklist decisions. Authorization and cookie
1805
+ headers are redacted by default.
548
1806
 
549
1807
  - Runtime blacklist storage uses SQLite through `utils/db.js`.
550
1808
  - Production DB file defaults to `./aiwaf.sqlite`.
@@ -562,14 +1820,14 @@ Current tests cover:
562
1820
  - `request_logs` -> `logs/storage/request_logs.csv` (`AIWAF_REQUEST_LOGS_CSV_PATH`)
563
1821
  - `dynamic_keywords` -> `logs/storage/dynamic_keywords.csv` (`AIWAF_DYNAMIC_KEYWORDS_CSV_PATH`)
564
1822
 
565
- ## Operational Notes
1823
+ ### Operational Notes
566
1824
 
567
1825
  - Middleware order matters; place AIWAF after body parsers if honeypot checks depend on parsed JSON/form body.
568
1826
  - If no trained model exists or loading fails, anomaly detector fails open.
569
1827
  - Dynamic keyword learning persists to DB/CSV via `dynamicKeywordStore`.
570
1828
  - Multi-instance deployments should use Redis/custom shared cache for limiter consistency.
571
1829
 
572
- ## Development
1830
+ ### Development
573
1831
 
574
1832
  ```bash
575
1833
  npm install
@@ -578,7 +1836,7 @@ npm run train
578
1836
  npm run aiwaf -- help
579
1837
  ```
580
1838
 
581
- ## Operations CLI
1839
+ ### Operations CLI
582
1840
 
583
1841
  ```bash
584
1842
  npm run aiwaf -- list blacklist
@@ -595,27 +1853,37 @@ npm run aiwaf -- whois example.com
595
1853
  npm run aiwaf -- diagnose 203.0.113.10
596
1854
  npm run aiwaf -- reset --all --confirm
597
1855
  npm run aiwaf -- pathshell
1856
+ npm run aiwaf -- status
1857
+ npm run aiwaf -- stats 5000
1858
+ npm run aiwaf -- logs analyze 5000
1859
+ npm run aiwaf -- export aiwaf-export.json
1860
+ npm run aiwaf -- import aiwaf-export.json
1861
+ npm run aiwaf -- model info
1862
+ npm run aiwaf -- model export aiwaf-model.json
1863
+ npm run aiwaf -- model import aiwaf-model.json
1864
+ npm run aiwaf -- model clear
598
1865
  ```
599
1866
 
600
- ## Sandbox (OWASP Juice Shop)
1867
+ ### Sandbox (OWASP Juice Shop)
601
1868
 
602
- The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF. It also includes an attack suite that generates comparable results for direct vs protected traffic.
603
-
604
- Run sandbox:
1869
+ The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF.
605
1870
 
606
1871
  ```bash
607
1872
  docker compose -f examples/sandbox/docker-compose.yml up --build
608
1873
  ```
609
1874
 
610
- Run the attack suite and compare:
1875
+ Fastify proxy is also available on `http://localhost:3002`.
611
1876
 
612
- ```bash
613
- node examples/sandbox/run-and-compare.js http://localhost:3001 http://localhost:3000
614
- ```
1877
+ ---
615
1878
 
616
- The comparison output includes per‑attack block rates and total blocked requests.
617
- Fastify proxy is also available on `http://localhost:3002`.
1879
+ ## Acknowledgements
1880
+
1881
+ GeoIP support uses the bundled IPinfo MMDB format for country mapping.
1882
+
1883
+ [DigitalOcean](https://www.digitalocean.com/) provides the cloud infrastructure that powers AIWAF development.
1884
+
1885
+ ---
618
1886
 
619
1887
  ## License
620
1888
 
621
- MIT
1889
+ MIT. See `LICENSE`.