Intercept an upstream JSON response and analyze it
November 06, 2023 10:30AM
I'm trying to intercept analyze and make a decision based on a JSON key/value pair from an upstream response.
The scenario is the following:
downstream: CLIENT->NGINX->PROXY_PASS->endpoint
upstream: endpoint (JSON frame)->NGINX->JSON analysis->CLIENT RESPONSE CODE 200/403

I'm trying to achieve this trying to look for a key/pair value in the upstream body.

I tried with LUA and js modules and partially achieved it.

With LUA I can find the key/pair I look for and avoid it to be sent back to the client, even if i can't send back the 403 HTTP response code:

listen; #Virtual server where to listen for incoming requests

location /endpoint #Test endpoint to redirect to actual server
proxy_pass; #Where to proxy (redirect) incoming request
proxy_set_header Accept-Encoding "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass_request_body on;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Original-Method $request_method;
proxy_store off;
proxy_buffering off;
body_filter_by_lua_block #Actual response check in upstream body response
local chunk = ngx.arg[1]
if string.match(chunk, "critical") then #Critical string found
ngx.log(ngx.STDERR, chunk) #Log denied request
return 403 #Return error code to client and flush response

I can log the requested json frame, so the lua block is working.
I think that the problem is that the Headers coming from the upstream have been already sent to the client before the body analysys kicks in.
Is it possibile to avoid this?
How is it possible to filter body content and send back a legitimate 403 (in example) response back to the client?

Thank you!
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 329
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready