Check `connected_` at the beginning of `TlsHandshaker::SetReadSecret`. If not connected, early return.

Protected by FLAGS_quic_reloadable_flag_quic_check_connected_before_set_read_secret.

PiperOrigin-RevId: 551287977
diff --git a/quiche/quic/core/quic_flags_list.h b/quiche/quic/core/quic_flags_list.h
index f8c0828..e62564d 100644
--- a/quiche/quic/core/quic_flags_list.h
+++ b/quiche/quic/core/quic_flags_list.h
@@ -37,6 +37,8 @@
 QUIC_FLAG(quic_reloadable_flag_quic_allow_client_enabled_bbr_v2, true)
 // If true, an endpoint does not detect path degrading or blackholing until handshake gets confirmed.
 QUIC_FLAG(quic_reloadable_flag_quic_no_path_degrading_before_handshake_confirmed, true)
+// If true, check connected at the beginning of TlsHandshaker::SetReadSecret.
+QUIC_FLAG(quic_reloadable_flag_quic_check_connected_before_set_read_secret, false)
 // If true, clear QuicSpdyStreamBodyManager in QuicSpdyStream::CloseReadSide().
 QUIC_FLAG(quic_reloadable_flag_quic_clear_body_manager, true)
 // If true, consider write blocked when destination CID is required but missing on the default path.
diff --git a/quiche/quic/core/tls_handshaker.cc b/quiche/quic/core/tls_handshaker.cc
index fa92057..7415441 100644
--- a/quiche/quic/core/tls_handshaker.cc
+++ b/quiche/quic/core/tls_handshaker.cc
@@ -288,7 +288,17 @@
 bool TlsHandshaker::SetReadSecret(EncryptionLevel level,
                                   const SSL_CIPHER* cipher,
                                   absl::Span<const uint8_t> read_secret) {
-  QUIC_DVLOG(1) << ENDPOINT << "SetReadSecret level=" << level;
+  QUIC_DVLOG(1) << ENDPOINT << "SetReadSecret level=" << level
+                << ", connection_closed=" << is_connection_closed();
+  if (check_connected_before_set_read_secret_) {
+    if (is_connection_closed()) {
+      QUIC_RELOADABLE_FLAG_COUNT_N(quic_check_connected_before_set_read_secret,
+                                   1, 2);
+      return false;
+    }
+    QUIC_RELOADABLE_FLAG_COUNT_N(quic_check_connected_before_set_read_secret, 2,
+                                 2);
+  }
   std::unique_ptr<QuicDecrypter> decrypter =
       QuicDecrypter::CreateFromCipherSuite(SSL_CIPHER_get_id(cipher));
   const EVP_MD* prf = Prf(cipher);
diff --git a/quiche/quic/core/tls_handshaker.h b/quiche/quic/core/tls_handshaker.h
index 8c1651c..0c7aa5d 100644
--- a/quiche/quic/core/tls_handshaker.h
+++ b/quiche/quic/core/tls_handshaker.h
@@ -205,6 +205,8 @@
 
   int expected_ssl_error_ = SSL_ERROR_WANT_READ;
   bool is_connection_closed_ = false;
+  const bool check_connected_before_set_read_secret_ =
+      GetQuicReloadableFlag(quic_check_connected_before_set_read_secret);
 
   QuicCryptoStream* stream_;
   HandshakerDelegateInterface* handshaker_delegate_;