GreedyBear icon indicating copy to clipboard operation
GreedyBear copied to clipboard

Invalid NDJSON response with Gunicorn

Open regulartim opened this issue 1 month ago • 6 comments

I tired to create a NDJSON data dump using a instance running in production mode. The output however was not valid NDJSON:

28F                                                                                                                                                                                     
  {"value": "x.x.x.x", "first_seen": "2026-09-21", "last_seen": "2026-10-19", "attack_count": 49, "credential_count": 0, "interaction_count": 35919, "scanner": true,                
  "payload_request"                                                                                                                                                                       
  : false, "ip_reputation": "", "login_attempts": 0, "recurrence_probability": 0.24703979005065393, "expected_interactions": 738.603571035778, "destination_ports": [5060],               
  "attacker_countr                                                                                                                                                                        
  y": "United States", "attacker_country_code": "US", "days_seen": ["2026-09-21", "2026-10-19"], "firehol_categories": [], "payload_hashes": [], "feed_type": ["sentrypeer"],             
  "destination_p                                                                                                                                                                          
  ort_count": 1, "asn": 204770, "tags": [], "sensors": [{"label": "", "address": "x.x.x.x"}]}                                                                                        
                                                                                                                                                                                          
  322                                                                                                                                                                                     
  {"value": "x.x.x.x", "first_seen": "2026-10-13", "last_seen": "2026-10-19", "attack_count": 1020, "credential_count": 328, "interaction_count": 38457, "scanner": true,          
  "payload_re                                                                                                                                                                             
  quest": false, "ip_reputation": "bad reputation", "login_attempts": 353, "recurrence_probability": 0.6976808545346538, "expected_interactions": 708.3292725123137, "destination_ports": 
  [5                                                                                                                                                                                      
  900, 5901, 5902, 5903, 5904], "attacker_country": "Canada", "attacker_country_code": "CA", "days_seen": ["2026-10-13", "2026-10-18", "2026-10-19"], "firehol_categories": [],           
  "payload_has                                                                                                                                                                            
  hes": [], "feed_type": ["heralding", "honeytrap"], "destination_port_count": 5, "asn": 14061, "tags": [{"key": "behavior", "value": "high_credential_reuse", "source":                  
  "credential_reuse"}                                                                                                                                                                     
  ], "sensors": [{"label": "", "address": "x.x.x.x"}]}  

28F and 322 seem to be hex chunk sizes. I guess this has something to do with Gunicorn running on protocol = "uwsgi" in conjunction with streaming responses. Maybe both together are incompatible.

regulartim avatar Oct 20 '26 13:10 regulartim

Hey @regulartim, I looked into this and I think it’s a known Gunicorn bug: benoitc/gunicorn#3697.

With protocol = "uwsgi", Gunicorn treats the connection as HTTP/1.1 and applies chunked transfer encoding to any response without a Content-Length header (i.e. streaming responses). nginx’s uwsgi_pass doesn’t decode that framing and passes it through as opaque body bytes, so the chunk sizes (28F, 322) end up in the NDJSON output. Regular JSON responses aren’t affected because Django sets Content-Length on them.

I’d suggest switching the production setup to Gunicorn’s http protocol with nginx proxy_pass (plus proxy_buffering off on the streaming endpoint), since nginx decodes chunked upstream responses correctly. Does that work for you, or is there a reason we’re using uwsgi? I’d be happy to take this on.

ABHIGYA0205 avatar Oct 20 '26 18:10 ABHIGYA0205

One clarification to my comment above: this isn’t limited to streaming responses—the underlying condition is any WSGI response that reaches Gunicorn without a Content-Length header. Streaming responses normally lack that header. GreedyBear’s CommonMiddleware adds it to non-streaming responses, which is why ordinary JSON responses generally avoid the problem.

I reproduced the framing mismatch with Gunicorn 26.2.0 and Nginx 1.26.3; in a minimal test, switching both sides to HTTP (protocol = "http" with proxy_pass) returned parseable NDJSON. I’ll prepare a focused config change and validate it against the repository’s pinned nginx:1.31.6-alpine image, preserving the existing forwarding headers, timeouts, and streaming behavior.

ABHIGYA0205 avatar Oct 20 '26 18:10 ABHIGYA0205

Hey @regulartim! I looked into this as well and found two things that might change which fix makes sense.

1. Gunicorn already fixed this upstream. benoitc/gunicorn@7545578 ("Fix response handling for uWSGI upstreams") makes Response.is_chunked() return False when protocol = "uwsgi", so the body is sent as raw bytes and the end of the connection marks where it ends. It is included in Gunicorn 26.2.1 and 26.2.2, which are published as GitHub releases but were never uploaded to PyPI (the latest there is still 26.2.0). That's why we can't simply bump the version right now.

2. We could keep the uWSGI protocol. In #904 you preferred uWSGI over HTTP for performance. Switching to proxy_pass would work, but it would undo that choice and change all the nginx configs. Instead we could:

  • bump to gunicorn>=26.2.1 as soon as it is available on PyPI (only pyproject.toml and uv.lock), and

  • until then, backport that one change in configuration/gunicorn/config.py, with a comment to remove it after the bump:

    from gunicorn.http.wsgi import Response
    
    _is_chunked = Response.is_chunked
    Response.is_chunked = lambda self: self.cfg.protocol != "uwsgi" and _is_chunked(self)
    

Saurabh-1785 avatar Oct 21 '26 04:10 Saurabh-1785

Hey @ABHIGYA0205, @Saurabh-1785, thanks for your thorough check. I was able to reproduce this against the actual app. I ran GreedyBear with the prod gunicorn config (uwsgi protocol, gunicorn 26.2.0) behind nginx 1.31.6 using the repo's locations.conf, and /api/feeds/all/all/likely_to_recur.ndjson came back with a 2A9 chunk size before the first row, same as in the output mentioned in the issue. The regular .json feed is fine because it has a Content-Length, and the NDJSON feed is the only StreamingHttpResponse we have, so that's the only place it shows up. It also doesn't happen with the dev setup since that goes through runserver and proxy_pass.

I then tried the backport @Saurabh-1785 suggested in configuration/gunicorn/config.py and got 202 rows of valid NDJSON in a single request, with and without gzip, and saw nothing in the gunicorn error log. With no Content-Length and no chunking, gunicorn's should_close() already closes the connection, so nginx receives the end of the body from the closed connection, as the uwsgi protocol expects. I also checked that 26.2.1/26.2.2 are still only GitHub releases, and PyPI is at 26.2.0, so for now the backport seems like the smallest fix that keeps uWSGI. Switching to HTTP and proxy_pass would work as well, but it means changing the Nginx configs.

Prasad8830 avatar Oct 22 '26 06:10 Prasad8830

Hey guys, thank you all for investigating! 👍 The NDJSON feature is quite new in GreedyBear and I expect that not may people use it (if any). So I'd just like to wait for Gunicorn releasing the patch on Pypi and bump to fix the issue.

regulartim avatar Oct 22 '26 13:10 regulartim

Gunicorn 27 has been released. It should fix the issue described here.

regulartim avatar Nov 11 '26 13:11 regulartim