Fix unsound Rust reference in np_ffi_CredentialSlab_add_v0_credential

Currently, in the Rust implementation of `np_ffi_CredentialSlab_add_v0_credential`, we take the underlying buffer of the passed `V0MatchableCredential` and turn it into a Rust `&[u8]` by calling `unsafe slice::from_raw_parts`. The safety contract of `from_raw_parts` states that the passed pointer can neither be null, nor be unaligned. In the `advertisment_decoder_rust_impl.cc` we have a code path that leads to a null pointer being passed, though. We get a nullpointer if we pass a `std::vector` of size 0. This change fixes the issue by making sure we always pass a non-null buffer.

PiperOrigin-RevId: 729417182
This commit is contained in:
Bryan Kersting
2025-02-21 00:37:51 -08:00
committed by Copybara-Service
parent 51607dc548
commit 79ae5cab5a
@@ -215,9 +215,14 @@ AdvertisementDecoderImpl::InitializeCredentialBook(
nearby_protocol::CredentialSlab slab;
for (const auto& credential : (*credentials_map)
[internal::IdentityType::IDENTITY_TYPE_PRIVATE_GROUP]) {
std::vector<uint8_t> metadata_bytes(
credential.encrypted_metadata_bytes_v0().begin(),
credential.encrypted_metadata_bytes_v0().end());
// Make sure the vector is not empty, as this is a prerequisite of the Rust
// code we call into.
std::vector<uint8_t> metadata_bytes(1);
if (!credential.encrypted_metadata_bytes_v0().empty()) {
metadata_bytes =
std::vector<uint8_t>(credential.encrypted_metadata_bytes_v0().begin(),
credential.encrypted_metadata_bytes_v0().end());
}
nearby_protocol::MatchedCredentialData matched_cred(credential.id(),
metadata_bytes);