aiwaf 1.1.6 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +192 -30
- package/index.js +3 -0
- package/lib/hapiPlugin.js +5 -2
- package/lib/nativePipeline.js +359 -25
- package/lib/nativeRateCounter.js +45 -0
- package/lib/nativeSettings.js +242 -0
- package/lib/wafMiddleware.js +57 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -39,14 +39,14 @@ the supported Redis backends when sharing limits across workers.
|
|
|
39
39
|
|
|
40
40
|
Each package is versioned and released independently.
|
|
41
41
|
|
|
42
|
-
Python 1.
|
|
42
|
+
Python 1.2.0, Rust/Python 0.2.9, Node.js 1.2.0, WASM 0.2.7, and Java 1.3.6 are local source targets. See the package table below and [CHANGELOG](CHANGELOG.md) for release changes.
|
|
43
43
|
|
|
44
44
|
| Runtime | Package | Repository version | Primary use |
|
|
45
45
|
| --- | --- | ---: | --- |
|
|
46
|
-
| Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.
|
|
47
|
-
| Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.
|
|
48
|
-
| Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.
|
|
49
|
-
| WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.
|
|
46
|
+
| Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.2.0` | Django, Flask, and FastAPI protection |
|
|
47
|
+
| Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.2.0` | Express and Node framework middleware |
|
|
48
|
+
| Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.9` | Native Python acceleration and JSON model inference |
|
|
49
|
+
| WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.7` | Rust detection and model primitives for JavaScript |
|
|
50
50
|
| Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.6` | Spring MVC and Jakarta Servlet protection |
|
|
51
51
|
|
|
52
52
|
Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
|
|
@@ -256,7 +256,7 @@ pip install "aiwaf[django]"
|
|
|
256
256
|
pip install "aiwaf[flask]"
|
|
257
257
|
pip install "aiwaf[fastapi]"
|
|
258
258
|
|
|
259
|
-
# Backward-compatible alias; Python 1.
|
|
259
|
+
# Backward-compatible alias; Python 1.2.0 already installs aiwaf-rust
|
|
260
260
|
pip install "aiwaf[rust]"
|
|
261
261
|
|
|
262
262
|
# Node.js middleware
|
|
@@ -280,7 +280,7 @@ Java 1.3.6, after it is published to Maven Central:
|
|
|
280
280
|
|
|
281
281
|
The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
|
|
282
282
|
|
|
283
|
-
Python 1.
|
|
283
|
+
Python 1.2.0 requires `aiwaf-rust>=0.2.9`; the `rust` extra remains an installation
|
|
284
284
|
alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
|
|
285
285
|
the Python release. The Rust release workflow builds Linux x86_64/aarch64,
|
|
286
286
|
musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
|
|
@@ -332,13 +332,81 @@ MIDDLEWARE = [
|
|
|
332
332
|
```
|
|
333
333
|
|
|
334
334
|
The configuration uses a dedicated lowercase profile; existing uppercase
|
|
335
|
-
framework settings, `AIWAFConfig` dictionaries,
|
|
336
|
-
|
|
335
|
+
framework settings, `AIWAFConfig` dictionaries, custom stores and policy callbacks
|
|
336
|
+
are not imported into it. Unknown keys are rejected. Path rules and the route
|
|
337
|
+
manifest work as in the regular chain, through three adapter keys:
|
|
338
|
+
|
|
339
|
+
- `path_rules`: the same rules as `AIWAF_PATH_RULES`. `DISABLE` turns stages off for
|
|
340
|
+
a prefix, and `RATE_LIMIT` (`WINDOW`, `MAX`, `FLOOD`) replaces the profile's rate
|
|
341
|
+
limits there. Invalid limits fail at startup.
|
|
342
|
+
- `manifest_path`: default `.aiwaf/paths.json`. Its route rules are added after
|
|
343
|
+
`path_rules`, and the route-specific checks saved by `init` run on matching requests.
|
|
344
|
+
- `injection_risk_mode`: `block` (default), `log` or `off`, defaulting to
|
|
345
|
+
`AIWAF_INJECTION_RISK_MODE`. A blocked request is logged with the matched rule.
|
|
337
346
|
Route decorators for full/partial exemptions and required middleware are read
|
|
338
347
|
once. Required decorators override decorator exemptions; profile-level path/IP
|
|
339
348
|
exemptions remain global. The profile is immutable: construct a new engine and
|
|
340
349
|
reload workers to change it.
|
|
341
350
|
|
|
351
|
+
**The regular setup runs as the native pipeline by default** when the installed aiwaf-rust
|
|
352
|
+
has every native feature (0.2.9 or newer) and every setting carries over exactly,
|
|
353
|
+
so the report below lists no differences. Nothing in the app changes:
|
|
354
|
+
- **Django:** the regular AIWAF classes in `MIDDLEWARE` run as one native middleware, at
|
|
355
|
+
the place of the last of them, so sessions and authentication have run before it. The
|
|
356
|
+
others step aside with `MiddlewareNotUsed`.
|
|
357
|
+
- **Flask and FastAPI:** `AIWAF(app)` installs the native pipeline instead of the regular
|
|
358
|
+
middleware, with the same stages its plan would register.
|
|
359
|
+
|
|
360
|
+
Request logs go to `aiwaf_native_access.csv` in the regular log directory, which the Flask
|
|
361
|
+
and FastAPI trainers read. A model the regular middleware has loaded carries over if
|
|
362
|
+
aiwaf-rust made it; an sklearn model, or a Flask model still held back for lack of logs,
|
|
363
|
+
is a difference. AIWAF logs one line on the `aiwaf.native` logger when it switches. To keep
|
|
364
|
+
the regular middleware, set `AIWAF_NATIVE_PIPELINE = False` in Django settings or Flask
|
|
365
|
+
config, pass `native_pipeline=False` to Flask's or FastAPI's `AIWAF(...)`, or set the
|
|
366
|
+
`AIWAF_NATIVE_PIPELINE=false` environment variable. `aiwaf init` says whether a project
|
|
367
|
+
switches and, if not, why.
|
|
368
|
+
|
|
369
|
+
To start from the settings the regular middleware already uses explicitly, pass
|
|
370
|
+
`"from_settings"`: `NativeAIWAF(app, "from_settings")` in Flask,
|
|
371
|
+
`AIWAF_CSV_PIPELINE = "from_settings"` in Django, or
|
|
372
|
+
`app.add_middleware(NativeAIWAFMiddleware, config="from_settings")` in FastAPI, which
|
|
373
|
+
converts the `AIWAFConfig` the regular middleware uses (or one passed as `aiwaf_config`). `{"from_settings": True, ...}` converts
|
|
374
|
+
and then applies the other keys on top. The same `AIWAF_*` names are read with the same
|
|
375
|
+
defaults, including Django's built-in login and admin exemptions and keyword list, and
|
|
376
|
+
Django's stages follow the regular classes in `MIDDLEWARE`. At startup AIWAF logs, on the
|
|
377
|
+
`aiwaf.native` logger, how many settings carried over unchanged and every one that didn't,
|
|
378
|
+
with the reason: for example, Flask's `*.css`-style exemptions and IP ranges in
|
|
379
|
+
`AIWAF_EXEMPT_IPS`, which the native pipeline can't match. It also uses the regular
|
|
380
|
+
stores (below), so blocks, exemptions and keywords already stored carry over, and Flask's
|
|
381
|
+
pattern exemptions and FastAPI's private-range exemptions keep working. FastAPI's header-only `exempt_paths` become path rules
|
|
382
|
+
that turn off header validation alone, and its private-range auto-exemptions are reported
|
|
383
|
+
because only exact addresses carry over. `aiwaf.core.native_settings.native_config()` and
|
|
384
|
+
`native_config_fastapi()` return the same profile and report without starting anything.
|
|
385
|
+
|
|
386
|
+
By default the native pipeline keeps its blocklist, exemptions, learned keywords and
|
|
387
|
+
blocked countries in CSV files in `data_dir`. To use the stores the rest of the app
|
|
388
|
+
already uses, set `"store"` in the native config: `"django"`, `"flask"` or `"fastapi"` use
|
|
389
|
+
that framework's regular stores, following its storage settings (`AIWAF_STORAGE_MODE`,
|
|
390
|
+
`AIWAF_USE_CSV` or `AIWAF_DATA_DIR`, or `AIWAFConfig`'s `storage`), so the native and regular
|
|
391
|
+
middleware and the management commands share one blocklist. Flask's store also matches its
|
|
392
|
+
`*.css`-style exemptions, and FastAPI's its private-range IP exemptions, which native
|
|
393
|
+
profiles can't. `"from_settings"` turns this on when the installed aiwaf-rust supports it.
|
|
394
|
+
Elsewhere, pass `stores=` to `CSVPipeline`. Before
|
|
395
|
+
each decision AIWAF reads what that request's stages use: whether it's exempt, then, if
|
|
396
|
+
not, whether the IP is blocked (IP/keyword and anomaly stages), the learned keywords
|
|
397
|
+
(IP/keyword stage) and blocked countries (geo stage). A route whose path rules turn those
|
|
398
|
+
stages off reads nothing. Answers are cached for `store_cache_seconds` (default 5):
|
|
399
|
+
keywords and countries, and the blocklist and exemption answers per IP and path, up to
|
|
400
|
+
10,000 of each. So a block or exemption made in another worker, the admin or the CLI can
|
|
401
|
+
take that long to apply; blocks this worker makes apply at once. `store_cache_seconds: 0`
|
|
402
|
+
reads the stores on every request. It then
|
|
403
|
+
writes the blocks and keywords the decision produced back through the stores. The
|
|
404
|
+
decision itself still runs in aiwaf-rust. A custom store is any object with
|
|
405
|
+
`is_blocked(ip)`, `is_exempted(ip, path)`, `top_keywords(n)`, `blocked_countries()`,
|
|
406
|
+
`block(ip, reason)` and `learn(keywords)`; `aiwaf.core.csv_pipeline.PipelineStores`
|
|
407
|
+
documents them. Rate limits, honeypot timing, UUID scores and anomaly history stay in
|
|
408
|
+
the engine.
|
|
409
|
+
|
|
342
410
|
Common profile keys and defaults:
|
|
343
411
|
|
|
344
412
|
| Setting | Default / meaning |
|
|
@@ -346,11 +414,12 @@ Common profile keys and defaults:
|
|
|
346
414
|
| `enabled` | All eight names: `geo_block`, `ip_keyword_block`, `rate_limit`, `ai_anomaly`, `honeypot`, `uuid_tamper`, `header_validation`, `logging` |
|
|
347
415
|
| `data_dir` | `aiwaf_data`; policy CSVs use the shared allowlist/blocklist/keyword/geo/path schemas |
|
|
348
416
|
| `exempt_paths`, `exempt_ips` | `/health`, `/robots.txt`, `/sitemap.xml`; empty IP list. Paths are literal, case-insensitive prefixes, not globs. Stored path exemptions use the same literal-prefix rule |
|
|
349
|
-
| `sql_mode`, `max_bytes` | `block`, `65536`; `
|
|
417
|
+
| `sql_mode`, `max_bytes` | `block`, `65536`; also `monitor`, which logs findings on the `aiwaf.payload` logger without blocking, and `off`. Structured JSON/form bodies and nested escaped strings are inspected with bounded traversal |
|
|
350
418
|
| `learning`, `top_n` | `True`, `10`; presence keywords use a sorted, stable subset instead of Python set iteration order |
|
|
351
419
|
| `static_keywords`, `legitimate_keywords`, `exempt_keywords`, `safe_prefixes` | Native policy defaults or explicit arrays; set route-specific safe vocabulary in the profile |
|
|
352
420
|
| `geo_allow`, `geo_block` | Empty lists; includes stored blocked countries. Unknown country remains allowed |
|
|
353
|
-
| `rate_backend`, `rate_key_mode` | `memory`, `ip_path`; `csv` shares buckets across workers; `ip` aggregates paths
|
|
421
|
+
| `rate_backend`, `rate_key_mode` | `memory`, `ip_path`; `csv` shares buckets across workers; `redis` and `django_cache` (Django) share counts through a cache, below; `ip` aggregates paths |
|
|
422
|
+
| `rate_redis_url`, `rate_cache_namespace`, `rate_cache_alias` | Required for `rate_backend="redis"`; key prefix, default `aiwaf:native:rate:v1`; Django cache alias for `django_cache`, default `default` |
|
|
354
423
|
| `rate_window`, `rate_max`, `rate_flood` | `10`, `20`, `40`; throttle at 429, flood at 403 with blocklist persistence |
|
|
355
424
|
| `soft_block_blocklist`, `ip_blocking`, `block_duration` | `False`, `True`, reputation-based duration; explicit seconds or nonpositive permanent duration |
|
|
356
425
|
| `honeypot_backend` | Django defaults to `django_cache`; Flask/FastAPI and direct construction default to `csv`. Optional `memory` is local to one engine; `redis` and `cache` delegate timestamp I/O while Rust enforces timing |
|
|
@@ -379,6 +448,22 @@ transfer timestamps automatically. Keep `csv` for shared or persistent timing;
|
|
|
379
448
|
CSV writes remain immediately synced. Blocklist, keyword, geo and allowlist
|
|
380
449
|
policy files and immediate request logging keep their configured CSV behavior.
|
|
381
450
|
|
|
451
|
+
### Shared native rate limits
|
|
452
|
+
|
|
453
|
+
With `rate_backend: "memory"` each worker counts on its own, so N workers allow N times
|
|
454
|
+
the limit. `rate_backend: "redis"` with `rate_redis_url` counts in Redis instead, with the
|
|
455
|
+
regular limiter's atomic sliding-window script, and in Django `"django_cache"` counts in a
|
|
456
|
+
Django cache (`rate_cache_alias`), as the regular rate limiter does. Only the count is
|
|
457
|
+
shared: aiwaf-rust still applies `rate_max`, `rate_flood` and path-rule limits to it.
|
|
458
|
+
`CSVPipeline(config, rate_counter=...)` with `rate_backend: "counter"` takes any object
|
|
459
|
+
with a synchronous, atomic `count(key, now, window_seconds)` that records the request and
|
|
460
|
+
returns the window's count. A failing counter answers 503, as the regular limiter does.
|
|
461
|
+
`from_settings` carries this over: Django counts in its default cache, and Flask
|
|
462
|
+
(`AIWAF_RATE_CACHE_BACKEND="redis"` with `AIWAF_REDIS_URL`) and FastAPI
|
|
463
|
+
(`rate_limiting.cache_backend`, `rate_limiting.redis_url`) count in the same Redis. It
|
|
464
|
+
needs `aiwaf-rust` 0.2.9 or newer; with 0.2.8 a counter fails at startup and `from_settings`
|
|
465
|
+
reports that rate limits stay per worker.
|
|
466
|
+
|
|
382
467
|
### Flask and FastAPI native honeypot cache
|
|
383
468
|
|
|
384
469
|
Both native adapters accept Redis or a supplied synchronous cache. CSV remains
|
|
@@ -586,6 +671,12 @@ aiwaf init --framework django --settings project.settings
|
|
|
586
671
|
aiwaf init --framework flask --app app:app --output .aiwaf/paths.json
|
|
587
672
|
```
|
|
588
673
|
|
|
674
|
+
`aiwaf init` then prints how to run the native pipeline for that framework, the
|
|
675
|
+
recommended setup for new installs, with the conversion report for the project's own
|
|
676
|
+
settings: what carries over and what wouldn't. In a Django project already using the
|
|
677
|
+
regular middleware, it says how to switch; nothing changes until you do. `--no-native`
|
|
678
|
+
skips this part.
|
|
679
|
+
|
|
589
680
|
Run the command in the same environment and checkout used to start the application. If it discovers only `/` and Flask's static route, verify the imported file and live route table:
|
|
590
681
|
|
|
591
682
|
```bash
|
|
@@ -990,22 +1081,91 @@ serializes the request envelope, emits responses, and appends the returned rows
|
|
|
990
1081
|
using cached file descriptors. Logging is immediate, not queued or batched.
|
|
991
1082
|
|
|
992
1083
|
The dedicated lowercase `profile` rejects unknown keys. It does not import legacy
|
|
993
|
-
settings
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1084
|
+
settings or Redis state on its own; see `from_settings` and `stores` below. Missing native support fails startup with no JavaScript policy fallback.
|
|
1085
|
+
Install this adapter instead of the existing chain, not alongside it. Body parsers
|
|
1086
|
+
can run before or after it. A parsed `req.body` is inspected as it is. An unparsed body
|
|
1087
|
+
is handled as in Python: uploads and other bodies that aren't JSON, form or XML
|
|
1088
|
+
(multipart, binary) pass through unread, so upload middleware such as multer still
|
|
1089
|
+
gets the whole stream. An unparsed JSON, form or XML body is read up to `max_bytes`,
|
|
1090
|
+
inspected, and put back on the stream for the parsers after it. A larger one is
|
|
1091
|
+
refused with 413 (`payload_inspection_limit`), or logged in monitor mode. A compressed
|
|
1092
|
+
or already-consumed inspectable body can't be read, and is refused with 413 as
|
|
1093
|
+
before. `uuidResolver(uid, req)`, as in the regular middleware, is asked
|
|
1094
|
+
whether the record named by a well-formed UUID under `uuid_prefix` exists. It can be
|
|
1095
|
+
async; only those requests wait for it, `false` blocks with `uuid_not_found`, and a
|
|
1096
|
+
failing resolver lets the request through. `countryLookup(req)`, `authenticated(req)` and `routeExists(req)`
|
|
999
1097
|
are optional synchronous fact callbacks; country defaults to unknown and route
|
|
1000
1098
|
existence to `Boolean(req.route)`. Supply accurate facts when the firewall runs
|
|
1001
1099
|
before Express resolves routes. Country headers are not implicitly trusted.
|
|
1002
1100
|
|
|
1101
|
+
**`aiwaf(options)` runs the native pipeline by default** when two things hold: the
|
|
1102
|
+
installed aiwaf-wasm is 0.2.7 or newer (it has every native feature), and every option
|
|
1103
|
+
carries over exactly, so the conversion report below lists no differences. Otherwise it
|
|
1104
|
+
runs the regular middleware, as before. It logs one line when it picks the native
|
|
1105
|
+
pipeline. To keep the regular middleware, set `AIWAF_NATIVE_PIPELINE: false` in the
|
|
1106
|
+
options or `AIWAF_NATIVE_PIPELINE=false` in the environment. A model saved by
|
|
1107
|
+
`aiwaf train` carries over; the sample model shipped in `resources/model.json` doesn't,
|
|
1108
|
+
since it's in the old format and only a sample. Another model in the old format, or one
|
|
1109
|
+
kept in the database or cache, is a difference, so those apps stay on the regular
|
|
1110
|
+
middleware. The client address is resolved as the regular middleware resolves it,
|
|
1111
|
+
through `AIWAF_TRUSTED_PROXIES` (the native adapter's `trustedProxies` option).
|
|
1112
|
+
|
|
1113
|
+
To start from the options the regular middleware already takes explicitly, add
|
|
1114
|
+
`AIWAF_NATIVE_PIPELINE: 'from_settings'` to them, as in Python: `aiwaf({ MAX_REQ: 50, ...,
|
|
1115
|
+
AIWAF_NATIVE_PIPELINE: 'from_settings' })`. Options are read through the same
|
|
1116
|
+
normalization, defaults and environment variables, so the regular defaults (60-second
|
|
1117
|
+
windows, no static keywords, header validation off) carry over rather than the native
|
|
1118
|
+
ones. `{ fromSettings: true, dataDir, logger, profile: {...} }` also passes native options,
|
|
1119
|
+
and its `profile` keys win. The startup report has the same form as Python's: how many
|
|
1120
|
+
options carried over unchanged, then every one that didn't, with the reason, written to
|
|
1121
|
+
`logger.warn` (or `logger.info` when nothing differs). `aiwaf.nativeOptionsFromSettings(options)`
|
|
1122
|
+
returns the converted `config`, ready for `aiwaf.native()`, with its `report()`, `notes` and
|
|
1123
|
+
`differences()`, without starting anything.
|
|
1124
|
+
|
|
1125
|
+
By default blocks and learned keywords stay in the adapter's own files (below). To share
|
|
1126
|
+
them with the regular middleware and its CLI, pass `stores: 'regular'`. The adapter
|
|
1127
|
+
then uses Node's regular blocklist, exemption, dynamic keyword and geo stores, from the
|
|
1128
|
+
database when one is configured or otherwise their CSV files. Their blocks apply,
|
|
1129
|
+
their IP and path exemptions keep logging only, a learned keyword applies once its count
|
|
1130
|
+
passes `dynamicTopN`, and blocked countries add to `geo_block`. `from_settings` turns
|
|
1131
|
+
this on, carrying `dynamicTopN` and `AIWAF_EXEMPTIONS_DB`. `stores` also takes any object
|
|
1132
|
+
with six methods, each sync or async:
|
|
1133
|
+
`isBlocked(ip)`, `isExempted(ip, path)`, `topKeywords(limit)`, `blockedCountries()`,
|
|
1134
|
+
`block(ip, reason, expiresAt)` and `learn(keyword)`. The adapter reads them before the
|
|
1135
|
+
engine decides, only for the stages the request runs, and keywords, countries and the
|
|
1136
|
+
blocklist and exemption answers are cached for `storeCacheSeconds` (default 5), so a block
|
|
1137
|
+
or exemption made elsewhere can take that long to apply; this worker's own blocks apply at
|
|
1138
|
+
once. A failed read goes to `onError` and counts as not blocked, not exempt and nothing
|
|
1139
|
+
learned. Blocks and keywords are written after the response, so a block applies from
|
|
1140
|
+
the client's next request once the write lands. The decision itself stays in aiwaf-wasm.
|
|
1141
|
+
Stores need `aiwaf-wasm` 0.2.7 or newer. With an older build, `stores` fails at startup, and
|
|
1142
|
+
`from_settings` (which adds `storesFallback: 'csv'`) keeps the adapter's own files and
|
|
1143
|
+
warns.
|
|
1144
|
+
|
|
1145
|
+
Rate limits are counted in each worker unless `rateCounter` is set. `aiwaf.redisRateCounter(client)`
|
|
1146
|
+
takes a node-redis v4 or ioredis client and counts in Redis atomically, with the same
|
|
1147
|
+
script and key format as Python's native Redis backend, so every worker shares one
|
|
1148
|
+
limit. Any object with `count(key, now, windowSeconds)`, sync or async, also works. The
|
|
1149
|
+
count is read before the engine decides, and the engine still applies the profile's and
|
|
1150
|
+
path rules' limits to it; exempt requests aren't counted. A failing counter answers 503,
|
|
1151
|
+
or lets the request through with `rateFailureMode: 'open'`. `from_settings` uses the
|
|
1152
|
+
regular middleware's `cache` option when it's a Redis client, and carries
|
|
1153
|
+
`AIWAF_RATE_CACHE_FAILURE_MODE`; with an older aiwaf-wasm it counts per worker and warns.
|
|
1154
|
+
|
|
1155
|
+
Path rules and the route manifest work as in the regular middleware, through three
|
|
1156
|
+
adapter options. `pathRules` takes the same rules as `AIWAF_PATH_RULES`: `DISABLE`
|
|
1157
|
+
turns stages off for a prefix, and `RATE_LIMIT` replaces the profile's rate limits
|
|
1158
|
+
there, with invalid limits failing at startup. `manifestPath` (default
|
|
1159
|
+
`AIWAF_PATH_MANIFEST`, then `.aiwaf/paths.json`) adds the manifest's route rules and
|
|
1160
|
+
the route-specific checks saved by `init`. `injectionRiskMode` is `block` (default),
|
|
1161
|
+
`log` or `off`, defaulting to `AIWAF_INJECTION_RISK_MODE`.
|
|
1162
|
+
|
|
1003
1163
|
All eight stages are enabled by default. Native defaults include:
|
|
1004
1164
|
|
|
1005
1165
|
| Profile setting | Default / scope |
|
|
1006
1166
|
| --- | --- |
|
|
1007
1167
|
| `exempt_paths`, `exempt_ips` | `/health`, `/robots.txt`, `/sitemap.xml`; no IPs; literal case-insensitive path prefixes |
|
|
1008
|
-
| `sql_mode`, `max_bytes` | `block`, `65536`; `
|
|
1168
|
+
| `sql_mode`, `max_bytes` | `block`, `65536`; also `monitor`, which logs `{event: 'aiwaf.payload', rule, mode}` through the `logger` option (default `console`) without blocking, and `off`; bounded nested JSON/form values and double URL decoding |
|
|
1009
1169
|
| `static_keywords`, `dynamic_keywords`, `legitimate_keywords`, `learning` | Native vocabulary, empty dynamic set, legitimate exact route names, `true`; learned probe segments capped at 4096 |
|
|
1010
1170
|
| `geo_allow`, `geo_block`, `blocklist` | Empty; blocklist maps IP to Unix expiry seconds (`0` permanent) |
|
|
1011
1171
|
| `rate_window`, `rate_max`, `rate_flood`, `rate_key_mode` | `10` seconds, `20`, `40`, `ip_path`; `ip` also supported |
|
|
@@ -1015,8 +1175,8 @@ All eight stages are enabled by default. Native defaults include:
|
|
|
1015
1175
|
| `anomaly_window`, `max_history`, `max_clients`, `max_pending` | `60` seconds, `1000`, `100000`, `10000`; periodic cleanup and bounded state |
|
|
1016
1176
|
| `block_duration` | `86400` seconds for newly generated blocks |
|
|
1017
1177
|
|
|
1018
|
-
Rate counters, honeypot timestamps, UUID scores, anomaly history and loaded policy
|
|
1019
|
-
snapshots are local to each engine/worker and reset on restart.
|
|
1178
|
+
Rate counters (without `rateCounter`), honeypot timestamps, UUID scores, anomaly history and loaded policy
|
|
1179
|
+
snapshots are local to each engine/worker and reset on restart. Without `stores`, blocks and learned
|
|
1020
1180
|
keywords append to dedicated `native_blocks.csv`/`native_keywords.csv`, synced
|
|
1021
1181
|
immediately, and replay at startup (`persistBlocks: false` disables this disk
|
|
1022
1182
|
history). Policy files are **not live synchronized across workers**; do not share
|
|
@@ -1506,10 +1666,10 @@ Release versions and tags must match the relevant manifest.
|
|
|
1506
1666
|
|
|
1507
1667
|
| Package | Manifest | Tag | Workflow |
|
|
1508
1668
|
| --- | --- | --- | --- |
|
|
1509
|
-
| Python `aiwaf` | `pyproject.toml` | `python-v1.
|
|
1510
|
-
| npm `aiwaf` | `js/package.json` | `js-v1.
|
|
1511
|
-
| PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.
|
|
1512
|
-
| npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.
|
|
1669
|
+
| Python `aiwaf` | `pyproject.toml` | `python-v1.2.0` | `python-publish.yml` |
|
|
1670
|
+
| npm `aiwaf` | `js/package.json` | `js-v1.2.0` | `npm-publish.yml` |
|
|
1671
|
+
| PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.9` | `rust-publish.yml` |
|
|
1672
|
+
| npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.7` | `wasm-publish.yml` |
|
|
1513
1673
|
| Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.6` | `java-publish.yml` |
|
|
1514
1674
|
|
|
1515
1675
|
Python and Rust publish to PyPI with trusted publishing. The npm workflows use npm trusted publishing and stage packages for approval. Configure the trusted publisher with organization `aiwaf-project`, repository `aiwaf`, the exact workflow filename, and the environment used by that workflow.
|
|
@@ -1518,12 +1678,14 @@ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE
|
|
|
1518
1678
|
|
|
1519
1679
|
Registry releases are immutable. Increment the relevant manifest version before publishing another release.
|
|
1520
1680
|
|
|
1521
|
-
For this release, publish `aiwaf-rust 0.2.
|
|
1522
|
-
`aiwaf-wasm 0.2.
|
|
1523
|
-
0.2.
|
|
1524
|
-
|
|
1525
|
-
`npm
|
|
1526
|
-
|
|
1681
|
+
For this release, publish `aiwaf-rust 0.2.9` before Python `aiwaf 1.2.0`, and
|
|
1682
|
+
`aiwaf-wasm 0.2.7` before npm `aiwaf 1.2.0`. Python `aiwaf` 1.2.0 requires
|
|
1683
|
+
`aiwaf-rust>=0.2.9`, so its CI installs need 0.2.9 published first. npm `aiwaf` 1.2.0
|
|
1684
|
+
needs `aiwaf-wasm` 0.2.7, but its dependency and lockfile still name 0.2.6 so that
|
|
1685
|
+
`npm ci` keeps working until 0.2.7 is published. After WASM publication, run
|
|
1686
|
+
`npm install aiwaf-wasm@^0.2.7` in `js/` to update both, commit that, run `npm ci`
|
|
1687
|
+
and the release checks, and only then publish npm `aiwaf`. Java has no changes since
|
|
1688
|
+
1.3.6, which is already published.
|
|
1527
1689
|
|
|
1528
1690
|
## Security and limitations
|
|
1529
1691
|
|
package/index.js
CHANGED
|
@@ -29,6 +29,9 @@ function withMiddlewares(selection) {
|
|
|
29
29
|
module.exports = createExpressMiddleware;
|
|
30
30
|
// Await startup once; this path requires native support and has no JS policy fallback.
|
|
31
31
|
module.exports.native = require('./lib/nativePipeline');
|
|
32
|
+
// Native options built from regular aiwaf(options), with a report of what didn't carry over.
|
|
33
|
+
module.exports.nativeOptionsFromSettings = require('./lib/nativeSettings').nativeOptionsFromSettings;
|
|
34
|
+
module.exports.redisRateCounter = require('./lib/nativeRateCounter').redisRateCounter;
|
|
32
35
|
module.exports.fastify = createFastifyPlugin;
|
|
33
36
|
module.exports.hapi = createHapiPlugin;
|
|
34
37
|
module.exports.koa = createKoaMiddleware;
|
package/lib/hapiPlugin.js
CHANGED
|
@@ -53,14 +53,17 @@ module.exports = {
|
|
|
53
53
|
if (middleware.ready) {
|
|
54
54
|
const native = await middleware.ready;
|
|
55
55
|
const { DEFER_BODY } = require('./nativePipeline');
|
|
56
|
-
server.ext('onRequest', (request, h) => {
|
|
56
|
+
server.ext('onRequest', async (request, h) => {
|
|
57
57
|
const req = request.raw.req;
|
|
58
58
|
req.ip = request.info.remoteAddress; req.path = request.path;
|
|
59
59
|
req.url = request.url.pathname + request.url.search;
|
|
60
60
|
req[DEFER_BODY] = true;
|
|
61
61
|
req.body = undefined; req.query = undefined;
|
|
62
62
|
const res = createExpressLikeResponse(h, request.raw.res);
|
|
63
|
-
|
|
63
|
+
let failure = null;
|
|
64
|
+
// An async uuidResolver makes the native middleware return a promise.
|
|
65
|
+
await native(req, res, error => { if (error) failure = error; });
|
|
66
|
+
if (failure) throw failure;
|
|
64
67
|
return res._handled ? res.toResponse().takeover() : h.continue;
|
|
65
68
|
});
|
|
66
69
|
server.ext('onPreHandler', (request,h) => {
|
package/lib/nativePipeline.js
CHANGED
|
@@ -5,7 +5,27 @@ const { performance } = require('perf_hooks');
|
|
|
5
5
|
const { createRequestPipeline } = require('./wasmAdapter');
|
|
6
6
|
const wasmChecks = require('./wasmChecks');
|
|
7
7
|
const routeRisks = require('./routeRisks');
|
|
8
|
-
const { ALL_MIDDLEWARES,
|
|
8
|
+
const { ALL_MIDDLEWARES, createRoutePlan } = require('./pathRules');
|
|
9
|
+
const { getEffectivePathRules } = require('./pathManifest');
|
|
10
|
+
const { getRequestIp } = require('./runtimeUtils');
|
|
11
|
+
|
|
12
|
+
// RATE_LIMIT names accepted in path rules, as in the regular rate limiter.
|
|
13
|
+
const RATE_KEYS = {
|
|
14
|
+
window: ['WINDOW_SEC', 'WINDOW', 'window_seconds', 'windowSeconds'],
|
|
15
|
+
max: ['MAX_REQ', 'MAX', 'max_requests', 'maxRequests'],
|
|
16
|
+
flood: ['FLOOD_REQ', 'FLOOD', 'flood_threshold', 'floodThreshold']
|
|
17
|
+
};
|
|
18
|
+
function rateOverrides(rule = {}) {
|
|
19
|
+
const limits = {};
|
|
20
|
+
for (const [name, keys] of Object.entries(RATE_KEYS)) {
|
|
21
|
+
const key = keys.find(k => rule[k] !== undefined && rule[k] !== null);
|
|
22
|
+
if (key === undefined) continue;
|
|
23
|
+
const value = Number(rule[key]);
|
|
24
|
+
if (!Number.isFinite(value) || (name !== 'window' && !Number.isInteger(value))) throw new Error(`RATE_LIMIT ${key} must be a number`);
|
|
25
|
+
limits[name] = value;
|
|
26
|
+
}
|
|
27
|
+
return limits;
|
|
28
|
+
}
|
|
9
29
|
|
|
10
30
|
const LOG_HEADER = 'timestamp,ip,method,path,status,response_time_ms,blocked,reason,country,user_agent\n';
|
|
11
31
|
const BLOCK_HEADER = 'ip,expires_at,reason\n';
|
|
@@ -56,13 +76,69 @@ function readRows(file, expected) {
|
|
|
56
76
|
return Object.fromEntries(expected.map((key, index) => [key, cells[index]]));
|
|
57
77
|
});
|
|
58
78
|
}
|
|
79
|
+
// The content types whose bodies are inspected, as in Python. Uploads and other bodies
|
|
80
|
+
// (multipart, binary) pass through unread, as in the regular middleware.
|
|
81
|
+
function inspectable(req) {
|
|
82
|
+
const media = String(req.headers?.['content-type'] || '').split(';', 1)[0].trim().toLowerCase();
|
|
83
|
+
return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'].includes(media)
|
|
84
|
+
|| media.endsWith('+json') || media.endsWith('+xml');
|
|
85
|
+
}
|
|
86
|
+
function declaredBody(req) {
|
|
87
|
+
return Number(req.headers?.['content-length'] || 0) > 0 || !!req.headers?.['transfer-encoding'];
|
|
88
|
+
}
|
|
89
|
+
// An unparsed inspectable body this adapter can read itself: identity-encoded and unread.
|
|
90
|
+
function readable(req) {
|
|
91
|
+
const encoding = String(req.headers?.['content-encoding'] || 'identity').trim().toLowerCase();
|
|
92
|
+
return req.body === undefined && declaredBody(req) && inspectable(req) && encoding === 'identity'
|
|
93
|
+
&& typeof req.read === 'function' && typeof req.unshift === 'function' && !req.readableEnded;
|
|
94
|
+
}
|
|
95
|
+
const PEEKED = Symbol('aiwaf.native.peeked-body');
|
|
96
|
+
// Reads at most limit + 1 bytes of the body, then puts them back on the stream, so body
|
|
97
|
+
// parsers after this adapter still read the whole body. Python's adapters do the same.
|
|
98
|
+
function peekBody(req, limit) {
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
const chunks = [];
|
|
101
|
+
let size = 0;
|
|
102
|
+
const expected = Number(req.headers?.['content-length']) || null;
|
|
103
|
+
const finish = () => {
|
|
104
|
+
req.removeListener('readable', onReadable);
|
|
105
|
+
req.removeListener('error', onError);
|
|
106
|
+
const prefix = Buffer.concat(chunks);
|
|
107
|
+
if (prefix.length) req.unshift(prefix);
|
|
108
|
+
resolve(prefix);
|
|
109
|
+
};
|
|
110
|
+
const onError = error => { req.removeListener('readable', onReadable); reject(error); };
|
|
111
|
+
function onReadable() {
|
|
112
|
+
let chunk;
|
|
113
|
+
while ((chunk = req.read()) !== null) {
|
|
114
|
+
chunks.push(chunk);
|
|
115
|
+
size += chunk.length;
|
|
116
|
+
if (size > limit || size === expected) return finish();
|
|
117
|
+
}
|
|
118
|
+
// The whole body is buffered: put it back before the stream emits 'end'.
|
|
119
|
+
if (req._readableState?.ended) finish();
|
|
120
|
+
}
|
|
121
|
+
req.on('error', onError);
|
|
122
|
+
req.on('readable', onReadable);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
59
125
|
function safeBody(req, limit) {
|
|
126
|
+
const peeked = req[PEEKED];
|
|
127
|
+
if (peeked) {
|
|
128
|
+
if (peeked.length > limit) return { body: null, exhausted: true };
|
|
129
|
+
const text = peeked.toString('utf8');
|
|
130
|
+
// JSON is parsed here, as a body parser would, so it's checked exactly like a parsed body.
|
|
131
|
+
if (/json/.test(String(req.headers?.['content-type']))) {
|
|
132
|
+
try { return { body: JSON.parse(text), exhausted: false }; } catch (_) { /* checked as text */ }
|
|
133
|
+
}
|
|
134
|
+
return { body: text, exhausted: false };
|
|
135
|
+
}
|
|
60
136
|
const body = req.body;
|
|
61
|
-
if (body === undefined) {
|
|
62
|
-
//
|
|
63
|
-
|
|
137
|
+
if (body === undefined || (body && typeof body.pipe === 'function')) {
|
|
138
|
+
// An upload or other body that isn't inspected passes unread. An inspectable one this
|
|
139
|
+
// adapter couldn't read (compressed, or already consumed) can't be checked.
|
|
140
|
+
return { body: null, exhausted: declaredBody(req) && inspectable(req) };
|
|
64
141
|
}
|
|
65
|
-
if (body && typeof body.pipe === 'function') return { body: null, exhausted: true };
|
|
66
142
|
try {
|
|
67
143
|
const value = Buffer.isBuffer(body) ? body.toString('utf8') : body;
|
|
68
144
|
const encoded = JSON.stringify(value);
|
|
@@ -70,12 +146,77 @@ function safeBody(req, limit) {
|
|
|
70
146
|
return { body: value, exhausted: false };
|
|
71
147
|
} catch (_) { return { body: null, exhausted: true }; }
|
|
72
148
|
}
|
|
149
|
+
// Express trust proxy controls forwarded-IP handling. Never trust XFF directly.
|
|
150
|
+
function peerIp(req) {
|
|
151
|
+
return String(req.ip || req.socket?.remoteAddress || 'unknown').replace(/^::ffff:/, '');
|
|
152
|
+
}
|
|
153
|
+
// A model saved by `aiwaf train`, as the regular middleware's file storage keeps it.
|
|
154
|
+
async function readModelFile(file) {
|
|
155
|
+
const data = JSON.parse(await fs.promises.readFile(file, 'utf8'));
|
|
156
|
+
if (data?.model_type !== 'aiwaf_wasm.IsolationForest' || !data.model_state) {
|
|
157
|
+
throw new Error(`${file} isn't a model the native pipeline can use. Retrain with: aiwaf train`);
|
|
158
|
+
}
|
|
159
|
+
return require('./wasmAdapter').createIsolationForestFromJSON(data.model_state);
|
|
160
|
+
}
|
|
73
161
|
function headers(raw = {}) {
|
|
74
162
|
return Object.fromEntries(Object.entries(raw).map(([key, value]) => [
|
|
75
163
|
['content-type', 'content-length'].includes(key.toLowerCase()) ? key.toUpperCase().replace(/-/g, '_') : `HTTP_${key.toUpperCase().replace(/-/g, '_')}`,
|
|
76
164
|
Array.isArray(value) ? value.join(', ') : String(value ?? '')
|
|
77
165
|
]));
|
|
78
166
|
}
|
|
167
|
+
const STAGE_NAMES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
|
|
168
|
+
// Recent true/false answers per key, for `seconds`, keeping at most `limit` keys. A failed
|
|
169
|
+
// read isn't kept.
|
|
170
|
+
function recentAnswers(seconds, limit = 10000) {
|
|
171
|
+
const items = new Map();
|
|
172
|
+
const set = (key, value) => {
|
|
173
|
+
if (!(seconds > 0)) return;
|
|
174
|
+
items.delete(key);
|
|
175
|
+
items.set(key, { until: performance.now() + seconds * 1000, value: !!value });
|
|
176
|
+
while (items.size > limit) items.delete(items.keys().next().value);
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
items,
|
|
180
|
+
set,
|
|
181
|
+
async get(key, load) {
|
|
182
|
+
const hit = items.get(key);
|
|
183
|
+
if (hit && hit.until > performance.now()) {
|
|
184
|
+
items.delete(key); items.set(key, hit);
|
|
185
|
+
return hit.value;
|
|
186
|
+
}
|
|
187
|
+
const value = !!(await load());
|
|
188
|
+
set(key, value);
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// The store methods a stores option provides. Each may return a promise.
|
|
194
|
+
const STORE_METHODS = ['isBlocked', 'isExempted', 'topKeywords', 'blockedCountries', 'block', 'learn'];
|
|
195
|
+
// Node's own blocklist, exemption, keyword and geo stores: a database when one is configured,
|
|
196
|
+
// otherwise their CSV files, as the regular middleware uses them.
|
|
197
|
+
function regularStores({ dynamicTopN = 10, exemptionsDb = true } = {}) {
|
|
198
|
+
const blocklistManager = require('./blocklistManager');
|
|
199
|
+
const exemptionStore = require('./exemptionStore');
|
|
200
|
+
const dynamicKeywordStore = require('./dynamicKeywordStore');
|
|
201
|
+
const geoStore = require('./geoStore');
|
|
202
|
+
return {
|
|
203
|
+
isBlocked: ip => blocklistManager.isBlocked(ip),
|
|
204
|
+
async isExempted(ip, requestPath) {
|
|
205
|
+
if (!exemptionsDb) return false;
|
|
206
|
+
// Exemption storage failures fail open, as in the regular middleware.
|
|
207
|
+
try {
|
|
208
|
+
return !!(await exemptionStore.isIpExempt(String(ip).toLowerCase())
|
|
209
|
+
|| await exemptionStore.isPathExempt(String(requestPath).toLowerCase()));
|
|
210
|
+
} catch (_) { return false; }
|
|
211
|
+
},
|
|
212
|
+
// A learned keyword applies once its count passes dynamicTopN, as in the regular middleware.
|
|
213
|
+
topKeywords: async limit => (await dynamicKeywordStore.list(limit))
|
|
214
|
+
.filter(row => Number(row.count || 0) > dynamicTopN).map(row => String(row.keyword)),
|
|
215
|
+
blockedCountries: async () => (await geoStore.listBlockedCountries()).map(row => String(row.country_code)),
|
|
216
|
+
block: (ip, reason) => blocklistManager.block(ip, reason),
|
|
217
|
+
learn: keyword => dynamicKeywordStore.increment(keyword)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
79
220
|
function synchronous(callback, req, fallback) {
|
|
80
221
|
const result = callback ? callback(req) : fallback;
|
|
81
222
|
if (result && typeof result.then === 'function') throw new TypeError('Native fact callbacks must return synchronous values');
|
|
@@ -85,19 +226,81 @@ function synchronous(callback, req, fallback) {
|
|
|
85
226
|
module.exports = async function createNativeMiddleware(options = {}) {
|
|
86
227
|
if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
|
|
87
228
|
if (options.profile !== undefined && (!options.profile || typeof options.profile !== 'object' || Array.isArray(options.profile))) throw new TypeError('Native profile must be an object');
|
|
88
|
-
const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError'
|
|
229
|
+
const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
|
|
230
|
+
'rateCounter', 'rateCounterFallback', 'rateFailureMode', 'trustedProxies', 'modelFile']);
|
|
89
231
|
for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
|
|
232
|
+
if (options.uuidResolver != null && typeof options.uuidResolver !== 'function') throw new TypeError('uuidResolver must be a function');
|
|
90
233
|
for (const key of ['countryLookup','authenticated','routeExists','onError']) {
|
|
91
234
|
if (options[key] != null && (typeof options[key] !== 'function' || options[key].constructor.name === 'AsyncFunction')) throw new TypeError(`${key} must be synchronous`);
|
|
92
235
|
}
|
|
236
|
+
if (options.pathRules != null && !Array.isArray(options.pathRules)) throw new TypeError('pathRules must be an array of rules');
|
|
237
|
+
let stores = null;
|
|
238
|
+
if (options.stores === 'regular') stores = regularStores();
|
|
239
|
+
else if (options.stores != null) {
|
|
240
|
+
if (typeof options.stores !== 'object') throw new TypeError('stores must be "regular" or an object with the store methods');
|
|
241
|
+
const missing = STORE_METHODS.filter(name => typeof options.stores[name] !== 'function');
|
|
242
|
+
if (missing.length) throw new TypeError(`stores is missing ${missing.join(', ')}`);
|
|
243
|
+
stores = options.stores;
|
|
244
|
+
}
|
|
245
|
+
if (options.storesFallback != null && options.storesFallback !== 'csv') throw new TypeError('storesFallback must be "csv"');
|
|
246
|
+
let rateCounter = options.rateCounter ?? null;
|
|
247
|
+
if (rateCounter !== null && typeof rateCounter?.count !== 'function') throw new TypeError('rateCounter must have a count(key, now, windowSeconds) method');
|
|
248
|
+
if (options.rateCounterFallback != null && options.rateCounterFallback !== 'memory') throw new TypeError('rateCounterFallback must be "memory"');
|
|
249
|
+
const rateFailureMode = options.rateFailureMode ?? 'closed';
|
|
250
|
+
if (!['closed', 'open'].includes(rateFailureMode)) throw new TypeError('rateFailureMode must be "closed" or "open"');
|
|
251
|
+
// With trustedProxies, the client address is resolved as the regular middleware resolves
|
|
252
|
+
// it (AIWAF_TRUSTED_PROXIES); without it, from req.ip, which Express trust proxy controls.
|
|
253
|
+
const clientIp = options.trustedProxies === undefined ? peerIp
|
|
254
|
+
: req => getRequestIp(req, options.trustedProxies).replace(/^::ffff:/, '');
|
|
255
|
+
if (options.modelFile != null && (options.model != null || typeof options.modelFile !== 'string')) {
|
|
256
|
+
throw new TypeError('modelFile must be a path, and can\'t be combined with model');
|
|
257
|
+
}
|
|
258
|
+
const storeCacheSeconds = Number(options.storeCacheSeconds ?? 5);
|
|
259
|
+
if (!(storeCacheSeconds >= 0)) throw new TypeError('storeCacheSeconds must be a non-negative number');
|
|
93
260
|
const profile = JSON.parse(JSON.stringify(options.profile || {}));
|
|
261
|
+
const manifestPath = options.manifestPath ?? process.env.AIWAF_PATH_MANIFEST;
|
|
262
|
+
const rules = getEffectivePathRules(options.pathRules || [], manifestPath ? { manifestPath } : undefined);
|
|
263
|
+
// Checked once, so a bad rule fails at startup rather than on a request.
|
|
264
|
+
const profileRate = { window: profile.rate_window ?? 10, max: profile.rate_max ?? 20, flood: profile.rate_flood ?? 40 };
|
|
265
|
+
for (const rule of rules) {
|
|
266
|
+
const limits = { ...profileRate, ...rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {}) };
|
|
267
|
+
if (!(limits.window > 0) || !(limits.max > 0) || limits.flood < limits.max || limits.flood > 100000) {
|
|
268
|
+
throw new Error(`Invalid RATE_LIMIT for path rule ${JSON.stringify(rule.PREFIX ?? rule.prefix)}`);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const routePlan = req => {
|
|
272
|
+
const meta = req.aiwafRoute || {};
|
|
273
|
+
const plan = createRoutePlan(String(req.path || req.url || '/').split('?')[0], rules, meta);
|
|
274
|
+
return { plan, disabled: ALL_MIDDLEWARES.filter(name => !plan.shouldApply(name)), rate: rateOverrides(plan.getOverrides('RATE_LIMIT')) };
|
|
275
|
+
};
|
|
94
276
|
if (!Object.hasOwn(profile, 'blocklist') && Object.hasOwn(profile, 'blacklist')) profile.blocklist = profile.blacklist;
|
|
95
277
|
delete profile.blacklist;
|
|
96
278
|
const dataDir = path.resolve(options.dataDir || 'aiwaf_native_data');
|
|
97
279
|
// State files are dedicated to this adapter. Legacy ORM/CSV schemas are not mixed.
|
|
98
280
|
const blockPath = path.join(dataDir, 'native_blocks.csv');
|
|
99
281
|
const keywordPath = path.join(dataDir, 'native_keywords.csv');
|
|
100
|
-
|
|
282
|
+
if (rateCounter) {
|
|
283
|
+
const probe = await createRequestPipeline({});
|
|
284
|
+
const supported = typeof probe.native.supports === 'function' && probe.native.supports('rate_count');
|
|
285
|
+
probe.native.free();
|
|
286
|
+
if (!supported && options.rateCounterFallback === 'memory') {
|
|
287
|
+
(options.logger || console).warn?.('AIWAF native: this aiwaf-wasm can\'t use a shared rate counter, so rate limits are counted in each worker. Run: npm install aiwaf-wasm@latest');
|
|
288
|
+
rateCounter = null;
|
|
289
|
+
} else if (!supported) throw new Error('rateCounter needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
290
|
+
}
|
|
291
|
+
if (stores) {
|
|
292
|
+
// Checked before the profile is built, since older engines reject policy_store.
|
|
293
|
+
const probe = await createRequestPipeline({});
|
|
294
|
+
const supported = typeof probe.native.supports === 'function' && probe.native.supports('host_store');
|
|
295
|
+
probe.native.free();
|
|
296
|
+
if (!supported && options.storesFallback === 'csv') {
|
|
297
|
+
(options.logger || console).warn?.('AIWAF native: this aiwaf-wasm can\'t use stores, so blocks and learned keywords are kept in dataDir. Run: npm install aiwaf-wasm@latest');
|
|
298
|
+
stores = null;
|
|
299
|
+
} else if (!supported) throw new Error('stores needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
300
|
+
}
|
|
301
|
+
// With stores, blocks and learned keywords live in the stores instead of dataDir.
|
|
302
|
+
const persist = !stores && options.persistBlocks !== false;
|
|
303
|
+
if (stores) profile.policy_store = 'host';
|
|
101
304
|
const opened = [];
|
|
102
305
|
let log, blocks, keywords, engine;
|
|
103
306
|
try {
|
|
@@ -112,55 +315,172 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
112
315
|
profile.blocklist = blocklist;
|
|
113
316
|
profile.dynamic_keywords = [...new Set([...(profile.dynamic_keywords || []), ...readRows(keywordPath, ['keyword']).map(r => r.keyword)])];
|
|
114
317
|
}
|
|
115
|
-
|
|
318
|
+
let model = options.model;
|
|
319
|
+
if (options.modelFile != null) model = await readModelFile(options.modelFile);
|
|
320
|
+
try {
|
|
321
|
+
engine = await createRequestPipeline(profile, model);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
// Older aiwaf-wasm builds reject monitor mode as an unsupported policy.
|
|
324
|
+
if (profile.sql_mode === 'monitor' && /Unsupported native policy/.test(String(error?.message ?? error))) {
|
|
325
|
+
throw new Error('sql_mode "monitor" needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
326
|
+
}
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
116
329
|
if (!profile.enabled || profile.enabled.includes('logging')) {
|
|
117
330
|
log = writer(path.resolve(options.logPath || path.join(dataDir, 'native_requests.csv')), LOG_HEADER, !!options.logFsync); opened.push(log);
|
|
118
331
|
}
|
|
119
332
|
} catch (error) { if (engine) engine.native.free(); for (const entry of opened) entry.close(); throw error; }
|
|
120
333
|
const { native, setModel } = engine;
|
|
334
|
+
const logger = options.logger || console;
|
|
335
|
+
// Monitored SQL findings are logged as the regular middleware logs them, and never block.
|
|
336
|
+
const monitored = finding => {
|
|
337
|
+
if (finding?.mode !== 'monitor') return finding;
|
|
338
|
+
logger.warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: 'monitor' });
|
|
339
|
+
return null;
|
|
340
|
+
};
|
|
341
|
+
if (options.uuidResolver && !(typeof native.supports === 'function' && native.supports('uuid_resolver'))) {
|
|
342
|
+
native.free(); for (const entry of opened) entry.close();
|
|
343
|
+
throw new Error('uuidResolver needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
344
|
+
}
|
|
345
|
+
const uuidPrefix = String(profile.uuid_prefix ?? '/user/').toLowerCase();
|
|
346
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
347
|
+
// The UUID the engine checks, as it finds it: one path segment under uuid_prefix.
|
|
348
|
+
const pathUuid = rawPath => {
|
|
349
|
+
if (!rawPath.toLowerCase().startsWith(uuidPrefix)) return null;
|
|
350
|
+
const uid = rawPath.slice(uuidPrefix.length).replace(/\/+$/, '');
|
|
351
|
+
return !uid.includes('/') && UUID.test(uid) ? uid : null;
|
|
352
|
+
};
|
|
353
|
+
const needsRateOverrides = rules.some(rule => Object.keys(rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {})).length);
|
|
354
|
+
if (needsRateOverrides && !(typeof native.supports === 'function' && native.supports('rate_overrides'))) {
|
|
355
|
+
native.free(); for (const entry of opened) entry.close();
|
|
356
|
+
throw new Error('Path-rule RATE_LIMIT needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
|
|
357
|
+
}
|
|
121
358
|
const maxBytes = profile.max_bytes ?? 65536;
|
|
122
359
|
let closed = false;
|
|
123
360
|
const contextKey = Symbol('aiwaf.native.context');
|
|
124
361
|
const pending = new Set();
|
|
362
|
+
// Keywords and countries change rarely, so they're read at most every storeCacheSeconds.
|
|
363
|
+
const cache = new Map();
|
|
364
|
+
const cached = (name, load) => {
|
|
365
|
+
const now = performance.now();
|
|
366
|
+
const entry = cache.get(name);
|
|
367
|
+
if (entry && now < entry.until) return entry.value;
|
|
368
|
+
const value = Promise.resolve().then(load).then(items => [...(items || [])].map(String));
|
|
369
|
+
cache.set(name, { until: now + storeCacheSeconds * 1000, value });
|
|
370
|
+
// A failed read isn't kept, so the next request tries again.
|
|
371
|
+
value.catch(() => { if (cache.get(name)?.value === value) cache.delete(name); });
|
|
372
|
+
return value;
|
|
373
|
+
};
|
|
374
|
+
// Blocklist and exemption answers, per IP and per IP and path, for storeCacheSeconds. A block
|
|
375
|
+
// or exemption made elsewhere can take that long to apply; this worker's own blocks apply at once.
|
|
376
|
+
const blockedIps = recentAnswers(storeCacheSeconds);
|
|
377
|
+
const exempted = recentAnswers(storeCacheSeconds);
|
|
378
|
+
const stageOn = (route, name) => route.plan.shouldApply(name) && (!profile.enabled || profile.enabled.includes(name));
|
|
379
|
+
// The host stores' facts for one request. A store read that fails is reported and treated
|
|
380
|
+
// as not blocked, not exempt and nothing learned, so storage outages don't block traffic.
|
|
381
|
+
const storeFacts = async (req, route) => {
|
|
382
|
+
const ip = clientIp(req);
|
|
383
|
+
const rawPath = String(req.path || req.url || '/').split('?')[0];
|
|
384
|
+
const read = async (load, fallback) => { try { return await load(); } catch (error) { report(error); return fallback; } };
|
|
385
|
+
// Only what this request's stages use: an exempt request runs logging alone.
|
|
386
|
+
const active = STAGE_NAMES.filter(name => stageOn(route, name));
|
|
387
|
+
if (!active.some(name => name !== 'logging')) return {};
|
|
388
|
+
const exempt = await read(() => exempted.get(`${ip}\u0000${rawPath}`, () => stores.isExempted(ip, rawPath)), false);
|
|
389
|
+
if (exempt) return { exempt: true };
|
|
390
|
+
const [blocked, keywords, countries] = await Promise.all([
|
|
391
|
+
active.includes('ip_keyword_block') || active.includes('ai_anomaly') ? read(() => blockedIps.get(ip, () => stores.isBlocked(ip)), false) : false,
|
|
392
|
+
active.includes('ip_keyword_block') ? read(() => cached('keywords', () => stores.topKeywords(2000)), []) : [],
|
|
393
|
+
active.includes('geo_block') ? read(() => cached('countries', () => stores.blockedCountries()), []) : []
|
|
394
|
+
]);
|
|
395
|
+
return { blocked: !!blocked, exempt: false, dynamic_keywords: keywords, geo_countries: countries };
|
|
396
|
+
};
|
|
397
|
+
// The engine's literal, case-insensitive exemptions: exempt requests aren't rate limited,
|
|
398
|
+
// so they aren't counted either.
|
|
399
|
+
const exemptIps = new Set(profile.exempt_ips || []);
|
|
400
|
+
const exemptPaths = (profile.exempt_paths ?? ['/health', '/robots.txt', '/sitemap.xml']).map(p => String(p).toLowerCase());
|
|
401
|
+
// The shared count for this request's rate window, counted before the engine decides.
|
|
402
|
+
const rateCount = async (req, route, exempt) => {
|
|
403
|
+
const ip = clientIp(req);
|
|
404
|
+
const rawPath = String(req.path || req.url || '/').split('?')[0];
|
|
405
|
+
if (exempt || exemptIps.has(ip) || exemptPaths.some(p => rawPath.toLowerCase().startsWith(p))) return undefined;
|
|
406
|
+
const key = profile.rate_key_mode === 'ip' ? `ratelimit:${ip}` : `ratelimit:${ip}:${rawPath}`;
|
|
407
|
+
const window = Math.max(route.rate.window ?? profile.rate_window ?? 10, 1);
|
|
408
|
+
return rateCounter.count(key, Date.now() / 1000, window);
|
|
409
|
+
};
|
|
125
410
|
const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
|
|
126
411
|
// This pipeline takes no general settings, so these two come from the environment. Route
|
|
127
412
|
// checks run in aiwaf-wasm, loaded here so requests can use them straight away.
|
|
128
|
-
const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST:
|
|
413
|
+
const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode });
|
|
129
414
|
if (observeRisks) await wasmChecks.load();
|
|
130
415
|
function payload(req) {
|
|
131
416
|
const b = safeBody(req, maxBytes);
|
|
132
417
|
const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
|
|
133
|
-
if (b.exhausted && profile.sql_mode !== 'off')
|
|
134
|
-
|
|
418
|
+
if (b.exhausted && profile.sql_mode !== 'off') {
|
|
419
|
+
return monitored({ status: 413, rule: 'payload_inspection_limit', mode: profile.sql_mode });
|
|
420
|
+
}
|
|
421
|
+
return monitored(JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null]))));
|
|
135
422
|
}
|
|
423
|
+
// A uuidResolver may be async, so only requests it applies to wait for it.
|
|
136
424
|
const middleware = (req, res, next) => {
|
|
137
425
|
if (closed) return next(new Error('Native pipeline is closed'));
|
|
138
|
-
let decision;
|
|
139
426
|
const start = performance.now();
|
|
427
|
+
let route;
|
|
428
|
+
try { route = routePlan(req); } catch (error) { return next(error); }
|
|
429
|
+
const uid = options.uuidResolver && route.plan.shouldApply('uuid_tamper')
|
|
430
|
+
&& (!profile.enabled || profile.enabled.includes('uuid_tamper'))
|
|
431
|
+
? pathUuid(String(req.path || req.url || '/').split('?')[0]) : null;
|
|
432
|
+
let found = null;
|
|
433
|
+
if (uid) {
|
|
434
|
+
// A failing resolver doesn't block, as in the regular middleware.
|
|
435
|
+
try { found = options.uuidResolver(uid, req); } catch (_) { found = null; }
|
|
436
|
+
if (found && typeof found.then === 'function') found = found.then(exists => !!exists, () => null);
|
|
437
|
+
else if (found !== null) found = !!found;
|
|
438
|
+
}
|
|
439
|
+
const counted = rateCounter && stageOn(route, 'rate_limit');
|
|
440
|
+
const peek = !req[DEFER_BODY] && !req[PEEKED] && profile.sql_mode !== 'off' && stageOn(route, 'ip_keyword_block') && readable(req)
|
|
441
|
+
? peekBody(req, maxBytes).then(prefix => { req[PEEKED] = prefix; }) : null;
|
|
442
|
+
if (!stores && !counted && !peek && !(found && typeof found.then === 'function')) return handle(req, res, next, route, start, found, null);
|
|
443
|
+
return Promise.all([found, stores ? storeFacts(req, route) : null, peek])
|
|
444
|
+
.then(async ([exists, facts]) => {
|
|
445
|
+
if (counted) {
|
|
446
|
+
let count;
|
|
447
|
+
try { count = await rateCount(req, route, facts?.exempt); } catch (error) {
|
|
448
|
+
report(error);
|
|
449
|
+
// As the regular rate limiter does: closed answers 503, open lets the request through.
|
|
450
|
+
if (rateFailureMode === 'closed') return res.status(503).json({ error: 'temporarily_unavailable' });
|
|
451
|
+
}
|
|
452
|
+
if (count !== undefined) facts = { ...(facts || {}), rate_count: count };
|
|
453
|
+
}
|
|
454
|
+
return handle(req, res, next, route, start, exists, facts);
|
|
455
|
+
}, next);
|
|
456
|
+
};
|
|
457
|
+
const handle = (req, res, next, route, start, uuidExists, facts) => {
|
|
458
|
+
if (closed) return next(new Error('Native pipeline is closed'));
|
|
459
|
+
let decision;
|
|
140
460
|
try {
|
|
141
|
-
const
|
|
142
|
-
if (observeRisks &&
|
|
461
|
+
const { plan, disabled, rate } = route;
|
|
462
|
+
if (observeRisks && plan.shouldApply('ip_keyword_block')
|
|
143
463
|
&& (!profile.enabled || profile.enabled.includes('ip_keyword_block'))) {
|
|
144
464
|
const riskFinding = observeRisks(req);
|
|
145
465
|
if (riskFinding) return res.status(riskFinding.status).json({ error: riskFinding.rule });
|
|
146
466
|
}
|
|
147
|
-
const required = new Set((meta.requiredMiddlewares || []).map(normalizeMiddlewareName));
|
|
148
|
-
const disabled = new Set((meta.fullyExempt ? ALL_MIDDLEWARES : meta.exemptMiddlewares || []).map(normalizeMiddlewareName));
|
|
149
|
-
for (const key of required) disabled.delete(key);
|
|
150
467
|
const rawPath = String(req.path || req.url || '/').split('?')[0];
|
|
151
468
|
const body = req[DEFER_BODY] ? {body:null,exhausted:false} : safeBody(req, maxBytes);
|
|
152
469
|
decision = JSON.parse(native.begin(JSON.stringify({
|
|
153
|
-
|
|
154
|
-
ip: String(req.ip || req.socket?.remoteAddress || 'unknown').replace(/^::ffff:/, ''),
|
|
470
|
+
ip: clientIp(req),
|
|
155
471
|
path: rawPath, method: String(req.method || 'GET'), headers: headers(req.headers),
|
|
156
472
|
query: String(req.originalUrl || req.url || '').split('?').slice(1).join('?'),
|
|
157
473
|
body: body.body, parsed_query: req.query ?? null,
|
|
158
474
|
now: Date.now() / 1000, country: String(synchronous(options.countryLookup, req, '') || ''),
|
|
159
475
|
authenticated: req[DEFER_BODY] ? false : !!synchronous(options.authenticated, req, false),
|
|
160
|
-
exists: !!synchronous(options.routeExists, req, !!req.route), disabled
|
|
161
|
-
payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY]
|
|
476
|
+
exists: !!synchronous(options.routeExists, req, !!req.route), disabled,
|
|
477
|
+
payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY],
|
|
478
|
+
...(Object.keys(rate).length ? { rate } : {}),
|
|
479
|
+
...(uuidExists === null ? {} : { uuid_exists: uuidExists }),
|
|
480
|
+
...(facts || {})
|
|
162
481
|
})));
|
|
163
482
|
} catch (error) { return next(error); }
|
|
483
|
+
if (decision.monitor) monitored({ rule: decision.monitor, mode: 'monitor' });
|
|
164
484
|
pending.add(decision.context);
|
|
165
485
|
req[contextKey] = decision.context;
|
|
166
486
|
let done = false;
|
|
@@ -172,6 +492,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
172
492
|
if (blocks && effects.block_csv) blocks.append(effects.block_csv);
|
|
173
493
|
if (keywords && effects.keyword_csv) keywords.append(effects.keyword_csv);
|
|
174
494
|
if (log && effects.log_csv) log.append(effects.log_csv);
|
|
495
|
+
if (stores) writeEffects(effects);
|
|
175
496
|
} catch (error) { report(error); }
|
|
176
497
|
};
|
|
177
498
|
res.on('finish', () => finalize(false));
|
|
@@ -179,10 +500,20 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
179
500
|
if (decision.status) return res.status(decision.status).json({ error: decision.reason });
|
|
180
501
|
return next();
|
|
181
502
|
};
|
|
503
|
+
// Store writes run after the response, so a slow or failing store never delays it.
|
|
504
|
+
const writeEffects = effects => {
|
|
505
|
+
if (effects.block) {
|
|
506
|
+
blockedIps.set(effects.block.ip, true);
|
|
507
|
+
Promise.resolve().then(() => stores.block(effects.block.ip, effects.block.reason, effects.block.expires_at)).catch(report);
|
|
508
|
+
}
|
|
509
|
+
if (effects.keyword) {
|
|
510
|
+
Promise.resolve().then(() => stores.learn(effects.keyword))
|
|
511
|
+
.then(() => cache.delete('keywords'), report);
|
|
512
|
+
}
|
|
513
|
+
};
|
|
182
514
|
middleware.inspectPayload = req => {
|
|
183
|
-
const disabled = req.aiwafRoute?.exemptMiddlewares || [];
|
|
184
515
|
if (profile.enabled && !profile.enabled.includes('ip_keyword_block')) return null;
|
|
185
|
-
if (req.
|
|
516
|
+
if (!routePlan(req).plan.shouldApply('ip_keyword_block')) return null;
|
|
186
517
|
const riskFinding = observeRisks ? observeRisks(req) : null;
|
|
187
518
|
if (riskFinding) return riskFinding;
|
|
188
519
|
return payload(req);
|
|
@@ -190,8 +521,8 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
190
521
|
middleware.diagnostics = () => JSON.parse(native.diagnostics());
|
|
191
522
|
middleware.inspectBody = (req, body) => {
|
|
192
523
|
const captured = safeBody({body,headers:{}},maxBytes);
|
|
193
|
-
return JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
|
|
194
|
-
!!synchronous(options.authenticated,req,false), Date.now()/1000));
|
|
524
|
+
return monitored(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
|
|
525
|
+
!!synchronous(options.authenticated,req,false), Date.now()/1000)));
|
|
195
526
|
};
|
|
196
527
|
middleware.setModel = setModel;
|
|
197
528
|
middleware.close = () => {
|
|
@@ -204,3 +535,6 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
204
535
|
return middleware;
|
|
205
536
|
};
|
|
206
537
|
module.exports.DEFER_BODY = DEFER_BODY;
|
|
538
|
+
module.exports.regularStores = regularStores;
|
|
539
|
+
module.exports.recentAnswers = recentAnswers;
|
|
540
|
+
module.exports.redisRateCounter = require('./nativeRateCounter').redisRateCounter;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Shared rate counts for the native pipeline. Redis counts; aiwaf-wasm still decides.
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
|
|
6
|
+
// The regular Python limiter's sliding window, so both runtimes keep the same bucket format.
|
|
7
|
+
const SCRIPT = `
|
|
8
|
+
local raw = redis.call('GET', KEYS[1])
|
|
9
|
+
local old = raw and cjson.decode(raw) or {}
|
|
10
|
+
local now, window = tonumber(ARGV[1]), tonumber(ARGV[2])
|
|
11
|
+
local current = {}
|
|
12
|
+
for _, timestamp in ipairs(old) do
|
|
13
|
+
if now - timestamp < window then table.insert(current, timestamp) end
|
|
14
|
+
end
|
|
15
|
+
table.insert(current, now)
|
|
16
|
+
redis.call('SET', KEYS[1], cjson.encode(current), 'PX', math.ceil(window * 1000))
|
|
17
|
+
return #current
|
|
18
|
+
`;
|
|
19
|
+
|
|
20
|
+
// A fixed-length key, so long paths can't make long Redis keys.
|
|
21
|
+
function boundedKey(namespace, key) {
|
|
22
|
+
return `${namespace}:${crypto.createHash('sha256').update(key).digest('hex')}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Counts native rate limits in Redis, atomically across workers. Takes a node-redis v4
|
|
27
|
+
* client (sendCommand) or an ioredis client (call).
|
|
28
|
+
*/
|
|
29
|
+
function redisRateCounter(client, { namespace = 'aiwaf:native:rate:v1' } = {}) {
|
|
30
|
+
const call = typeof client?.call === 'function' ? args => client.call(...args)
|
|
31
|
+
: typeof client?.sendCommand === 'function' ? args => client.sendCommand(args) : null;
|
|
32
|
+
if (!call) throw new TypeError('redisRateCounter needs a node-redis or ioredis client');
|
|
33
|
+
if (typeof namespace !== 'string' || !namespace || Buffer.byteLength(namespace) > 100) {
|
|
34
|
+
throw new TypeError('namespace must be a nonempty string of at most 100 bytes');
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
async count(key, now, windowSeconds) {
|
|
38
|
+
const count = Number(await call(['EVAL', SCRIPT, '1', boundedKey(namespace, key), String(now), String(windowSeconds)]));
|
|
39
|
+
if (!Number.isInteger(count) || count < 1) throw new Error('Invalid Redis rate count');
|
|
40
|
+
return count;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { redisRateCounter, boundedKey, SCRIPT };
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Builds native pipeline options from the options the regular aiwaf(options) middleware takes.
|
|
4
|
+
// Options are read through the same normalizeSettings(), with the same defaults and environment
|
|
5
|
+
// variables, and every option that doesn't carry over exactly is reported with the reason.
|
|
6
|
+
const { normalizeSettings } = require('./settingsCompat');
|
|
7
|
+
const { planEnabledMiddlewares, isAutoSelection } = require('./middlewarePlan');
|
|
8
|
+
const { normalizeMiddlewareName } = require('./pathRules');
|
|
9
|
+
// Loaded when first used, since nativePipeline loads this module's callers.
|
|
10
|
+
const regularStores = settings => require('./nativePipeline').regularStores(settings);
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const crypto = require('crypto');
|
|
15
|
+
|
|
16
|
+
// The sample model shipped in resources/model.json. Its old format can't be loaded natively,
|
|
17
|
+
// and it's only a sample, so the native pipeline runs without it, as a new install does.
|
|
18
|
+
const SHIPPED_MODEL_SHA256 = '56254f9bdeba0f96bed3c72ce88ed9f1e5ad552d7510c84742fd6a349e72c091';
|
|
19
|
+
const SHIPPED_MODEL = path.join(__dirname, '..', 'resources', 'model.json');
|
|
20
|
+
|
|
21
|
+
/** What the regular middleware would load as its anomaly model, read without loading it. */
|
|
22
|
+
function settingsModel(opts) {
|
|
23
|
+
if ((opts.AIWAF_MODEL_STORAGE || 'file') !== 'file') return { kind: 'storage' };
|
|
24
|
+
const file = opts.AIWAF_MODEL_PATH || SHIPPED_MODEL;
|
|
25
|
+
let text;
|
|
26
|
+
try { text = fs.readFileSync(file); } catch (_) { return { kind: 'none', file }; }
|
|
27
|
+
if (crypto.createHash('sha256').update(text).digest('hex') === SHIPPED_MODEL_SHA256) return { kind: 'shipped', file };
|
|
28
|
+
try {
|
|
29
|
+
const data = JSON.parse(text);
|
|
30
|
+
return { kind: data?.model_type === 'aiwaf_wasm.IsolationForest' && data.model_state ? 'wasm' : 'js', file };
|
|
31
|
+
} catch (_) { return { kind: 'unreadable', file }; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const STAGES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
|
|
35
|
+
const PATTERN = /[*?[]/;
|
|
36
|
+
// Options with no native equivalent, reported when they differ from the regular defaults.
|
|
37
|
+
const NOT_CARRIED = {
|
|
38
|
+
AIWAF_ALLOWED_PATH_KEYWORDS: 'The native pipeline has its own legitimate_keywords list.',
|
|
39
|
+
AIWAF_EXEMPT_KEYWORDS: 'The native pipeline has no exempt keywords.',
|
|
40
|
+
AIWAF_LOGIN_PATH_PREFIXES: 'The native pipeline treats paths under /login and /admin/login as login forms.',
|
|
41
|
+
AIWAF_POST_ONLY_SUFFIXES: 'The native method policy is allowed_methods only.',
|
|
42
|
+
AIWAF_MAX_HEADER_BYTES: 'The native header limits are fixed.',
|
|
43
|
+
AIWAF_MAX_HEADER_COUNT: 'The native header limits are fixed.',
|
|
44
|
+
AIWAF_MAX_USER_AGENT_LENGTH: 'The native header limits are fixed.',
|
|
45
|
+
AIWAF_MAX_ACCEPT_LENGTH: 'The native header limits are fixed.',
|
|
46
|
+
AIWAF_BLOCKED_USER_AGENTS: 'The native header check has its own list of scanner user agents.',
|
|
47
|
+
AIWAF_GEO_MMDB_PATH: 'Pass a countryLookup(req) option to the native pipeline instead.',
|
|
48
|
+
AIWAF_GEO_CACHE_SECONDS: 'Country lookups come from countryLookup(req).',
|
|
49
|
+
AIWAF_GEO_CACHE_PREFIX: 'Country lookups come from countryLookup(req).',
|
|
50
|
+
AIWAF_MODEL_STORAGE: 'The native pipeline loads a model from a file only; pass a model option instead.',
|
|
51
|
+
AIWAF_MODEL_STORAGE_FALLBACK: 'The native pipeline loads a model from a file only; pass a model option instead.',
|
|
52
|
+
AIWAF_MODEL_CACHE_KEY: 'Pass a model option to the native pipeline instead.',
|
|
53
|
+
AIWAF_MODEL_CACHE_TTL: 'Pass a model option to the native pipeline instead.',
|
|
54
|
+
AIWAF_MIDDLEWARE_LOG_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
|
|
55
|
+
AIWAF_MIDDLEWARE_LOG_DB: 'The native pipeline logs to a CSV file only.',
|
|
56
|
+
AIWAF_MIDDLEWARE_LOG_CSV: 'The native pipeline logs to a CSV file only.',
|
|
57
|
+
AIWAF_MIDDLEWARE_LOG_CSV_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
|
|
58
|
+
AIWAF_CAPTURE_EXTENDED_REQUEST_INFO: 'The native log has fixed columns.',
|
|
59
|
+
AIWAF_EXTENDED_INFO_MAX_HEADERS: 'The native log has fixed columns.',
|
|
60
|
+
AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH: 'The native log has fixed columns.',
|
|
61
|
+
AIWAF_DYNAMIC_KEYWORDS_DB: 'The native pipeline reads learned keywords from the keyword store.',
|
|
62
|
+
AIWAF_MIN_AI_LOGS: 'Training settings don\'t apply to request handling.',
|
|
63
|
+
AIWAF_ROUTE_PLAN_VERSION: 'The native pipeline compiles path rules once at startup.',
|
|
64
|
+
AIWAF_FORCE_JSON_ERRORS: 'Native responses are always JSON.'
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Options that carry over exactly, reported as carried when they differ from the regular defaults.
|
|
68
|
+
const CARRIED = ['WINDOW_SEC', 'MAX_REQ', 'FLOOD_REQ', 'AIWAF_MIN_FORM_TIME', 'AIWAF_MAX_PAGE_TIME', 'HONEYPOT_FIELD',
|
|
69
|
+
'AIWAF_METHOD_POLICY_ENABLED', 'AIWAF_ALLOWED_METHODS', 'staticKeywords', 'AIWAF_ENABLE_KEYWORD_LEARNING',
|
|
70
|
+
'AIWAF_GEO_BLOCK_ENABLED', 'AIWAF_GEO_ALLOW_COUNTRIES', 'AIWAF_GEO_BLOCK_COUNTRIES', 'AIWAF_HEADER_VALIDATION',
|
|
71
|
+
'AIWAF_REQUIRED_HEADERS', 'AIWAF_HEADER_QUALITY_MIN_SCORE', 'AIWAF_EXEMPT_PATHS', 'AIWAF_EXEMPT_IPS',
|
|
72
|
+
'AIWAF_MIDDLEWARES', 'AIWAF_DISABLE_MIDDLEWARES', 'AIWAF_MIDDLEWARE_LOGGING', 'AIWAF_PATH_RULES',
|
|
73
|
+
'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES'];
|
|
74
|
+
// Where settingsCompat reads each number from, in the same order, so unreadable values can be reported.
|
|
75
|
+
const NUMBER_SOURCES = {
|
|
76
|
+
WINDOW_SEC: ['WINDOW_SEC', 'windowSec', 'AIWAF_WINDOW_SECONDS', 'env:AIWAF_RATE_WINDOW'],
|
|
77
|
+
MAX_REQ: ['MAX_REQ', 'maxReq', 'env:AIWAF_RATE_MAX'],
|
|
78
|
+
FLOOD_REQ: ['FLOOD_REQ', 'floodReq', 'env:AIWAF_RATE_FLOOD'],
|
|
79
|
+
AIWAF_MIN_FORM_TIME: ['AIWAF_MIN_FORM_TIME', 'minFormTime', 'env:AIWAF_MIN_FORM_TIME'],
|
|
80
|
+
AIWAF_MAX_PAGE_TIME: ['AIWAF_MAX_PAGE_TIME', 'maxPageTime', 'env:AIWAF_MAX_PAGE_TIME'],
|
|
81
|
+
AIWAF_HEADER_QUALITY_MIN_SCORE: ['AIWAF_HEADER_QUALITY_MIN_SCORE', 'headerQualityMinScore', 'env:AIWAF_HEADER_QUALITY_MIN_SCORE']
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
85
|
+
const headerName = name => (String(name).toUpperCase().startsWith('HTTP_')
|
|
86
|
+
? String(name).toUpperCase() : `HTTP_${String(name).toUpperCase().replace(/-/g, '_')}`);
|
|
87
|
+
|
|
88
|
+
function nativeOptionsFromSettings(rawOpts = {}) {
|
|
89
|
+
const opts = normalizeSettings(rawOpts);
|
|
90
|
+
const defaults = normalizeSettings({});
|
|
91
|
+
const notes = [];
|
|
92
|
+
const note = (setting, outcome, detail = '') => notes.push({ setting, outcome, detail });
|
|
93
|
+
const profile = {};
|
|
94
|
+
|
|
95
|
+
// Regular defaults differ from the native ones, so effective values are always written.
|
|
96
|
+
profile.rate_window = opts.WINDOW_SEC;
|
|
97
|
+
profile.rate_max = opts.MAX_REQ;
|
|
98
|
+
profile.rate_flood = opts.FLOOD_REQ;
|
|
99
|
+
if (profile.rate_flood < profile.rate_max) {
|
|
100
|
+
profile.rate_max = profile.rate_flood;
|
|
101
|
+
note('MAX_REQ', 'changed', `It's above FLOOD_REQ (${profile.rate_flood}), so requests were flood-blocked first. The native limit is ${profile.rate_flood}.`);
|
|
102
|
+
}
|
|
103
|
+
if (profile.rate_flood > 100000) {
|
|
104
|
+
profile.rate_flood = 100000;
|
|
105
|
+
note('FLOOD_REQ', 'changed', 'The native flood threshold is at most 100000.');
|
|
106
|
+
}
|
|
107
|
+
profile.min_form_time = opts.AIWAF_MIN_FORM_TIME;
|
|
108
|
+
if (opts.AIWAF_MAX_PAGE_TIME > 0) profile.max_page_time = opts.AIWAF_MAX_PAGE_TIME;
|
|
109
|
+
else note('AIWAF_MAX_PAGE_TIME', 'not carried', 'The native page expiry must be positive, so its default applies.');
|
|
110
|
+
profile.honeypot_field = opts.HONEYPOT_FIELD ? String(opts.HONEYPOT_FIELD) : '';
|
|
111
|
+
profile.allowed_methods = opts.AIWAF_METHOD_POLICY_ENABLED === true
|
|
112
|
+
? (opts.AIWAF_ALLOWED_METHODS || []).map(method => String(method).toUpperCase()) : [];
|
|
113
|
+
profile.static_keywords = [...(opts.staticKeywords || [])].map(String);
|
|
114
|
+
profile.learning = opts.AIWAF_ENABLE_KEYWORD_LEARNING !== false;
|
|
115
|
+
profile.geo_allow = [...(opts.AIWAF_GEO_ALLOW_COUNTRIES || [])];
|
|
116
|
+
profile.geo_block = [...(opts.AIWAF_GEO_BLOCK_COUNTRIES || [])];
|
|
117
|
+
const required = opts.AIWAF_REQUIRED_HEADERS || [];
|
|
118
|
+
if (required && typeof required === 'object' && !Array.isArray(required)) {
|
|
119
|
+
profile.required_headers = (required.DEFAULT || []).map(headerName);
|
|
120
|
+
note('AIWAF_REQUIRED_HEADERS', 'changed', 'Per-method lists aren\'t supported natively, so its DEFAULT list applies to every method.');
|
|
121
|
+
} else {
|
|
122
|
+
profile.required_headers = [].concat(required).map(headerName);
|
|
123
|
+
}
|
|
124
|
+
// With no required headers, the regular check also skips the quality score.
|
|
125
|
+
profile.header_min_score = profile.required_headers.length ? opts.AIWAF_HEADER_QUALITY_MIN_SCORE : 0;
|
|
126
|
+
profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
|
|
127
|
+
profile.max_bytes = Number(rawOpts.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
|
|
128
|
+
|
|
129
|
+
const paths = (opts.AIWAF_EXEMPT_PATHS || []).map(String);
|
|
130
|
+
profile.exempt_paths = paths.filter(path => !PATTERN.test(path));
|
|
131
|
+
const pathPatterns = paths.filter(path => PATTERN.test(path));
|
|
132
|
+
if (pathPatterns.length) {
|
|
133
|
+
note('AIWAF_EXEMPT_PATHS', 'changed', `The native pipeline matches literal prefixes only, so these patterns aren't exempt: ${pathPatterns.join(', ')}.`);
|
|
134
|
+
}
|
|
135
|
+
const ips = (opts.AIWAF_EXEMPT_IPS || []).map(String);
|
|
136
|
+
profile.exempt_ips = ips.filter(ip => !ip.includes('/') && !ip.includes('*'));
|
|
137
|
+
const ranges = ips.filter(ip => ip.includes('/') || ip.includes('*'));
|
|
138
|
+
if (ranges.length) {
|
|
139
|
+
note('AIWAF_EXEMPT_IPS', 'changed', `The native pipeline exempts exact addresses only, so these ranges aren't exempt: ${ranges.join(', ')}.`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The same stage plan as the regular middleware, then its per-stage switches.
|
|
143
|
+
const requested = Array.isArray(opts.AIWAF_MIDDLEWARES) ? opts.AIWAF_MIDDLEWARES.map(normalizeMiddlewareName) : opts.AIWAF_MIDDLEWARES;
|
|
144
|
+
const enabled = planEnabledMiddlewares({
|
|
145
|
+
orderedAvailable: STAGES, requested, disabled: (opts.AIWAF_DISABLE_MIDDLEWARES || []).map(normalizeMiddlewareName),
|
|
146
|
+
accessLog: opts.AIWAF_ACCESS_LOG, geoEnabledFlag: !!opts.AIWAF_GEO_BLOCK_ENABLED,
|
|
147
|
+
staticBlockCountries: opts.AIWAF_GEO_BLOCK_COUNTRIES, dynamicBlockCountries: []
|
|
148
|
+
});
|
|
149
|
+
const auto = isAutoSelection(requested);
|
|
150
|
+
const explicit = key => Object.hasOwn(rawOpts, key) || process.env[key] !== undefined;
|
|
151
|
+
const logging = opts.AIWAF_MIDDLEWARE_LOGGING || (auto && enabled.has('logging') && !explicit('AIWAF_MIDDLEWARE_LOGGING'));
|
|
152
|
+
if (!opts.AIWAF_HEADER_VALIDATION) enabled.delete('header_validation');
|
|
153
|
+
if (!logging) enabled.delete('logging');
|
|
154
|
+
profile.enabled = STAGES.filter(stage => enabled.has(stage));
|
|
155
|
+
if (enabled.has('logging')) {
|
|
156
|
+
note('AIWAF_MIDDLEWARE_LOGGING', 'changed', 'Requests are logged to native_requests.csv in dataDir, with the native log\'s columns.');
|
|
157
|
+
}
|
|
158
|
+
// The regular middleware's stores: the same blocks, exemptions, learned keywords and blocked
|
|
159
|
+
// countries. An older aiwaf-wasm can't use them, and then the adapter keeps its own in dataDir.
|
|
160
|
+
note('stores', 'carried');
|
|
161
|
+
|
|
162
|
+
const options = {
|
|
163
|
+
stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB }),
|
|
164
|
+
storesFallback: 'csv',
|
|
165
|
+
rateFailureMode: opts.AIWAF_RATE_CACHE_FAILURE_MODE,
|
|
166
|
+
// Resolved as the regular middleware resolves it, with its default trusted proxies.
|
|
167
|
+
trustedProxies: opts.AIWAF_TRUSTED_PROXIES ?? 'default',
|
|
168
|
+
pathRules: opts.AIWAF_PATH_RULES || [],
|
|
169
|
+
manifestPath: opts.AIWAF_PATH_MANIFEST,
|
|
170
|
+
injectionRiskMode: opts.AIWAF_INJECTION_RISK_MODE
|
|
171
|
+
};
|
|
172
|
+
// The regular UUID check matches one segment under uuidRoutePrefix, and asks uuidResolver.
|
|
173
|
+
const uuidPrefix = rawOpts.uuidRoutePrefix || '/user';
|
|
174
|
+
profile.uuid_prefix = `${String(uuidPrefix).replace(/\/+$/, '')}/`;
|
|
175
|
+
if (rawOpts.uuidRoutePrefix) note('uuidRoutePrefix', 'carried');
|
|
176
|
+
if (typeof rawOpts.uuidResolver === 'function') {
|
|
177
|
+
options.uuidResolver = rawOpts.uuidResolver;
|
|
178
|
+
note('uuidResolver', 'carried');
|
|
179
|
+
}
|
|
180
|
+
// The regular rate limiter counts in its cache option. A Redis client there is shared the
|
|
181
|
+
// same way natively; an older aiwaf-wasm counts in each worker instead, and warns.
|
|
182
|
+
const cache = rawOpts.cache;
|
|
183
|
+
if (cache && (typeof cache.call === 'function' || typeof cache.sendCommand === 'function')) {
|
|
184
|
+
options.rateCounter = require('./nativeRateCounter').redisRateCounter(cache);
|
|
185
|
+
options.rateCounterFallback = 'memory';
|
|
186
|
+
note('cache', 'carried');
|
|
187
|
+
} else if (cache) {
|
|
188
|
+
note('cache', 'not carried', 'Shared native rate limits need a node-redis or ioredis client, so rate limits are counted in each worker.');
|
|
189
|
+
}
|
|
190
|
+
if (opts.AIWAF_RATE_CACHE_FAILURE_MODE !== 'closed') note('AIWAF_RATE_CACHE_FAILURE_MODE', 'carried');
|
|
191
|
+
const model = settingsModel(opts);
|
|
192
|
+
if (model.kind === 'wasm') {
|
|
193
|
+
options.modelFile = model.file;
|
|
194
|
+
note('AIWAF_MODEL_PATH', 'carried');
|
|
195
|
+
} else if (model.kind === 'js' || model.kind === 'unreadable') {
|
|
196
|
+
note('AIWAF_MODEL_PATH', 'not carried', `${model.file} is in an older model format the native pipeline can't load. Retrain with: aiwaf train`);
|
|
197
|
+
} else if (model.kind === 'none' && opts.AIWAF_MODEL_PATH) {
|
|
198
|
+
note('AIWAF_MODEL_PATH', 'carried', 'No model file exists there yet, so anomaly detection runs without a model, as in the regular middleware.');
|
|
199
|
+
}
|
|
200
|
+
for (const [key, reason] of Object.entries(NOT_CARRIED)) {
|
|
201
|
+
if (!same(opts[key], defaults[key])) note(key, 'not carried', reason);
|
|
202
|
+
}
|
|
203
|
+
// A number that couldn't be read falls back to the regular default, which is what's converted.
|
|
204
|
+
for (const [key, sources] of Object.entries(NUMBER_SOURCES)) {
|
|
205
|
+
const source = sources.find(name => (name.startsWith('env:') ? process.env[name.slice(4)] : rawOpts[name]) != null
|
|
206
|
+
&& (name.startsWith('env:') ? process.env[name.slice(4)] : rawOpts[name]) !== '');
|
|
207
|
+
if (!source) continue;
|
|
208
|
+
const raw = source.startsWith('env:') ? process.env[source.slice(4)] : rawOpts[source];
|
|
209
|
+
if (!Number.isFinite(Number(raw))) {
|
|
210
|
+
note(key, 'not carried', `Its value couldn't be read (expected a number), so the regular default of ${defaults[key]} applies, as in the regular middleware.`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const noted = new Set(notes.map(n => n.setting));
|
|
214
|
+
for (const key of CARRIED) {
|
|
215
|
+
if (!noted.has(key) && !same(opts[key], defaults[key])) note(key, 'carried');
|
|
216
|
+
}
|
|
217
|
+
for (const key of ['AIWAF_SQL_INJECTION_MODE', 'AIWAF_PAYLOAD_MAX_BYTES']) {
|
|
218
|
+
if (rawOpts[key] !== undefined || process.env[key] !== undefined) note(key, 'carried');
|
|
219
|
+
}
|
|
220
|
+
const differences = () => notes.filter(n => n.outcome !== 'carried');
|
|
221
|
+
const report = () => {
|
|
222
|
+
const carried = notes.filter(n => n.outcome === 'carried').length;
|
|
223
|
+
return [`Native pipeline settings: ${carried} carried over unchanged.`,
|
|
224
|
+
...differences().map(n => `- ${n.setting}: ${n.outcome}. ${n.detail}`.trimEnd())].join('\n');
|
|
225
|
+
};
|
|
226
|
+
return {
|
|
227
|
+
// Ready for aiwaf.native(); profile and options are also available separately.
|
|
228
|
+
config: { ...options, profile },
|
|
229
|
+
profile,
|
|
230
|
+
options,
|
|
231
|
+
notes,
|
|
232
|
+
differences,
|
|
233
|
+
report,
|
|
234
|
+
/** Logs the report: a warning when anything differs, otherwise one info line, as in Python. */
|
|
235
|
+
log(logger = console) {
|
|
236
|
+
const write = differences().length ? logger.warn : (logger.info || logger.log);
|
|
237
|
+
write?.call(logger, report());
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256 };
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -130,12 +130,65 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
|
|
|
130
130
|
}
|
|
131
131
|
|
|
132
132
|
|
|
133
|
+
// The first aiwaf-wasm with every engine feature from_settings relies on: stores, shared rate
|
|
134
|
+
// counts, path-rule limits, monitor mode and UUID resolvers.
|
|
135
|
+
const NATIVE_DEFAULT_WASM = '0.2.7';
|
|
136
|
+
|
|
137
|
+
function installedWasmVersion() {
|
|
138
|
+
const fs = require('fs');
|
|
139
|
+
const path = require('path');
|
|
140
|
+
for (const file of [path.join(__dirname, '..', 'node_modules', 'aiwaf-wasm', 'package.json'),
|
|
141
|
+
() => require.resolve('aiwaf-wasm/package.json')]) {
|
|
142
|
+
try { return JSON.parse(fs.readFileSync(typeof file === 'function' ? file() : file, 'utf8')).version; } catch (_) { /* next */ }
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
function atLeast(version, minimum) {
|
|
147
|
+
const parse = v => String(v).split('-')[0].split('.').map(Number);
|
|
148
|
+
const [a, b] = [parse(version), parse(minimum)];
|
|
149
|
+
for (let i = 0; i < 3; i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
const OFF = new Set(['false', '0', 'off', 'no']);
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether aiwaf(options) runs the native pipeline when AIWAF_NATIVE_PIPELINE isn't set: when
|
|
156
|
+
* the installed aiwaf-wasm has every native feature and every option carries over exactly.
|
|
157
|
+
*/
|
|
158
|
+
function automaticNative(rawOpts) {
|
|
159
|
+
if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
|
|
160
|
+
const version = installedWasmVersion();
|
|
161
|
+
if (!version || !atLeast(version, NATIVE_DEFAULT_WASM)) return null;
|
|
162
|
+
const conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
|
|
163
|
+
return conversion.differences().length ? null : conversion;
|
|
164
|
+
}
|
|
165
|
+
|
|
133
166
|
module.exports = function aiwaf(rawOpts = {}) {
|
|
167
|
+
if (rawOpts.AIWAF_NATIVE_PIPELINE === false) {
|
|
168
|
+
const { AIWAF_NATIVE_PIPELINE: _off, ...regularOpts } = rawOpts;
|
|
169
|
+
rawOpts = regularOpts;
|
|
170
|
+
} else if (rawOpts.AIWAF_NATIVE_PIPELINE === undefined) {
|
|
171
|
+
const conversion = automaticNative(rawOpts);
|
|
172
|
+
if (conversion) {
|
|
173
|
+
console.info('AIWAF: using the native pipeline, since every option carries over to it. '
|
|
174
|
+
+ 'Set AIWAF_NATIVE_PIPELINE: false (or the environment variable) to keep the regular middleware.');
|
|
175
|
+
rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion } };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
134
178
|
if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
|
|
135
|
-
|
|
179
|
+
let native = rawOpts.AIWAF_NATIVE_PIPELINE;
|
|
180
|
+
const fromSettings = native === 'from_settings' || (native && typeof native === 'object' && native.fromSettings);
|
|
181
|
+
if (fromSettings) {
|
|
182
|
+
// Convert the regular options passed alongside; native options given here win, as in Python.
|
|
183
|
+
const { AIWAF_NATIVE_PIPELINE: _ignored, ...regular } = rawOpts;
|
|
184
|
+
const { fromSettings: _flag, profile: overrides, conversion: converted, ...nativeOptions } = typeof native === 'object' ? native : {};
|
|
185
|
+
const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
|
|
186
|
+
conversion.log(nativeOptions.logger || console);
|
|
187
|
+
native = { ...conversion.options, ...nativeOptions, profile: { ...conversion.profile, ...(overrides || {}) } };
|
|
188
|
+
} else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
|
|
136
189
|
throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
|
|
137
190
|
}
|
|
138
|
-
const ready = require('./nativePipeline')(
|
|
191
|
+
const ready = require('./nativePipeline')(native);
|
|
139
192
|
// Compatibility wrapper for framework adapters. Await ready during application startup.
|
|
140
193
|
// No legacy modules are initialized and no fallback is selected on this branch.
|
|
141
194
|
const middleware = async (req, res, next) => (await ready)(req, res, next);
|
|
@@ -514,3 +567,5 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
514
567
|
middleware.inspectPayload = inspectPayload;
|
|
515
568
|
return middleware;
|
|
516
569
|
};
|
|
570
|
+
|
|
571
|
+
module.exports.NATIVE_DEFAULT_WASM = NATIVE_DEFAULT_WASM;
|