Skip to content

gh-163110: Don't read the body of a redirect response in urllib.request - #163111

Open
Dashtid wants to merge 1 commit into
python:mainfrom
Dashtid:urllib-redirect-unread
Open

Dashtid wants to merge 1 commit into
python:mainfrom
Dashtid:urllib-redirect-unread

Conversation

@Dashtid

@Dashtid Dashtid commented Dec 3, 2026 •

Copy link
Copy Markdown

I used Claude to help write the fix and its test, and I reviewed both.

@Dashtid
Dashtid requested a review from orsenthil as a code owner December 3, 2026 20:54
@python-cla-bot

python-cla-bot Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@efanntyo

efanntyo commented Dec 4, 2026

Copy link
Copy Markdown

One additional regression boundary is cleanup/error propagation when opening the redirect target fails. A body stub whose read() raises (rather than just setting a flag), plus a parent opener that asserts fp.closed and raises a sentinel OSError, checks both ordering and error identity.

On the installed CPython 3.12.16/Linux handler, that fixture calls read(), raises the body EOFError, leaves closed=False and never reaches the target opener. Running the exact http_error_302 method extracted from head 8ea4a5f with host urllib globals instead gives: read_called=False, closed=True, target opener called, and the identical downstream OSError propagated. No network or full main/PR module was used.

The new test already covers successful opening across redirect codes. Extending it with a raising target opener would also pin down closing the discarded response before delegation, without swallowing the target failure. AI-assisted source probe; this is method-level evidence on a 3.12 host, not a full PR-build or suite-passing claim.

Comment thread Lib/urllib/request.py

# Don't close the fp until we are sure that we won't use it
# with HTTPError.
fp.read()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we know why we are reading it? What was the reason to read it in the first place?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Not that I could find. It was already in urllib2's first commit in 2000, and no commit message since explains it; the comment above it was added in 2001 and is about when fp gets closed. The old urllib had the same read from 1995 with no stated reason either (gh-54786), and it was removed there for bpo-8035. Reading the rest of a response is normally done so the connection can be reused, but do_open() sends Connection: close and closes the socket.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants