Skip to content

Commit 5985be5

Browse files
Copilotmykaul
authored andcommitted
Only cache TLS sessions after successful connection
Previously, TLS sessions were stored immediately after wrap_socket() completed, but before the actual TCP connection was established. This meant we could cache sessions for connections that subsequently failed. Now sessions are only stored after the connection is fully established and validated, ensuring we only cache sessions for successful connections. The session storage logic has been moved from _wrap_socket_from_context() to _connect_socket(), after _initiate_connection() and _validate_hostname() have succeeded. Co-authored-by: mykaul <4655593+mykaul@users.noreply.github.com>
1 parent 7a680b6 commit 5985be5

1 file changed

Lines changed: 15 additions & 9 deletions

File tree

cassandra/connection.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,15 +1046,8 @@ def _wrap_socket_from_context(self):
10461046

10471047
ssl_socket = self.ssl_context.wrap_socket(self._socket, **opts)
10481048

1049-
# Store the session for future reuse
1050-
if self.tls_session_cache and ssl_socket.session:
1051-
self.tls_session_cache.set_session(
1052-
self.endpoint.address, self.endpoint.port, ssl_socket.session)
1053-
# Track if the session was reused
1054-
self.session_reused = ssl_socket.session_reused
1055-
if self.session_reused:
1056-
log.debug("TLS session was reused for %s:%s",
1057-
self.endpoint.address, self.endpoint.port)
1049+
# Note: Session is NOT stored here - it will be stored after successful connection
1050+
# in _connect_socket() to ensure we only cache sessions for successful connections
10581051

10591052
return ssl_socket
10601053

@@ -1111,6 +1104,19 @@ def _connect_socket(self):
11111104
# run that here.
11121105
if self._check_hostname:
11131106
self._validate_hostname()
1107+
1108+
# Store the TLS session after successful connection
1109+
# This ensures we only cache sessions for connections that actually succeeded
1110+
if self.tls_session_cache and self.ssl_context and hasattr(self._socket, 'session'):
1111+
if self._socket.session:
1112+
self.tls_session_cache.set_session(
1113+
self.endpoint.address, self.endpoint.port, self._socket.session)
1114+
# Track if the session was reused
1115+
self.session_reused = self._socket.session_reused
1116+
if self.session_reused:
1117+
log.debug("TLS session was reused for %s:%s",
1118+
self.endpoint.address, self.endpoint.port)
1119+
11141120
sockerr = None
11151121
break
11161122
except socket.error as err:

0 commit comments

Comments
 (0)