| 1 |
use km_common::algorithms::HpkeAlgorithm; |
| 2 |
use km_common::crypto::PublicKey; |
| 3 |
use km_common::crypto::secret_box::SecretBox; |
| 4 |
use km_common::key_types::{KeyRecord, KeyRegistry, KeySpec}; |
| 5 |
use prost::Message; |
| 6 |
use std::slice; |
| 7 |
use std::sync::Arc; |
| 8 |
use std::sync::LazyLock; |
| 9 |
use std::sync::atomic::AtomicBool; |
| 10 |
use std::time::Duration; |
| 11 |
use uuid::Uuid; |
| 12 |
|
| 13 |
static KEY_REGISTRY: LazyLock<KeyRegistry> = LazyLock::new(|| { |
| 14 |
let registry = KeyRegistry::default(); |
| 15 |
registry.start_reaper(Arc::new(AtomicBool::new(false))); |
| 16 |
registry |
| 17 |
}); |
| 18 |
|
| 19 |
/// Internal function to generate a binding keypair and store it in the registry. |
| 20 |
fn generate_binding_keypair_internal( |
| 21 |
algo: HpkeAlgorithm, |
| 22 |
expiry_secs: u64, |
| 23 |
) -> Result<(uuid::Uuid, PublicKey), i32> { |
| 24 |
let result = KeyRecord::create_binding_key(algo, Duration::from_secs(expiry_secs)); |
| 25 |
|
| 26 |
match result { |
| 27 |
Ok(record) => { |
| 28 |
let id = record.meta.id; |
| 29 |
let pubkey = match &record.meta.spec { |
| 30 |
KeySpec::Binding { |
| 31 |
binding_public_key, .. |
| 32 |
} => binding_public_key.clone(), |
| 33 |
_ => return Err(-1), |
| 34 |
}; |
| 35 |
KEY_REGISTRY.add_key(record); |
| 36 |
Ok((id, pubkey)) |
| 37 |
} |
| 38 |
Err(_) => Err(-1), |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
/// Generates a new binding HPKE keypair. |
| 43 |
/// |
| 44 |
/// ## Arguments |
| 45 |
/// * `algo_ptr` - A pointer to the serialized HPKE algorithm proto bytes. |
| 46 |
/// * `algo_len` - The length of the serialized HPKE algorithm proto bytes. |
| 47 |
/// * `expiry_secs` - The expiration time of the key in seconds from now. |
| 48 |
/// * `out_uuid` - A pointer to a 16-byte buffer where the key UUID will be written. |
| 49 |
/// * `out_pubkey` - A pointer to a buffer where the public key will be written. |
| 50 |
/// * `out_pubkey_len` - A pointer to a `usize` that contains the size of `out_pubkey` buffer. |
| 51 |
/// On success, it will be updated with the actual size of the public key. |
| 52 |
/// |
| 53 |
/// ## Safety |
| 54 |
/// This function is unsafe because it dereferences the provided raw pointers. |
| 55 |
/// The caller must ensure that: |
| 56 |
/// * `algo_ptr` points to a valid buffer of at least `algo_len` bytes. |
| 57 |
/// * `out_uuid` is either null or points to a valid 16-byte buffer. |
| 58 |
/// * `out_pubkey` is either null or points to a valid buffer of at least `*out_pubkey_len` bytes. |
| 59 |
/// * `out_pubkey_len` is either null or points to a valid `usize`. |
| 60 |
/// |
| 61 |
/// ## Returns |
| 62 |
/// * `0` on success. |
| 63 |
/// * `-1` if an error occurred during key generation. |
| 64 |
/// * `-2` if the `out_pubkey` buffer size does not match the key size. |
| 65 |
#[unsafe(no_mangle)] |
| 66 |
pub unsafe extern "C" fn key_manager_generate_binding_keypair( |
| 67 |
algo_ptr: *const u8, |
| 68 |
algo_len: usize, |
| 69 |
expiry_secs: u64, |
| 70 |
out_uuid: *mut u8, |
| 71 |
out_pubkey: *mut u8, |
| 72 |
out_pubkey_len: usize, |
| 73 |
) -> i32 { |
| 74 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 75 |
// Safety Invariant Checks |
| 76 |
if out_pubkey.is_null() || out_uuid.is_null() || algo_ptr.is_null() || algo_len == 0 { |
| 77 |
return -1; |
| 78 |
} |
| 79 |
|
| 80 |
// Convert to Safe Types |
| 81 |
let algo_slice = unsafe { slice::from_raw_parts(algo_ptr, algo_len) }; |
| 82 |
let out_uuid = unsafe { slice::from_raw_parts_mut(out_uuid, 16) }; |
| 83 |
let out_pubkey = unsafe { slice::from_raw_parts_mut(out_pubkey, out_pubkey_len) }; |
| 84 |
|
| 85 |
let algo = match HpkeAlgorithm::decode(algo_slice) { |
| 86 |
Ok(a) => a, |
| 87 |
Err(_) => return -1, |
| 88 |
}; |
| 89 |
|
| 90 |
// Call Safe Internal Function |
| 91 |
match generate_binding_keypair_internal(algo, expiry_secs) { |
| 92 |
Ok((id, pubkey)) => { |
| 93 |
if out_pubkey_len != pubkey.as_bytes().len() { |
| 94 |
return -2; |
| 95 |
} |
| 96 |
out_uuid.copy_from_slice(id.as_bytes()); |
| 97 |
out_pubkey.copy_from_slice(pubkey.as_bytes()); |
| 98 |
0 // Success |
| 99 |
} |
| 100 |
Err(e) => e, |
| 101 |
} |
| 102 |
})) |
| 103 |
.unwrap_or(-1) |
| 104 |
} |
| 105 |
|
| 106 |
/// Destroys the binding key associated with the given UUID. |
| 107 |
/// |
| 108 |
/// ## Arguments |
| 109 |
/// * `uuid_bytes` - A pointer to a 16-byte buffer containing the key UUID. |
| 110 |
/// |
| 111 |
/// ## Safety |
| 112 |
/// This function is unsafe because it dereferences the provided raw pointer. |
| 113 |
/// The caller must ensure that `uuid_bytes` points to a valid 16-byte buffer. |
| 114 |
/// |
| 115 |
/// ## Returns |
| 116 |
/// * `0` on success. |
| 117 |
/// * `-1` if the UUID pointer is null or the key was not found. |
| 118 |
#[unsafe(no_mangle)] |
| 119 |
pub unsafe extern "C" fn key_manager_destroy_binding_key(uuid_bytes: *const u8) -> i32 { |
| 120 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 121 |
if uuid_bytes.is_null() { |
| 122 |
return -1; |
| 123 |
} |
| 124 |
let bytes = unsafe { slice::from_raw_parts(uuid_bytes, 16) }; |
| 125 |
let uuid = Uuid::from_bytes(bytes.try_into().expect("invalid UUID bytes")); |
| 126 |
|
| 127 |
match KEY_REGISTRY.remove_key(&uuid) { |
| 128 |
Some(_) => 0, // Success |
| 129 |
None => -1, // Not found |
| 130 |
} |
| 131 |
})) |
| 132 |
.unwrap_or(-1) |
| 133 |
} |
| 134 |
|
| 135 |
/// Internal function to decrypt a ciphertext using a stored binding key. |
| 136 |
fn open_internal(uuid: Uuid, enc: &[u8], ciphertext: &[u8], aad: &[u8]) -> Result<SecretBox, i32> { |
| 137 |
let record = KEY_REGISTRY.get_key(&uuid).ok_or(-1)?; |
| 138 |
|
| 139 |
let algo = match &record.meta.spec { |
| 140 |
KeySpec::Binding { algo, .. } => algo, |
| 141 |
_ => return Err(-1), |
| 142 |
}; |
| 143 |
|
| 144 |
let priv_key = record.get_private_key(); |
| 145 |
|
| 146 |
match km_common::crypto::hpke_open(&priv_key, enc, ciphertext, aad, algo) { |
| 147 |
Ok(pt) => Ok(pt), |
| 148 |
Err(_) => Err(-3), |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
/// Decrypts a ciphertext using the binding key associated with the given UUID. |
| 153 |
/// |
| 154 |
/// ## Arguments |
| 155 |
/// * `uuid_bytes` - A pointer to a 16-byte buffer containing the key UUID. |
| 156 |
/// * `enc` - A pointer to the encapsulated shared secret. |
| 157 |
/// * `enc_len` - The length of the encapsulated shared secret. |
| 158 |
/// * `ciphertext` - A pointer to the ciphertext to decrypt. |
| 159 |
/// * `ciphertext_len` - The length of the ciphertext. |
| 160 |
/// * `aad` - A pointer to the additional authenticated data. |
| 161 |
/// * `aad_len` - The length of the additional authenticated data. |
| 162 |
/// * `out_plaintext` - A pointer to a buffer where the decrypted plaintext will be written. |
| 163 |
/// * `out_plaintext_len` - The size of `out_plaintext` buffer. |
| 164 |
/// |
| 165 |
/// ## Safety |
| 166 |
/// This function is unsafe because it dereferences raw pointers. The caller must ensure that: |
| 167 |
/// * `uuid_bytes` points to a valid 16-byte buffer. |
| 168 |
/// * `enc` points to a valid buffer of `enc_len` bytes. |
| 169 |
/// * `ciphertext` points to a valid buffer of `ciphertext_len` bytes. |
| 170 |
/// * `aad` points to a valid buffer of `aad_len` bytes. |
| 171 |
/// * `out_plaintext` points to a valid buffer of `*out_plaintext_len` bytes. |
| 172 |
/// * `out_plaintext_len` points to a valid `usize`. |
| 173 |
/// |
| 174 |
/// ## Returns |
| 175 |
/// * `0` on success. |
| 176 |
/// * `-1` if arguments are invalid (e.g., key not found, null pointers). |
| 177 |
/// * `-2` if the `out_plaintext` buffer is too small. |
| 178 |
/// * `-3` if decryption failed. |
| 179 |
#[unsafe(no_mangle)] |
| 180 |
pub unsafe extern "C" fn key_manager_open( |
| 181 |
uuid_bytes: *const u8, |
| 182 |
enc: *const u8, |
| 183 |
enc_len: usize, |
| 184 |
ciphertext: *const u8, |
| 185 |
ciphertext_len: usize, |
| 186 |
aad: *const u8, |
| 187 |
aad_len: usize, |
| 188 |
out_plaintext: *mut u8, |
| 189 |
out_plaintext_len: usize, |
| 190 |
) -> i32 { |
| 191 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 192 |
if uuid_bytes.is_null() |
| 193 |
|| enc.is_null() |
| 194 |
|| ciphertext.is_null() |
| 195 |
|| out_plaintext.is_null() |
| 196 |
|| out_plaintext_len == 0 |
| 197 |
{ |
| 198 |
return -1; |
| 199 |
} |
| 200 |
|
| 201 |
let uuid_slice = unsafe { std::slice::from_raw_parts(uuid_bytes, 16) }; |
| 202 |
let enc_slice = unsafe { std::slice::from_raw_parts(enc, enc_len) }; |
| 203 |
let ct_slice = unsafe { std::slice::from_raw_parts(ciphertext, ciphertext_len) }; |
| 204 |
let aad_slice = if !aad.is_null() && aad_len > 0 { |
| 205 |
unsafe { slice::from_raw_parts(aad, aad_len) } |
| 206 |
} else { |
| 207 |
&[] |
| 208 |
}; |
| 209 |
let out_plaintext_slice = |
| 210 |
unsafe { std::slice::from_raw_parts_mut(out_plaintext, out_plaintext_len) }; |
| 211 |
|
| 212 |
let uuid = match Uuid::from_slice(uuid_slice) { |
| 213 |
Ok(u) => u, |
| 214 |
Err(_) => return -1, |
| 215 |
}; |
| 216 |
|
| 217 |
// Call Safe Internal Function |
| 218 |
match open_internal(uuid, enc_slice, ct_slice, aad_slice) { |
| 219 |
Ok(pt) => { |
| 220 |
if out_plaintext_len != pt.as_slice().len() { |
| 221 |
return -2; |
| 222 |
} |
| 223 |
out_plaintext_slice.copy_from_slice(pt.as_slice()); |
| 224 |
0 // Success |
| 225 |
} |
| 226 |
Err(e) => e, |
| 227 |
} |
| 228 |
})) |
| 229 |
.unwrap_or(-1) |
| 230 |
} |
| 231 |
|
| 232 |
pub const MAX_ALGORITHM_LEN: usize = 128; |
| 233 |
pub const MAX_PUBLIC_KEY_LEN: usize = 2048; |
| 234 |
|
| 235 |
#[derive(Clone, Copy, Debug)] |
| 236 |
#[repr(C)] |
| 237 |
pub struct WsKeyInfo { |
| 238 |
pub uuid: [u8; 16], |
| 239 |
pub algorithm: [u8; MAX_ALGORITHM_LEN], |
| 240 |
pub algorithm_len: usize, |
| 241 |
pub pub_key: [u8; MAX_PUBLIC_KEY_LEN], |
| 242 |
pub pub_key_len: usize, |
| 243 |
pub remaining_lifespan_secs: u64, |
| 244 |
} |
| 245 |
|
| 246 |
impl Default for WsKeyInfo { |
| 247 |
fn default() -> Self { |
| 248 |
WsKeyInfo { |
| 249 |
uuid: [0; 16], |
| 250 |
algorithm: [0; MAX_ALGORITHM_LEN], |
| 251 |
algorithm_len: 0, |
| 252 |
pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 253 |
pub_key_len: 0, |
| 254 |
remaining_lifespan_secs: 0, |
| 255 |
} |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
fn enumerate_binding_keys_internal( |
| 260 |
entries: &mut [WsKeyInfo], |
| 261 |
offset: usize, |
| 262 |
) -> Result<(usize, bool), i32> { |
| 263 |
let (metas, total_count) = KEY_REGISTRY.list_all_keys(offset, entries.len()); |
| 264 |
let count = metas.len(); |
| 265 |
let has_more = offset + count < total_count; |
| 266 |
|
| 267 |
for (entry, meta) in entries.iter_mut().zip(metas.into_iter()) { |
| 268 |
let KeySpec::Binding { |
| 269 |
algo, |
| 270 |
binding_public_key: pub_key, |
| 271 |
} = &meta.spec |
| 272 |
else { |
| 273 |
return Err(-1); |
| 274 |
}; |
| 275 |
|
| 276 |
let algo_bytes = algo.encode_to_vec(); |
| 277 |
|
| 278 |
if pub_key.as_bytes().len() > MAX_PUBLIC_KEY_LEN || algo_bytes.len() > MAX_ALGORITHM_LEN { |
| 279 |
debug_assert!( |
| 280 |
false, |
| 281 |
"Implementation error: Key size exceeds buffer limits! (algo={}, pub={})", |
| 282 |
algo_bytes.len(), |
| 283 |
pub_key.as_bytes().len() |
| 284 |
); |
| 285 |
return Err(-2); // Buffer Limit Exceeded |
| 286 |
} |
| 287 |
|
| 288 |
let now = std::time::Instant::now(); |
| 289 |
let remaining = meta.delete_after.saturating_duration_since(now).as_secs(); |
| 290 |
|
| 291 |
*entry = WsKeyInfo::default(); |
| 292 |
|
| 293 |
entry.uuid.copy_from_slice(meta.id.as_bytes()); |
| 294 |
|
| 295 |
entry.algorithm[..algo_bytes.len()].copy_from_slice(&algo_bytes); |
| 296 |
entry.algorithm_len = algo_bytes.len(); |
| 297 |
|
| 298 |
entry.pub_key[..pub_key.as_bytes().len()].copy_from_slice(pub_key.as_bytes()); |
| 299 |
entry.pub_key_len = pub_key.as_bytes().len(); |
| 300 |
|
| 301 |
entry.remaining_lifespan_secs = remaining; |
| 302 |
} |
| 303 |
|
| 304 |
Ok((count, has_more)) |
| 305 |
} |
| 306 |
|
| 307 |
#[unsafe(no_mangle)] |
| 308 |
pub unsafe extern "C" fn key_manager_enumerate_binding_keys( |
| 309 |
out_entries: *mut WsKeyInfo, |
| 310 |
max_entries: usize, |
| 311 |
offset: usize, |
| 312 |
out_has_more: Option<&mut bool>, |
| 313 |
) -> i32 { |
| 314 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 315 |
if out_entries.is_null() { |
| 316 |
return -1; |
| 317 |
} |
| 318 |
|
| 319 |
let entries = unsafe { slice::from_raw_parts_mut(out_entries, max_entries) }; |
| 320 |
|
| 321 |
match enumerate_binding_keys_internal(entries, offset) { |
| 322 |
Ok((count, has_more)) => { |
| 323 |
if let Some(has_more_ref) = out_has_more { |
| 324 |
*has_more_ref = has_more; |
| 325 |
} |
| 326 |
count as i32 |
| 327 |
} |
| 328 |
Err(e) => e, |
| 329 |
} |
| 330 |
})) |
| 331 |
.unwrap_or(-1) |
| 332 |
} |
| 333 |
|
| 334 |
/// Internal function to retrieve a binding key's public key and algorithm. |
| 335 |
fn get_binding_key_internal(uuid: Uuid) -> Result<(HpkeAlgorithm, PublicKey), i32> { |
| 336 |
let record = KEY_REGISTRY.get_key(&uuid).ok_or(-1)?; |
| 337 |
match &record.meta.spec { |
| 338 |
KeySpec::Binding { |
| 339 |
algo, |
| 340 |
binding_public_key, |
| 341 |
} => Ok((algo.clone(), binding_public_key.clone())), |
| 342 |
_ => Err(-1), |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
/// Retrieves the binding public key associated with the given UUID. |
| 347 |
/// |
| 348 |
/// ## Arguments |
| 349 |
/// * `uuid_bytes` - A pointer to a 16-byte buffer containing the key UUID. |
| 350 |
/// * `out_pubkey` - A pointer to a buffer where the public key will be written. |
| 351 |
/// * `out_pubkey_len` - The size of `out_pubkey` buffer. |
| 352 |
/// * `out_algo` - A pointer to a buffer where the serialized HPKE algorithm proto bytes will be written. |
| 353 |
/// * `out_algo_len` - A pointer to a `usize` that contains the size of `out_algo` buffer. On success, updated with actual size. |
| 354 |
/// |
| 355 |
/// ## Safety |
| 356 |
/// This function is unsafe because it dereferences raw pointers. |
| 357 |
/// |
| 358 |
/// ## Returns |
| 359 |
/// * `0` on success. |
| 360 |
/// * `-1` if arguments are invalid or key is not found. |
| 361 |
/// * `-2` if either output buffer is too small. |
| 362 |
#[unsafe(no_mangle)] |
| 363 |
pub unsafe extern "C" fn key_manager_get_binding_key( |
| 364 |
uuid_bytes: *const u8, |
| 365 |
out_pubkey: *mut u8, |
| 366 |
out_pubkey_len: usize, |
| 367 |
out_algo: *mut u8, |
| 368 |
out_algo_len: *mut usize, |
| 369 |
) -> i32 { |
| 370 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 371 |
if uuid_bytes.is_null() |
| 372 |
|| out_pubkey.is_null() |
| 373 |
|| out_pubkey_len == 0 |
| 374 |
|| out_algo.is_null() |
| 375 |
|| out_algo_len.is_null() |
| 376 |
{ |
| 377 |
return -1; |
| 378 |
} |
| 379 |
|
| 380 |
// Convert to Safe Types |
| 381 |
let uuid_slice = unsafe { std::slice::from_raw_parts(uuid_bytes, 16) }; |
| 382 |
let out_pubkey_slice = |
| 383 |
unsafe { std::slice::from_raw_parts_mut(out_pubkey, out_pubkey_len) }; |
| 384 |
let out_algo_len_ref = unsafe { &mut *out_algo_len }; |
| 385 |
let out_algo_slice = unsafe { std::slice::from_raw_parts_mut(out_algo, *out_algo_len) }; |
| 386 |
|
| 387 |
let uuid = match Uuid::from_slice(uuid_slice) { |
| 388 |
Ok(u) => u, |
| 389 |
Err(_) => return -1, |
| 390 |
}; |
| 391 |
|
| 392 |
// Call Safe Internal Function |
| 393 |
match get_binding_key_internal(uuid) { |
| 394 |
Ok((algo, pubkey)) => { |
| 395 |
let algo_bytes = algo.encode_to_vec(); |
| 396 |
if out_pubkey_slice.len() != pubkey.as_bytes().len() |
| 397 |
|| *out_algo_len_ref < algo_bytes.len() |
| 398 |
{ |
| 399 |
return -2; |
| 400 |
} |
| 401 |
out_pubkey_slice.copy_from_slice(pubkey.as_bytes()); |
| 402 |
out_algo_slice[..algo_bytes.len()].copy_from_slice(&algo_bytes); |
| 403 |
*out_algo_len_ref = algo_bytes.len(); |
| 404 |
0 // Success |
| 405 |
} |
| 406 |
Err(e) => e, |
| 407 |
} |
| 408 |
})) |
| 409 |
.unwrap_or(-1) |
| 410 |
} |
| 411 |
|
| 412 |
#[cfg(test)] |
| 413 |
mod tests { |
| 414 |
use super::*; |
| 415 |
use km_common::algorithms::{AeadAlgorithm, KdfAlgorithm, KemAlgorithm}; |
| 416 |
use prost::Message; |
| 417 |
|
| 418 |
struct KeyCleanup(Uuid); |
| 419 |
impl Drop for KeyCleanup { |
| 420 |
fn drop(&mut self) { |
| 421 |
let _ = KEY_REGISTRY.remove_key(&self.0); |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
#[test] |
| 426 |
fn test_create_binding_keypair_internal_success() { |
| 427 |
let algo = HpkeAlgorithm { |
| 428 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 429 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 430 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 431 |
}; |
| 432 |
|
| 433 |
let result = generate_binding_keypair_internal(algo, 3600); |
| 434 |
assert!(result.is_ok()); |
| 435 |
|
| 436 |
let (id, _) = result.unwrap(); |
| 437 |
let _cleanup = KeyCleanup(id); |
| 438 |
|
| 439 |
// Verify UUID is present |
| 440 |
assert!(!id.is_nil()); |
| 441 |
} |
| 442 |
|
| 443 |
#[test] |
| 444 |
fn test_generate_binding_keypair_ffi_success() { |
| 445 |
let mut uuid_bytes = [0u8; 16]; |
| 446 |
let mut pubkey_bytes = [0u8; 32]; |
| 447 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 448 |
let algo = HpkeAlgorithm { |
| 449 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 450 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 451 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 452 |
}; |
| 453 |
let algo_bytes = algo.encode_to_vec(); |
| 454 |
|
| 455 |
let result = unsafe { |
| 456 |
key_manager_generate_binding_keypair( |
| 457 |
algo_bytes.as_ptr(), |
| 458 |
algo_bytes.len(), |
| 459 |
3600, |
| 460 |
uuid_bytes.as_mut_ptr(), |
| 461 |
pubkey_bytes.as_mut_ptr(), |
| 462 |
pubkey_len, |
| 463 |
) |
| 464 |
}; |
| 465 |
|
| 466 |
assert_eq!(result, 0); |
| 467 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 468 |
|
| 469 |
assert_ne!(uuid_bytes, [0u8; 16]); |
| 470 |
assert_eq!(pubkey_len, 32); // X25519 public key is 32 bytes |
| 471 |
assert_ne!(&pubkey_bytes[..32], &[0u8; 32]); |
| 472 |
} |
| 473 |
|
| 474 |
#[test] |
| 475 |
fn test_generate_binding_keypair_invalid_algo() { |
| 476 |
let mut uuid_bytes = [0u8; 16]; |
| 477 |
let mut pubkey_bytes = [0u8; 32]; |
| 478 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 479 |
// Invalid protobuf bytes |
| 480 |
let algo_bytes = vec![0xFF, 0xFF]; |
| 481 |
|
| 482 |
let result = unsafe { |
| 483 |
key_manager_generate_binding_keypair( |
| 484 |
algo_bytes.as_ptr(), |
| 485 |
algo_bytes.len(), |
| 486 |
3600, |
| 487 |
uuid_bytes.as_mut_ptr(), |
| 488 |
pubkey_bytes.as_mut_ptr(), |
| 489 |
pubkey_len, |
| 490 |
) |
| 491 |
}; |
| 492 |
|
| 493 |
assert_eq!(result, -1); |
| 494 |
assert_eq!(uuid_bytes, [0u8; 16]); // Should remain untouched/zero |
| 495 |
} |
| 496 |
|
| 497 |
#[test] |
| 498 |
fn test_generate_binding_keypair_null_uuid_ptr() { |
| 499 |
let algo = HpkeAlgorithm { |
| 500 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 501 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 502 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 503 |
}; |
| 504 |
let algo_bytes = algo.encode_to_vec(); |
| 505 |
|
| 506 |
// Pass null pointers, should succeed (return 0) but not crash |
| 507 |
let result = unsafe { |
| 508 |
key_manager_generate_binding_keypair( |
| 509 |
algo_bytes.as_ptr(), |
| 510 |
algo_bytes.len(), |
| 511 |
3600, |
| 512 |
std::ptr::null_mut(), |
| 513 |
std::ptr::null_mut(), |
| 514 |
0, |
| 515 |
) |
| 516 |
}; |
| 517 |
|
| 518 |
assert_eq!(result, -1); |
| 519 |
} |
| 520 |
|
| 521 |
#[test] |
| 522 |
fn test_generate_binding_keypair_invalid_pubkey_len() { |
| 523 |
let mut uuid_bytes = [0u8; 16]; |
| 524 |
let mut pubkey_bytes = [0u8; 64]; |
| 525 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 526 |
let algo = HpkeAlgorithm { |
| 527 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 528 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 529 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 530 |
}; |
| 531 |
let algo_bytes = algo.encode_to_vec(); |
| 532 |
|
| 533 |
let result = unsafe { |
| 534 |
key_manager_generate_binding_keypair( |
| 535 |
algo_bytes.as_ptr(), |
| 536 |
algo_bytes.len(), |
| 537 |
3600, |
| 538 |
uuid_bytes.as_mut_ptr(), |
| 539 |
pubkey_bytes.as_mut_ptr(), |
| 540 |
pubkey_len, |
| 541 |
) |
| 542 |
}; |
| 543 |
|
| 544 |
assert_eq!(result, -2); |
| 545 |
assert_eq!(uuid_bytes, [0u8; 16]); // Should remain untouched/zero |
| 546 |
assert_eq!(&pubkey_bytes[..32], &[0u8; 32]); // Should remain untouched/zero |
| 547 |
} |
| 548 |
|
| 549 |
#[test] |
| 550 |
fn test_destroy_binding_key_success() { |
| 551 |
let mut uuid_bytes = [0u8; 16]; |
| 552 |
let mut pubkey_bytes = [0u8; 32]; |
| 553 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 554 |
let algo = HpkeAlgorithm { |
| 555 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 556 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 557 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 558 |
}; |
| 559 |
let algo_bytes = algo.encode_to_vec(); |
| 560 |
let res = unsafe { |
| 561 |
key_manager_generate_binding_keypair( |
| 562 |
algo_bytes.as_ptr(), |
| 563 |
algo_bytes.len(), |
| 564 |
3600, |
| 565 |
uuid_bytes.as_mut_ptr(), |
| 566 |
pubkey_bytes.as_mut_ptr(), |
| 567 |
pubkey_len, |
| 568 |
) |
| 569 |
}; |
| 570 |
assert_eq!(res, 0); |
| 571 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 572 |
|
| 573 |
let result = unsafe { key_manager_destroy_binding_key(uuid_bytes.as_ptr()) }; |
| 574 |
assert_eq!(result, 0); |
| 575 |
|
| 576 |
// Second destroy should fail |
| 577 |
let result = unsafe { key_manager_destroy_binding_key(uuid_bytes.as_ptr()) }; |
| 578 |
assert_eq!(result, -1); |
| 579 |
} |
| 580 |
|
| 581 |
#[test] |
| 582 |
fn test_destroy_binding_key_not_found() { |
| 583 |
let uuid_bytes = [0u8; 16]; |
| 584 |
let result = unsafe { key_manager_destroy_binding_key(uuid_bytes.as_ptr()) }; |
| 585 |
assert_eq!(result, -1); |
| 586 |
} |
| 587 |
|
| 588 |
#[test] |
| 589 |
fn test_destroy_binding_key_null_ptr() { |
| 590 |
let result = unsafe { key_manager_destroy_binding_key(std::ptr::null()) }; |
| 591 |
assert_eq!(result, -1); |
| 592 |
} |
| 593 |
|
| 594 |
#[test] |
| 595 |
fn test_key_manager_open_success() { |
| 596 |
let mut uuid_bytes = [0u8; 16]; |
| 597 |
let mut pubkey_bytes = [0u8; 32]; |
| 598 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 599 |
let algo = HpkeAlgorithm { |
| 600 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 601 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 602 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 603 |
}; |
| 604 |
|
| 605 |
// 1. Generate keypair |
| 606 |
let algo_bytes = algo.encode_to_vec(); |
| 607 |
unsafe { |
| 608 |
key_manager_generate_binding_keypair( |
| 609 |
algo_bytes.as_ptr(), |
| 610 |
algo_bytes.len(), |
| 611 |
3600, |
| 612 |
uuid_bytes.as_mut_ptr(), |
| 613 |
pubkey_bytes.as_mut_ptr(), |
| 614 |
pubkey_len, |
| 615 |
); |
| 616 |
} |
| 617 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 618 |
|
| 619 |
// 2. Encrypt something for this key |
| 620 |
const PT: &[u8] = b"secret message"; |
| 621 |
const AAD: &[u8] = b"test aad"; |
| 622 |
let pub_key = PublicKey::try_from(pubkey_bytes.to_vec()).unwrap(); |
| 623 |
let pt_box = km_common::crypto::secret_box::SecretBox::new(PT.to_vec()); |
| 624 |
let (enc, ct) = km_common::crypto::hpke_seal(&pub_key, &pt_box, AAD, &algo).unwrap(); |
| 625 |
|
| 626 |
// 3. Decrypt using key_manager_open |
| 627 |
let mut out_pt = [0u8; PT.len()]; |
| 628 |
let out_pt_len = out_pt.len(); |
| 629 |
let result = unsafe { |
| 630 |
key_manager_open( |
| 631 |
uuid_bytes.as_ptr(), |
| 632 |
enc.as_ptr(), |
| 633 |
enc.len(), |
| 634 |
ct.as_ptr(), |
| 635 |
ct.len(), |
| 636 |
AAD.as_ptr(), |
| 637 |
AAD.len(), |
| 638 |
out_pt.as_mut_ptr(), |
| 639 |
out_pt_len, |
| 640 |
) |
| 641 |
}; |
| 642 |
|
| 643 |
assert_eq!(result, 0); |
| 644 |
assert_eq!(&out_pt, PT); |
| 645 |
} |
| 646 |
|
| 647 |
#[test] |
| 648 |
fn test_key_manager_open_invalid_uuid() { |
| 649 |
let uuid_bytes = [0u8; 16]; |
| 650 |
let mut out_pt = [0u8; 64]; |
| 651 |
let out_pt_len = out_pt.len(); |
| 652 |
let result = unsafe { |
| 653 |
key_manager_open( |
| 654 |
uuid_bytes.as_ptr(), |
| 655 |
[0u8; 32].as_ptr(), |
| 656 |
32, |
| 657 |
[0u8; 32].as_ptr(), |
| 658 |
32, |
| 659 |
[0u8; 8].as_ptr(), |
| 660 |
8, |
| 661 |
out_pt.as_mut_ptr(), |
| 662 |
out_pt_len, |
| 663 |
) |
| 664 |
}; |
| 665 |
assert_eq!(result, -1); |
| 666 |
} |
| 667 |
|
| 668 |
#[test] |
| 669 |
fn test_key_manager_open_buffer_too_small() { |
| 670 |
let mut uuid_bytes = [0u8; 16]; |
| 671 |
let mut pubkey_bytes = [0u8; 32]; |
| 672 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 673 |
let algo = HpkeAlgorithm { |
| 674 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 675 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 676 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 677 |
}; |
| 678 |
let algo_bytes = algo.encode_to_vec(); |
| 679 |
let res = unsafe { |
| 680 |
key_manager_generate_binding_keypair( |
| 681 |
algo_bytes.as_ptr(), |
| 682 |
algo_bytes.len(), |
| 683 |
3600, |
| 684 |
uuid_bytes.as_mut_ptr(), |
| 685 |
pubkey_bytes.as_mut_ptr(), |
| 686 |
pubkey_len, |
| 687 |
) |
| 688 |
}; |
| 689 |
assert_eq!(res, 0, "Setup failed: key generation returned error"); |
| 690 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 691 |
|
| 692 |
let pt = b"secret message"; |
| 693 |
let pub_key = PublicKey::try_from(pubkey_bytes.to_vec()).unwrap(); |
| 694 |
let pt_box = km_common::crypto::secret_box::SecretBox::new(pt.to_vec()); |
| 695 |
let (enc, ct) = km_common::crypto::hpke_seal(&pub_key, &pt_box, b"", &algo).unwrap(); |
| 696 |
|
| 697 |
let mut out_pt = [0u8; 5]; // smaller than pt |
| 698 |
let out_pt_len = out_pt.len(); |
| 699 |
let result = unsafe { |
| 700 |
key_manager_open( |
| 701 |
uuid_bytes.as_ptr(), |
| 702 |
enc.as_ptr(), |
| 703 |
enc.len(), |
| 704 |
ct.as_ptr(), |
| 705 |
ct.len(), |
| 706 |
b"".as_ptr(), |
| 707 |
0, |
| 708 |
out_pt.as_mut_ptr(), |
| 709 |
out_pt_len, |
| 710 |
) |
| 711 |
}; |
| 712 |
|
| 713 |
assert_eq!(result, -2); |
| 714 |
assert_eq!(out_pt, [0u8; 5]); // Should remain untouched/zero |
| 715 |
} |
| 716 |
|
| 717 |
#[test] |
| 718 |
fn test_key_manager_enumerate_binding_keys_success() { |
| 719 |
let mut uuid_bytes = [0u8; 16]; |
| 720 |
let mut pubkey_bytes = [0u8; 32]; |
| 721 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 722 |
let algo = HpkeAlgorithm { |
| 723 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 724 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 725 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 726 |
}; |
| 727 |
let algo_bytes = algo.encode_to_vec(); |
| 728 |
|
| 729 |
// Create a key so there is something to enumerate |
| 730 |
let result = unsafe { |
| 731 |
key_manager_generate_binding_keypair( |
| 732 |
algo_bytes.as_ptr(), |
| 733 |
algo_bytes.len(), |
| 734 |
3600, |
| 735 |
uuid_bytes.as_mut_ptr(), |
| 736 |
pubkey_bytes.as_mut_ptr(), |
| 737 |
pubkey_len, |
| 738 |
) |
| 739 |
}; |
| 740 |
assert_eq!(result, 0); |
| 741 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 742 |
|
| 743 |
let mut out_entries = [WsKeyInfo::default(); 32]; |
| 744 |
let mut out_has_more = false; |
| 745 |
|
| 746 |
let enum_result = unsafe { |
| 747 |
key_manager_enumerate_binding_keys( |
| 748 |
out_entries.as_mut_ptr(), |
| 749 |
out_entries.len(), |
| 750 |
0, |
| 751 |
Some(&mut out_has_more), |
| 752 |
) |
| 753 |
}; |
| 754 |
|
| 755 |
assert!(enum_result >= 1, "Should have enumerated at least one key"); |
| 756 |
|
| 757 |
let mut found_uuid = false; |
| 758 |
for i in 0..enum_result as usize { |
| 759 |
if out_entries[i].uuid == uuid_bytes { |
| 760 |
found_uuid = true; |
| 761 |
break; |
| 762 |
} |
| 763 |
} |
| 764 |
assert!(found_uuid, "Generated UUID should be in returned keys"); |
| 765 |
} |
| 766 |
|
| 767 |
#[test] |
| 768 |
fn test_get_binding_key_success() { |
| 769 |
let mut uuid_bytes = [0u8; 16]; |
| 770 |
let mut generated_pubkey_bytes = [0u8; 32]; |
| 771 |
let pubkey_len: usize = generated_pubkey_bytes.len(); |
| 772 |
let algo = HpkeAlgorithm { |
| 773 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 774 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 775 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 776 |
}; |
| 777 |
let algo_bytes = algo.encode_to_vec(); |
| 778 |
|
| 779 |
// Generate a key to retrieve. |
| 780 |
let res = unsafe { |
| 781 |
key_manager_generate_binding_keypair( |
| 782 |
algo_bytes.as_ptr(), |
| 783 |
algo_bytes.len(), |
| 784 |
3600, |
| 785 |
uuid_bytes.as_mut_ptr(), |
| 786 |
generated_pubkey_bytes.as_mut_ptr(), |
| 787 |
pubkey_len, |
| 788 |
) |
| 789 |
}; |
| 790 |
assert_eq!(res, 0); |
| 791 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 792 |
|
| 793 |
// Now, retrieve it. |
| 794 |
let mut retrieved_pubkey_bytes = [0u8; 32]; |
| 795 |
let mut retrieved_algo_bytes = [0u8; 64]; |
| 796 |
let mut retrieved_algo_len = retrieved_algo_bytes.len(); |
| 797 |
let result = unsafe { |
| 798 |
key_manager_get_binding_key( |
| 799 |
uuid_bytes.as_ptr(), |
| 800 |
retrieved_pubkey_bytes.as_mut_ptr(), |
| 801 |
retrieved_pubkey_bytes.len(), |
| 802 |
retrieved_algo_bytes.as_mut_ptr(), |
| 803 |
&mut retrieved_algo_len, |
| 804 |
) |
| 805 |
}; |
| 806 |
|
| 807 |
assert_eq!(result, 0); |
| 808 |
assert_eq!(generated_pubkey_bytes, retrieved_pubkey_bytes); |
| 809 |
assert_eq!(algo_bytes, &retrieved_algo_bytes[..retrieved_algo_len]); |
| 810 |
} |
| 811 |
|
| 812 |
#[test] |
| 813 |
fn test_get_binding_key_not_found() { |
| 814 |
let uuid_bytes = [42u8; 16]; // Some non-existent UUID. |
| 815 |
let mut pubkey_bytes = [0u8; 32]; |
| 816 |
let mut retrieved_algo_bytes = [0u8; 64]; |
| 817 |
let mut retrieved_algo_len = retrieved_algo_bytes.len(); |
| 818 |
|
| 819 |
let result = unsafe { |
| 820 |
key_manager_get_binding_key( |
| 821 |
uuid_bytes.as_ptr(), |
| 822 |
pubkey_bytes.as_mut_ptr(), |
| 823 |
pubkey_bytes.len(), |
| 824 |
retrieved_algo_bytes.as_mut_ptr(), |
| 825 |
&mut retrieved_algo_len, |
| 826 |
) |
| 827 |
}; |
| 828 |
assert_eq!(result, -1); |
| 829 |
} |
| 830 |
} |