NulByteValidationMiddleware rejects requests containing NUL bytes in URL path or query parameters. This prevents PostgreSQL encoding errors (SQLSTATE 22021) and returns a proper 400 Bad Request. Checks for both literal NUL bytes (\x00) and URL-encoded form (%00).
(next http.Handler)
| 23 | // This prevents PostgreSQL encoding errors (SQLSTATE 22021) and returns a proper 400 Bad Request. |
| 24 | // Checks for both literal NUL bytes (\x00) and URL-encoded form (%00). |
| 25 | func NulByteValidationMiddleware(next http.Handler) http.Handler { |
| 26 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 27 | // Check URL path for literal NUL bytes or URL-encoded %00 |
| 28 | // Path needs %00 check because handlers call url.PathUnescape() which would decode it |
| 29 | if containsNulByte(r.URL.Path) { |
| 30 | writeErrorResponse(w, http.StatusBadRequest, "Invalid request: URL path contains null bytes") |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | // Check raw query string for literal NUL bytes or URL-encoded %00 |
| 35 | if containsNulByte(r.URL.RawQuery) { |
| 36 | writeErrorResponse(w, http.StatusBadRequest, "Invalid request: query parameters contain null bytes") |
| 37 | return |
| 38 | } |
| 39 | |
| 40 | next.ServeHTTP(w, r) |
| 41 | }) |
| 42 | } |
| 43 | |
| 44 | // writeErrorResponse writes a JSON error response using huma's ErrorModel format |
| 45 | // for consistency with the rest of the API. |
searching dependent graphs…