Files
zigp2p/tests/core/test_buffer_limits.zig
2026-02-06 21:03:59 -03:00

372 lines
13 KiB
Zig

//! Comprehensive tests for buffer overflow prevention and size limits
//!
//! This test suite validates that all size limits and buffer overflow
//! protections are working correctly across the codebase.
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
// Import modules to test
const core = @import("core");
const Error = core.errors.Error;
const Address = core.address.Address;
const AddressResolver = core.address.AddressResolver;
const MAX_DNS_RESULTS = core.address.MAX_DNS_RESULTS;
const BufferPool = core.buffer.BufferPool;
const PoolConfig = core.buffer.PoolConfig;
const files = @import("files");
const TransferMessage = files.transfer.TransferMessage;
const TransferLimits = files.transfer.TransferLimits;
const network = @import("network");
const NetworkManager = network.network_manager.NetworkManager;
const NetworkManagerConfig = network.network_manager.Config;
//============================================================================
// Transfer Message Size Limit Tests
//============================================================================
test "transfer message: reject oversized messages" {
const allocator = testing.allocator;
// Create a message with total size exceeding MAX_MESSAGE_SIZE
const huge_data = try allocator.alloc(u8, TransferLimits.MAX_MESSAGE_SIZE);
defer allocator.free(huge_data);
@memset(huge_data, 0xFF);
const message = TransferMessage{
.message_type = .piece_data,
.message_id = 123,
.peer_id = "peer123",
.data = huge_data,
.timestamp = std.time.timestamp(),
};
// Should fail due to size limit
const result = message.serialize(allocator);
try testing.expectError(Error.MessageTooLarge, result);
}
test "transfer message: reject oversized peer ID" {
const allocator = testing.allocator;
// Create peer ID exceeding MAX_PEER_ID_LEN
const huge_peer_id = try allocator.alloc(u8, TransferLimits.MAX_PEER_ID_LEN + 1);
defer allocator.free(huge_peer_id);
@memset(huge_peer_id, 'A');
// Create a valid message first
const valid_msg = TransferMessage{
.message_type = .handshake,
.message_id = 1,
.peer_id = "normal_peer",
.data = "test",
.timestamp = std.time.timestamp(),
};
const serialized = try valid_msg.serialize(allocator);
defer allocator.free(serialized);
// Manually craft a buffer with oversized peer_id_len
const buffer_size = 1024;
const bad_buffer = try allocator.alloc(u8, buffer_size);
defer allocator.free(bad_buffer);
@memset(bad_buffer, 0);
// Header: type(1) + id(4) + peer_id_len(2) + timestamp(8) + data_len(4)
bad_buffer[0] = @intFromEnum(TransferMessage.MessageType.handshake);
// Set peer_id_len to exceed limit
const bad_len: u16 = TransferLimits.MAX_PEER_ID_LEN + 1;
@memcpy(bad_buffer[5..7], &std.mem.toBytes(std.mem.nativeToBig(u16, bad_len)));
// Should fail during deserialization
const result = TransferMessage.deserialize(bad_buffer, allocator);
try testing.expectError(Error.InvalidData, result);
}
test "transfer message: reject oversized data" {
const allocator = testing.allocator;
// Manually craft a buffer with oversized data_len
const buffer_size = 1024;
const bad_buffer = try allocator.alloc(u8, buffer_size);
defer allocator.free(bad_buffer);
@memset(bad_buffer, 0);
// Header: type(1) + id(4) + peer_id_len(2) + timestamp(8) + data_len(4)
bad_buffer[0] = @intFromEnum(TransferMessage.MessageType.piece_data);
// Set small peer_id_len
const peer_len: u16 = 10;
@memcpy(bad_buffer[5..7], &std.mem.toBytes(std.mem.nativeToBig(u16, peer_len)));
// Set data_len to exceed limit
const bad_data_len: u32 = TransferLimits.MAX_DATA_LEN + 1;
@memcpy(bad_buffer[15..19], &std.mem.toBytes(std.mem.nativeToBig(u32, bad_data_len)));
// Should fail during deserialization
const result = TransferMessage.deserialize(bad_buffer, allocator);
try testing.expectError(Error.InvalidData, result);
}
test "transfer message: accept valid sized messages" {
const allocator = testing.allocator;
// Create a message within limits
const valid_data = "This is valid data";
const message = TransferMessage{
.message_type = .handshake,
.message_id = 456,
.peer_id = "valid_peer_id",
.data = valid_data,
.timestamp = std.time.timestamp(),
};
// Should succeed
const serialized = try message.serialize(allocator);
defer allocator.free(serialized);
var deserialized = try TransferMessage.deserialize(serialized, allocator);
defer deserialized.deinit(allocator);
try testing.expectEqual(message.message_type, deserialized.message_type);
try testing.expectEqual(message.message_id, deserialized.message_id);
try testing.expectEqualSlices(u8, message.peer_id, deserialized.peer_id);
try testing.expectEqualSlices(u8, message.data, deserialized.data);
}
//============================================================================
// Buffer Pool Allocation Limit Tests
//============================================================================
test "buffer pool: reject allocation exceeding max_single_allocation" {
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024,
.initial_chunks = 2,
.max_chunks = 10,
.max_single_allocation = 10 * 1024 * 1024, // 10MB
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Try to acquire buffer larger than max_single_allocation
const result = pool.acquire(config.max_single_allocation + 1);
try testing.expectError(Error.AllocationTooLarge, result);
}
test "buffer pool: accept allocation within max_single_allocation" {
const config = PoolConfig{
.min_chunk_size = 1024,
.max_chunk_size = 1024 * 1024,
.initial_chunks = 2,
.max_chunks = 10,
.max_single_allocation = 10 * 1024 * 1024, // 10MB
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Acquire buffer within limits
const buffer = try pool.acquire(1024);
try testing.expect(buffer.len == 1024);
pool.release(buffer);
}
test "buffer pool: enforce maximum allocation size" {
const config = PoolConfig{
.max_single_allocation = 1024, // Very small limit for testing
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Try various sizes
try testing.expectError(Error.AllocationTooLarge, pool.acquire(1025));
try testing.expectError(Error.AllocationTooLarge, pool.acquire(2048));
try testing.expectError(Error.AllocationTooLarge, pool.acquire(10000));
// This should work
const valid = try pool.acquire(1024);
try testing.expect(valid.len == 1024);
pool.release(valid);
}
//============================================================================
// Network Manager Buffer Size Tests
//============================================================================
test "network manager: configurable receive buffer size" {
const config = NetworkManagerConfig{
.receive_buffer_size = 8192, // 8KB
.max_message_size = 4096, // 4KB
};
var connections = std.AutoHashMap(network.peer.PeerId, *core.socket.Socket).init(testing.allocator);
defer connections.deinit();
var manager = NetworkManager.initWithConfig(testing.allocator, &connections, config);
defer manager.deinit();
try testing.expectEqual(@as(usize, 8192), manager.config.receive_buffer_size);
try testing.expectEqual(@as(usize, 4096), manager.config.max_message_size);
}
//============================================================================
// DNS Resolution Limit Tests
//============================================================================
test "dns resolution: limit results to MAX_DNS_RESULTS" {
// Note: This is a conceptual test. Actual DNS resolution would require
// a real network connection or mock. We verify the constant exists.
try testing.expect(MAX_DNS_RESULTS == 100);
}
test "address resolver: verify MAX_DNS_RESULTS constant" {
// Verify the constant is properly defined
const max_results: usize = MAX_DNS_RESULTS;
try testing.expect(max_results > 0);
try testing.expect(max_results <= 1000); // Reasonable upper bound
}
//============================================================================
// Integration Tests
//============================================================================
test "integration: transfer limits prevent resource exhaustion" {
// Verify all limits are reasonable and coordinated
try testing.expect(TransferLimits.MAX_PEER_ID_LEN < TransferLimits.MAX_MESSAGE_SIZE);
try testing.expect(TransferLimits.MAX_DATA_LEN < TransferLimits.MAX_MESSAGE_SIZE);
try testing.expect(TransferLimits.MAX_HANDSHAKE_SIZE < TransferLimits.MAX_MESSAGE_SIZE);
// Verify limits are large enough for practical use
try testing.expect(TransferLimits.MAX_PEER_ID_LEN >= 64);
try testing.expect(TransferLimits.MAX_DATA_LEN >= 1024 * 1024); // At least 1MB
try testing.expect(TransferLimits.MAX_MESSAGE_SIZE >= 1024 * 1024); // At least 1MB
}
test "integration: buffer pool limits prevent memory exhaustion" {
const default_config = PoolConfig{};
// Verify defaults are reasonable
try testing.expect(default_config.max_single_allocation > default_config.max_chunk_size);
try testing.expect(default_config.max_chunks > 0);
try testing.expect(default_config.initial_chunks <= default_config.max_chunks);
}
test "integration: network manager config prevents stack overflow" {
const default_config = NetworkManagerConfig{};
// Verify receive buffer is allocated on heap (not stack)
// Stack allocation was 65536 bytes, now configurable
try testing.expect(default_config.receive_buffer_size == 64 * 1024);
try testing.expect(default_config.max_message_size <= default_config.receive_buffer_size * 16);
}
//============================================================================
// Edge Case Tests
//============================================================================
test "edge case: zero-sized allocations" {
var pool = BufferPool.init(.{}, testing.allocator);
defer pool.deinit();
// Zero-sized allocation should be handled gracefully
const result = pool.acquire(0);
if (result) |buffer| {
try testing.expect(buffer.len == 0);
pool.release(buffer);
} else |_| {
// Also acceptable to reject zero-sized allocations
}
}
test "edge case: boundary conditions for transfer limits" {
const allocator = testing.allocator;
// Test at exact limits
const peer_id = try allocator.alloc(u8, TransferLimits.MAX_PEER_ID_LEN);
defer allocator.free(peer_id);
@memset(peer_id, 'A');
const data = try allocator.alloc(u8, 1024);
defer allocator.free(data);
@memset(data, 'B');
const message = TransferMessage{
.message_type = .handshake,
.message_id = 999,
.peer_id = peer_id,
.data = data,
.timestamp = std.time.timestamp(),
};
// Should succeed if total size is within limit
const total_size = TransferMessage.HEADER_SIZE + peer_id.len + data.len;
if (total_size <= TransferLimits.MAX_MESSAGE_SIZE) {
const serialized = try message.serialize(allocator);
defer allocator.free(serialized);
try testing.expect(serialized.len > 0);
}
}
//============================================================================
// Performance/Stress Tests
//============================================================================
test "stress: multiple allocations within limits" {
const config = PoolConfig{
.max_single_allocation = 1024 * 1024, // 1MB
.max_chunks = 100,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
// Allocate and release many buffers
var i: usize = 0;
while (i < 50) : (i += 1) {
const size = (i + 1) * 1024; // 1KB, 2KB, 3KB, ...
if (size <= config.max_single_allocation) {
const buffer = try pool.acquire(size);
pool.release(buffer);
}
}
// Check pool stats
const stats = pool.stats();
try testing.expect(stats.total_chunks > 0);
}
test "stress: rapid allocation and deallocation" {
const config = PoolConfig{
.min_chunk_size = 512,
.max_chunk_size = 4096,
.max_single_allocation = 8192,
.initial_chunks = 4,
.max_chunks = 20,
};
var pool = BufferPool.init(config, testing.allocator);
defer pool.deinit();
var buffers: [10][]u8 = undefined;
// Allocate 10 buffers
for (&buffers, 0..) |*buf, idx| {
buf.* = try pool.acquire(1024 + idx * 128);
}
// Release them in reverse order
var idx: usize = buffers.len;
while (idx > 0) {
idx -= 1;
pool.release(buffers[idx]);
}
// Verify pool is in good state
const stats = pool.stats();
try testing.expect(stats.free_chunks + stats.used_chunks == stats.total_chunks);
}