Skip to content

Retry without keep-alive after a premature close error - #10697

Merged
joehan merged 1 commit into
firebase:mainfrom
fabienvauchelles:fix/apiv2-premature-close-keepalive
Jun 24, 2026
Merged

joehan merged 1 commit into
firebase:mainfrom
fabienvauchelles:fix/apiv2-premature-close-keepalive

Conversation

@fabienvauchelles

@fabienvauchelles fabienvauchelles commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

firebase login and other authenticated API calls can fail while exchanging the OAuth code:

Token Fetch Error: FetchError: Invalid response body while trying to fetch https://accounts.google.com/o/oauth2/token: Premature close
Authentication Error: Your credentials are no longer valid. Please run firebase login --reauth
Error: Unable to authenticate using the provided code. Please try again.

Root cause

apiv2 sends Connection: keep-alive and uses Node's global HTTP agent, which defaults to keepAlive: true since Node 19. On some networks, and especially on recent Node.js releases that changed keep-alive socket reuse timing (nodejs/node#63989), node-fetch throws a Premature close error while reading the response body even though the response is complete. This is a known node-fetch bug in its chunked-response handling when an HTTP agent is involved (node-fetch/node-fetch#1767).

I narrowed it down with a few probes against https://accounts.google.com/o/oauth2/token:

  • a plain https POST and a global fetch (undici) POST both return the response (HTTP 401 for a dummy body)
  • node-fetch with the default keep-alive agent fails with Premature close every time
  • node-fetch with new https.Agent({ keepAlive: false }) works every time

So the cause is not the user's clock, account, Node major version, TLS interception, or a proxy.

Fix

If a request fails with a premature close (or ECONNRESET) error, apiv2 retries it once with keep-alive turned off (Connection: close and a non-keep-alive agent). Only requests whose body can be sent again are retried: multipart FormData bodies, such as the OAuth token request, are serialized to a Buffer up front so the retry can replay them, and raw streams are left untouched. The normal path keeps using keep-alive, so flows like deploy are unaffected, and the fallback only runs on that error and only when no proxy is configured.

Fixes #10692. Also reported in #10681.

Scenarios Tested

  • New unit tests in src/apiv2.spec.ts:
    • a request that fails once with a Premature close error is retried without keep-alive and succeeds
    • a request that keeps closing prematurely is retried once and then rejects (no infinite retry)
    • a multipart body is resent in full on the retry (the OAuth login case)
  • npm run test:compile, npm run lint:ts, prettier --check, and mocha src/apiv2.spec.ts (40 passing) pass locally
  • Verified on Windows 10 / Node v24.17.0 / firebase-tools 15.22.1: firebase login and firebase projects:list failed consistently with Premature close before this change and work after it

Sample Commands

No command or flag changes. The fix lives in the HTTP client and applies to every apiv2 request, for example:

firebase login
firebase projects:list

@google-cla

google-cla Bot commented Jun 22, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses intermittent 'Premature close' errors during API requests by retrying the request once without keep-alive. It introduces helper functions to detect premature close errors and dynamically downgrade the connection to use non-keep-alive agents. Unit tests have been added to verify this retry behavior. The review feedback suggests improving type safety by explicitly declaring the return type of 'noKeepAliveAgent' as 'http.Agent | https.Agent', and avoiding potential side effects by not mutating the shared 'options.headers' directly during a retry.

Comment thread src/apiv2.ts Outdated
// https://github.com/node-fetch/node-fetch/issues/1767.
const httpAgentNoKeepAlive = new http.Agent({ keepAlive: false });
const httpsAgentNoKeepAlive = new https.Agent({ keepAlive: false });
function noKeepAliveAgent(parsedURL: URL): http.Agent {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The return type of noKeepAliveAgent is declared as http.Agent, but it can return an https.Agent when the protocol is HTTPS. While https.Agent is structurally compatible with http.Agent in Node.js, explicitly declaring the union type http.Agent | https.Agent is more precise and type-safe.

Suggested change
function noKeepAliveAgent(parsedURL: URL): http.Agent {
function noKeepAliveAgent(parsedURL: URL): http.Agent | https.Agent {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, done in 9cbad7a. The return type is now http.Agent | https.Agent.

Comment thread src/apiv2.ts Outdated
if (!disabledKeepAlive && !proxyURIFromEnv() && isPrematureCloseError(err)) {
disabledKeepAlive = true;
fetchOptions.agent = noKeepAliveAgent;
options.headers?.set("Connection", "close");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Mutating the input options.headers directly can lead to unexpected side effects if the options object or its headers are reused or shared across other requests. Instead, consider creating a new Headers instance and assigning it to fetchOptions.headers to keep the retry logic pure and free of side effects.

            const headers = new Headers(fetchOptions.headers);
            headers.set("Connection", "close");
            fetchOptions.headers = headers;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9cbad7a. The retry now copies the headers into a fresh Headers instance and sets Connection: close on the copy, so the shared options.headers is no longer mutated.

@fabienvauchelles
fabienvauchelles force-pushed the fix/apiv2-premature-close-keepalive branch from 3fe5200 to caa0c23 Compare June 22, 2026 20:26
@fabienvauchelles

Copy link
Copy Markdown
Contributor Author

@googlebot I signed it!

@fabienvauchelles
fabienvauchelles force-pushed the fix/apiv2-premature-close-keepalive branch 2 times, most recently from 12a22db to 9cbad7a Compare June 22, 2026 21:01
@rockwotj

Copy link
Copy Markdown
Contributor

cc: @joehan would be great to fix this

@joehan

joehan commented Jun 24, 2026

Copy link
Copy Markdown
Member

Hey! This does seem like a relatively safe change that would address the issue on 24.17. However, Node 24.18 has already released (and it addressed the root cause of this bug), and I'm planning to migrate off of node-fetch entirely in the medium term.

If anyone is still seeing this on node 24.18, please let me know here and we'll consider getting this fix in as a bandaid. Otherwise, I'm gonna push forward with getting node-fetch out of our direct deps entirely.

Either way - thanks for contributing this!

Some networks close keep-alive sockets in a way that makes node-fetch
throw "Invalid response body ...: Premature close" while reading the
response body, even when the response is complete. This breaks
`firebase login` (the OAuth token exchange) and other API calls,
especially on recent Node.js releases.

Retry the request once with keep-alive turned off (Connection: close)
when this happens. Only requests with a replayable body are retried:
multipart FormData bodies (such as the token request) are serialized to
a Buffer up front so they can be sent again, and raw streams are left
untouched. The normal path still uses keep-alive.

Fixes firebase#10692
@fabienvauchelles
fabienvauchelles force-pushed the fix/apiv2-premature-close-keepalive branch from 9cbad7a to d24ce7c Compare June 24, 2026 17:17
@fabienvauchelles

Copy link
Copy Markdown
Contributor Author

Thanks for the look @joehan, and for the 24.18 context.

I'm still hitting this on Node 26.x, so newer Node releases don't avoid it on my setup. It does seem to depend on the network (it reproduces consistently on some and not at all on others, which fits a keep-alive socket-timing issue), so it likely isn't tied to a single Node version. Since it still affects users on current Node, this retry looks like a cheap, low-risk bandaid until node-fetch is gone, but I'm happy to defer to your plan.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 3 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@85fd359). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/apiv2.ts 90.90% 0 Missing and 3 partials ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10697   +/-   ##
=======================================
  Coverage        ?   57.84%           
=======================================
  Files           ?      609           
  Lines           ?    39205           
  Branches        ?     7863           
=======================================
  Hits            ?    22677           
  Misses          ?    14705           
  Partials        ?     1823           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@joehan

joehan commented Jun 24, 2026

Copy link
Copy Markdown
Member

Oddly enough, the latest 26.x release is older than 24.18 (https://github.com/nodejs/node/releases). Unsure if they will release a patch for this on 26.x soon.

@joehan
joehan merged commit 72dccb3 into firebase:main Jun 24, 2026
70 of 76 checks passed
@joehan

joehan commented Jun 24, 2026

Copy link
Copy Markdown
Member

Turns out moving off of node-fetch is a bit of a messy endeavor (because nock does not work with native fetch()). Instead of rushing out a fix for that, merging this in for todays release to mitigate the issue

bkendall pushed a commit that referenced this pull request Jul 9, 2026
Some networks close keep-alive sockets in a way that makes node-fetch
throw "Invalid response body ...: Premature close" while reading the
response body, even when the response is complete. This breaks
`firebase login` (the OAuth token exchange) and other API calls,
especially on recent Node.js releases.

Retry the request once with keep-alive turned off (Connection: close)
when this happens. Only requests with a replayable body are retried:
multipart FormData bodies (such as the token request) are serialized to
a Buffer up front so they can be sent again, and raw streams are left
untouched. The normal path still uses keep-alive.

Fixes #10692
bkendall pushed a commit that referenced this pull request Jul 9, 2026
Some networks close keep-alive sockets in a way that makes node-fetch
throw "Invalid response body ...: Premature close" while reading the
response body, even when the response is complete. This breaks
`firebase login` (the OAuth token exchange) and other API calls,
especially on recent Node.js releases.

Retry the request once with keep-alive turned off (Connection: close)
when this happens. Only requests with a replayable body are retried:
multipart FormData bodies (such as the token request) are serialized to
a Buffer up front so they can be sent again, and raw streams are left
untouched. The normal path still uses keep-alive.

Fixes #10692
yuichi0301 pushed a commit to yuichi0301/firebase-tools that referenced this pull request Aug 16, 2026
Some networks close keep-alive sockets in a way that makes node-fetch
throw "Invalid response body ...: Premature close" while reading the
response body, even when the response is complete. This breaks
`firebase login` (the OAuth token exchange) and other API calls,
especially on recent Node.js releases.

Retry the request once with keep-alive turned off (Connection: close)
when this happens. Only requests with a replayable body are retried:
multipart FormData bodies (such as the token request) are serialized to
a Buffer up front so they can be sent again, and raw streams are left
untouched. The normal path still uses keep-alive.

Fixes firebase#10692
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.

firebase login --no-localhost fails with "Premature close" on macOS Tahoe (fresh install, multiple Node versions tested)

4 participants