Fix critical bugs in base64 implementation - array bounds and substr length

Co-authored-by: nyh <584227+nyh@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2025-08-10 11:41:57 +00:00
parent 5c7d63da6a
commit 31c79f6cd7
2 changed files with 27 additions and 3 deletions

View File

@@ -202,3 +202,27 @@ BOOST_AUTO_TEST_CASE(test_magnitude_and_precision_edge_cases) {
BOOST_FAIL("Number with 'e' but no exponent should not cause exception");
}
}
// Test edge cases in base64 functions that could expose bugs
BOOST_AUTO_TEST_CASE(test_base64_edge_cases) {
// Test BUG 7: Character with value 255 should not cause out-of-bounds access
try {
std::string test_with_255;
test_with_255.push_back(char(255)); // Add character with value 255
base64_encode(to_bytes_view(test_with_255)); // Should not crash
BOOST_CHECK(true); // If we get here, it didn't crash
} catch (...) {
BOOST_FAIL("Character with value 255 should not cause exception");
}
// Test BUG 8: base64_begins_with with edge case sizes
std::string base = "QUJDRA=="; // "ABCD" encoded
std::string operand = "QUJD"; // "ABC" encoded (incomplete)
// This should not crash or access out of bounds
try {
bool result = base64_begins_with(base, operand);
BOOST_CHECK(true); // If we get here, it didn't crash
} catch (...) {
BOOST_FAIL("base64_begins_with should handle edge cases without exception");
}
}

View File

@@ -17,10 +17,10 @@ public:
static constexpr const char to[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr uint8_t invalid_char = 255;
uint8_t from[255];
uint8_t from[256]; // BUG FIX 7: Increased size to handle all unsigned char values (0-255)
base64_chars() {
static_assert(sizeof(to) == 64 + 1);
for (int i = 0; i < 255; i++) {
for (int i = 0; i < 256; i++) { // BUG FIX 7: Loop to 256 to initialize all indices
from[i] = invalid_char; // signal invalid character
}
for (int i = 0; i < 64; i++) {
@@ -128,7 +128,7 @@ bool base64_begins_with(std::string_view base, std::string_view operand) {
return false;
}
// Decode and compare last 4 bytes of base64-encoded strings
const std::string base_remainder = base64_decode_string(base.substr(operand.size() - 4, operand.size()));
const std::string base_remainder = base64_decode_string(base.substr(operand.size() - 4, 4)); // BUG FIX 8: Fixed substr length parameter
const std::string operand_remainder = base64_decode_string(operand.substr(operand.size() - 4));
return base_remainder.starts_with(operand_remainder);
}