aiwaf
v1.3.7
Published
AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks
Maintainers
Readme
AIWAF
AIWAF is a multi-runtime web application firewall toolkit for Python, Node.js, WebAssembly, and Java applications. It combines deterministic request controls with route-aware policies, reputation tracking, request logging, training pipelines, and optional Isolation Forest anomaly detection.
This is the single authoritative README for the monorepo and every published AIWAF package. Release workflows stage this file, the root LICENSE, NOTICE, and licenses/ into package artifacts when a registry requires package-local copies.
AIWAF is a defense-in-depth component. It does not replace secure application code, authentication and authorization, dependency patching, TLS, a reverse proxy, or a managed edge WAF.
Packages
The next local drafts add bounded Java SQL inspection, a JavaScript bodyParser
helper, and atomic Python Redis rate buckets. They have not been published.
For custom Node HTTP servers or middleware registered before a framework's
parser, call aiwaf.bodyParser() before AIWAF and before forwarding requests.
It parses JSON and URL-encoded bodies, retains the original forwarding bytes,
and rejects oversized bodies (default 64 KiB). Native Fastify/Hapi integrations
must run AIWAF after body parsing and before their proxy handler.
Java SQL inspection defaults to security.sql_injection_mode: "block";
monitor records findings without denying requests and off disables it.
AIWAF_SQL_INJECTION_MODE provides the environment override. Inspection uses
the configured body byte limit and rejects over-budget inspection with 413.
Previously learned benign keywords no longer block ordinary Java routes.
Redis rate-cache failures now produce generic HTTP 503 responses in JavaScript
and Python rate-limit middleware. JavaScript defaults to
AIWAF_RATE_CACHE_FAILURE_MODE: 'closed'; explicitly setting 'open' preserves
availability at the cost of enforcement when the cache fails. Flask rejects
invalid Redis configuration at initialization, and FastAPI rejects requests
instead of silently selecting a process-local cache. Python rediss:// URLs
are delegated to redis-py for TLS support when that driver is installed.
Python Flask/FastAPI Redis buckets now update atomically across workers.
Django's native django.core.cache.backends.redis.RedisCache uses Redis
transactions while preserving its existing serialized bucket values. Memory
and other custom cache backends serialize updates within one process; use
the supported Redis backends when sharing limits across workers.
Each package is versioned and released independently.
Python 1.3.5, Rust/Python 0.2.19, Node.js 1.3.5, WASM 0.2.15, and Java 1.4.0 are local source targets. See the package table below and CHANGELOG for release changes.
| Runtime | Package | Repository version | Primary use |
| --- | --- | ---: | --- |
| Python | aiwaf | 1.3.6 | Django, Flask, and FastAPI protection |
| Node.js | aiwaf | 1.3.7 | Express and Node framework middleware |
| Rust/Python | aiwaf-rust | 0.2.20 | Native Python acceleration and JSON model inference |
| WebAssembly | aiwaf-wasm | 0.2.16 | Rust detection and model primitives for JavaScript |
| Java | io.github.aiwaf-project:aiwaf-java | 1.4.0 | Spring MVC and Jakarta Servlet protection |
Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
What AIWAF provides
- IP blocklist, exemption, reputation, expiry, and progressive-block handling
- Sliding-window rate limiting and flood detection
- Header, method, request-size, content-type, and parameter validation
- Static and learned malicious keyword detection
- Honeypot field and form-timing checks
- UUID probing and tamper detection
- GeoIP allow/block policies using the bundled MMDB data
- Route manifests, path-specific overrides, and decorator/annotation exemptions
- Memory, file, CSV, SQLite, database, and cache-backed runtime state, depending on the runtime
- Structured request logging and offline training
- Six-feature anomaly models with Rust, JavaScript, and Java implementations
- Required Rust runtime for Python 1.1.4 and optional WebAssembly acceleration for Node.js
The runtimes share policy intent and training feature names, but their framework adapters and model implementations remain language-native. Model artifacts are not generally interchangeable across languages.
Profiles
AIWAF_PROFILE sets sensible defaults with one setting, in Django and Flask settings,
FastAPI's AIWAFConfig (or AIWAF(app, profile=...)), the Node.js options, the Java config
(profile) or the environment. A setting you give explicitly always wins over the profile.
| Profile | What it does |
| --- | --- |
| balanced (default) | Every default as it is. |
| strict | Halves the rate and flood limits (Django, Flask, FastAPI and Java: 10 and 20 a window; Node.js: 50 and 100), turns on UUID scoring, header validation and the method policy where the runtime has them as settings, and keeps the SQL and route checks blocking. |
| monitor | A dry run. Every check runs, and what it would block is logged instead, as AIWAF monitor: would block GET /.env from 203.0.113.9 with 403 (...). Nothing is blocked and no IP is added to the blocklist. |
Use monitor to try AIWAF on real traffic before turning it on. Its log lines go to the
aiwaf.monitor logger in Python, console.warn in Node.js and com.aiwaf.monitor in Java.
Monitor runs in the native pipeline too (aiwaf-rust 0.2.20 and aiwaf-wasm 0.2.16 or later), which
logs what it would block; its rate and honeypot state live under separate monitor namespaces, so a
monitored run never touches the live counters. Where the native pipeline can't start, the regular
middleware runs in monitor mode instead. Java's request body size limit still applies.
Client IP addresses and proxies
Blocks, exemptions, rate limits, and geo policies all depend on the client address. Python, Node.js, and Java read X-Forwarded-For and X-Real-IP only when the connecting peer is a trusted proxy. They walk X-Forwarded-For from the right and stop at the first untrusted address, because anything further left is client-supplied. CF-Connecting-IP and other vendor headers are not read for this purpose. In Python and Node.js the walk runs in aiwaf-rust and aiwaf-wasm, which also write IPv6 addresses in canonical form.
By default, Python and Node.js trust loopback, RFC 1918, link-local, and IPv6 unique-local peers, so a proxy on a private network needs no configuration. Java trusts loopback only. Set AIWAF_TRUSTED_PROXIES to a list or comma-separated string of addresses and CIDR ranges to replace those defaults. An empty value trusts no proxy. Two names can be used alongside addresses: default for the runtime's built-in ranges and cloudflare for Cloudflare's published ranges. Behind Cloudflare, use AIWAF_TRUSTED_PROXIES=default,cloudflare to keep trusting a local proxy as well.
When a peer that isn't trusted sends X-Forwarded-For or X-Real-IP, all three runtimes log one warning per process naming that peer. If the peer is your proxy or CDN, add it to AIWAF_TRUSTED_PROXIES. A client sending the header directly causes the same warning, and then no action is needed.
| Runtime | Where to set it |
| --- | --- |
| Django | AIWAF_TRUSTED_PROXIES in settings, or the environment variable |
| Flask | app.config["AIWAF_TRUSTED_PROXIES"], or the environment variable |
| FastAPI | The environment variable |
| Node.js | The AIWAF_TRUSTED_PROXIES or trustedProxies option, or the environment variable |
| Java | aiwaf.trusted-proxies in Spring properties, the environment variable, security.trusted_proxies in the JSON config file, or the trustedProxyCidrs field |
[!IMPORTANT] If your proxy or CDN connects from a public address (Cloudflare or Google Cloud load balancers, for example), add its ranges to
AIWAF_TRUSTED_PROXIES. Otherwise every visitor appears to come from the proxy, and rate limiting or a block can then affect all of them. Thecloudflarename trusts every Cloudflare address, and anyone can send requests through Cloudflare. If clients could also send requests through Cloudflare to your origin from outside your zone, restrict the origin to your zone, for example with authenticated origin pulls.
If untrusted hosts can reach the application directly from your private network, narrow the list to your proxy's addresses. Addresses already resolved by Flask's ProxyFix, Uvicorn's --proxy-headers, or Express trust proxy are respected, except that AIWAF still walks the headers when the resolved address is itself in a trusted range. The Rust-owned Node pipeline resolves the address the same way when it runs from the regular options (the default, or from_settings); configured on its own, it uses req.ip unless its trustedProxies option is set.
Injection audit
audit reads your source code and reports where request input can reach a dangerous
operation. It parses files without running them, and it doesn't change how requests are
handled.
aiwaf audit path/to/app # Python
npx aiwaf audit path/to/app # Node.js
java -cp <classpath> com.aiwaf.cli.AiwafConsole audit src # Java, needs a JDK| Language | Frameworks | Parser |
| --- | --- | --- |
| Python | Django, Flask, FastAPI, Graphene, Strawberry, Ariadne, Channels, Flask-SocketIO | ast |
| Node.js | Express, Fastify, Hapi, Koa, NestJS, Next.js (routes and server actions), Remix, tRPC, GraphQL resolvers, AdonisJS, Sails, ws and Socket.IO | @babel/parser |
| Java | Spring MVC and WebFlux, Spring GraphQL, Netflix DGS, Jakarta Servlet, JAX-RS, Spring messaging and Jakarta WebSocket | JDK Compiler Tree API |
It reports these operations:
| Operation | Examples |
| --- | --- |
| sql, nosql | cursor.execute, db.query, jdbcTemplate.update, collection.find |
| command | os.system, exec, Runtime.exec, ProcessBuilder |
| path | open, fs.readFile, new File, Path.read_text |
| ssrf | requests.get, fetch, RestTemplate |
| code, template, deserialization | eval, render_template_string, pickle.loads |
| xss | text returned from a Flask view, res.send, ctx.body, response.getWriter() |
| redirect | redirect, res.redirect, sendRedirect |
| ldap, xpath | conn.search, client.search, xpath, XPath.evaluate |
| xxe | XML parsers with external entities turned on |
| redos | regular expressions built from input |
| prototype (Node.js) | obj[key] = value with a key from input, _.merge |
It follows input through helpers, return values, other files and classes, objects that
keep input in fields, middleware that keeps input on the request, and callbacks such as
.then() and .map(). It understands checks: if not name.isalnum(): return, allowlists,
regex tests and '..' checks make a value safe, and encoders such as html.escape make
it safe only for what they encode for (HTML, not SQL). Values decided before the program
runs, dict keys and list positions are followed, so m['safe'] isn't confused with
m['input'].
On the OWASP Benchmark, whose labelled test
cases are real vulnerabilities or safe look-alikes, the Java audit finds every one of
1,572 injection cases with no false alarms, and the Python audit every one of 677
(scores of +100 on OWASP's scale). The benchmarks are small synthetic cases, so this isn't
proof of the same on real applications; scripts/audit_benchmark.py repeats the
measurement on a checkout of either.
All three accept --format text|json|sarif, --output <file>, --include-tests,
--fail-on-findings, --manifest <file> and --baseline <file>. The exit status is 0
when the scan completes, 1 with --fail-on-findings when something is found, and 2 for a
bad path or argument.
--format sarifwrites SARIF 2.1.0, which GitHub code scanning and other tools read.--baseline report.jsonleaves out findings already in an earlier JSON report, so CI fails only on new ones. Findings match by file, operation, call, function and input, not line, so moved code still matches.- A comment
aiwaf: ignoreon a finding's line or the line above leaves it out, andaiwaf: ignore[sql, xss]leaves out only those operations. The report counts them.
A finding is a path worth reading, not a confirmed vulnerability. A reverse proxy, for example, will report its upstream request because forwarding input is its job. A clean report doesn't prove the code is safe: reflection, dynamic calls and library code can be missed, and helpers are followed three calls deep.
Java can also build a route manifest from source, without starting the application. This is how plain Servlet applications get a manifest:
java -cp <classpath> com.aiwaf.cli.AiwafConsole init --source src --output .aiwaf/paths.jsoninit --app <SpringApplicationClass> starts the Spring application instead and reads its live
routes, then closes it. Its web server listens on a free port meanwhile (--server.port=0), so
init works while the app, or anything else, holds the configured port. As in Python and
Node.js, init writes nothing when it finds no routes, and every failure (no routes, a class
or folder it can't find, a usage error) exits non-zero, so a build step running it fails too.
SQL detection
AIWAF checks request values for SQL injection with a tokenizer. It tries each value as a
bare number, inside single quotes, and inside double quotes, and flags it only when the
value closes that SQL value and what follows reads as SQL. It catches a number followed by an
always-true condition or a time delay, which needs no quote, and MySQL's version comments,
whose contents MySQL executes. It passes text like "Item" #3, o'reilly, union select committee
and Drop table tennis; update your set list.
SQL keywords on their own, with no value to close, aren't flagged, because they can't change a query.
Besides the query string and body, the check reads the URL path and the headers, where SQL
injection also reaches applications. The path is checked one segment at a time, so a SQL
condition after a post ID in the path is found. Cookies are checked by their names and values, and the Referer,
X-Original-URL and X-Rewrite-URL by their path and query string. Every other header is
checked as one value, such as User-Agent, X-Forwarded-For, Accept-Language or an app's own
X- headers. Headers that hold credentials, framing or browser-set values aren't checked:
Authorization, Accept, Content-*, Sec-*, If-*, Host, CSRF tokens and tracing IDs.
Values are decoded the same way, including IIS %uXXXX escapes and null bytes, and JSON and XML
documents are checked by their values. Real browser, app, crawler, client and proxy headers,
analytics and session cookies, and search referers are in tests/fixtures/sql_header_cases.json,
and ordinary and attack paths in tests/fixtures/sql_path_cases.json. Every implementation runs
both. None of the 11,743 URL paths found in the documentation of this project's dependencies is
flagged. AIWAF_SQL_INJECTION_MODE still chooses whether a finding
blocks (the default), is only logged, or is ignored.
In Python, the whole request check runs in aiwaf-rust, which is required: one call walks
the query and body, decodes values, reads JSON bodies by their values, applies the size limits
and runs the tokenizer. It runs whatever AIWAF_USE_RUST says, because there's no Python copy.
Node.js runs the same Rust code through aiwaf-wasm, which it requires in the same way, so
AIWAF_DISABLE_WASM doesn't turn these checks off. Java has its own copy.
The cases in tests/fixtures/sql_injection_cases.json run against every copy in CI, and
python scripts/sql_accuracy.py reports the result. They were written alongside the
tokenizer, so passing them doesn't prove real-world accuracy. Add any miss or false block you
see there.
Outside test data is measured too. python scripts/sql_benchmark.py runs the whole SQL check
against the OWASP Core Rule Set's SQL injection tests and libinjection's test data, and CI
fails if the results get worse:
| Test set | Attacks caught | Ordinary values flagged |
| --- | --- | --- |
| libinjection sqli-*.txt | 84,830 of 85,791 (98.9%) | 1 of 421 in false_positives.txt |
| CRS 942, paranoia level 1 | 230 of 324 (71%) | 0 of 49 |
| CRS 942, paranoia level 2 | 209 of 498 (42%) | 2 of 90 |
CRS also matches SQL keywords and function names on their own, such as concat( or
cast(, especially at higher paranoia levels. AIWAF flags values that break out of a
SQL value, plus names that only appear in SQL, such as delay functions and the schema catalog, so
it misses many of those CRS fragments by design: matching them would block code snippets and
ordinary text. Each CRS test's whole request is checked, including its path and headers. Three
CRS tests marked benign carry SQL injection, such as a post path ending in a UNION query,
because CRS only means that one rule shouldn't match them. AIWAF flags them, and the benchmark
lists them apart from false positives.
The SQL tokenizer, request walker and route checks are fuzzed: for two minutes per target on
each pull request, and for 30 minutes each week (rust/fuzz). Short random-input tests also
run with every cargo test.
Remote code execution
The same payload check looks in every request value for text that runs code on the server:
| Rule | What it matches |
| --- | --- |
| rce_jndi_lookup | Log4Shell JNDI lookups, including nested lookups that spell out the keyword |
| rce_shellshock | Shellshock function definitions in headers and values |
| rce_serialized_object | Serialized Java, Python pickle, PHP, .NET and node-serialize objects, and unsafe YAML tags |
| rce_gadget | Deserialization gadgets: Fastjson and Jackson type keys that name known gadget classes, XStream dynamic proxies and XMLDecoder documents that start a process |
| rce_expression | OGNL, SpEL, EL, Thymeleaf preprocessing and Java reflection that reach a process, and Spring4Shell's class-loader property path |
| rce_template_escape | Jinja, Twig, Smarty, Velocity, Mako, Ruby ERB and Node.js sandbox escapes that reach Python internals, shell filters or Node's process module |
| rce_webshell | JSP, ASP and ASP.NET webshell code, and PHP that runs code or function names taken from the request, including base64-encoded code |
| rce_script_upload | Uploads named as server scripts: PHP, JSP, ASPX, .htaccess and similar |
| rce_command_injection | A probe or timing command chained onto the end of a value, as scanners send it: an identity, system-information or delay command after a semicolon, pipe or &&, or inside backticks or command substitution. A short probe must touch its separator, so ordinary text with a semicolon passes |
| rce_shell_payload | Reverse shells, download-and-run commands, reads of system account files, shell field-separator tricks, and Windows download commands and PowerShell download cradles |
| rce_php | PHP opening tags, PHP calls that run request input, and the PHP stream wrappers that run or unpack code |
| rce_prototype_pollution | Prototype-pollution keys in JSON bodies, forms and query strings |
Each value is checked as sent, then again with the disguises attackers use undone: \u0024,
\x24 and %u0024 escapes, HTML entities such as $ and $, fullwidth
characters such as %, invisible characters inside a word, Log4j lookups nested inside other
lookups, and a whole value sent as base64.
Each field of a query string or form body is also checked on its own, so a serialized Java
object in one field is found whether it's base64 or percent-encoded, and base64 is unwrapped up to three layers deep,
including base64 of gzip or deflate. A raw binary serialized body (Java, pickle, .NET
BinaryFormatter, Ruby Marshal) is checked before it's read as text. A prototype key in a
JSON body, form or query string is blocked as rce_prototype_pollution, since in Node.js it turns into code execution through
options that libraries pass to child_process and template compilers.
A multipart form is checked by its first AIWAF_PAYLOAD_MAX_BYTES, part by part: each
part's headers (such as a file name ending in .php) and field name, each text field as any
other value, and each file for a binary serialized object or PHP, JSP or ASP code, such as PHP
hidden in an image.
A file isn't checked for SQL or the other rules, since an ordinary document can quote them,
and a large upload isn't refused: the rest of it reaches your app unread. Node.js reads the
start of an unparsed multipart body and puts it back for your upload parser; Java reads the
parts the container parsed, when the servlet has a multipart config.
A gzip or deflate body (Content-Encoding) is read inflated, within
AIWAF_PAYLOAD_MAX_BYTES, so one that inflates past it is refused with 413. Node.js also
reads br. A body in an encoding that can't be read is refused with 413, since it can't be
checked (Java refuses compressed bodies unless allowCompressedRequestBodies is on). Every
header is checked; a request with more than 256 headers or 256 cookies is refused with 413
rather than checked in part.
It reads the query, the body (JSON, XML and forms), path segments and headers, including
User-Agent, Accept and Content-Disposition, which the SQL check skips. Every rule is checked against the shared
list of ordinary text and must match none of it, and shell syntax on its own (;, |, a
backtick) isn't matched: only the probes rce_command_injection lists are, and routes whose input
reaches a command get the full command checks from init.
The rules are in aiwaf-rust and aiwaf-wasm. Java's copy is generated from them by
scripts/sync_rce_rules.py, and a test fails when it's out of date. The cases in
tests/fixtures/rce_cases.json (73 attacks and 57 ordinary look-alikes, plus whole form and JSON bodies, such as JSON-LD
"@type": "Person" and filename="report.pdf") run against both. It follows AIWAF_SQL_INJECTION_MODE:
block (the default) answers 403, monitor logs the rule, and off turns both checks off.
WebSocket messages
HTTP checks don't see what a WebSocket carries after its handshake, so each message a client
sends can be checked like a request body. When AIWAF_SQL_INJECTION_MODE (or the guard's mode
/ sqlInjectionMode) is unset, Python and Node.js guards inherit AIWAF_PROFILE (so
AIWAF_PROFILE=monitor logs findings without disconnecting sockets unless overridden), and
Java uses config.applyProfile(...). A message with a finding closes the socket with 1008
(1009 when it exceeds AIWAF_PAYLOAD_MAX_BYTES / requestBodyInspectionBytes) and never
reaches your handlers; log events carry the rule and path, never the message.
What the message checks cover:
- Size cap:
AIWAF_PAYLOAD_MAX_BYTES(JavarequestBodyInspectionBytes) caps how large a single message can be before closing with1009. - Message rate:
AIWAF_WEBSOCKET_MAX_MESSAGESlimits how many messages one connection may send in anyAIWAF_WEBSOCKET_MESSAGE_WINDOW_SECONDS(default 10). It's off until set. A client past it is closed with1008(rulewebsocket_message_rate), and in monitor mode it's logged and the message passes. A message sent in parts counts once. Passmax_messagesandmessage_windowto the Python guards,maxMessagesandmessageWindowSecondsto the Node.js guards, or set Java'swebsocketMaxMessagesandwebsocketMessageWindowSeconds(aiwaf.websocket.max-messagesandaiwaf.websocket.message-window-secondsin Spring). The count is per connection: withAIWAF_WEBSOCKET_MAX_CONNECTIONS_PER_IPit bounds what one address can send. - Split messages: a message sent in parts is checked whole. Spring's wrapper asks for whole
messages, and Jakarta's
AiwafEndpointputsMessageHandler.Partialparts together, up torequestBodyInspectionBytesin all, before any reach your handler. An annotated@ServerEndpointcallingAiwafMessageCore.checkshould take whole messages.
The guards also check the handshake, before your app hears of the connection. Each check is off until you set it:
| Check | Setting | Rule |
| --- | --- | --- |
| Origin | AIWAF_WEBSOCKET_ALLOWED_ORIGINS (comma-separated; exact, https://*.example.com, or *) | websocket_origin |
| Your own authorization | an authorize hook passed to the guard (true lets the client in) | websocket_unauthorized |
| Connections per client address | AIWAF_WEBSOCKET_MAX_CONNECTIONS_PER_IP | websocket_connection_limit |
A handshake without an Origin header passes the origin check: browsers always send one, and other
clients can send anything. Client addresses come through AIWAF_TRUSTED_PROXIES as they do for
HTTP requests. A hook that throws lets no one in. In monitor mode a refusal is logged and the
connection allowed.
Python ASGI:
WebSocketGuard(app, allowed_origins=[...], max_connections_per_ip=5, authorize=check), wherecheck(scope)may be async. Refused onwebsocket.connectwith1008.Flask-SocketIO:
guard_socketio(socketio, allowed_origins=..., max_connections_per_ip=..., authorize=check), wherecheck(request)gets the handshake's Flask request. Refused before yourconnecthandler runs.Node.js:
guardWebSocketServer(wss, { allowedOrigins, maxConnectionsPerIp, authorize })(refused with403inverifyClient; your ownverifyClientstill runs), and the same options forguardSocketIo(io, ...)(refused inallowRequest).authorize(req)may be async. A client over the limit is closed with1008once connected.Spring: Java config is
websocketAllowedOriginsandwebsocketMaxConnectionsPerIp(aiwaf.websocket.allowed-originsandaiwaf.websocket.max-connections-per-ip, orwebsocket_allowed_originsandwebsocket_max_connections_per_ipundersecurity).new AiwafWebSocketHandler(handler, config, session -> ...)closes a refused session with1008after the upgrade, before your handler'safterConnectionEstablished. To answer403during the handshake instead, add the handler's own interceptor:registry.addHandler(guarded, "/ws").addInterceptors(guarded.handshakeInterceptor(request -> ...)). It refuses an origin not allowed, a request its hook turns away, and an address already at the connection limit. It shares the handler's count, and the handler still counts each session as it opens.Jakarta WebSocket: register
ServerEndpointConfig.Builder.create(AiwafEndpoint.class, "/chat").configurator(new AiwafEndpoint.Handshake(new ChatEndpoint(), config, request -> ...)). An origin not allowed is refused with403during the handshake; authorization and the limit close with1008before your endpoint'sonOpen. The client address is read from Tomcat's handshake request; on a container where it can't be, the limit isn't applied and a warning says so once.Python (FastAPI, Starlette, Django Channels):
app.add_middleware(WebSocketGuard), fromaiwaf.core.websocket(alsoaiwaf.fast.WebSocketGuard), or wrap your ASGI application. Flask-SocketIO:guard_socketio(socketio)for every event, or@aiwaf_message()under@socketio.on(...)for one handler, fromaiwaf.flask.websocket.inspect_message(data)checks one message anywhere else.Node.js:
await aiwaf.guardWebSocketServer(wss)forws,await aiwaf.guardSocketIo(io)for socket.io, oraiwaf.inspectMessage(data).Java:
new AiwafWebSocketHandler(handler, config)for Spring WebSocket, andnew AiwafEndpoint(endpoint, config)for a Jakarta WebSocket endpoint (return it from yourServerEndpointConfig.Configurator). In an annotated@ServerEndpoint, callAiwafMessageCore.check(message, config, path)and close withAiwafMessageCore.closeCode(rule).
These are tested against real servers: Starlette, Flask-SocketIO's test server, ws and
socket.io with their clients, and Tomcat's WebSocket container with the JDK client.
Route-specific checks from init
init audits your source as it builds the route manifest, and saves which operation each
route's input reaches. Requests to those routes are then checked for patterns that matter to
that operation, in the parameter that reaches it. A route whose input reaches a file path is
checked for traversal, and a route whose input reaches SQL gets the SQL tokenizer on its route
values too. A match blocks the request with 403 and logs an event like this:
{"event": "aiwaf.injection_risk", "mode": "block", "method": "GET", "route": "/files", "sink": "path", "input": "name", "rule": "path_traversal", "confidence": "medium"}| Operation | Rules: what a value must contain to match |
| --- | --- |
| sql | The SQL tokenizer: a value that closes its SQL literal and continues as SQL |
| command | command_chain, command_substitution: ;, & or \| and a command, $(...), backticks |
| path | path_traversal, path_sensitive_location, path_null_byte |
| ssrf | ssrf_scheme, ssrf_internal_host: file:// and similar, private and metadata hosts |
| nosql, code, template, deserialization | query operators, code evaluation calls, template expressions, serialized object markers |
| xss | xss_markup, xss_event_handler, xss_script_url: script tags, event-handler attributes, script URLs |
| redirect | redirect_external: protocol-relative, backslash, script-URL, user-info and scheme-only targets |
| ldap | ldap_filter: filter breakouts, OR filters and leading wildcards |
| xpath | xpath_quote_break, xpath_tautology: quote breakouts and always-true conditions |
| xxe | xxe_entity: document type and entity declarations |
| redos | redos_nested_quantifier: nested quantifiers |
| prototype | prototype_key: prototype-pollution keys |
Every rule is checked against a shared list of ordinary values (names, addresses, prose with quotes and parentheses) that must never match. A plain absolute URL passes the redirect rule, because the site's own host isn't known there.
aiwaf init --framework flask --app app:app # audits the current folder
aiwaf init --framework flask --app app:app --source src # audits another folder
aiwaf init --framework flask --app app:app --no-audit # saves no route checksThe manifest is written atomically, to a temporary file beside it that replaces the old one, so a failed write never leaves a truncated manifest.
When the audit source doesn't exist, or the scan fails, init stops with exit status 1 and
writes nothing, so an existing manifest stays. A source with no files to read counts as
--no-audit, with a warning.
With --no-audit the inputs init still knows are saved with their types: the framework's
own lists (a Fastify or Hapi schema, Nest DTOs, FastAPI parameters, Spring's bound parameters
and body classes), .aiwaf/inputs.json, and in Java --source what the parse read. Their
types are checked, but no list is marked complete (not_audited): a complete list with no
saved injection risks tells AIWAF the route reaches no risky call, which only the audit can
say. So strict inputs, and the relaxed SQL rules for typed routes, need the audit.
Node.js aiwaf init and aiwaf manifest accept --source and --no-audit too. Java init --source uses
the same parse for routes and findings, and init --app audits src/main/java (or
--audit-source). aiwaf audit --manifest <file> refreshes the saved findings without
rebuilding the manifest.
AIWAF_INJECTION_RISK_MODE is block by default. Set it to log to only log matches, or
off to skip route checks. Flask and Django settings and the Node.js options accept the same
name, Spring uses aiwaf.injection-risk-mode, and the Java config file uses
security.injection_risk_mode. The Node.js native pipeline reads AIWAF_INJECTION_RISK_MODE
and AIWAF_PATH_MANIFEST from the environment.
- Only routes with findings: a route with no saved findings keeps its normal checks, and saved findings never turn a protection off.
- Logs hold no request values: events contain route, rule and parameter names from the manifest only.
- What it reads: query strings, route values, and buffered JSON or form bodies. Headers, cookies and multipart uploads aren't checked.
- Unlinked findings:
initreports findings it can't tie to a manifest route, and those get no route-specific checks. Handlers are matched by path or function name, so routes missing from the manifest, or reused function names in Node.js, can stay unlinked. - Stale results: run
initagain when code changes, for example in your build. - Where they run: route checks run in Rust: through
aiwaf-rustin Python andaiwaf-wasmin Node.js. Java has its own copy. - Accuracy isn't measured on real traffic yet: if a rule blocks real users on a route,
set
AIWAF_INJECTION_RISK_MODE=logwhile you report it.
Route schemas from init
init also saves what each route reads from the query and body, and a type for each input,
from your code: int, float, bool, uuid or text.
"/comments": {"inputs": {"body": "text", "post_id": "int"}, "inputs_complete": true}Types come from what the code says:
- Python:
int(request.GET["page"]),type=int, FastAPI type hints and Pydantic models, Django forms and DRF serializers. A read kept in a variable takes the type of its later cast, aspage = request.GET.get("page")thenint(page), orsize = int(size)in atry. - Node.js:
parseInt(req.query.page),Number(...), destructuring, and zod object schemas, and the same later casts:const { limit } = req.querythenNumber(limit). - Java:
@RequestParam int page,@RequestBodyand@ModelAttributeclasses and records,Pageable, andInteger.parseInt(request.getParameter("n")), also through a local:String raw = request.getParameter("n")thenInteger.parseInt(raw).
Forms, serializers, models, zod schemas, helper functions and string constants are followed
into the project's other files through imports: from .forms import ContactForm, import {
Body } from './schemas', require('./helpers'), or a static Paging.page(request) in Java. A key
held in a constant, as in request.GET[PAGE_PARAM] or getParameter(PAGE), is known.
A name read with different types by different methods on one path (a GET's text mode, a
POST's integer mode) is saved as text in inputs, the type every method agrees on, and each
method's own type in inputs_types_by_method, which aiwaf-rust 0.2.18, aiwaf-wasm 0.2.14 and
Java 1.4.0 check for that method alone:
"/plans": {"inputs": {"mode": "text", "weeks": "int"},
"inputs_types_by_method": {"POST": {"mode": "int"}},
"inputs_by_method": {"GET": ["mode"], "POST": ["mode", "weeks"]}}An older engine reads only inputs, so it keeps checking the agreed type. Each method also has
its own list of names.
A name sent in both the query and the body with different types (a query limit that's an
integer, a JSON limit that's text) keeps each location's type in inputs_types_by_location,
as {"POST": {"query": {"limit": "int"}}}; each value is checked against its own location's
type, then its method's, then the route's. init warns when the installed aiwaf-rust or
aiwaf-wasm can't check an entry it wrote.
inputs_complete is true only when every read was understood. When it isn't, the route's
inputs_incomplete says why, with the file and line, and init's summary counts the reasons:
| Code | Meaning |
| --- | --- |
| helper | The request is passed to code that isn't followed. |
| container_whole | request.POST, req.body or the parameter map is used whole. |
| dynamic_key | An input is read with a key that isn't a constant. |
| raw_body | The raw body, query string or a multipart part is read. |
| class_view | A class view inherits handlers that aren't read, or @InitBinder runs first. |
| dependency | A FastAPI dependency takes the request itself. |
| external_class | A form, schema or body class isn't in the scanned sources. |
| model_fields | A ModelForm, ModelSerializer or @JsonAnySetter class takes fields from elsewhere. |
| middleware | Node.js route middleware that isn't a body parser may read the body. |
| observed | A recording saw the code read a name the analysis didn't find. |
| unread_view | The audit didn't read the code of a handler serving the path, so its risks aren't known. |
| not_audited | init ran without the injection audit, so the route's risks aren't known. |
Then init fills in what reading the code can't see:
The framework.
initruns with your app loaded, so it asks the framework: Django generic views (forms,ModelFormfields, pagination,next), DRF views (serializer fields, pagination, search, ordering and filterset parameters,format), FastAPI's resolved parameters and dependencies, and in Java each Spring handler method and its body classes by reflection, including classes from libraries. Python also reads the fields of any form, serializer, Pydantic model, marshmallow schema, WTForms form or dataclass the code reading couldn't, from the modules the app already imported. Flask and Django views read the fields of their webargs@use_args/@use_kwargsand flask-smorest@blp.argumentsschemas (marshmallow), both from the live app and from source; a view only receives those fields, plus anything it reads fromrequestitself. When both the query and the body arguments reject unknown names (unknown=RAISE), requests with any other name fail before the view runs, so the route is complete. In Node.js, when you generate the manifest from the live app (generateFrameworkManifest(framework, app)), it reads Fastify route schemas (querystringandbody, including TypeBox; register the aiwaf plugin before your routes so it sees them), Hapivalidate.queryandvalidate.payload(Joi), and each NestJS handler's@Query()and@Body()parameters, with their pipes and the fields of their DTO classes from class-validator or@nestjs/swaggermetadata, at the paths Nest registers (global prefix and its exclusions,RouterModulepaths, URI versioning). On Express routes it reads validation middleware: celebrate schemas and express-validator chains (query(),body(),check(),checkSchema()). Validators only check the names they list, so the handler's code still says what it reads; when every middleware before the handler is a validator, its fields replace themiddlewarereason. A validation middleware of the app's own that keeps its zod or Joi schema in its closure, asvalidate(schema, 'query')does, is read too, through Node's inspector while the manifest is built (never per request). Route middleware the project defines itself, asapp.post('/x', checkBody, handler), is read from source like the handler, so a schema it parses with (even one defined at the top of the module) and anything it reads count for the route. zod schemas (zod 3 and 4) are read wherever these accept one: Fastify route schemas (as fastify-type-provider-zod uses them) and nestjs-zod DTOs.Reading the source does the same for validator calls written on the route (
app.post('/x', body('name'), ...),checkSchema({...}),celebrate({...}), also through a namespace import such asev.body('name'), an object onthis, or a function's result). A route behindcheckExact(...), or a celebrate schema closing both query and body, rejects requests with any other name before the handler runs, so it's complete with the names its validators list plus what the handler reads.Declarations, for code that can't be read. In Python,
@aiwaf.inputs(q=str, page=int); in Node.js,aiwaf.inputs({ q: 'text', page: 'int' })(handler); in Java,@AiwafInputs({"q", "page:int"}), on a handler or its class. Or in.aiwaf/inputs.json, for any language:{"/search": {"inputs": {"q": "text", "page": "int"}}}. A declaration makes the route's list complete: what it lists, plus anything the code is seen reading. Passcomplete=False({ complete: false },complete = false) to only add names. In Node.js,aiwaf.inputs()also takes the schema the handler validates with, a zod or Joi schema or a DTO class:aiwaf.inputs(SearchQuery)(handler). A schema that allows names it doesn't list only adds them.An OpenAPI spec, with
AIWAF_OPENAPI_SPEC=openapi.json. An operation whose body schema names every property, and whose route's methods it all lists, is a declaration too.Recordings, from tests or staging. Set
AIWAF_RECORD_INPUTS=1(or a file path). Flask's and FastAPI'sAIWAF(app), the Node.js middleware, Spring Boot (aiwaf.record-inputs) and Django (theAIWAF_RECORD_INPUTSsetting or variable, with aiwaf inINSTALLED_APPS, which addsDjangoInputRecorderlast toMIDDLEWARE) then record on their own, after AIWAF's own checks so its reads aren't counted. Elsewhere userecord_flask_inputs(app),app.add_middleware(AsgiInputRecorder),app.use(aiwaf.recordInputs())before Express routes, orAiwafInputRecorderFilterin a servlet app. This is how handlers no reading or declaration covers get their lists. It records the names each handler reads, not what clients send, to.aiwaf/observed_inputs.jsonl, which the nextinitreads. Recorded names are added to the routes' inputs, and a route the analysis called complete that read something else is made incomplete. WithoutAIWAF_RECORD_INPUTSthe recorders do nothing. The Java recorder recordsgetParameterreads, and the application's own whole reads (getParameterMap, the body stream) as reading everything; reads Spring itself makes for binding aren't counted. Django's can't seejson.loads(request.body).
Requests to those routes are then reviewed after the general check:
- A typed input sent with a value of another type, as in a SQL condition sent as a numeric
ID, is
schema_type_mismatch. - A finding from
sql_function,sql_commentorsql_breakout_numericis checked again without the inputs the schema clears: typed inputs of their type, text that reaches no operation, and, when the list is complete, inputs the route never reads. When nothing else is found, the finding is cleared. This is where prose and pasted code, such as a question about a SQL function, stops being blocked. - A finding from the URL path, such as a blog slug that names a SQL function, is reviewed by the
route's parameters: static segments are code, typed parameters (
<int:id>,{id:uuid}, or a saved type) must fit, and text parameters that reach no operation are cleared the same way. - Quote breakouts and every remote code execution rule still block on every input. An incomplete list, a sink reached by an input the audit couldn't name, a body that isn't a form or JSON object, or a finding from headers or the path keeps the finding.
AIWAF_ROUTE_SCHEMA_MODE is monitor by default: it logs what it would do
({"event": "aiwaf.route_schema", "action": "relax", "rule": "sql_function", ...}, never
request values) and changes nothing. Set it to enforce to act on it, or off. Java reads
security.route_schema_mode and aiwaf.route-schema-mode. The native pipelines review in the
engine too: Python's reads route_schema_mode (or AIWAF_ROUTE_SCHEMA_MODE), and Node.js's
takes routeSchemaMode, including its inspectPayload(). The cases in tests/fixtures/route_schema_cases.json run against aiwaf-rust, aiwaf-wasm
and Java.
Strict inputs
With AIWAF_STRICT_INPUTS=1, a route whose saved input list is complete accepts only the names
on it: a query or body name the route never reads is schema_unexpected_input. It follows
AIWAF_ROUTE_SCHEMA_MODE, so it's logged in monitor ("action": "unexpected" with the name,
cut to 64 characters) and blocked in enforce. The query and a form, multipart or JSON object
body are checked, a multipart file part by its field name. Routes whose list is incomplete,
routes with no saved inputs, path parameters, headers and other bodies are never checked.
Keys inside an object-valued input are checked too when init knows them all
(inputs_nested): from code that reads only constant keys inside it, as
data["user"]["name"] or req.body.user.name, in every handler that reads it, from a JSON
Schema object property that lists its properties and allows no others (Fastify, Hapi,
OpenAPI-style), from a FastAPI body model whose field is itself a Pydantic model (customer: Customer gives customer's
declared fields, one level down), or from a Java body class's nested classes. A JSON
{"user": {"role": "admin"}}, or a form's user[role], is then user.role, unexpected.
Deeper levels are saved by path where a closed schema or Pydantic model gives them, as
"customer.address": ["city", "zip"] and "lines[]": ["qty", "sku"] for each item of a list,
up to four levels; objects that allow other keys are left alone. An
input a handler passes on whole, a model that allows undeclared fields, or one that another
framework schema or declaration names, has no such list and isn't checked inside.
AIWAF_STRICT_INPUTS_EXEMPT=/webhooks/,/legacy/* lists path prefixes strict inputs skips, for
routes that take whatever their senders add.
When a path's methods are served by different handlers, as a GET view that reads q and a POST
view that reads title, init saves each method's own list (inputs_by_method), and strict
inputs check a request against its method's: title on the GET is unexpected. A method takes
the names its own handler's code (or the framework's per-route schema, or its OpenAPI
operation) reads, plus every name nothing ties to one method: declarations, recordings and the
like. HEAD uses GET's list, and a method without its own list uses the whole path's.
CSRF tokens (csrfmiddlewaretoken, csrf_token, _csrf, _token, authenticity_token) and
tracking and cache-busting parameters (utm_*, fbclid, gclid, msclkid, _) are always
allowed. Add more with AIWAF_STRICT_INPUTS_ALLOW=trace_id,ref_*; a trailing * matches any rest.
Turn it on in monitor first and read the log: a name that turns up there for a real client is
either one the analysis missed (record it, or declare it) or one to allow. The setting is
AIWAF_STRICT_INPUTS/AIWAF_STRICT_INPUTS_ALLOW in Django settings, Flask config and FastAPI
config; strictInputs/strictInputsAllow for the Node.js native pipeline; and
security.strict_inputs, aiwaf.strict-inputs or AiwafConfig.strictInputs in Java. It needs
aiwaf-rust 0.2.16 or aiwaf-wasm 0.2.12; with an older engine it logs a warning and stays
off. The cases under strict_cases in tests/fixtures/route_schema_cases.json run against all
three.
Repository layout
.
├── py/aiwaf/ Python package and adapters
├── js/ Node.js package and adapters
├── rust/ Rust core and Python bindings
│ └── crates/aiwaf_wasm/ WebAssembly bindings
├── java/ Java 17 package
├── tests/ Python integration and parity tests
├── examples/ Focused Python examples
├── .github/workflows/ Tests, security checks, and releases
├── README.md Canonical project documentation
└── LICENSE Canonical Elastic License 2.0 (see NOTICE)Quick installation
Choose the package for the application runtime:
# Python core or a framework extra
pip install aiwaf
pip install "aiwaf[django]"
pip install "aiwaf[flask]"
pip install "aiwaf[fastapi]"
# Backward-compatible alias; Python 1.3.0 already installs aiwaf-rust
pip install "aiwaf[rust]"
# Node.js middleware
npm install aiwaf
# Standalone WebAssembly bindings
npm install aiwaf-wasmnpm 12 runs a dependency's install script only after you approve it, and sqlite3, where
Node.js AIWAF keeps its blocklist, exemptions and logs, gets its native binary from its install
script. Without approval AIWAF still runs, keeps that data in CSV files under logs/storage, and
prints one warning. To use SQLite, approve and build it once in your app:
npm approve-scripts sqlite3
npm rebuild sqlite3Java 1.4.0, after it is published to Maven Central:
<dependency>
<groupId>io.github.aiwaf-project</groupId>
<artifactId>aiwaf-java</artifactId>
<version>1.4.0</version>
</dependency>Python package
The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
Python 1.3.6 requires aiwaf-rust>=0.2.20; the rust extra remains an installation
alias. Publish the matching Rust wheel with NativeCSVPipeline support before
the Python release. The Rust release workflow builds Linux x86_64/aarch64,
musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
pipeline API. Windows and WSL builds are checked locally; the other wheel
targets must pass CI before publication.
Rust-owned CSV pipeline
The complete CSV request pipeline is available through explicit adapters below.
Install it instead of the existing eight-middleware chain. The existing
AIWAF adapters remain available for compatibility with custom stores and hooks;
they do not switch automatically to this pipeline.
Rust owns the immutable configuration, enforcement order, SQL and keyword inspection, geo and blocklist decisions, rate buckets, form timing state, UUID scores, anomaly inference/history, keyword learning and CSV logging. Python supplies framework routing/authentication facts, obtains GeoIP country data, buffers a bounded body prefix and constructs responses. Each request crosses into the engine once before the handler and once when its response is available. The engine never calls Python policy callbacks or falls back to Python execution. Missing native support, unsupported settings and invalid CSV schemas fail at startup.
# Flask
from flask import Flask
from aiwaf.flask import NativeAIWAF
app = Flask(__name__)
NativeAIWAF(app, config={"data_dir": "aiwaf_data"})# FastAPI / pure ASGI
from fastapi import FastAPI
from aiwaf.fast import NativeAIWAFMiddleware
app = FastAPI()
app.add_middleware(NativeAIWAFMiddleware, config={"data_dir": "aiwaf_data"})# Django settings: replace the existing AIWAF middleware entries
AIWAF_CSV_PIPELINE = {"data_dir": "aiwaf_data"}
MIDDLEWARE = [
# Keep the application's other middleware in the required order.
"aiwaf.django.csv_pipeline.NativeAIWAFMiddleware",
]The configuration uses a dedicated lowercase profile; existing uppercase
framework settings, AIWAFConfig dictionaries, custom stores and policy callbacks
are not imported into it. Unknown keys are rejected. Path rules and the route
manifest work as in the regular chain, through three adapter keys:
path_rules: the same rules asAIWAF_PATH_RULES.DISABLEturns stages off for a prefix, andRATE_LIMIT(WINDOW,MAX,FLOOD) replaces the profile's rate limits there. Invalid limits fail at startup.manifest_path: default.aiwaf/paths.json. Its route rules are added afterpath_rules, and the route-specific checks saved byinitrun on matching requests.injection_risk_mode:block(default),logoroff, defaulting toAIWAF_INJECTION_RISK_MODE. A blocked request is logged with the matched rule. Route decorators for full/partial exemptions and required middleware are read once. Required decorators override decorator exemptions; profile-level path/IP exemptions remain global. The profile is immutable: construct a new engine and reload workers to change it.
The regular setup runs as the native pipeline by default when the installed aiwaf-rust has every native feature (0.2.9 or newer) and every setting carries over exactly, so the report below lists no differences. Nothing in the app changes:
- Django: the regular AIWAF classes in
MIDDLEWARErun as one native middleware, at the place of the last of them, so sessions and authentication have run before it. The others step aside withMiddlewareNotUsed. - Flask and FastAPI:
AIWAF(app)installs the native pipeline instead of the regular middleware, with the same stages its plan would register.
Request logs go to aiwaf_native_access.csv in the regular log directory, which the Flask
and FastAPI trainers read. A model the regular middleware has loaded carries over if
aiwaf-rust made it; an sklearn model, or a Flask model still held back for lack of logs,
is a difference. AIWAF logs one line on the aiwaf.native logger when it switches. To keep
the regular middleware, set AIWAF_NATIVE_PIPELINE = False in Django settings or Flask
config, pass native_pipeline=False to Flask's or FastAPI's AIWAF(...), or set the
AIWAF_NATIVE_PIPELINE=false environment variable. aiwaf init says whether a project
switches and, if not, why.
To start from the settings the regular middleware already uses explicitly, pass
"from_settings": NativeAIWAF(app, "from_settings") in Flask,
AIWAF_CSV_PIPELINE = "from_settings" in Django, or
app.add_middleware(NativeAIWAFMiddleware, config="from_settings") in FastAPI, which
converts the AIWAFConfig the regular middleware uses (or one passed as aiwaf_config). {"from_settings": True, ...} converts
and then applies the other keys on top. The same AIWAF_* names are read with the same
defaults, including Django's built-in login and admin exemptions and keyword list, and
Django's stages follow the regular classes in MIDDLEWARE. At startup AIWAF logs, on the
aiwaf.native logger, how many settings carried over unchanged and every one that didn't,
with the reason: for example, Flask's *.css-style exemptions and IP ranges in
AIWAF_EXEMPT_IPS, which the native pipeline can't match. It also uses the regular
stores (below), so blocks, exemptions and keywords already stored carry over, and Flask's
pattern exemptions and FastAPI's private-range exemptions keep working. FastAPI's header-only exempt_paths become path rules
that turn off header validation alone, and its private-range auto-exemptions are reported
because only exact addresses carry over. aiwaf.core.native_settings.native_config() and
native_config_fastapi() return the same profile and report without starting anything.
By default the native pipeline keeps its blocklist, exemptions, learned keywords and
blocked countries in CSV files in data_dir. To use the stores the rest of the app
already uses, set "store" in the native config: "django", "flask" or "fastapi" use
that framework's regular stores, following its storage settings (AIWAF_STORAGE_MODE,
AIWAF_USE_CSV or AIWAF_DATA_DIR, or AIWAFConfig's storage), so the native and regular
middleware and the management commands share one blocklist. Flask's store also matches its
*.css-style exemptions, and FastAPI's its private-range IP exemptions, which native
profiles can't. "from_settings" turns this on when the installed aiwaf-rust supports it.
Elsewhere, pass stores= to CSVPipeline. Before
each decision AIWAF reads what that request's stages use: whether it's exempt, then, if
not, whether the IP is blocked (IP/keyword and anomaly stages), the learned keywords
(IP/keyword stage) and blocked countries (geo stage). A route whose path rules turn those
stages off reads nothing. Answers are cached for store_cache_seconds (default 5):
keywords and countries, and the blocklist and exemption answers per IP and path, up to
10,000 of each. So a block or exemption made in another worker, the admin or the CLI can
take that long to apply; blocks this worker makes apply at once. store_cache_seconds: 0
reads the stores on every request. It then
writes the blocks and keywords the decision produced back through the stores. The
decision itself still runs in aiwaf-rust. A custom store is any object with
is_blocked(ip), is_exempted(ip, path), top_keywords(n), blocked_countries(),
block(ip, reason) and learn(keywords); aiwaf.core.csv_pipeline.PipelineStores
documents them. Rate limits, honeypot timing, UUID scores and anomaly history stay in
the engine.
Common profile keys and defaults:
| Setting | Default / meaning |
| --- | --- |
| enabled | All eight names: geo_block, ip_keyword_block, rate_limit, ai_anomaly, honeypot, uuid_tamper, header_validation, logging |
| data_dir | aiwaf_data; policy CSVs use the shared allowlist/blocklist/keyword/geo/path schemas |
| 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 |
| 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 |
| learning, top_n | True, 10; presence keywords use a sorted, stable subset instead of Python set iteration order |
| static_keywords, legitimate_keywords, exempt_keywords, safe_prefixes | Native policy defaults or explicit arrays; set route-specific safe vocabulary in the profile |
| geo_allow, geo_block | Empty lists; includes stored blocked countries. Unknown country remains allowed |
| 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 |
| 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 |
| rate_window, rate_max, rate_flood | 10, 20, 40; throttle at 429, flood at 403 with blocklist persistence |
| soft_block_blocklist, ip_blocking, block_duration | False, True, reputation-based duration; explicit seconds or nonpositive permanent duration |
| 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 |
| honeypot_cache_alias | Django-only; default. Uses the named CACHES entry for honeypot timestamps, not other policy or rate state |
| honeypot_redis_url | Required for honeypot_backend="redis"; stripped before native profile serialization. rediss:// requires redis-py |
| honeypot_cache_namespace | Redis/custom cache key prefix, default aiwaf:native:honeypot:v1; use the same value across workers and a distinct value for unrelated applications |
| min_form_time, max_page_time, skip_authenticated | 1.0, 240, True; native Rust applies the timing policy |
| uuid_score_enabled, uuid_window, uuid_threshold | True, 60, 5; weights: uuid_malformed_weight=5, uuid_not_found_weight=1, uuid_success_decay=2 |
| required_headers, header_min_score | HTTP_USER_AGENT and HTTP_ACCEPT, 3; empty required list disables required-header/quality checks, retains safety caps |
| anomaly_window, anomaly_keywords | 60, standard anomaly vocabulary; history/scoring is held in Rust per worker |
| log_path, log_fsync | data_dir/requests.csv, False; immediate CSV append, optional per-row fsync |
Pass a trained aiwaf_rust.IsolationForest as model= to Flask/FastAPI, or
set AIWAF_CSV_PIPELINE_MODEL in Django. Without a model, the anomaly stage
maintains history and learns suspicious 404 keywords but performs no model-based
blocking. pipeline.native.set_model(model) replaces the model with an owned
snapshot; set_model(None) disables inference. Training and management APIs
remain available through the existing Python interface.
For deployments that accept per-worker form timing, set
"honeypot_backend": "memory" in the native profile. Rust then holds GET
timestamps in an expiring map and evaluates/clears POST timing atomically,
avoiding a durable CSV rewrite on each GET. Timing state is isolated per engine,
is not shared across workers and resets on restart. Backend switches do not
transfer timestamps automatically. Keep csv for shared or persistent timing;
CSV writes remain immediately synced. Blocklist, keyword, geo and allowlist
policy files and immediate request logging keep their configured CSV behavior.
Shared native rate limits
With rate_backend: "memory" each worker counts on its own, so N workers allow N times
the limit. rate_backend: "redis" with rate_redis_url counts in Redis instead, with the
regular limiter's atomic sliding-window script, and in Django "django_cache" counts in a
Django cache (rate_cache_alias), as the regular rate limiter does. Only the count is
shared: aiwaf-rust still applies rate_max, rate_flood and path-rule limits to it.
CSVPipeline(config, rate_counter=...) with rate_backend: "counter" takes any object
with a synchronous, atomic count(key, now, window_seconds) that records the request and
returns the window's count. A failing counter answers 503, as the regular limiter does.
from_settings carries this over: Django counts in its default cache, and Flask
(AIWAF_RATE_CACHE_BACKEND="redis" with AIWAF_REDIS_URL) and FastAPI
(rate_limiting.cache_backend, rate_limiting.redis_url) count in the same Redis. It
needs aiwaf-rust 0.2.9 or newer; with 0.2.8 a counter fails at startup and from_settings
reports that rate limits stay per worker.
Flask and FastAPI native honeypot cache
Both native adapters accept Redis or a supplied synchronous cache. CSV remains their default. This changes honeypot timestamp storage only; other policies and rate-limit backends retain their configured behavior.
import os
from aiwaf.flask.csv_pipeline import NativeAIWAF
profile = {
"data_dir": "aiwaf_data",
"honeypot_backend": "redis",
"honeypot_redis_url": os.environ["AIWAF_REDIS_URL"],
"honeypot_cache_namespace": "myapp:honeypot:v1",
}
NativeAIWAF(app, config=profile) # Flask
# FastAPI alternative:
# from aiwaf.fast.csv_pipeline import NativeAIWAFMiddleware
# app.add_middleware(NativeAIWAFMiddleware, config=profile)For an existing Flask-Caching instance or another compatible object, select
honeypot_backend="cache" and pass honeypot_cache=cache to either native adapter.
The contract is get(key) returning a stored value or None, and
set(key, value, timeout=seconds) returning success or None. Explicit False
means failure. Methods must be synchronous, preserve a timestamp/expiry pair,
honor TTL, and propagate storage errors. Disable any ignored-error option;
no-op cache backends are unsuitable. Custom adapters must translate their own
cache's TTL argument if it differs. A local cache still isolates workers.
Rust retains timing decisions, exemptions and logical expiry. Entries have a 300-second TTL; misses/evictions permit the POST timing check, while exceptions, invalid records and failed writes return generic HTTP 503. Expired-page POSTs return 409 until a new GET or TTL expiry, without deleting a concurrent refresh. FastAPI offloads the cache-backed native request check to its worker thread pool so synchronous network I/O does not block the event loop. Pool saturation and cache latency still affect request latency. Existing CSV/memory timing behavior and the legacy middleware chain are unchanged.
To exercise independent workers against a dedicated test Redis instance, set
AIWAF_TEST_REDIS_URL and run
python -m pytest tests/integration/test_native_honeypot_cache.py.
Django native honeypot cache
Starting with Python 1.1.7 / aiwaf-rust 0.2.6, Django's native middleware uses the existing Django cache for honeypot GET timestamps by default. Rust calls a small Python storage adapter; form timing, logical expiry, exemptions and block decisions remain native. Other policies retain their configured CSV storage.
AIWAF_CSV_PIPELINE = {
"data_dir": "aiwaf_data",
"honeypot_cache_alias": "default", # optional; uses CACHES["default"]
}Use a shared Django cache backend for cross-worker timing. For example, Django's built-in Redis cache can be configured as follows (install its Redis Python driver and configure the URL for your deployment):
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
