Files
ladybird/Tests/AK/TestBase64.cpp
Ben Wiederhake 3bf1f7ae87 AK: Don't crash on invalid Base64 input
In the long-term, we should probably have a way to signal decoding
failure. For now, it should suffice to at least not crash. This is
particularly relevant because apparently this can be triggered while
parsing a PEM certificate, which happens during every TLS connection.

Found by OSS Fuzz
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=38979
2021-10-23 19:16:40 +01:00

54 lines
1.5 KiB
C++

/*
* Copyright (c) 2020, Tom Lebreux <tomlebreux@hotmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/Base64.h>
#include <AK/String.h>
#include <string.h>
TEST_CASE(test_decode)
{
auto decode_equal = [&](const char* input, const char* expected) {
auto decoded = decode_base64(StringView(input));
EXPECT(String::copy(decoded) == String(expected));
EXPECT(StringView(expected).length() <= calculate_base64_decoded_length(StringView(input).bytes()));
};
decode_equal("", "");
decode_equal("Zg==", "f");
decode_equal("Zm8=", "fo");
decode_equal("Zm9v", "foo");
decode_equal("Zm9vYg==", "foob");
decode_equal("Zm9vYmE=", "fooba");
decode_equal("Zm9vYmFy", "foobar");
}
TEST_CASE(test_decode_nocrash)
{
// Any output is fine, we only check that we don't crash here.
decode_base64(StringView("asdf\xffqwer"));
decode_base64(StringView("asdf\x80qwer"));
// TODO: Handle decoding failure.
}
TEST_CASE(test_encode)
{
auto encode_equal = [&](const char* input, const char* expected) {
auto encoded = encode_base64({ input, strlen(input) });
EXPECT(encoded == String(expected));
EXPECT_EQ(StringView(expected).length(), calculate_base64_encoded_length(StringView(input).bytes()));
};
encode_equal("", "");
encode_equal("f", "Zg==");
encode_equal("fo", "Zm8=");
encode_equal("foo", "Zm9v");
encode_equal("foob", "Zm9vYg==");
encode_equal("fooba", "Zm9vYmE=");
encode_equal("foobar", "Zm9vYmFy");
}