This document outlines security best practices for contributing to cardano-base-rust.
When writing unsafe code, always add a SAFETY comment explaining:
Example:
// SAFETY: ptr is guaranteed non-null by the caller contract.
// We verified the allocation succeeded before reaching this point.
let non_null = unsafe { NonNull::new_unchecked(ptr) };
unwrap() in production code paths
expect() with descriptive messages for programmer errors? or explicit error handling for runtime errorsResult typesthiserror crate for custom error typesGood:
pub fn parse_key(bytes: &[u8]) -> Result<Key, KeyError> {
if bytes.len() != KEY_SIZE {
return Err(KeyError::InvalidLength {
expected: KEY_SIZE,
actual: bytes.len(),
});
}
// ... safe parsing logic
}
Bad:
pub fn parse_key(bytes: &[u8]) -> Key {
assert_eq!(bytes.len(), KEY_SIZE); // DON'T PANIC ON INPUT
// ...
}
MLockedBytes for cryptographic secretsptr::write_bytes(ptr, 0, len) in Drop implementationssubtle crate for equality checks on secretsExample:
use subtle::ConstantTimeEq;
// Good: constant-time comparison
if key1.ct_eq(key2).into() {
// ...
}
// Bad: timing attack vulnerable
if key1 == key2 { // DON'T DO THIS
// ...
}
let total = size1.checked_add(size2)
.ok_or(Error::SizeOverflow)?;
Example test structure:
#[cfg(test)]
mod security_tests {
use super::*;
#[test]
fn rejects_invalid_length() {
let result = parse_key(&[0u8; 31]); // wrong size
assert!(matches!(result, Err(KeyError::InvalidLength { .. })));
}
#[test]
fn zeros_memory_on_drop() {
let mut bytes = MLockedBytes::new(32).unwrap();
bytes.as_mut_slice().fill(0xff);
let ptr = bytes.as_ptr();
drop(bytes);
// Memory should be zeroed (requires careful testing)
}
}
Before submitting a PR with security-sensitive code, verify:
unsafe blocks have SAFETY commentsunwrap() calls in production pathsDO NOT open public issues for security vulnerabilities.
Instead, email: security@intersectmbo.org
Include:
See SECURITY.md for full details.
When adding dependencies:
unsafe codecargo audit after addingcargo outdated to find updatesInstall these tools for security checking:
# Security audit
cargo install cargo-audit
# License checking
cargo install cargo-deny
# Code coverage
cargo install cargo-tarpaulin
# Fuzzing (optional)
cargo install cargo-fuzz
# Run all checks
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo audit
cargo deny check
# Generate coverage report
cargo tarpaulin --workspace --out Html
For security questions or concerns: