Refactoring OHTTP common code. This will be needed for chunk implementation.

PiperOrigin-RevId: 794258371
diff --git a/quiche/oblivious_http/buffers/oblivious_http_request.cc b/quiche/oblivious_http/buffers/oblivious_http_request.cc
index 6a8536b..246141c 100644
--- a/quiche/oblivious_http/buffers/oblivious_http_request.cc
+++ b/quiche/oblivious_http/buffers/oblivious_http_request.cc
@@ -17,6 +17,8 @@
 #include "quiche/common/platform/api/quiche_bug_tracker.h"
 #include "quiche/common/platform/api/quiche_logging.h"
 #include "quiche/common/quiche_crypto_logging.h"
+#include "quiche/common/quiche_data_reader.h"
+#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
 
 namespace quiche {
 // Ctor.
@@ -42,39 +44,12 @@
     absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key,
     const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
     absl::string_view request_label) {
-  if (EVP_HPKE_KEY_kem(&gateway_key) == nullptr) {
-    return absl::InvalidArgumentError(
-        "Invalid input param. Failed to import gateway_key.");
-  }
-  bssl::UniquePtr<EVP_HPKE_CTX> gateway_ctx(EVP_HPKE_CTX_new());
-  if (gateway_ctx == nullptr) {
-    return SslErrorAsStatus("Failed to initialize Gateway/Server's Context.");
-  }
-
   QuicheDataReader reader(encrypted_data);
-
-  auto is_hdr_ok = ohttp_key_config.ParseOhttpPayloadHeader(reader);
-  if (!is_hdr_ok.ok()) {
-    return is_hdr_ok;
-  }
-
-  size_t enc_key_len = EVP_HPKE_KEM_enc_len(EVP_HPKE_KEY_kem(&gateway_key));
-
-  absl::string_view enc_key_received;
-  if (!reader.ReadStringPiece(&enc_key_received, enc_key_len)) {
-    return absl::FailedPreconditionError(absl::StrCat(
-        "Failed to extract encapsulation key of expected len=", enc_key_len,
-        "from payload."));
-  }
-  std::string info =
-      ohttp_key_config.SerializeRecipientContextInfo(request_label);
-  if (!EVP_HPKE_CTX_setup_recipient(
-          gateway_ctx.get(), &gateway_key, ohttp_key_config.GetHpkeKdf(),
-          ohttp_key_config.GetHpkeAead(),
-          reinterpret_cast<const uint8_t*>(enc_key_received.data()),
-          enc_key_received.size(),
-          reinterpret_cast<const uint8_t*>(info.data()), info.size())) {
-    return SslErrorAsStatus("Failed to setup recipient context");
+  absl::StatusOr<ObliviousHttpRequest::Context> gateway_context =
+      ObliviousHttpRequest::DecodeEncapsulatedRequestHeader(
+          reader, gateway_key, ohttp_key_config, request_label);
+  if (!gateway_context.ok()) {
+    return gateway_context.status();
   }
 
   absl::string_view ciphertext_received = reader.ReadRemainingPayload();
@@ -82,8 +57,9 @@
   std::string decrypted(ciphertext_received.size(), '\0');
   size_t decrypted_len;
   if (!EVP_HPKE_CTX_open(
-          gateway_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()),
-          &decrypted_len, decrypted.size(),
+          gateway_context->hpke_context_.get(),
+          reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len,
+          decrypted.size(),
           reinterpret_cast<const uint8_t*>(ciphertext_received.data()),
           ciphertext_received.size(), nullptr, 0)) {
     return SslErrorAsStatus("Failed to decrypt.",
@@ -91,7 +67,8 @@
   }
   decrypted.resize(decrypted_len);
   return ObliviousHttpRequest(
-      std::move(gateway_ctx), std::string(enc_key_received), ohttp_key_config,
+      std::move(gateway_context->hpke_context_),
+      std::string(gateway_context->encapsulated_key_), ohttp_key_config,
       std::string(ciphertext_received), std::move(decrypted));
 }
 
@@ -211,4 +188,45 @@
   return request_plaintext_;
 }
 
+absl::StatusOr<ObliviousHttpRequest::Context>
+ObliviousHttpRequest::DecodeEncapsulatedRequestHeader(
+    QuicheDataReader& reader, const EVP_HPKE_KEY& gateway_key,
+    const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
+    absl::string_view request_label) {
+  if (EVP_HPKE_KEY_kem(&gateway_key) == nullptr) {
+    return absl::InvalidArgumentError(
+        "Invalid input param. Failed to import gateway_key.");
+  }
+  bssl::UniquePtr<EVP_HPKE_CTX> gateway_ctx(EVP_HPKE_CTX_new());
+  if (gateway_ctx == nullptr) {
+    return SslErrorAsStatus("Failed to initialize Gateway/Server's Context.");
+  }
+
+  auto is_hdr_ok = ohttp_key_config.ParseOhttpPayloadHeader(reader);
+  if (!is_hdr_ok.ok()) {
+    return is_hdr_ok;
+  }
+
+  size_t enc_key_len = EVP_HPKE_KEM_enc_len(EVP_HPKE_KEY_kem(&gateway_key));
+
+  absl::string_view enc_key_received;
+  if (!reader.ReadStringPiece(&enc_key_received, enc_key_len)) {
+    return absl::FailedPreconditionError(absl::StrCat(
+        "Failed to extract encapsulation key of expected len=", enc_key_len,
+        "from payload."));
+  }
+  std::string info =
+      ohttp_key_config.SerializeRecipientContextInfo(request_label);
+  if (!EVP_HPKE_CTX_setup_recipient(
+          gateway_ctx.get(), &gateway_key, ohttp_key_config.GetHpkeKdf(),
+          ohttp_key_config.GetHpkeAead(),
+          reinterpret_cast<const uint8_t*>(enc_key_received.data()),
+          enc_key_received.size(),
+          reinterpret_cast<const uint8_t*>(info.data()), info.size())) {
+    return SslErrorAsStatus("Failed to setup recipient context");
+  }
+
+  return Context(std::move(gateway_ctx), std::string(enc_key_received));
+}
+
 }  // namespace quiche
diff --git a/quiche/oblivious_http/buffers/oblivious_http_request.h b/quiche/oblivious_http/buffers/oblivious_http_request.h
index d65c00d..8fa6e3e 100644
--- a/quiche/oblivious_http/buffers/oblivious_http_request.h
+++ b/quiche/oblivious_http/buffers/oblivious_http_request.h
@@ -8,6 +8,7 @@
 #include "absl/status/statusor.h"
 #include "absl/strings/string_view.h"
 #include "openssl/hpke.h"
+#include "quiche/common/quiche_data_reader.h"
 #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
 
 namespace quiche {
@@ -103,6 +104,13 @@
     return std::move(oblivious_http_request_context_.value());
   }
 
+  // Reads the OHTTP request header from the given `reader`.
+  // On success, attempts to setup and return the Gateway Context.
+  static absl::StatusOr<Context> DecodeEncapsulatedRequestHeader(
+      QuicheDataReader& reader, const EVP_HPKE_KEY& gateway_key,
+      const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
+      absl::string_view request_label);
+
  private:
   explicit ObliviousHttpRequest(
       bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key,
diff --git a/quiche/oblivious_http/buffers/oblivious_http_request_test.cc b/quiche/oblivious_http/buffers/oblivious_http_request_test.cc
index 0afeaa5..af80873 100644
--- a/quiche/oblivious_http/buffers/oblivious_http_request_test.cc
+++ b/quiche/oblivious_http/buffers/oblivious_http_request_test.cc
@@ -16,6 +16,7 @@
 #include "openssl/hpke.h"
 #include "quiche/common/platform/api/quiche_test.h"
 #include "quiche/common/quiche_data_reader.h"
+#include "quiche/common/test_tools/quiche_test_utils.h"
 #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
 
 namespace quiche {
@@ -85,6 +86,58 @@
 }
 }  // namespace
 
+TEST(ObliviousHttpRequest, DecodeEncapsulatedRequestHeader) {
+  auto ohttp_key_config =
+      GetOhttpKeyConfig(/*key_id=*/1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
+                        EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM);
+
+  auto hpke_key = ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config);
+
+  std::string payload =
+      "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad1"
+      "9dec96c208b4726374e469135906992e1268c594d2a10c695d858c40a026e796"
+      "5e7d86b83dd440b2c0185204b4d63525";
+  std::string payload_bytes;
+  ASSERT_TRUE(absl::HexStringToBytes(payload, &payload_bytes));
+  QuicheDataReader reader(payload_bytes);
+
+  QUICHE_EXPECT_OK(ObliviousHttpRequest::DecodeEncapsulatedRequestHeader(
+      reader, *hpke_key, ohttp_key_config, "test"));
+}
+
+TEST(ObliviousHttpRequest, DecodeEncapsulatedRequestHeaderInvalidInputs) {
+  auto ohttp_key_config =
+      GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256,
+                        EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM);
+
+  auto hpke_key = ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config);
+
+  std::string payload = "";
+  QuicheDataReader reader(payload);
+
+  // Empty payload.
+  EXPECT_EQ(ObliviousHttpRequest::DecodeEncapsulatedRequestHeader(
+                reader, *hpke_key, ohttp_key_config, "test")
+                .status()
+                .code(),
+            absl::StatusCode::kInvalidArgument);
+
+  payload =
+      "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad1"
+      "9dec96c208b4726374e469135906992e1268c594d2a10c695d858c40a026e796"
+      "5e7d86b83dd440b2c0185204b4d63525";
+  std::string payload_bytes;
+  ASSERT_TRUE(absl::HexStringToBytes(payload, &payload_bytes));
+  QuicheDataReader reader2(payload_bytes);
+
+  // Empty key
+  EXPECT_EQ(ObliviousHttpRequest::DecodeEncapsulatedRequestHeader(
+                reader2, {}, ohttp_key_config, "test")
+                .status()
+                .code(),
+            absl::StatusCode::kInvalidArgument);
+}
+
 // Direct test example from RFC.
 // https://www.rfc-editor.org/rfc/rfc9458.html#appendix-A
 TEST(ObliviousHttpRequest, TestDecapsulateWithSpecAppendixAExample) {
diff --git a/quiche/oblivious_http/buffers/oblivious_http_response.cc b/quiche/oblivious_http/buffers/oblivious_http_response.cc
index fbf7052..ea872bd 100644
--- a/quiche/oblivious_http/buffers/oblivious_http_response.cc
+++ b/quiche/oblivious_http/buffers/oblivious_http_response.cc
@@ -18,6 +18,7 @@
 #include "quiche/common/platform/api/quiche_bug_tracker.h"
 #include "quiche/common/quiche_crypto_logging.h"
 #include "quiche/common/quiche_random.h"
+#include "quiche/oblivious_http/buffers/oblivious_http_request.h"
 #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h"
 
 namespace quiche {
@@ -49,19 +50,6 @@
     std::string encrypted_data,
     ObliviousHttpRequest::Context& oblivious_http_request_context,
     absl::string_view resp_label) {
-  if (oblivious_http_request_context.hpke_context_ == nullptr) {
-    return absl::FailedPreconditionError(
-        "HPKE context wasn't initialized before proceeding with this Response "
-        "Decapsulation on Client-side.");
-  }
-  size_t expected_key_len = EVP_HPKE_KEM_enc_len(
-      EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get()));
-  if (oblivious_http_request_context.encapsulated_key_.size() !=
-      expected_key_len) {
-    return absl::InvalidArgumentError(absl::StrCat(
-        "Invalid len for encapsulated_key arg. Expected:", expected_key_len,
-        " Actual:", oblivious_http_request_context.encapsulated_key_.size()));
-  }
   if (encrypted_data.empty()) {
     return absl::InvalidArgumentError("Empty encrypted_data input param.");
   }
@@ -132,19 +120,6 @@
     std::string plaintext_payload,
     ObliviousHttpRequest::Context& oblivious_http_request_context,
     absl::string_view response_label, QuicheRandom* quiche_random) {
-  if (oblivious_http_request_context.hpke_context_ == nullptr) {
-    return absl::FailedPreconditionError(
-        "HPKE context wasn't initialized before proceeding with this Response "
-        "Encapsulation on Server-side.");
-  }
-  size_t expected_key_len = EVP_HPKE_KEM_enc_len(
-      EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get()));
-  if (oblivious_http_request_context.encapsulated_key_.size() !=
-      expected_key_len) {
-    return absl::InvalidArgumentError(absl::StrCat(
-        "Invalid len for encapsulated_key arg. Expected:", expected_key_len,
-        " Actual:", oblivious_http_request_context.encapsulated_key_.size()));
-  }
   if (plaintext_payload.empty()) {
     return absl::InvalidArgumentError("Empty plaintext_payload input param.");
   }
@@ -220,6 +195,19 @@
 absl::StatusOr<ObliviousHttpResponse::CommonAeadParamsResult>
 ObliviousHttpResponse::GetCommonAeadParams(
     ObliviousHttpRequest::Context& oblivious_http_request_context) {
+  if (oblivious_http_request_context.hpke_context_ == nullptr) {
+    return absl::FailedPreconditionError(
+        "HPKE context wasn't initialized before proceeding with this Response");
+  }
+  size_t expected_key_len = EVP_HPKE_KEM_enc_len(
+      EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get()));
+  if (oblivious_http_request_context.encapsulated_key_.size() !=
+      expected_key_len) {
+    return absl::InvalidArgumentError(absl::StrCat(
+        "Invalid len for encapsulated_key arg. Expected:", expected_key_len,
+        " Actual:", oblivious_http_request_context.encapsulated_key_.size()));
+  }
+
   const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead(
       EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get()));
   if (evp_hpke_aead == nullptr) {
diff --git a/quiche/oblivious_http/oblivious_http_gateway.cc b/quiche/oblivious_http/oblivious_http_gateway.cc
index e788369..4a15cb6 100644
--- a/quiche/oblivious_http/oblivious_http_gateway.cc
+++ b/quiche/oblivious_http/oblivious_http_gateway.cc
@@ -24,11 +24,9 @@
       ohttp_key_config_(ohttp_key_config),
       quiche_random_(quiche_random) {}
 
-// Initialize ObliviousHttpGateway(Recipient/Server) context.
-absl::StatusOr<ObliviousHttpGateway> ObliviousHttpGateway::Create(
+absl::StatusOr<bssl::UniquePtr<EVP_HPKE_KEY>> CreateServerRecipientKey(
     absl::string_view hpke_private_key,
-    const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
-    QuicheRandom* quiche_random) {
+    const ObliviousHttpHeaderKeyConfig& ohttp_key_config) {
   if (hpke_private_key.empty()) {
     return absl::InvalidArgumentError("Invalid/Empty HPKE private key.");
   }
@@ -44,8 +42,21 @@
           hpke_private_key.size())) {
     return SslErrorAsStatus("Failed to import HPKE private key.");
   }
+  return recipient_key;
+}
+
+// Initialize ObliviousHttpGateway(Recipient/Server) context.
+absl::StatusOr<ObliviousHttpGateway> ObliviousHttpGateway::Create(
+    absl::string_view hpke_private_key,
+    const ObliviousHttpHeaderKeyConfig& ohttp_key_config,
+    QuicheRandom* quiche_random) {
+  absl::StatusOr<bssl::UniquePtr<EVP_HPKE_KEY>> recipient_key =
+      CreateServerRecipientKey(hpke_private_key, ohttp_key_config);
+  if (!recipient_key.ok()) {
+    return recipient_key.status();
+  }
   if (quiche_random == nullptr) quiche_random = QuicheRandom::GetInstance();
-  return ObliviousHttpGateway(std::move(recipient_key), ohttp_key_config,
+  return ObliviousHttpGateway(std::move(*recipient_key), ohttp_key_config,
                               quiche_random);
 }