Skip to content

fix: Handle malformed Content-Length in size metrics - #405

Open
Sam-Razavi wants to merge 1 commit into
trallnag:masterfrom
Sam-Razavi:fix/malformed-content-length
Open

Sam-Razavi wants to merge 1 commit into
trallnag:masterfrom
Sam-Razavi:fix/malformed-content-length

Conversation

@Sam-Razavi

Copy link
Copy Markdown

What does this do?

Adds a small _parse_content_length helper and uses it wherever the size metrics convert a Content-Length header. A value that isn't a valid integer is now observed as 0, the same as a missing header. This covers request_size, response_size, combined_size and default, on both the request and response side.

Why do we need it?

int() raises ValueError on a malformed value. The exception escapes the instrumentation callback and the size isn't recorded.

The impact is narrower than #404 describes. I tested Content-Length: abc against Uvicorn (h11 and httptools), Hypercorn, Daphne and Granian, and all of them return 400 before the app sees the request. Calling the app directly at the ASGI level, the client still gets its normal 200, and the ValueError propagates to the server afterwards. So I'd treat this as hardening for servers or adapters that pass the header through, rather than a way for clients to force a 500.

Linked issues

Fixes #404

Reviewer notes

  • Tests cover each instrumentation on both sides. They fail without the fix.
  • A negative value such as Content-Length: -5 doesn't raise, so I left it out of scope, though it would be observed as a negative size. Happy to handle it here if you'd prefer.
  • I ran the suite on Windows. 12 tests in test_instrumentation.py fail with or without this change because process_cpu_seconds_total isn't available there.

int() raises ValueError on a Content-Length value that is not a valid
integer. The exception escaped the instrumentation callback and the size
was not recorded. Observe 0 instead, the same as a missing header.

Fixes trallnag#404
@Sam-Razavi

Copy link
Copy Markdown
Author

Hi @trallnag, a gentle ping on this one when you have time. It's a small fix for #404: a malformed Content-Length header is now observed as 0 instead of raising ValueError in the size metrics. CI is green and it merges cleanly. Happy to change anything, including handling negative values here too.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

int(Content-Length) raises uncaught ValueError on malformed header → 500s instrumented apps

1 participant