Skip to content

open_url re-raises non-401/403 HTTP errors without closing the response body #5516

Done

Description

@soarkit

open_url re-raises non-401/403 HTTP errors without closing the response body

Summary

open_url walks the configured auth entries and closes the failed HTTPError only for 401 and 403, so a later entry or the unauthenticated fallback can be tried. Every other HTTP status is re-raised while the response body is still open, and the caller receives an exception holding a live file descriptor that is never closed.

Expected behavior

When open_url gives up on a request, the failed response should be closed before the error propagates (or the caller should get an error that does not retain an open body). Repeating the call — for example a retry loop over a host that answers 5xx — should not accumulate open sockets.

Actual behavior

A 500 response leaves the exception's fp open:

HTTPError code: 500
fp is None: False
fp closed: False
LEAK: HTTPError raised with an open response body

The same probe was run against the current default branch (a4d5712) and produces identical output, so the defect is still present upstream:

HTTPError code: 500
fp is None: False
fp closed: False
LEAK: HTTPError raised with an open response body

Reproduction

git clone https://github.com/github/spec-kit.git
cd spec-kit
git checkout 1c799bda

cat > /tmp/auth_repro.py <<'PY'
import os, threading, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer

os.environ["GITHUB_TOKEN"] = "dummy-token"

from specify_cli.authentication import http as h
from specify_cli.authentication.config import AuthConfigEntry


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(500)
        self.send_header("Content-Length", "2")
        self.end_headers()
        self.wfile.write(b"no")

    def log_message(self, *args):
        pass


server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()

h._config_override = [AuthConfigEntry(provider="github", hosts=["127.0.0.1"], auth={})]
try:
    h.open_url(f"http://127.0.0.1:{port}/x")
except urllib.error.HTTPError as exc:
    fp = getattr(exc, "fp", None)
    print("HTTPError code:", exc.code)
    print("fp is None:", fp is None)
    print("fp closed:", None if fp is None else fp.closed)
    if fp is not None and not fp.closed:
        print("LEAK: HTTPError raised with an open response body")
PY

docker run --rm -v "$PWD":/w -v /tmp/auth_repro.py:/r.py -w /w python:3.12-slim \
  bash -lc 'pip install -q -e /w >/dev/null 2>&1; python /r.py'

Observed output:

HTTPError code: 500
fp is None: False
fp closed: False
LEAK: HTTPError raised with an open response body

Root cause

In src/specify_cli/authentication/http.py, the per-entry loop handles the error like this:

except urllib.error.HTTPError as exc:
    if exc.code in (401, 403):
        exc.close()
        continue  # try next entry
    raise

Only the “try the next credential” path releases the response. Any other status (5xx, 404, 429, …) is raised with exc.fp still attached, so the socket stays open until the exception object is collected. The same happens in the unauthenticated fallback at the end of the function, where opener.open(req, timeout=timeout) propagates the HTTPError directly.

Suggested fix

Close the response before propagating:

except urllib.error.HTTPError as exc:
    if exc.code in (401, 403):
        exc.close()
        continue
    exc.close()
    raise

(or except urllib.error.HTTPError as exc: exc.close(); raise), and add a regression test that serves a 500 from a local HTTP server and asserts the raised HTTPError has no open body.

Activity

  1. added
    triage-must-have
    on Nov 22, 2026
  2. media-ctrl commented on Nov 23, 2026

    @media-ctrl

    Confirmed at HEAD (a4d5712), and the leak has a second site the report doesn't name. The per-entry loop at line 265 closes 401/403 and re-raises everything else, but the unauthenticated fallback at the end of open_url returns opener.open(...) directly, so a 500 on that last attempt propagates with the same open body. A fix in the loop alone still leaks whenever no auth entry matched.

    Measured on CPython 3.14 with a local 500 server: the raised HTTPError has fp open, exc.read() returns the body without closing it, and exc.close() is what closes it. After close, exc.read() returns b"".

    That ordering matters. Closing before re-raising is the obvious one-liner, but it destroys the body callers log, and a 500 body is often the only diagnostic a user gets. Read first, then close, then let the exception carry the bytes: set exc.body = exc.read(65536) before exc.close(). Capping the read keeps a large error page from buffering on a retry loop.

    The 401/403 discard is fine, since that attempt is abandoned. Worth a comment saying so, or the asymmetry reads like an oversight.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage-must-have

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions