Skip to content

stripe api with requests leaks socket file descriptors via unclosed Session #874

Open
@asottile-sentry

Description

@asottile-sentry

Describe the bug

the http request client is assigned to a global variable here:

stripe.default_http_client = http_client.new_default_http_client(
verify_ssl_certs=verify, proxy=proxy
)

requests client is defined here:

class RequestsClient(HTTPClient):

the Session is assigned here:

if getattr(self._thread_local, "session", None) is None:
self._thread_local.session = self._session or requests.Session()

this Session is never closed leading to file descriptor leak and a ResourceWarning -- the correct usage of a Session is to either utilize the with statement or explicitly .close() it

To Reproduce

the simplest reproduction I can come up with is this one liner:

$ python3  -Wonce -c $'import stripe; stripe.api_key="placeholder"; import contextlib\nwith contextlib.suppress(Exception):\n stripe.Account.list()'
sys:1: ResourceWarning: unclosed <ssl.SSLSocket fd=3, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('10.0.2.15', 44434), raddr=('34.200.27.109', 443)>

the ResourceWarning there is coming from the teardown of that Session object I mentioned above -- it's an unclosed connection to the stripe api:

$ nslookup 34.200.27.109
109.27.200.34.in-addr.arpa	name = api-34-200-27-109.stripe.com.

Authoritative answers can be found from:

Expected behavior

utilization of the stripe api should not lead to ResourceWarnings

Code snippets

above

OS

any, though I'm on linux

Language version

any, though I'm using 3.10.4

Library version

4.1.0

API version

N/A

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions