Skip to content

fix: don't KeyError when a connection_id is reused before cleanup runs - #8376

Open
citizen204 wants to merge 1 commit into
mitmproxy:mainfrom
citizen204:fix-6405-connection-id-reuse-keyerror
Open

fix: don't KeyError when a connection_id is reused before cleanup runs#8376
citizen204 wants to merge 1 commit into
mitmproxy:mainfrom
citizen204:fix-6405-connection-id-reuse-keyerror

Conversation

@citizen204

Copy link
Copy Markdown

Summary

Proxyserver.register_connection() unconditionally does
del self.connections[connection_id] in its finally block. connection_id
is a client address/port 4-tuple for connections that don't have a uuid
(per ServerManager's own docstring: "temporary workaround"), so it can be
reused before an earlier handler's context manager has unwound — e.g. a
client reconnecting quickly on the same source port. When that happens, the
newer registration overwrites the dict entry, the newer handler's cleanup
deletes it, and the older handler's later cleanup then hits KeyError on
an entry that's already gone:

File ".../mitmproxy/addons/proxyserver.py", line 122, in register_connection
    del self.connections[connection_id]
KeyError: ('tcp', ('127.0.0.1', 51356), ('127.0.0.1', 8080))

Fixes #6405

Changes

  • mitmproxy/addons/proxyserver.py: only delete the dict entry in the
    finally block if it still points at this handler (i.e. hasn't been
    overwritten by a newer registration under the same id).
  • test/mitmproxy/addons/test_proxyserver.py: regression test that
    simulates two overlapping register_connection() calls under the same
    connection_id and asserts neither raises (verified fails on current
    main with the exact reported KeyError, passes with the fix).

🤖 Generated with Claude Code

Proxyserver.register_connection() unconditionally did
`del self.connections[connection_id]` in its finally block. If the same
connection_id (e.g. a client address/port 4-tuple, per the ServerManager
docstring's own note that this is a 'temporary workaround' for connections
without a uuid) gets reused and re-registered before the earlier handler's
context manager has unwound, the newer registration overwrites the dict
entry, and when the newer handler's own cleanup deletes it, the older
handler's later cleanup hits a KeyError on an entry that's already gone.

Fixes mitmproxy#6405

## Changes

- `mitmproxy/addons/proxyserver.py`: only delete the dict entry in the
  finally block if it still points at this handler.
- `test/mitmproxy/addons/test_proxyserver.py`: regression test simulating
  two overlapping registrations under the same connection_id.
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.

KeyError in proxyserver.py when handling TCP connection

1 participant