aiwaf 1.0.0 → 1.0.1

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,1248 @@
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 both 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
+
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).
18
+
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.
20
+
21
+ Run the complete monorepo test suite with `python aiwaf_test.py`. Use `--python-only` or `--js-only` when working on one package.
22
+
23
+ ## Latest Enhancements
24
+
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
35
+
36
+ ---
37
+
38
+ ## Quick Installation
39
+
40
+ Python:
41
+
42
+ ```bash
43
+ pip install aiwaf
44
+ ```
45
+
46
+ JavaScript:
47
+
48
+ ```bash
49
+ npm install aiwaf
50
+ ```
51
+
52
+ Optional framework extras:
53
+
54
+ ```bash
55
+ pip install "aiwaf[django]"
56
+ pip install "aiwaf[flask]"
57
+ 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
+ - 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
+ ---
79
+
80
+ ## Package Structure
81
+
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
92
+ ```
93
+
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
101
+
102
+ # Flask
103
+ import aiwaf.flask as aiwaf
104
+
105
+ # FastAPI
106
+ import aiwaf.fast as aiwaf
107
+ ```
108
+
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
123
+
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
128
+
129
+ - **Dynamic keyword learning**
130
+ - learns suspicious path terms from attack-like traffic
131
+ - excludes exempt/allowed terms to reduce false positives
132
+
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:
180
+
181
+ ```bash
182
+ # often low-quality header profile
183
+ curl http://your-app.example/
184
+
185
+ # compare against normal browser traffic
186
+ ```
187
+
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.
223
+
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:
241
+
242
+ ```python
243
+ AIWAF_ACCESS_LOG = "/var/log/nginx/access.log"
244
+ ```
245
+
246
+ Core defaults (examples):
247
+
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
+ ```
275
+
276
+ Model storage:
277
+
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
284
+ ```
285
+
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
+ ```
295
+
296
+ GeoIP:
297
+
298
+ ```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:
308
+
309
+ ```python
310
+ AIWAF_RUST_ISOLATION_FOREST = True
311
+ ```
312
+
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:
345
+
346
+ ```python
347
+ MIDDLEWARE = [
348
+ "aiwaf.django.middleware.JsonExceptionMiddleware",
349
+ "aiwaf.django.middleware.GeoBlockMiddleware",
350
+ "aiwaf.django.middleware.IPAndKeywordBlockMiddleware",
351
+ "aiwaf.django.middleware.RateLimitMiddleware",
352
+ "aiwaf.django.middleware.AIAnomalyMiddleware",
353
+ "aiwaf.django.middleware.HoneypotTimingMiddleware",
354
+ "aiwaf.django.middleware.UUIDTamperMiddleware",
355
+ "aiwaf.django.middleware.HeaderValidationMiddleware",
356
+ "aiwaf.django.middleware_logger.AIWAFLoggerMiddleware",
357
+ ]
358
+ ```
359
+
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
+ ---
400
+
401
+ ## Operations
402
+
403
+ Django adapter examples:
404
+
405
+ ```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
420
+
421
+ FastAPI adapter:
422
+ - use `aiwaf.fast.AIWAF` for middleware registration
423
+ - use `aiwaf fast ...` or `aiwaf-fast ...` for CLI operations
424
+
425
+ ### Django Command Reference
426
+
427
+ Common management commands:
428
+
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
444
+ ```
445
+
446
+ `aiwaf_pathshell` helpers:
447
+
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
455
+ ```
456
+
457
+ ### Flask Adapter Reference
458
+
459
+ Programmatic integration:
460
+
461
+ ```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
+ ],
480
+ )
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
+
496
+ Blacklist migration commands:
497
+
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
514
+ ```
515
+
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 |
533
+
534
+ Django ORM:
535
+
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
540
+
541
+ aiwaf django blacklist migrate
542
+ # Equivalent:
543
+ python manage.py aiwaf_migrate_blacklist
544
+ ```
545
+
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.
550
+
551
+ Flask SQLAlchemy ORM:
552
+
553
+ ```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
+ ```
591
+
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:
605
+
606
+ ```bash
607
+ aiwaf fast --help
608
+ aiwaf-fast --help
609
+ ```
610
+
611
+ ### Path-Specific Rules
612
+
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.
616
+
617
+ Generate a manifest:
618
+
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
+ ```
719
+
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.
724
+
725
+ You can still define manual path rules to selectively disable middleware or
726
+ override rate limits without globally weakening protection:
727
+
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
+ }
742
+ ```
743
+
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.
750
+
751
+ ### Blocking Behavior
752
+
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.
760
+
761
+ ### Rate Limiting Cache (Multi-worker)
762
+
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:"
773
+ ```
774
+
775
+ **FastAPI**
776
+
777
+ ```python
778
+ from aiwaf.fast import AIWAF
779
+
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
+ )
789
+ ```
790
+
791
+ Environment variables (both adapters):
792
+
793
+ ```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:
797
+ ```
798
+
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
811
+
812
+ The sandbox in `examples/sandbox/` provides:
813
+
814
+ - `direct` (no AIWAF)
815
+ - `protected_django`
816
+ - `protected_flask`
817
+ - `protected_fastapi`
818
+
819
+ Run full benchmark:
820
+
821
+ ```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
843
+
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
865
+ ```
866
+
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
872
+
873
+ ---
874
+
875
+ ## Troubleshooting
876
+
877
+ ### Legitimate pages blocked
878
+
879
+ Cause:
880
+ - learned keywords included legitimate app vocabulary
881
+
882
+ Fix:
883
+
884
+ ```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
997
+ ```
998
+
999
+ Header validation:
1000
+
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:
1008
+
1009
+ ```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"]
1044
+ ```
1045
+
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:
1187
+
1188
+ ```bash
1189
+ cd examples/sandbox
1190
+ python run-and-compare.py -n 5
1191
+ ```
1192
+
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.
1207
+
1208
+ **Can I disable one middleware for a single route?**
1209
+ Yes, use `AIWAF_SETTINGS["PATH_RULES"]` with `DISABLE` for that prefix.
1210
+
1211
+ **Does Rust mode change detection outcomes?**
1212
+ It should preserve behavior while improving some execution paths; verify with A/B multi-iteration benchmarks.
1213
+
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.
1219
+
1220
+ **Do I need Django to use AIWAF?**
1221
+ No. Core supports both Django and Flask adapters, but some operational commands are Django-specific.
1222
+
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`.
2
1241
 
3
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.
4
1243
  Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fastify wrappers), Next.js (API route wrapper), AdonisJS, and Sails.js.
5
1244
 
6
- ## What It Does
1245
+ ### What It Does
7
1246
 
8
1247
  - Blocks known bad traffic with static keyword rules and IP blacklisting
9
1248
  - Enforces rate limits with flood detection
@@ -17,7 +1256,7 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
17
1256
  - CSV fallback storage when DB is unavailable
18
1257
  - Operational CLI for blacklist, exemptions, geo, request logs, training and diagnostics
19
1258
 
20
- ## Repository Layout
1259
+ ### Repository Layout
21
1260
 
22
1261
  - `index.js`: package entrypoint
23
1262
  - `lib/wafMiddleware.js`: main middleware orchestration
@@ -40,7 +1279,7 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
40
1279
  - `utils/db.js`: SQLite connection (memory DB in test)
41
1280
  - `test/`: Jest test suite
42
1281
 
43
- ## Request Processing Flow
1282
+ ### Request Processing Flow
44
1283
 
45
1284
  1. Initialize module options for rate limiter, keyword detectors, honeypot, UUID checks, and anomaly detector.
46
1285
  2. Resolve client IP (`x-forwarded-for` first, then `req.ip`) and normalized path.
@@ -57,13 +1296,13 @@ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fast
57
1296
  13. Request logging (JSONL/CSV/DB) and optional dynamic keyword learning on 404s.
58
1297
  14. Allow request through `next()` when no rule triggers.
59
1298
 
60
- ## Installation
1299
+ ### Installation
61
1300
 
62
1301
  ```bash
63
1302
  npm install aiwaf
64
1303
  ```
65
1304
 
66
- ### Optional WASM Acceleration
1305
+ #### Optional WASM Acceleration
67
1306
 
68
1307
  AIWAF can use the `aiwaf-wasm` optional dependency for faster IsolationForest scoring and deterministic feature validation.
69
1308
  If the WASM module fails to load, it automatically falls back to the JS implementation.
@@ -72,7 +1311,7 @@ If the WASM module fails to load, it automatically falls back to the JS implemen
72
1311
  npm install aiwaf-wasm
73
1312
  ```
74
1313
 
75
- ## Quick Start
1314
+ ### Quick Start
76
1315
 
77
1316
  ```js
78
1317
  const express = require('express');
@@ -98,7 +1337,7 @@ app.get('/', (req, res) => res.send('Protected'));
98
1337
  app.listen(3000);
99
1338
  ```
100
1339
 
101
- ## Path Rules and Auto Middleware
1340
+ ### Path Rules and Auto Middleware
102
1341
 
103
1342
  Use path rules to disable selected AIWAF checks or override rate limits for a route prefix:
104
1343
 
@@ -165,7 +1404,7 @@ app.use(aiwaf.auto({
165
1404
  app.use(aiwaf({ AIWAF_MIDDLEWARES: ['auto'] }));
166
1405
  ```
167
1406
 
168
- ## Fastify Usage
1407
+ ### Fastify Usage
169
1408
 
170
1409
  ```js
171
1410
  const fastify = require('fastify')({ logger: true });
@@ -184,7 +1423,7 @@ fastify.get('/', async () => 'Protected');
184
1423
  fastify.listen({ port: 3000 });
185
1424
  ```
186
1425
 
187
- ## Hapi Usage
1426
+ ### Hapi Usage
188
1427
 
189
1428
  ```js
190
1429
  const Hapi = require('@hapi/hapi');
@@ -207,7 +1446,7 @@ server.route({ method: 'GET', path: '/', handler: () => 'Protected' });
207
1446
  await server.start();
208
1447
  ```
209
1448
 
210
- ## Koa Usage
1449
+ ### Koa Usage
211
1450
 
212
1451
  ```js
213
1452
  const Koa = require('koa');
@@ -233,7 +1472,7 @@ app.use(ctx => {
233
1472
  app.listen(3000);
234
1473
  ```
235
1474
 
236
- ## NestJS (Express) Usage
1475
+ ### NestJS (Express) Usage
237
1476
 
238
1477
  ```ts
239
1478
  import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
@@ -278,7 +1517,7 @@ async function bootstrap() {
278
1517
  bootstrap();
279
1518
  ```
280
1519
 
281
- ## NestJS (Fastify) Usage
1520
+ ### NestJS (Fastify) Usage
282
1521
 
283
1522
  Use the Fastify plugin when running Nest with `FastifyAdapter`:
284
1523
 
@@ -303,7 +1542,7 @@ async function bootstrap() {
303
1542
  bootstrap();
304
1543
  ```
305
1544
 
306
- ## Next.js (API Routes) Usage
1545
+ ### Next.js (API Routes) Usage
307
1546
 
308
1547
  Use the `aiwaf.next` helper to wrap a Next.js API route handler.
309
1548
 
@@ -324,7 +1563,7 @@ export default aiwaf.next(handler, {
324
1563
  });
325
1564
  ```
326
1565
 
327
- ## AdonisJS Usage
1566
+ ### AdonisJS Usage
328
1567
 
329
1568
  Register the middleware in your Adonis middleware stack:
330
1569
 
@@ -343,7 +1582,7 @@ export const middleware = [
343
1582
  ];
344
1583
  ```
345
1584
 
346
- ## Sails.js Usage
1585
+ ### Sails.js Usage
347
1586
 
348
1587
  Use the Express-compatible middleware in your Sails `config/http.js`:
349
1588
 
@@ -364,9 +1603,9 @@ module.exports.http = {
364
1603
  };
365
1604
  ```
366
1605
 
367
- ## Configuration
1606
+ ### Configuration
368
1607
 
369
- ### Core Controls
1608
+ #### Core Controls
370
1609
 
371
1610
  | Option | Default | Description |
372
1611
  |---|---|---|
@@ -384,7 +1623,7 @@ module.exports.http = {
384
1623
  | `AIWAF_WASM_VALIDATION` | `true` | Enable WASM validation when available (headers, URL, content, recent) |
385
1624
  | `AIWAF_WASM_VALIDATE_RECENT` | `false` | Run WASM recent-behavior validation on recent request logs |
386
1625
 
387
- ### Header Validation
1626
+ #### Header Validation
388
1627
 
389
1628
  | Option | Default | Description |
390
1629
  |---|---|---|
@@ -399,7 +1638,7 @@ module.exports.http = {
399
1638
  | `AIWAF_SUSPICIOUS_USER_AGENTS` | regex list | Regex list for suspicious UA detection |
400
1639
  | `AIWAF_LEGITIMATE_BOTS` | regex list | Regex allow list for legitimate crawlers |
401
1640
 
402
- ### Method Policy
1641
+ #### Method Policy
403
1642
 
404
1643
  | Option | Default | Description |
405
1644
  |---|---|---|
@@ -408,7 +1647,7 @@ module.exports.http = {
408
1647
  | `AIWAF_POST_ONLY_SUFFIXES` | `['/create/','/submit/','/upload/','/delete/','/process/']` | GET to these triggers 405 when policy enabled |
409
1648
  | `AIWAF_LOGIN_PATH_PREFIXES` | common login paths | Shorten min form time for login |
410
1649
 
411
- ### Middleware Selection / Path Rules
1650
+ #### Middleware Selection / Path Rules
412
1651
 
413
1652
  | Option | Default | Description |
414
1653
  |---|---|---|
@@ -418,7 +1657,7 @@ module.exports.http = {
418
1657
  | `AIWAF_PATH_MANIFEST` | `.aiwaf/paths.json` | Route manifest compiled into additional path rules |
419
1658
  | `AIWAF_ROUTE_PLAN_VERSION` | `0` | User-controlled version marker for route policy changes |
420
1659
 
421
- ### Keyword Learning
1660
+ #### Keyword Learning
422
1661
 
423
1662
  | Option | Default | Description |
424
1663
  |---|---|---|
@@ -427,7 +1666,7 @@ module.exports.http = {
427
1666
  | `AIWAF_EXEMPT_KEYWORDS` | `[]` | Skip these keywords |
428
1667
  | `AIWAF_ALLOWED_PATH_KEYWORDS` | `[]` | Allowlist of path fragments |
429
1668
 
430
- ### Model / Training
1669
+ #### Model / Training
431
1670
 
432
1671
  | Option | Default | Description |
433
1672
  |---|---|---|
@@ -441,7 +1680,7 @@ module.exports.http = {
441
1680
  | `AIWAF_MODEL_CACHE_KEY` | `aiwaf:model` | Cache key when using cache backend |
442
1681
  | `AIWAF_MODEL_CACHE_TTL` | `0` | Cache TTL in seconds |
443
1682
 
444
- ### Geo Blocking
1683
+ #### Geo Blocking
445
1684
 
446
1685
  | Option | Default | Description |
447
1686
  |---|---|---|
@@ -452,7 +1691,7 @@ module.exports.http = {
452
1691
  | `AIWAF_GEO_CACHE_SECONDS` | `3600` | Geo cache TTL |
453
1692
  | `AIWAF_GEO_CACHE_PREFIX` | `aiwaf:geo:` | Geo cache key prefix |
454
1693
 
455
- ### Logging / Storage
1694
+ #### Logging / Storage
456
1695
 
457
1696
  | Option | Default | Description |
458
1697
  |---|---|---|
@@ -468,8 +1707,8 @@ module.exports.http = {
468
1707
  | `AIWAF_REQUEST_LOGS_CSV_PATH` | `logs/storage/request_logs.csv` | CSV fallback for request logs |
469
1708
  | `AIWAF_DYNAMIC_KEYWORDS_CSV_PATH` | `logs/storage/dynamic_keywords.csv` | CSV fallback for dynamic keywords |
470
1709
 
471
- ### Redis / Cache
472
- ## Redis and Cache Behavior
1710
+ #### Redis / Cache
1711
+ ### Redis and Cache Behavior
473
1712
 
474
1713
  - Set `REDIS_URL` (or `AIWAF_REDIS_URL`) to enable Redis connectivity (`lib/redisClient.js`).
475
1714
  - If Redis is unavailable, runtime falls back to in-memory behavior.
@@ -487,7 +1726,7 @@ Feature cache custom backend supports:
487
1726
  - `get(key)`
488
1727
  - `set(key, value, ttl)`
489
1728
 
490
- ## Geo Blocking (MMDB)
1729
+ ### Geo Blocking (MMDB)
491
1730
 
492
1731
  - Put your DB at `geolock/ipinfo_lite.mmdb` (default) or set `AIWAF_GEO_MMDB_PATH`.
493
1732
  - Enable with `AIWAF_GEO_BLOCK_ENABLED: true`.
@@ -496,7 +1735,7 @@ Feature cache custom backend supports:
496
1735
  - `npm install maxmind`
497
1736
  - If MMDB is unavailable, the middleware falls back to `x-country-code` header.
498
1737
 
499
- ## Offline Training
1738
+ ### Offline Training
500
1739
 
501
1740
  Train a model using access logs:
502
1741
 
@@ -526,7 +1765,7 @@ Training pipeline in `train.js`:
526
1765
  - `AIWAF_MODEL_STORAGE_FALLBACK` (fallback backend)
527
1766
  - `AIWAF_MODEL_CACHE_KEY`, `AIWAF_MODEL_CACHE_TTL` (cache backend)
528
1767
 
529
- ## Testing
1768
+ ### Testing
530
1769
 
531
1770
  ```bash
532
1771
  npm test
@@ -544,7 +1783,25 @@ Current tests cover:
544
1783
  - CSV/DB fallback storage
545
1784
  - CLI and settings compatibility
546
1785
 
547
- ## Data and Persistence
1786
+ ### Data and Persistence
1787
+
1788
+ #### Reputation-aware blacklist
1789
+
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:
1795
+
1796
+ ```bash
1797
+ npm run aiwaf -- blacklist cleanup
1798
+ npm run aiwaf -- blacklist migrate
1799
+ npm run aiwaf -- blacklist migrate --duration 24h
1800
+ ```
1801
+
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.
548
1805
 
549
1806
  - Runtime blacklist storage uses SQLite through `utils/db.js`.
550
1807
  - Production DB file defaults to `./aiwaf.sqlite`.
@@ -562,14 +1819,14 @@ Current tests cover:
562
1819
  - `request_logs` -> `logs/storage/request_logs.csv` (`AIWAF_REQUEST_LOGS_CSV_PATH`)
563
1820
  - `dynamic_keywords` -> `logs/storage/dynamic_keywords.csv` (`AIWAF_DYNAMIC_KEYWORDS_CSV_PATH`)
564
1821
 
565
- ## Operational Notes
1822
+ ### Operational Notes
566
1823
 
567
1824
  - Middleware order matters; place AIWAF after body parsers if honeypot checks depend on parsed JSON/form body.
568
1825
  - If no trained model exists or loading fails, anomaly detector fails open.
569
1826
  - Dynamic keyword learning persists to DB/CSV via `dynamicKeywordStore`.
570
1827
  - Multi-instance deployments should use Redis/custom shared cache for limiter consistency.
571
1828
 
572
- ## Development
1829
+ ### Development
573
1830
 
574
1831
  ```bash
575
1832
  npm install
@@ -578,7 +1835,7 @@ npm run train
578
1835
  npm run aiwaf -- help
579
1836
  ```
580
1837
 
581
- ## Operations CLI
1838
+ ### Operations CLI
582
1839
 
583
1840
  ```bash
584
1841
  npm run aiwaf -- list blacklist
@@ -595,27 +1852,37 @@ npm run aiwaf -- whois example.com
595
1852
  npm run aiwaf -- diagnose 203.0.113.10
596
1853
  npm run aiwaf -- reset --all --confirm
597
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
598
1864
  ```
599
1865
 
600
- ## Sandbox (OWASP Juice Shop)
1866
+ ### Sandbox (OWASP Juice Shop)
601
1867
 
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:
1868
+ The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF.
605
1869
 
606
1870
  ```bash
607
1871
  docker compose -f examples/sandbox/docker-compose.yml up --build
608
1872
  ```
609
1873
 
610
- Run the attack suite and compare:
1874
+ Fastify proxy is also available on `http://localhost:3002`.
611
1875
 
612
- ```bash
613
- node examples/sandbox/run-and-compare.js http://localhost:3001 http://localhost:3000
614
- ```
1876
+ ---
615
1877
 
616
- The comparison output includes per‑attack block rates and total blocked requests.
617
- Fastify proxy is also available on `http://localhost:3002`.
1878
+ ## Acknowledgements
1879
+
1880
+ GeoIP support uses the bundled IPinfo MMDB format for country mapping.
1881
+
1882
+ [DigitalOcean](https://www.digitalocean.com/) provides the cloud infrastructure that powers AIWAF development.
1883
+
1884
+ ---
618
1885
 
619
1886
  ## License
620
1887
 
621
- MIT
1888
+ MIT. See `LICENSE`.