Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#include <gtest/gtest.h>
#include <react/utils/Base64.h>
#include <string>

namespace facebook::react {

TEST(Base64Tests, encodesAsciiString) {
EXPECT_EQ(base64Encode("hello"), "aGVsbG8=");
}

TEST(Base64Tests, encodesEmptyString) {
EXPECT_EQ(base64Encode(""), "");
}

// Padding depends on input length modulo 3.
TEST(Base64Tests, encodesWithCorrectPadding) {
EXPECT_EQ(base64Encode("a"), "YQ==");
EXPECT_EQ(base64Encode("ab"), "YWI=");
EXPECT_EQ(base64Encode("abc"), "YWJj");
}

// Binary safety: bytes that are invalid UTF-8 / contain NULs must round-trip.
// This is the case that matters for binary ('base64'/arraybuffer) response
// bodies in the NetworkingModule -- sending such bytes verbatim corrupts them.
TEST(Base64Tests, encodesBinaryBytes) {
EXPECT_EQ(base64Encode(std::string("\x00\xff", 2)), "AP8=");
}

} // namespace facebook::react
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "NetworkingModule.h"

#include <react/debug/react_native_assert.h>
#include <react/utils/Base64.h>

namespace facebook::react {

Expand Down Expand Up @@ -270,15 +271,35 @@ int64_t NetworkingModule::didReceiveNetworkIncrementalData(
return bytesRead;
};

namespace {
// Encodes a response body for delivery to JS according to responseType.
//
// The JS XMLHttpRequest layer base64-decodes the delivered string for
// 'base64'-type responses (responseType 'arraybuffer'), so binary bodies must
// be base64-encoded here, matching the Android and iOS NetworkingModule
// implementations. Without this, base64.toByteArray() on the JS side
// mis-decodes the raw payload and corrupts the response (e.g. JSON.parse
// failures on arraybuffer fetches). All other response types are delivered
// unchanged.
std::string encodeResponseBody(
const std::string& responseType,
std::string body) {
if (responseType == "base64") {
return base64Encode(body);
}
return body;
}
} // namespace

void NetworkingModule::didReceiveNetworkData(
uint32_t requestId,
const std::string& /*responseType*/,
const std::string& responseType,
std::unique_ptr<folly::IOBuf> buf) {
if (requests_.isStopped()) {
return;
}

auto responseData = buf->toString();
auto responseData = encodeResponseBody(responseType, buf->toString());
emitDeviceEvent(
"didReceiveNetworkData",
[requestId,
Expand Down
Loading