Skip to content

fix: prevent crash when Node rejects Set-Cookie header#4583

Closed
wwhsaber wants to merge 1 commit into
hapijs:masterfrom
wwhsaber:fix/4527-invalid-cookie-crash
Closed

fix: prevent crash when Node rejects Set-Cookie header#4583
wwhsaber wants to merge 1 commit into
hapijs:masterfrom
wwhsaber:fix/4527-invalid-cookie-crash

Conversation

@wwhsaber

Copy link
Copy Markdown

What

Prevent process crashes when a response sets a cookie value that Node rejects (for example non-ASCII characters that pass statehood validation but fail res.setHeader with ERR_INVALID_CHAR).

Why

When writeHead fails because of an invalid Set-Cookie value, exports.send recovers by calling internals.fail() to send a 500. The fail path re-runs the route marshal cycle, which re-applies pending request._states and re-emits the same bad cookie. The second setHeader throws again and is not recovered, so Node crashes.

This was reported in #4527 with values like Cyrillic cookie contents ("тест").

Changes

  • In lib/transmit.js exports.send catch path: clear request._states before recovering with internals.fail(), so the error response does not re-apply rejected cookies.
  • Add a regression test in test/state.js covering a non-ASCII cookie value that Node rejects.

Verification

# Repro (before fix: process crash; after fix: HTTP 500)
node -e '
const Hapi = require("./");
(async () => {
  const server = Hapi.server({ debug: false });
  server.route({
    method: "GET",
    path: "/",
    handler: (request, h) => h.response("ok").state("cookieName2", "тест")
  });
  const res = await server.inject("/");
  console.log(res.statusCode, res.headers["set-cookie"], res.result);
})();
'

# Targeted suites
npx lab -a @hapi/code -m 5000 test/state.js test/transmit.js
# 115 tests complete

Observed after fix:

  • status 500
  • no set-cookie header
  • standard internal server error payload
  • process does not crash

Closes #4527

Clear pending request states before recovering from a failed response
so the error path does not re-apply invalid cookie values that Node
already rejected (ERR_INVALID_CHAR). Previously this looped and crashed
the process.

Closes hapijs#4527
@kanongil kanongil closed this Jul 18, 2026
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.

The application crashes when setting an invalid cookie value

3 participants