Make sure we have the right key before sending data.

Protected by FLAGS_quic_reloadable_flag_quic_check_keys_before_writing.

PiperOrigin-RevId: 333559010
Change-Id: I4ac0ed51c5401ef8b872c06c32148fa554eead54
diff --git a/quic/core/quic_session.cc b/quic/core/quic_session.cc
index e3c389b..cec2337 100644
--- a/quic/core/quic_session.cc
+++ b/quic/core/quic_session.cc
@@ -774,6 +774,17 @@
                                    QuicStreamOffset offset,
                                    TransmissionType type) {
   DCHECK(QuicVersionUsesCryptoFrames(transport_version()));
+  if (connection()->check_keys_before_writing() &&
+      !connection()->framer().HasEncrypterOfEncryptionLevel(level)) {
+    const std::string error_details = quiche::QuicheStrCat(
+        "Try to send crypto data with missing keys of encryption level: ",
+        EncryptionLevelToString(level));
+    QUIC_BUG << ENDPOINT << error_details;
+    connection()->CloseConnection(
+        QUIC_MISSING_WRITE_KEYS, error_details,
+        ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
+    return 0;
+  }
   SetTransmissionType(type);
   const auto current_level = connection()->encryption_level();
   connection_->SetDefaultEncryptionLevel(level);