WebSocket Protection
Source and package versions
One AIWAF repository.
Python: py/aiwaf/ · Node.js: js/ · Rust/WASM: rust/ · Java: java/.
Source and canonical README.
Versions shown are the latest published releases; each package is versioned independently.
Current versions are aiwaf 1.3.6 (Python) and
aiwaf 1.3.6 (npm), with Rust/Python 0.2.20 and
WASM 0.2.16 and Java 1.4.0. Sandbox guides retain their separately pinned builds.
HTTP checks never see what a WebSocket carries after its handshake. AIWAF's WebSocket guards close that gap in three ways, in Python, Node.js and Java:
- Messages are checked like request bodies: SQL injection, remote code execution and their disguises, and JSON messages by their values.
- Handshakes are checked before your app hears of the connection: the Origin, your own authorization, and how many connections one client address holds open.
- Message rate: each connection may send only so many messages in a window.
Every check except the message check is off until you set it. Log events carry the rule and path, never the message.
Message checks
A message with a finding closes the socket with 1008 (policy violation) and never reaches your handlers. A message larger than AIWAF_PAYLOAD_MAX_BYTES (Java requestBodyInspectionBytes) closes it with 1009. A message sent in parts is checked whole: the parts are put together, up to that size, before any reach your handler.
The guards follow AIWAF_SQL_INJECTION_MODE: block closes the socket, monitor logs the rule and passes the message, and off checks nothing. When it's unset, Python and Node.js follow AIWAF_PROFILE, so AIWAF_PROFILE=monitor logs without closing sockets. Java uses config.applyProfile(...).
Handshake checks
| Check | Setting | Rule |
|---|---|---|
| Origin | AIWAF_WEBSOCKET_ALLOWED_ORIGINS: comma-separated, exact (https://app.example.com), any subdomain (https://*.example.com) or * | websocket_origin |
| Your 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. - An
authorizehook that throws lets no one in. - In monitor mode a refusal is logged and the connection allowed.
Message rate
AIWAF_WEBSOCKET_MAX_MESSAGES limits how many messages one connection may send in any AIWAF_WEBSOCKET_MESSAGE_WINDOW_SECONDS (default 10), over a sliding window. A client past it is closed with 1008 (rule websocket_message_rate); in monitor mode it's logged and the message passes. A message sent in parts counts once. The limit is its own setting, so AIWAF_SQL_INJECTION_MODE=off doesn't turn it off.
The count is per connection. Set it together with AIWAF_WEBSOCKET_MAX_CONNECTIONS_PER_IP to bound what one address can send.
Python
FastAPI, Starlette and Django Channels
WebSocketGuard is ASGI middleware, from aiwaf.core.websocket (also aiwaf.fast.WebSocketGuard). HTTP requests pass through it untouched.
from aiwaf.core.websocket import WebSocketGuard
async def check(scope):
return await session_is_valid(scope) # sync or async
app.add_middleware(
WebSocketGuard,
allowed_origins=["https://app.example.com"],
max_connections_per_ip=5,
authorize=check,
max_messages=30,
message_window=10,
)
For Django Channels, wrap the ASGI application: application = WebSocketGuard(ProtocolTypeRouter({...})). A refused handshake is closed on websocket.connect, before your consumer runs.
Flask-SocketIO
from aiwaf.flask.websocket import guard_socketio
guard_socketio(
socketio,
allowed_origins=["https://app.example.com"],
max_connections_per_ip=5,
authorize=lambda request: request.cookies.get("session") is not None,
max_messages=30,
)
guard_socketio checks every event. authorize gets the handshake's Flask request, and a refused client is turned away before your connect handler runs. To check one handler only, put @aiwaf_message() under @socketio.on(...). inspect_message(data) checks one message anywhere else.
Node.js
const aiwaf = require('aiwaf');
const options = {
allowedOrigins: ['https://app.example.com'],
maxConnectionsPerIp: 5,
authorize: async req => isValidSession(req),
maxMessages: 30,
messageWindowSeconds: 10,
};
await aiwaf.guardWebSocketServer(wss, options); // ws
await aiwaf.guardSocketIo(io, options); // Socket.IO
- ws: a refused handshake gets
403inverifyClient; your ownverifyClientstill runs after AIWAF's. - Socket.IO: refused in Engine.IO's
allowRequest, before any namespace; your ownallowRequeststill runs. - A client over the connection limit since its handshake was checked is closed with
1008once connected.
aiwaf.inspectMessage(data) checks one message anywhere else.
Java
Java config: websocketAllowedOrigins, websocketMaxConnectionsPerIp, websocketMaxMessages and websocketMessageWindowSeconds. Spring reads aiwaf.websocket.allowed-origins, aiwaf.websocket.max-connections-per-ip, aiwaf.websocket.max-messages and aiwaf.websocket.message-window-seconds; structured config reads the same names under security (websocket_allowed_origins and so on). The handshake checks and message rate arrived in Java 1.4.0.
Spring WebSocket
AiwafWebSocketHandler guarded =
new AiwafWebSocketHandler(chatHandler, config, session -> isValid(session));
registry.addHandler(guarded, "/ws")
.addInterceptors(guarded.handshakeInterceptor(request -> isValid(request)));
The wrapper asks Spring for whole messages. On its own it closes a refused session with 1008 after the upgrade, before your handler's afterConnectionEstablished. Its handshakeInterceptor(...) refuses with HTTP 403 before the upgrade instead: an Origin not allowed, a request the hook turns away, and an address already at the connection limit. The two share one connection count.
Jakarta WebSocket
ServerEndpointConfig.Builder.create(AiwafEndpoint.class, "/chat")
.configurator(new AiwafEndpoint.Handshake(new ChatEndpoint(), config, request -> isValid(request)))
.build();
An Origin not allowed is refused with 403 during the handshake; authorization and the connection limit close with 1008 before your endpoint's onOpen. 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. To check messages only, return new AiwafEndpoint(endpoint, config) from your own configurator.
In an annotated @ServerEndpoint, take whole messages, call AiwafMessageCore.check(message, config, path) in @OnMessage, and close with AiwafMessageCore.closeCode(rule) when it returns a rule.
What the guards don't do
- They don't authenticate users themselves:
authorizeis where your session or token check goes. - Messages your server sends to clients aren't checked.
- Counts are per process. With several workers or servers behind a load balancer, each keeps its own connection and message counts; set limits at the proxy too if you need a shared bound.
The guards are tested against real servers: Starlette, Flask-SocketIO's test server, ws and Socket.IO with their clients, and Tomcat with Spring and Jakarta endpoints and the JDK client.
