FlorianREGAZ / Python-Tls-Client

Advanced HTTP Library
MIT License
660 stars 136 forks source link

"session.cookies.clear()" does not work properly #25

Open KohnoseLami opened 1 year ago

KohnoseLami commented 1 year ago

tls_client 0.1.6

Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tls_client
>>> session = tls_client.Session('chrome_108')
>>> session.get('https://httpbin.org/cookies/set/testcookie/12345')
<Response [302]>
>>> session.get('https://httpbin.org/cookies').json()
{'cookies': {'testcookie': '12345'}}
>>> session.cookies.get_dict()
{'testcookie': '12345'}
>>> session.cookies.clear()
>>> session.cookies.get_dict()
{}
>>> session.get('https://httpbin.org/cookies').json()
{'cookies': {'testcookie': '12345'}}
>>>
fnk93 commented 1 year ago

Session cookies are stored in the Golang shared library's session representation automatically. So, without an exported function which allows you to reset the session's cookies, you will currently need to create a new session to get the expected behaviour.

Edit: This is only part of the problem. First of all, the library is writing to self.headers during execute_request. I have created a fork and added a utility function clear_cookies() which basically clears the cookie jar and resets the session ID as well as cleaned up the handling of headers and self.headers which prevents the self.headers to be changed during execution. Another issue was, that the header "Content-Type" would have been set in self.headers when posting, which could have led to issues when doing a GET later on.

Running this code:

client_identifier = "chrome_107"
session = tls_client.Session(
    client_identifier=client_identifier,
    random_tls_extension_order=True,
)
print(session.get('https://httpbin.org/cookies/set/testcookie/12345'))
print(session.get('https://httpbin.org/cookies').json())
print(session.cookies.get_dict())
print(session.get_cookies(url='https://httpbin.org'))
print(session.clear_cookies())
print(session.cookies.get_dict())
print(session.get_cookies(url='https://httpbin.org'))
print(session.get('https://httpbin.org/cookies').json())

produces the following output:

<Response [302]>
{'cookies': {'testcookie': '12345'}}
{'testcookie': '12345'}
{'id': '4ac860c2-9b6d-4a89-8b8c-809a8003d904', 'cookies': [{'Name': 'testcookie', 'Value': '12345', 'Path': '/', 'Domain': '','Expires': '0001-01-01T00:00:00Z', 'RawExpires': '', 'MaxAge': 0, 'Secure': False, 'HttpOnly': False, 'SameSite': 0, 'Raw':'testcookie=12345; Path=/', 'Unparsed': None}]}
None
{}
{'id': '8e42f955-960d-4930-a6f3-4b4232ac4649', 'sessionId': 'a8067d88-3a7f-435e-92a3-899c2062a490', 'status': 0,'target': '', 'body': 'no client found for sessionId: a8067d88-3a7f-435e-92a3-899c2062a490', 'headers': None, 'cookies':None}
{'cookies': {}}