Skip to content
Open
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
3 changes: 2 additions & 1 deletion cpp/src/arrow/flight/flight_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,8 @@ void ParseBasicHeader(const CallHeaders& incoming_headers, std::string& username
std::string& password) {
std::string encoded_credentials =
FindKeyValPrefixInCallHeaders(incoming_headers, kAuthHeader, kBasicPrefix);
std::stringstream decoded_stream(arrow::util::base64_decode(encoded_credentials));
ASSERT_OK_AND_ASSIGN(auto decoded, arrow::util::base64_decode(encoded_credentials));
std::stringstream decoded_stream(decoded);
std::getline(decoded_stream, username, ':');
std::getline(decoded_stream, password, ':');
}
Expand Down
1 change: 1 addition & 0 deletions cpp/src/arrow/util/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ add_arrow_test(utility-test
SOURCES
align_util_test.cc
atfork_test.cc
base64_test.cc
byte_size_test.cc
byte_stream_split_test.cc
cache_test.cc
Expand Down
3 changes: 2 additions & 1 deletion cpp/src/arrow/util/base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <string>
#include <string_view>

#include "arrow/result.h"
#include "arrow/util/visibility.h"

namespace arrow {
Expand All @@ -29,7 +30,7 @@ ARROW_EXPORT
std::string base64_encode(std::string_view s);

ARROW_EXPORT
std::string base64_decode(std::string_view s);
arrow::Result<std::string> base64_decode(std::string_view s);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to change the callers?
Perhaps a single integration test that would call a caller function with an invalid input to validate.

Copy link
Copy Markdown
Author

@Reranko05 Reranko05 Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on @kou's earlier suggestion, I proceeded with updating base64_decode() to return arrow::Result<std::string> and adjusted the existing usages accordingly.

Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

base64_decode was changed from returning std::string to arrow::Result<std::string>, but there are existing call sites in the repo that still treat it as a std::string (e.g., constructing streams, assigning to std::string). As-is, this is an API/ABI breaking change and will not compile unless all callers are updated or a backwards-compatible overload/wrapper is kept.

Suggested change
arrow::Result<std::string> base64_decode(std::string_view s);
std::string base64_decode(std::string_view s);

Copilot uses AI. Check for mistakes.

Comment on lines 30 to 34
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change conflicts with the PR description/user-facing behavior: the description says invalid input should return an empty string, but the new signature returns Result<std::string> and the implementation returns Status::Invalid(...) on malformed inputs. Please align the implementation/API and the stated behavior (either update the description and downstream expectations, or preserve the old std::string API that returns "" on invalid input).

Copilot uses AI. Check for mistakes.
} // namespace util
} // namespace arrow
84 changes: 84 additions & 0 deletions cpp/src/arrow/util/base64_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

#include "arrow/util/base64.h"
#include "arrow/testing/gtest_util.h"

namespace arrow {
namespace util {

TEST(Base64DecodeTest, ValidInputs) {
ASSERT_OK_AND_ASSIGN(auto empty, arrow::util::base64_decode(""));
EXPECT_EQ(empty, "");

ASSERT_OK_AND_ASSIGN(auto two_paddings, arrow::util::base64_decode("Zg=="));
EXPECT_EQ(two_paddings, "f");

ASSERT_OK_AND_ASSIGN(auto one_padding, arrow::util::base64_decode("Zm8="));
EXPECT_EQ(one_padding, "fo");

ASSERT_OK_AND_ASSIGN(auto no_padding, arrow::util::base64_decode("Zm9v"));
EXPECT_EQ(no_padding, "foo");

ASSERT_OK_AND_ASSIGN(auto multiblock, arrow::util::base64_decode("SGVsbG8gd29ybGQ="));
EXPECT_EQ(multiblock, "Hello world");
}

TEST(Base64DecodeTest, BinaryOutput) {
// 'A' maps to index 0 — same zero value used for padding slots
// verifies the 'A' bug is not present
ASSERT_OK_AND_ASSIGN(auto all_A, arrow::util::base64_decode("AAAA"));
EXPECT_EQ(all_A, std::string("\x00\x00\x00", 3));

// Arbitrary non-ASCII output bytes
ASSERT_OK_AND_ASSIGN(auto binary, arrow::util::base64_decode("AP8A"));
EXPECT_EQ(binary, std::string("\x00\xff\x00", 3));
}

TEST(Base64DecodeTest, InvalidLength) {
ASSERT_RAISES_WITH_MESSAGE(
Invalid, "Invalid: Invalid base64 input: length is not a multiple of 4",
arrow::util::base64_decode("abc"));
}

TEST(Base64DecodeTest, InvalidCharacters) {
ASSERT_RAISES(Invalid, arrow::util::base64_decode("ab$="));

// Non-ASCII byte
std::string non_ascii = std::string("abc") + static_cast<char>(0xFF);
ASSERT_RAISES(Invalid, arrow::util::base64_decode(non_ascii));

// Corruption mid-string across multiple blocks
ASSERT_RAISES(Invalid, arrow::util::base64_decode("aGVs$G8gd29ybGQ="));
}

TEST(Base64DecodeTest, InvalidPadding) {
// Padding in wrong position within block
ASSERT_RAISES(Invalid, arrow::util::base64_decode("ab=c"));

// 3 padding characters — exceeds maximum of 2
ASSERT_RAISES(Invalid, arrow::util::base64_decode("a==="));

// 4 padding characters
ASSERT_RAISES(Invalid, arrow::util::base64_decode("===="));

// Padding in non-final block across multiple blocks
ASSERT_RAISES(Invalid, arrow::util::base64_decode("Zm8=Zm8="));
}

} // namespace util
} // namespace arrow
77 changes: 51 additions & 26 deletions cpp/src/arrow/vendored/base64.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
*/

#include "arrow/util/base64.h"
#include "arrow/result.h"
#include <iostream>

namespace arrow {
Expand All @@ -40,11 +41,6 @@ static const std::string base64_chars =
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";


static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}

static std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
Expand Down Expand Up @@ -93,38 +89,67 @@ std::string base64_encode(std::string_view string_to_encode) {
return base64_encode(bytes_to_encode, in_len);
}

std::string base64_decode(std::string_view encoded_string) {
Result<std::string> base64_decode(std::string_view encoded_string) {
size_t in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
std::string_view::size_type in_ = 0;
int padding_count = 0;
int block_padding = 0;
bool padding_started = false;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;

while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff;
if (encoded_string.size() % 4 != 0) {
return Status::Invalid("Invalid base64 input: length is not a multiple of 4");
}
Comment on lines +102 to +104
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR description says invalid input should "return an empty string", but the implementation now returns Status::Invalid(...) (and the header signature is Result<std::string>). Either update the PR description/user-facing notes to reflect the new error-reporting API, or adjust the implementation to match the documented behavior (e.g. preserve the std::string API and return "" on invalid input).

Copilot uses AI. Check for mistakes.

char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
while (in_len--) {
unsigned char c = encoded_string[in_];

for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
if (c == '=') {
padding_started = true;
padding_count++;

if (padding_count > 2) {
return Status::Invalid("Invalid base64 input: too many padding characters");
}

char_array_4[i++] = 0;
} else {
if (padding_started) {
return Status::Invalid("Invalid base64 input: padding characters must be at the end");
}

if (base64_chars.find(c) == std::string::npos) {
return Status::Invalid(
"Invalid base64 input: contains non-base64 byte at position " +
std::to_string(in_));
}
Comment on lines +123 to +127
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

base64_chars.find() is called for validation on every input byte and then again during the decode step, adding extra work per character. Consider switching to a 256-entry lookup table (byte -> sextet or -1) to validate and map in one step, keeping strict validation without repeated linear searches.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good optimization, but out of scope for this PR which focuses on correctness and validation. Can be addressed in a follow-up if needed.


char_array_4[i++] = c;
}
}

if (i) {
for (j = 0; j < i; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]) & 0xff;
in_++;

if (i == 4) {
for (i = 0; i < 4; i++) {
if (char_array_4[i] != 0) {
char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff;
}
}

char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

block_padding = padding_count;

char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
for (i = 0; i < 3 - block_padding; i++) {
ret += char_array_3[i];
}

for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
i = 0;
}
}

return ret;
Expand Down
10 changes: 9 additions & 1 deletion cpp/src/gandiva/gdv_function_stubs.cc
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,15 @@ const char* gdv_fn_base64_decode_utf8(int64_t context, const char* in, int32_t i
return "";
}
// use arrow method to decode base64 string
std::string decoded_str = arrow::util::base64_decode(std::string_view(in, in_len));
auto result = arrow::util::base64_decode(std::string_view(in, in_len));
if (!result.ok()) {
gdv_fn_context_set_error_msg(context, result.status().message().c_str());
*out_len = 0;
return "";
}

std::string decoded_str = std::move(result).ValueOrDie();

*out_len = static_cast<int32_t>(decoded_str.length());
// allocate memory for response
char* ret = reinterpret_cast<char*>(
Expand Down
9 changes: 7 additions & 2 deletions cpp/src/parquet/arrow/fuzz_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,13 @@ class FuzzDecryptionKeyRetriever : public DecryptionKeyRetriever {
}
// Is it a key generated by MakeEncryptionKey?
if (key_id.starts_with(kInlineKeyPrefix)) {
return SecureString(
::arrow::util::base64_decode(key_id.substr(kInlineKeyPrefix.length())));
auto result =
::arrow::util::base64_decode(key_id.substr(kInlineKeyPrefix.length()));
if (!result.ok()) {
throw ParquetException(result.status().message());
}

return SecureString(std::move(result).ValueOrDie());
}
throw ParquetException("Unknown fuzz encryption key_id");
}
Expand Down
3 changes: 2 additions & 1 deletion cpp/src/parquet/arrow/schema.cc
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,8 @@ Status GetOriginSchema(const std::shared_ptr<const KeyValueMetadata>& metadata,
// The original Arrow schema was serialized using the store_schema option.
// We deserialize it here and use it to inform read options such as
// dictionary-encoded fields.
auto decoded = ::arrow::util::base64_decode(metadata->value(schema_index));
ARROW_ASSIGN_OR_RAISE(auto decoded,
::arrow::util::base64_decode(metadata->value(schema_index)));
auto schema_buf = std::make_shared<Buffer>(decoded);

::arrow::ipc::DictionaryMemo dict_memo;
Expand Down
7 changes: 6 additions & 1 deletion cpp/src/parquet/encryption/file_key_unwrapper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,12 @@ KeyWithMasterId FileKeyUnwrapper::GetDataEncryptionKey(const KeyMaterial& key_ma
});

// Decrypt the data key
std::string aad = ::arrow::util::base64_decode(encoded_kek_id);
auto result = ::arrow::util::base64_decode(encoded_kek_id);
if (!result.ok()) {
throw ParquetException(result.status().message());
}

std::string aad = std::move(result).ValueOrDie();
data_key = internal::DecryptKeyLocally(encoded_wrapped_dek, kek_bytes, aad);
}

Expand Down
7 changes: 6 additions & 1 deletion cpp/src/parquet/encryption/key_toolkit_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ std::string EncryptKeyLocally(const SecureString& key_bytes,

SecureString DecryptKeyLocally(const std::string& encoded_encrypted_key,
const SecureString& master_key, const std::string& aad) {
std::string encrypted_key = ::arrow::util::base64_decode(encoded_encrypted_key);
auto result = ::arrow::util::base64_decode(encoded_encrypted_key);
if (!result.ok()) {
throw ParquetException(result.status().message());
}

std::string encrypted_key = std::move(result).ValueOrDie();

AesDecryptor key_decryptor(ParquetCipher::AES_GCM_V1,
static_cast<int>(master_key.size()), false,
Expand Down