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
8 changes: 7 additions & 1 deletion src/attachments.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -301,14 +301,20 @@ std::array<std::byte, ENCRYPT_KEY_SIZE> encrypt(
const std::filesystem::path& file,
Domain domain,
std::function<std::span<std::byte>(size_t enc_size)> make_buffer,
bool /*allow_large*/) {
bool allow_large) {

if (seed.size() < 32)
throw std::invalid_argument{"attachment::encrypt requires a 32-byte uploader seed"};

std::ifstream in;
in.exceptions(std::ios::badbit);
in.open(file, std::ios::binary | std::ios::ate);
size_t size = in.tellg();
in.seekg(0, std::ios::beg);

if (size > MAX_REGULAR_SIZE && !allow_large)
throw std::invalid_argument{"data to encrypt is too large"};

size = encrypted_size(size);

std::array<unsigned char, ENCRYPT_HEADER + ENCRYPT_KEY_SIZE> nonce_key;
Expand Down
20 changes: 20 additions & 0 deletions tests/test_attachment_encrypt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,26 @@ TEST_CASE(
CHECK(!!(decr == make_data(DATA_SIZE)));
}

TEST_CASE("Attachment file encryption validates its inputs", "[attachments][files][encrypt]") {
auto seed = "5123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"_hex_b;
temp_data_file f{0};

CHECK_THROWS_MATCHES(
attachment::encrypt(
std::span{seed}.first<31>(), f.path, attachment::Domain::ATTACHMENT),
std::invalid_argument,
Message("attachment::encrypt requires a 32-byte uploader seed"));

std::filesystem::resize_file(f.path, attachment::MAX_REGULAR_SIZE + 1);
CHECK_THROWS_MATCHES(
attachment::encrypt(seed, f.path, attachment::Domain::ATTACHMENT),
std::invalid_argument,
Message("data to encrypt is too large"));

auto [enc, key] = attachment::encrypt(seed, f.path, attachment::Domain::ATTACHMENT, true);
CHECK(attachment::decrypt(enc, key).size() == attachment::MAX_REGULAR_SIZE + 1);
}

static std::vector<std::byte> slurp_file(const std::filesystem::path& filename) {
std::ifstream in;
in.exceptions(std::ios::failbit | std::ios::badbit);
Expand Down