//! Message serialization and deserialization const std = @import("std"); const protocol = @import("protocol.zig"); const message = @import("message.zig"); const crypto = @import("crypto.zig"); const platform_time = @import("platform").time; /// Helper to read little-endian integers from buffer slices fn readLittle(comptime T: type, buf: []const u8) T { const size = @divExact(@typeInfo(T).int.bits, 8); return std.mem.readInt(T, buf[0..size], .little); } const core = @import("core"); /// Memory exhaustion protection limits /// MED-12 FIX: Added runtime accessors for centralized limits configuration pub const Limits = struct { // Compile-time constants for backwards compatibility pub const MAX_MESSAGE_SIZE: usize = 64 * 1024 * 1024; // 64MB max total message pub const MAX_PAYLOAD_SIZE: usize = 16 * 1024 * 1024; // 16MB max payload pub const MAX_DATA_ID_LENGTH: usize = 4096; // 4KB max data ID pub const MAX_TOPOLOGY_DATA_SIZE: usize = 1024 * 1024; // 1MB max topology data pub const MAX_ROUTE_INFO_SIZE: usize = 512 * 1024; // 512KB max route info pub const MAX_ERROR_MESSAGE_LENGTH: usize = 4096; // 4KB max error message pub const MAX_APP_DATA_SIZE: usize = 8 * 1024 * 1024; // 8MB max app data pub const MAX_PEER_LIST_SIZE: usize = 1000; // Max peers in discovery response pub const MAX_NODE_LIST_SIZE: usize = 1000; // Max nodes in topology messages /// Get max message size from centralized config pub fn maxMessageSize() usize { return core.limits.global.network.max_message_size; } /// Get max piece data size from centralized config pub fn maxPieceDataSize() usize { return core.limits.global.file.max_piece_data_size; } }; /// Serialization error types pub const SerializationError = error{ InvalidMagicNumber, UnsupportedVersion, MessageTooLarge, InvalidMessageType, SerializationFailed, DeserializationFailed, ChecksumMismatch, BufferTooSmall, InvalidLength, AuthenticationFailed, /// SECURITY: Message authentication (HMAC) is required but was not present AuthenticationRequired, NoHmacKey, DecryptionFailed, PayloadTooLarge, DataIdTooLong, TooManyItems, TopologyDataTooLarge, RouteInfoTooLarge, ErrorMessageTooLong, AppDataTooLarge, /// SECURITY: Encryption is required but crypto manager not configured EncryptionRequired, /// SECURITY: No encryption key available for the target peer NoKeyForPeer, /// Message type is not yet implemented (e.g., DHT messages pending full implementation) UnsupportedMessageType, /// CRIT-NEW-9 FIX: crypto_manager is required but not set /// This error occurs when trying to serialize/deserialize without proper crypto setup NoCryptoManager, }; /// Safe addition that returns null on overflow /// Public for testing overflow protection pub fn safeAdd(a: usize, b: usize) ?usize { return std.math.add(usize, a, b) catch null; } /// Check buffer bounds with overflow protection /// This function ensures that offset + required does not overflow /// and that the resulting end position is within buffer bounds. /// Public for testing overflow protection pub fn checkBounds(buffer: []const u8, offset: usize, required: usize) SerializationError!void { // First check if offset is already beyond buffer if (offset > buffer.len) return SerializationError.BufferTooSmall; // Then check if required length would overflow or exceed buffer const end = safeAdd(offset, required) orelse return SerializationError.InvalidLength; if (end > buffer.len) return SerializationError.BufferTooSmall; } // SEC-M9 FIX: Removed redundant CRC32 implementation. // HMAC-SHA256 already provides message integrity (as well as authentication). // Using CRC32 alongside HMAC is redundant and wastes CPU cycles. // All message integrity is now handled by the HMAC in serializeWithAuth/deserializeWithAuth. /// Serializer for message types pub const MessageSerializer = struct { /// SECURITY: Authentication is MANDATORY. This is a compile-time constant. /// Disabling authentication would allow message forgery and tampering. const REQUIRE_AUTHENTICATION: bool = true; /// SECURITY: Encryption is MANDATORY. This is a compile-time constant. /// Disabling encryption would allow message eavesdropping and data exposure. pub const REQUIRE_ENCRYPTION: bool = true; allocator: std.mem.Allocator, crypto_manager: ?*crypto.CryptoManager, /// Local node's peer ID (used as source in outgoing messages) local_peer_id: [32]u8, /// Target peer ID for encryption/decryption key lookup peer_id: [32]u8, /// CRIT-NEW-9 FIX: Flag to indicate test mode (allows null crypto_manager) /// This MUST only be true for test code - production code MUST have crypto is_test_mode: bool, /// SECURITY: This initializer creates a serializer WITHOUT encryption. /// CRIT-NEW-9: This will fail at runtime if crypto_manager is not set before use. /// Use initWithCrypto() or initFull() for production use. /// Use setCryptoManager() if you need deferred crypto setup. pub fn init(allocator: std.mem.Allocator) MessageSerializer { return .{ .allocator = allocator, .crypto_manager = null, .local_peer_id = [_]u8{0} ** 32, .peer_id = [_]u8{0} ** 32, .is_test_mode = false, // CRIT-NEW-9: Will fail without crypto }; } pub fn initWithCrypto(allocator: std.mem.Allocator, crypto_manager: *crypto.CryptoManager, peer_id: [32]u8) MessageSerializer { return .{ .allocator = allocator, .crypto_manager = crypto_manager, .local_peer_id = peer_id, // For backwards compatibility, use peer_id as local .peer_id = peer_id, .is_test_mode = false, }; } /// Initialize with explicit local and remote peer IDs pub fn initFull( allocator: std.mem.Allocator, crypto_manager: *crypto.CryptoManager, local_peer_id: [32]u8, remote_peer_id: [32]u8, ) MessageSerializer { return .{ .allocator = allocator, .crypto_manager = crypto_manager, .local_peer_id = local_peer_id, .peer_id = remote_peer_id, .is_test_mode = false, }; } /// TESTING ONLY: Create an insecure serializer for testing /// This bypasses authentication checks - DO NOT use in production /// CRIT-3 FIX: This function is only available in debug/test builds /// In release builds, attempting to call this will cause a compile error pub fn initInsecureForTesting(allocator: std.mem.Allocator) MessageSerializer { // CRIT-3 FIX: Disable insecure initialization in release builds const is_debug = @import("builtin").mode == .Debug; const is_test = @import("builtin").is_test; if (!is_debug and !is_test) { @compileError("CRIT-3 SECURITY: initInsecureForTesting() is disabled in release builds. Use init() with a CryptoManager for production."); } return .{ .allocator = allocator, .crypto_manager = null, .local_peer_id = [_]u8{0} ** 32, .peer_id = [_]u8{0} ** 32, .is_test_mode = true, }; } /// CRIT-NEW-9 FIX: Set crypto manager after initialization /// This allows deferred crypto setup while maintaining security enforcement pub fn setCryptoManager(self: *MessageSerializer, crypto_manager: *crypto.CryptoManager) void { self.crypto_manager = crypto_manager; } /// Set destination peer for this serializer pub fn setDestinationPeer(self: *MessageSerializer, dest_peer_id: [32]u8) void { self.peer_id = dest_peer_id; } /// Serialize a message to bytes with HMAC authentication /// CRIT-NEW-9 FIX: crypto_manager is now required for all non-test serialization pub fn serialize(self: *MessageSerializer, msg: message.Message, buffer: []u8) SerializationError!usize { // CRIT-NEW-9 FIX: Enforce crypto_manager is set for production use // This prevents accidentally sending unauthenticated messages if (self.crypto_manager == null and !self.is_test_mode) { core.log.err("SECURITY CRIT-NEW-9: Attempted to serialize without crypto_manager - ALL messages MUST be authenticated", .{}); return SerializationError.NoCryptoManager; } var header = self.getHeaderForMessage(msg); const header_size = @sizeOf(message.MessageHeader); if (buffer.len < protocol.Serialization.HEADER_SIZE + header_size) { return SerializationError.BufferTooSmall; } // Check if we should authenticate this message const should_authenticate = self.crypto_manager != null and self.shouldAuthenticateMessage(); // Calculate base size (header + payload) using checked arithmetic to prevent overflow const payload_size = self.getPayloadSize(msg); const base_size = std.math.add(usize, protocol.Serialization.HEADER_SIZE, header_size) catch { return SerializationError.MessageTooLarge; }; const base_size_with_payload = std.math.add(usize, base_size, payload_size) catch { return SerializationError.MessageTooLarge; }; // If authenticating, add space for HMAC (32 bytes) const hmac_size: usize = if (should_authenticate) 32 else 0; const total_size = std.math.add(usize, base_size_with_payload, hmac_size) catch { return SerializationError.MessageTooLarge; }; if (total_size > buffer.len) { return SerializationError.BufferTooSmall; } if (base_size_with_payload > protocol.ProtocolHelpers.getMessageSizeLimit(msg.getType())) { return SerializationError.MessageTooLarge; } // Set AUTHENTICATED flag if we're authenticating if (should_authenticate) { header.flags |= protocol.MessageFlags.AUTHENTICATED; } // Serialize header const header_bytes = buffer[0..protocol.Serialization.HEADER_SIZE]; self.serializeHeader(header, header_bytes) catch return SerializationError.SerializationFailed; // Serialize payload const payload_start = protocol.Serialization.HEADER_SIZE + header_size; const payload_bytes = buffer[payload_start..]; try self.serializePayload(msg, payload_bytes); // Compute and append HMAC if authenticating if (should_authenticate) { const hmac_key = if (self.crypto_manager) |cm| cm.getHmacKeyForPeer(self.peer_id) catch return SerializationError.NoHmacKey else return SerializationError.NoHmacKey; // Compute HMAC over entire message (header + payload, excluding HMAC itself) const data_to_auth = buffer[0..base_size_with_payload]; const mac = crypto.HmacAuthenticator.computeHmac(hmac_key, data_to_auth); // Append HMAC to message (after payload) @memcpy(buffer[base_size_with_payload..base_size_with_payload + 32], &mac); } return total_size; } /// Check if message should be authenticated fn shouldAuthenticateMessage(self: *MessageSerializer) bool { _ = self; // For now, authenticate all messages when crypto_manager is available // Can be extended to check message type or other criteria return true; } /// Check if a message type should be encrypted /// Key exchange messages MUST NOT be encrypted (they're used to establish encryption) fn shouldEncryptMessageType(msg_type: protocol.MessageType) bool { return switch (msg_type) { // SEC-H2: Key confirmation also not encrypted (sent during key exchange phase) .key_exchange_init, .key_exchange_response, .key_confirmation => false, else => true, }; } /// Serialize a message with encryption support /// If encryption is enabled and the message type supports it, the payload /// will be encrypted using ChaCha20-Poly1305. /// /// Message format with encryption: /// [header][encrypted_payload][HMAC] /// Where encrypted_payload = nonce(12) + ciphertext + tag(16) pub fn serializeEncrypted(self: *MessageSerializer, msg: message.Message, buffer: []u8) SerializationError!usize { // First, check if we should encrypt this message const msg_type = msg.getType(); // SECURITY: Fail if encryption is required but not available if (comptime REQUIRE_ENCRYPTION) { if (self.crypto_manager == null) { core.log.err("SECURITY: Encryption required but no crypto manager configured", .{}); return SerializationError.EncryptionRequired; } const cm = self.crypto_manager.?; // SECURITY: Fail if we don't have a key for this peer if (!cm.hasKeyForPeer(self.peer_id) and shouldEncryptMessageType(msg_type)) { core.log.err("SECURITY: Encryption required but no key for peer", .{}); return SerializationError.NoKeyForPeer; } } const should_encrypt = (comptime REQUIRE_ENCRYPTION) and self.crypto_manager != null and shouldEncryptMessageType(msg_type); if (!should_encrypt) { // Only allow unencrypted for message types that explicitly don't need encryption // (like key exchange messages) return self.serialize(msg, buffer); } const cm = self.crypto_manager orelse return SerializationError.EncryptionRequired; // Serialize the payload to a temporary buffer first var header = self.getHeaderForMessage(msg); const header_size = @sizeOf(message.MessageHeader); const payload_size = self.getPayloadSize(msg); // Allocate temporary buffer for plaintext payload const temp_buffer = self.allocator.alloc(u8, payload_size) catch { return SerializationError.BufferTooSmall; }; defer self.allocator.free(temp_buffer); // Serialize payload to temp buffer try self.serializePayload(msg, temp_buffer); // Encrypt the payload: nonce(12) + ciphertext + tag(16) const encrypted_payload = cm.encrypt(self.peer_id, temp_buffer) catch |err| { return switch (err) { crypto.CryptoError.NoKeyForPeer => SerializationError.NoHmacKey, crypto.CryptoError.OutOfMemory => SerializationError.BufferTooSmall, else => SerializationError.SerializationFailed, }; }; defer self.allocator.free(encrypted_payload); // Calculate sizes const base_size = protocol.Serialization.HEADER_SIZE + header_size + encrypted_payload.len; const should_authenticate = self.shouldAuthenticateMessage(); const hmac_size: usize = if (should_authenticate) 32 else 0; const total_size = base_size + hmac_size; if (total_size > buffer.len) { return SerializationError.BufferTooSmall; } // Set flags header.flags |= protocol.MessageFlags.ENCRYPTED; if (should_authenticate) { header.flags |= protocol.MessageFlags.AUTHENTICATED; } // Serialize header const header_bytes = buffer[0..protocol.Serialization.HEADER_SIZE]; self.serializeHeader(header, header_bytes) catch return SerializationError.SerializationFailed; // Copy encrypted payload const payload_start = protocol.Serialization.HEADER_SIZE + header_size; @memcpy(buffer[payload_start .. payload_start + encrypted_payload.len], encrypted_payload); // Add HMAC if authenticating if (should_authenticate) { const hmac_key = cm.getHmacKeyForPeer(self.peer_id) catch return SerializationError.NoHmacKey; const data_to_auth = buffer[0..base_size]; const mac = crypto.HmacAuthenticator.computeHmac(hmac_key, data_to_auth); @memcpy(buffer[base_size .. base_size + 32], &mac); } return total_size; } /// Deserialize a message from bytes with HMAC verification /// CRIT-NEW-9 FIX: crypto_manager is now required for all non-test deserialization pub fn deserialize(self: *MessageSerializer, buffer: []const u8) SerializationError!message.BaseMessage { // CRIT-NEW-9 FIX: Enforce crypto_manager is set for production use // This prevents accidentally accepting unauthenticated messages if (self.crypto_manager == null and !self.is_test_mode) { core.log.err("SECURITY CRIT-NEW-9: Attempted to deserialize without crypto_manager - ALL messages MUST be verified", .{}); return SerializationError.NoCryptoManager; } if (buffer.len < protocol.Serialization.HEADER_SIZE) { return SerializationError.BufferTooSmall; } // Deserialize header const header_bytes = buffer[0..protocol.Serialization.HEADER_SIZE]; const header = try self.deserializeHeader(header_bytes); // Validate magic number if (header.magic != protocol.Serialization.MAGIC_NUMBER) { return SerializationError.InvalidMagicNumber; } // Validate version if (!protocol.ProtocolHelpers.isVersionCompatible(header.version)) { return SerializationError.UnsupportedVersion; } // Validate message type if (!protocol.ProtocolHelpers.isValidMessageType(header.msg_type)) { return SerializationError.InvalidMessageType; } // Check if message is authenticated const is_authenticated = (header.flags & protocol.MessageFlags.AUTHENTICATED) != 0; // Calculate expected size with or without HMAC const header_size = @sizeOf(message.MessageHeader); const payload_start = protocol.Serialization.HEADER_SIZE + header_size; if (is_authenticated) { // Message should have HMAC appended (32 bytes) if (buffer.len < payload_start + 32) { return SerializationError.BufferTooSmall; } // Extract HMAC from end of message const hmac_start = buffer.len - 32; const provided_hmac = buffer[hmac_start..buffer.len][0..32].*; // SECURITY FIX: Use self.peer_id (from the connection/session) instead of // header.source (which is unauthenticated and can be spoofed). // The peer_id should be set based on the network connection, not the message. // // This prevents source field spoofing attacks where an attacker could: // 1. Claim to be peer A in the header // 2. Cause us to look up peer A's HMAC key // 3. Bypass authentication if they know peer A's key // // By using self.peer_id (the actual connected peer), we verify against // the correct key for the connection. const hmac_key = if (self.crypto_manager) |cm| cm.getHmacKeyForPeer(self.peer_id) catch return SerializationError.NoHmacKey else return SerializationError.NoHmacKey; // Verify HMAC over entire message (excluding HMAC itself) const data_to_verify = buffer[0..hmac_start]; if (!crypto.HmacAuthenticator.verifyHmac(hmac_key, data_to_verify, provided_hmac)) { std.log.warn("SECURITY: HMAC verification failed for peer {any}", .{self.peer_id[0..8].*}); return SerializationError.AuthenticationFailed; } // SECURITY: Verify source field matches authenticated peer (timing-safe comparison) if (!std.crypto.timing_safe.eql([32]u8, header.source, self.peer_id)) { core.log.err("SECURITY: Source field spoofing detected! Header claims source={any}, but authenticated peer={any}", .{ header.source[0..8].*, self.peer_id[0..8].*, }); return SerializationError.AuthenticationFailed; } // Extract payload (between header and HMAC) if (payload_start >= hmac_start) { return message.BaseMessage{ .header = header, .payload = &.{} }; } // SECURITY: Bounds check before accessing buffer slice try checkBounds(buffer, payload_start, hmac_start - payload_start); const payload = buffer[payload_start..hmac_start]; return message.BaseMessage{ .header = header, .payload = payload }; } else { // SECURITY: Reject unauthenticated messages (always required) if (comptime REQUIRE_AUTHENTICATION) { core.log.err("SECURITY: Received unauthenticated message but authentication is required", .{}); return SerializationError.AuthenticationRequired; } // Unauthenticated message (unreachable in production due to compile-time check) if (payload_start >= buffer.len) { return message.BaseMessage{ .header = header, .payload = &.{} }; } const payload = buffer[payload_start..]; return message.BaseMessage{ .header = header, .payload = payload }; } } /// Deserialize and decrypt an encrypted message /// This handles messages encrypted with serializeEncrypted. /// /// The function: /// 1. Verifies HMAC (if AUTHENTICATED flag is set) /// 2. Decrypts payload (if ENCRYPTED flag is set) /// 3. Returns the decrypted base message /// /// MEMORY NOTE: If the message is encrypted, this allocates a new buffer /// for the decrypted payload. The caller must free it using the allocator /// from the returned DecryptedMessage. pub const DecryptedMessage = struct { base: message.BaseMessage, /// If non-null, this is an allocated buffer that must be freed decrypted_payload: ?[]u8, allocator: std.mem.Allocator, pub fn deinit(self: *DecryptedMessage) void { if (self.decrypted_payload) |payload| { self.allocator.free(payload); } } }; pub fn deserializeDecrypted(self: *MessageSerializer, buffer: []const u8) SerializationError!DecryptedMessage { if (buffer.len < protocol.Serialization.HEADER_SIZE) { return SerializationError.BufferTooSmall; } // Deserialize header const header_bytes = buffer[0..protocol.Serialization.HEADER_SIZE]; const header = try self.deserializeHeader(header_bytes); // Validate magic number if (header.magic != protocol.Serialization.MAGIC_NUMBER) { return SerializationError.InvalidMagicNumber; } // Validate version if (!protocol.ProtocolHelpers.isVersionCompatible(header.version)) { return SerializationError.UnsupportedVersion; } // Validate message type if (!protocol.ProtocolHelpers.isValidMessageType(header.msg_type)) { return SerializationError.InvalidMessageType; } // Check flags const is_authenticated = (header.flags & protocol.MessageFlags.AUTHENTICATED) != 0; const is_encrypted = (header.flags & protocol.MessageFlags.ENCRYPTED) != 0; // SECURITY: Reject unauthenticated messages (always required) if (!is_authenticated and comptime REQUIRE_AUTHENTICATION) { core.log.err("SECURITY: Received unauthenticated message but authentication is required", .{}); return SerializationError.AuthenticationRequired; } // Calculate expected size const header_size = @sizeOf(message.MessageHeader); const payload_start = protocol.Serialization.HEADER_SIZE + header_size; // Determine where payload ends var payload_end = buffer.len; if (is_authenticated) { if (buffer.len < payload_start + 32) { return SerializationError.BufferTooSmall; } payload_end = buffer.len - 32; // SECURITY FIX: Verify HMAC using self.peer_id (from connection) instead of // untrusted header.source field. See comments in deserialize() for details. const provided_hmac = buffer[payload_end..buffer.len][0..32].*; const hmac_key = if (self.crypto_manager) |cm| cm.getHmacKeyForPeer(self.peer_id) catch return SerializationError.NoHmacKey else return SerializationError.NoHmacKey; const data_to_verify = buffer[0..payload_end]; if (!crypto.HmacAuthenticator.verifyHmac(hmac_key, data_to_verify, provided_hmac)) { std.log.warn("SECURITY: HMAC verification failed for peer {any}", .{self.peer_id[0..8].*}); return SerializationError.AuthenticationFailed; } // SECURITY: Verify source field matches authenticated peer (timing-safe comparison) if (!std.crypto.timing_safe.eql([32]u8, header.source, self.peer_id)) { core.log.err("SECURITY: Source field spoofing detected! Header claims source={any}, but authenticated peer={any}", .{ header.source[0..8].*, self.peer_id[0..8].*, }); return SerializationError.AuthenticationFailed; } } // Extract payload if (payload_start >= payload_end) { return DecryptedMessage{ .base = message.BaseMessage{ .header = header, .payload = &.{} }, .decrypted_payload = null, .allocator = self.allocator, }; } const encrypted_payload = buffer[payload_start..payload_end]; // Decrypt if encrypted if (is_encrypted) { const cm = self.crypto_manager orelse return SerializationError.NoHmacKey; const decrypted = cm.decrypt(header.source, encrypted_payload) catch |err| { return switch (err) { crypto.CryptoError.NoKeyForPeer => SerializationError.NoHmacKey, crypto.CryptoError.InvalidCiphertext => SerializationError.DecryptionFailed, crypto.CryptoError.DecryptionFailed => SerializationError.DecryptionFailed, crypto.CryptoError.OutOfMemory => SerializationError.BufferTooSmall, else => SerializationError.SerializationFailed, }; }; return DecryptedMessage{ .base = message.BaseMessage{ .header = header, .payload = decrypted }, .decrypted_payload = decrypted, .allocator = self.allocator, }; } // Not encrypted, return as-is return DecryptedMessage{ .base = message.BaseMessage{ .header = header, .payload = encrypted_payload }, .decrypted_payload = null, .allocator = self.allocator, }; } /// Get the full message by deserializing payload pub fn deserializeFull(self: *MessageSerializer, base_msg: message.BaseMessage) SerializationError!message.Message { return switch (base_msg.header.msg_type) { .discovery_hello => .{ .discovery_hello = try self.deserializeDiscoveryHello(base_msg.payload), }, .discovery_response => .{ .discovery_response = try self.deserializeDiscoveryResponse(base_msg.payload), }, .discovery_announce => .{ .discovery_announce = try self.deserializeDiscoveryAnnounce(base_msg.payload), }, .topology_query => .{ .topology_query = try self.deserializeTopologyQuery(base_msg.payload), }, .topology_response => .{ .topology_response = try self.deserializeTopologyResponse(base_msg.payload), }, .topology_update => .{ .topology_update = try self.deserializeTopologyUpdate(base_msg.payload), }, .data_request => .{ .data_request = try self.deserializeDataRequest(base_msg.payload), }, .data_response => .{ .data_response = try self.deserializeDataResponse(base_msg.payload), }, .data_chunk => .{ .data_chunk = try self.deserializeDataChunk(base_msg.payload), }, .route_query => .{ .route_query = try self.deserializeRouteQuery(base_msg.payload), }, .route_response => .{ .route_response = try self.deserializeRouteResponse(base_msg.payload), }, .route_update => .{ .route_update = try self.deserializeRouteUpdate(base_msg.payload), }, .ping => .{ .ping = try self.deserializePing(base_msg.payload), }, .pong => .{ .pong = try self.deserializePong(base_msg.payload), }, .err => .{ .err = try self.deserializeError(base_msg.payload), }, .key_exchange_init => .{ .key_exchange_init = try self.deserializeKeyExchangeInit(base_msg.payload), }, .key_exchange_response => .{ .key_exchange_response = try self.deserializeKeyExchangeResponse(base_msg.payload), }, .key_confirmation => .{ .key_confirmation = try self.deserializeKeyConfirmation(base_msg.payload), }, .app_data => .{ .app_data = try self.deserializeAppData(base_msg.payload), }, .app_control => .{ .app_control = try self.deserializeAppControl(base_msg.payload), }, // DHT message types - return error until DHT is fully implemented .dht_find_node, .dht_find_node_response, .dht_store, .dht_store_response, .dht_find_value, .dht_find_value_response, => return SerializationError.UnsupportedMessageType, }; } /// Get header for message fn getHeaderForMessage(self: *MessageSerializer, msg: message.Message) message.MessageHeader { const id = msg.getId() orelse 0; return .{ .msg_type = msg.getType(), .id = id, .source = self.local_peer_id, .dest = self.peer_id, .timestamp = platform_time.timestamp(), }; } /// Get payload size for message with overflow protection fn getPayloadSize(self: *MessageSerializer, msg: message.Message) usize { _ = self; return switch (msg) { .discovery_hello => |hello| blk: { const base = 2 + 4 + @sizeOf(message.NetworkAddress); break :blk if (hello.isSigned()) base + 64 + 32 + 8 else base; }, .discovery_response => |resp| blk: { const base = 8 + 4 + @sizeOf(message.NetworkAddress); break :blk if (resp.isSigned()) base + 64 + 32 + 8 else base; }, .discovery_announce => |announce| blk: { const base = 4 + @sizeOf(message.NetworkAddress) + 1; // +1 for TTL break :blk if (announce.isSigned()) base + 64 + 32 + 8 else base; }, .topology_query => 8 + 1, .topology_response => |resp| blk: { // Safe addition with overflow check break :blk safeAdd(8, resp.topology_data.len) orelse std.math.maxInt(usize); }, .topology_update => |update| blk: { // Safe addition with overflow check break :blk safeAdd(4, update.changes.len) orelse std.math.maxInt(usize); }, .data_request => |req| blk: { // Safe addition with overflow check: 8 + 4 + data_id.len + 8 + 4 const base = safeAdd(8, 4) orelse std.math.maxInt(usize); const with_id = safeAdd(base, req.data_id.len) orelse std.math.maxInt(usize); const with_offset = safeAdd(with_id, 8) orelse std.math.maxInt(usize); break :blk safeAdd(with_offset, 4) orelse std.math.maxInt(usize); }, .data_response => |resp| blk: { // Safe addition with overflow check: 8 + 4 + data_id.len + 4 + data.len const base = safeAdd(8, 4) orelse std.math.maxInt(usize); const with_id = safeAdd(base, resp.data_id.len) orelse std.math.maxInt(usize); const with_len = safeAdd(with_id, 4) orelse std.math.maxInt(usize); break :blk safeAdd(with_len, resp.data.len) orelse std.math.maxInt(usize); }, .data_chunk => |chunk| blk: { // Safe addition with overflow check: 4 + 4 + data_id.len + 1 + chunk_data.len const base = safeAdd(4, 4) orelse std.math.maxInt(usize); const with_id = safeAdd(base, chunk.data_id.len) orelse std.math.maxInt(usize); const with_flag = safeAdd(with_id, 1) orelse std.math.maxInt(usize); break :blk safeAdd(with_flag, chunk.chunk_data.len) orelse std.math.maxInt(usize); }, .route_query => 8 + protocol.Network.NODE_ID_SIZE, .route_response => |resp| blk: { // HIGH-5 FIX: Updated size calculation with security fields // Format: query_id(8) + has_next_hop(1) + [next_hop(32)] + signature(64) + signer_id(32) + timestamp(8) + origin(32) + route_info const base_size = 8 + 1 + 64 + 32 + 8 + 32; // Without next_hop const next_hop_size: usize = if (resp.next_hop != null) 32 else 0; const with_hop = safeAdd(base_size, next_hop_size) orelse std.math.maxInt(usize); break :blk safeAdd(with_hop, resp.route_info.len) orelse std.math.maxInt(usize); }, .route_update => |update| blk: { // Safe addition with overflow check break :blk safeAdd(4, update.route_changes.len) orelse std.math.maxInt(usize); }, .ping => 4, .pong => 8, .err => |err_msg| blk: { // Safe addition with overflow check: 8 + 2 + message.len const base = safeAdd(8, 2) orelse std.math.maxInt(usize); break :blk safeAdd(base, err_msg.message.len) orelse std.math.maxInt(usize); }, .key_exchange_init => 168, // public_key(32) + signature(64) + identity_key(32) + session_nonce(32) + timestamp(8) .key_exchange_response => 168, // public_key(32) + signature(64) + identity_key(32) + timestamp(8) + initiator_session_nonce(32) .key_confirmation => 32, // SEC-H2: confirmation_tag(32) // DHT messages - basic size calculations .dht_find_node => 8 + 32 + 32, // request_id + target_id + sender_id .dht_find_node_response => |resp| blk: { // 8 (request_id) + array of NodeInfo (node_id + address + len) + observed_addr (1 + len) // Variable-length encoding: len byte + actual address bytes const node_size = 32 + 46 + 1; // NodeInfo size const nodes_size = resp.closest_nodes.len * node_size; const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18)); const base = safeAdd(8, nodes_size) orelse std.math.maxInt(usize); break :blk safeAdd(base, addr_overhead) orelse std.math.maxInt(usize); }, .dht_store => |store| blk: { // 8 + 32 + value.len + 4 + 32 const base = safeAdd(8 + 32, store.value.len) orelse std.math.maxInt(usize); break :blk safeAdd(base, 4 + 32) orelse std.math.maxInt(usize); }, .dht_store_response => |resp| blk: { // request_id + success + observed_addr (1 + len) - variable-length encoding const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18)); break :blk 8 + 1 + addr_overhead; }, .dht_find_value => 8 + 32 + 32, // request_id + key + sender_id .dht_find_value_response => |resp| blk: { // request_id + found + observed_addr (1 + len) - variable-length encoding const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18)); const base = 8 + 1 + addr_overhead; const value_size = if (resp.value) |v| v.len else 0; const with_value = safeAdd(base, value_size) orelse std.math.maxInt(usize); const node_size = 32 + 46 + 1; const nodes_size = resp.closest_nodes.len * node_size; break :blk safeAdd(with_value, nodes_size) orelse std.math.maxInt(usize); }, .app_data => |app| blk: { // Safe addition with overflow check break :blk safeAdd(2, app.data.len) orelse std.math.maxInt(usize); }, .app_control => |ctrl| blk: { // Safe addition with overflow check break :blk safeAdd(4, ctrl.params.len) orelse std.math.maxInt(usize); }, }; } /// Public wrapper for getPayloadSize to allow callers to estimate buffer size /// SEC-M1 FIX: Enables dynamic buffer allocation based on actual message size pub fn getPayloadSizePublic(self: *MessageSerializer, msg: message.Message) usize { return self.getPayloadSize(msg); } /// Serialize header to bytes fn serializeHeader(self: *MessageSerializer, header: message.MessageHeader, buffer: []u8) !void { _ = self; var offset: usize = 0; // Magic number (4 bytes) @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&header.magic)); offset += 4; // Version (2 bytes) @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&header.version)); offset += 2; // Message type (1 byte) buffer[offset] = @intFromEnum(header.msg_type); offset += 1; // Flags (1 byte) buffer[offset] = header.flags; offset += 1; // Message ID (8 bytes) @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&header.id)); offset += 8; // Source node ID (32 bytes) @memcpy(buffer[offset..offset + protocol.Network.NODE_ID_SIZE], &header.source); offset += protocol.Network.NODE_ID_SIZE; // Destination node ID (32 bytes) @memcpy(buffer[offset..offset + protocol.Network.NODE_ID_SIZE], &header.dest); offset += protocol.Network.NODE_ID_SIZE; // Priority (1 byte) buffer[offset] = @intFromEnum(header.priority); offset += 1; // TTL (1 byte) buffer[offset] = header.ttl; offset += 1; // Timestamp (8 bytes) @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&header.timestamp)); offset += 8; // Reserved (1 byte) buffer[offset] = header.reserved; } /// Deserialize header from bytes fn deserializeHeader(self: *MessageSerializer, buffer: []const u8) !message.MessageHeader { _ = self; var offset: usize = 0; // Magic number if (buffer.len < offset + 4) return SerializationError.BufferTooSmall; const magic = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // Version if (buffer.len < offset + 2) return SerializationError.BufferTooSmall; const version = readLittle(u16, buffer[offset..offset + 2]); offset += 2; // Message type // CRIT-NEW-1 FIX: Safe enum conversion with bounds checking if (buffer.len < offset + 1) return SerializationError.BufferTooSmall; const msg_type_int = buffer[offset]; const msg_type = std.meta.intToEnum(protocol.MessageType, msg_type_int) catch { core.log.err("SECURITY: Invalid message type 0x{x:0>2} - possible attack or corruption", .{msg_type_int}); return SerializationError.InvalidMessageType; }; offset += 1; // Flags if (buffer.len < offset + 1) return SerializationError.BufferTooSmall; const flags = buffer[offset]; offset += 1; // Message ID if (buffer.len < offset + 8) return SerializationError.BufferTooSmall; const id = readLittle(u64, buffer[offset..offset + 8]); offset += 8; // Source node ID if (buffer.len < offset + protocol.Network.NODE_ID_SIZE) return SerializationError.BufferTooSmall; var source: message.NodeId = undefined; @memcpy(&source, buffer[offset..offset + protocol.Network.NODE_ID_SIZE]); offset += protocol.Network.NODE_ID_SIZE; // Destination node ID if (buffer.len < offset + protocol.Network.NODE_ID_SIZE) return SerializationError.BufferTooSmall; var dest: message.NodeId = undefined; @memcpy(&dest, buffer[offset..offset + protocol.Network.NODE_ID_SIZE]); offset += protocol.Network.NODE_ID_SIZE; // Priority // CRIT-NEW-1 FIX: Safe enum conversion with bounds checking if (buffer.len < offset + 1) return SerializationError.BufferTooSmall; const priority_int = buffer[offset]; // Priority is u2 (0-3), so validate the byte value first if (priority_int > 3) { core.log.err("SECURITY: Invalid priority value {} - possible attack or corruption", .{priority_int}); return SerializationError.InvalidMessageType; } const priority = @as(protocol.Priority, @enumFromInt(@as(u2, @intCast(priority_int)))); offset += 1; // TTL if (buffer.len < offset + 1) return SerializationError.BufferTooSmall; const ttl = buffer[offset]; offset += 1; // Timestamp if (buffer.len < offset + 8) return SerializationError.BufferTooSmall; const timestamp = readLittle(i64, buffer[offset..offset + 8]); offset += 8; // Reserved if (buffer.len < offset + 1) return SerializationError.BufferTooSmall; const reserved = buffer[offset]; return message.MessageHeader{ .magic = magic, .version = version, .msg_type = msg_type, .flags = flags, .id = id, .source = source, .dest = dest, .priority = priority, .ttl = ttl, .timestamp = timestamp, .reserved = reserved, }; } /// Serialize message payload fn serializePayload(self: *MessageSerializer, msg: message.Message, buffer: []u8) !void { _ = self; var offset: usize = 0; switch (msg) { .discovery_hello => |hello| { // Base fields: version(2) + capabilities(4) + address const base = safeAdd(safeAdd(2, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; const sig_size: usize = if (hello.isSigned()) 64 + 32 + 8 else 0; const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&hello.version)); offset += 2; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&hello.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&hello.address)); offset += @sizeOf(message.NetworkAddress); // Serialize signature fields if signed if (hello.isSigned()) { @memcpy(buffer[offset..][0..64], &hello.signature); offset += 64; @memcpy(buffer[offset..][0..32], &hello.signer_id); offset += 32; std.mem.writeInt(i64, buffer[offset..][0..8], hello.timestamp, .little); } }, .discovery_response => |resp| { // Base fields: original_id(8) + capabilities(4) + address const base = safeAdd(safeAdd(8, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; const sig_size: usize = if (resp.isSigned()) 64 + 32 + 8 else 0; const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.original_id)); offset += 8; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&resp.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&resp.address)); offset += @sizeOf(message.NetworkAddress); // Serialize signature fields if signed if (resp.isSigned()) { @memcpy(buffer[offset..][0..64], &resp.signature); offset += 64; @memcpy(buffer[offset..][0..32], &resp.signer_id); offset += 32; std.mem.writeInt(i64, buffer[offset..][0..8], resp.timestamp, .little); } }, .discovery_announce => |announce| { // Base fields: capabilities(4) + address + ttl(1) const base = safeAdd(safeAdd(4, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength, 1) orelse return SerializationError.InvalidLength; const sig_size: usize = if (announce.isSigned()) 64 + 32 + 8 else 0; const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&announce.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&announce.address)); offset += @sizeOf(message.NetworkAddress); buffer[offset] = announce.ttl; offset += 1; // Serialize signature fields if signed if (announce.isSigned()) { @memcpy(buffer[offset..][0..64], &announce.signature); offset += 64; @memcpy(buffer[offset..][0..32], &announce.signer_id); offset += 32; std.mem.writeInt(i64, buffer[offset..][0..8], announce.timestamp, .little); } }, .topology_query => |query| { // SECURITY: Safe bounds check with overflow protection try checkBounds(buffer, offset, 9); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&query.query_id)); offset += 8; buffer[offset] = query.topology_type; }, .topology_response => |resp| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(8, resp.topology_data.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.query_id)); offset += 8; if (resp.topology_data.len > 0) { @memcpy(buffer[offset..offset + resp.topology_data.len], resp.topology_data); } }, .topology_update => |update| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(4, update.changes.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&update.sequence)); offset += 4; if (update.changes.len > 0) { @memcpy(buffer[offset..offset + update.changes.len], update.changes); } }, .data_request => |req| { // SECURITY: Safe bounds check with overflow protection var required = safeAdd(8, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, req.data_id.len) orelse return SerializationError.InvalidLength; required = safeAdd(required, 8) orelse return SerializationError.InvalidLength; required = safeAdd(required, 4) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&req.request_id)); offset += 8; const data_id_len = std.math.cast(u32, req.data_id.len) orelse return SerializationError.MessageTooLarge; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&data_id_len)); offset += 4; if (req.data_id.len > 0) { @memcpy(buffer[offset..offset + req.data_id.len], req.data_id); offset += req.data_id.len; } @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&req.offset)); offset += 8; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&req.size)); }, .data_response => |resp| { // SECURITY: Safe bounds check with overflow protection var required = safeAdd(8, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, resp.data_id.len) orelse return SerializationError.InvalidLength; required = safeAdd(required, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, resp.data.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.request_id)); offset += 8; const data_id_len = std.math.cast(u32, resp.data_id.len) orelse return SerializationError.MessageTooLarge; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&data_id_len)); offset += 4; if (resp.data_id.len > 0) { @memcpy(buffer[offset..offset + resp.data_id.len], resp.data_id); offset += resp.data_id.len; } const data_len = std.math.cast(u32, resp.data.len) orelse return SerializationError.MessageTooLarge; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&data_len)); offset += 4; if (resp.data.len > 0) { @memcpy(buffer[offset..offset + resp.data.len], resp.data); } }, .data_chunk => |chunk| { // SECURITY: Safe bounds check with overflow protection var required = safeAdd(4, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, chunk.data_id.len) orelse return SerializationError.InvalidLength; required = safeAdd(required, 1) orelse return SerializationError.InvalidLength; required = safeAdd(required, chunk.chunk_data.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&chunk.sequence)); offset += 4; const data_id_len = std.math.cast(u32, chunk.data_id.len) orelse return SerializationError.MessageTooLarge; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&data_id_len)); offset += 4; if (chunk.data_id.len > 0) { @memcpy(buffer[offset..offset + chunk.data_id.len], chunk.data_id); offset += chunk.data_id.len; } buffer[offset] = if (chunk.is_final) 1 else 0; offset += 1; if (chunk.chunk_data.len > 0) { @memcpy(buffer[offset..offset + chunk.chunk_data.len], chunk.chunk_data); } }, .route_query => |query| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(8, protocol.Network.NODE_ID_SIZE) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&query.query_id)); offset += 8; @memcpy(buffer[offset..offset + protocol.Network.NODE_ID_SIZE], &query.target); }, .route_response => |resp| { // HIGH-5 FIX: Serialize with security fields // Format: query_id(8) + has_next_hop(1) + [next_hop(32)] + signature(64) + signer_id(32) + timestamp(8) + origin(32) + route_info const base_size = 8 + 1 + 64 + 32 + 8 + 32; const next_hop_size: usize = if (resp.next_hop != null) 32 else 0; const with_hop = safeAdd(base_size, next_hop_size) orelse return SerializationError.InvalidLength; const required = safeAdd(with_hop, resp.route_info.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); // Query ID @memcpy(buffer[offset..][0..8], std.mem.asBytes(&resp.query_id)); offset += 8; // Has next hop flag buffer[offset] = if (resp.next_hop != null) 1 else 0; offset += 1; // Next hop (if present) if (resp.next_hop) |hop| { @memcpy(buffer[offset..][0..32], &hop); offset += 32; } // Signature @memcpy(buffer[offset..][0..64], &resp.signature); offset += 64; // Signer ID @memcpy(buffer[offset..][0..32], &resp.signer_id); offset += 32; // Timestamp std.mem.writeInt(i64, buffer[offset..][0..8], resp.timestamp, .little); offset += 8; // Origin @memcpy(buffer[offset..][0..32], &resp.origin); offset += 32; // Route info if (resp.route_info.len > 0) { @memcpy(buffer[offset..][0..resp.route_info.len], resp.route_info); } }, .route_update => |update| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(4, update.route_changes.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&update.sequence)); offset += 4; if (update.route_changes.len > 0) { @memcpy(buffer[offset..offset + update.route_changes.len], update.route_changes); } }, .ping => |ping| { // SECURITY: Safe bounds check with overflow protection try checkBounds(buffer, offset, 4); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&ping.sequence)); }, .pong => |pong| { // SECURITY: Safe bounds check with overflow protection try checkBounds(buffer, offset, 8); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&pong.sequence)); offset += 4; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&pong.rtt)); }, .err => |err_msg| { // SECURITY: Safe bounds check with overflow protection var required = safeAdd(8, 2) orelse return SerializationError.InvalidLength; required = safeAdd(required, err_msg.message.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); const original_id = err_msg.original_id orelse 0; @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&original_id)); offset += 8; const error_code_int: u16 = @intFromEnum(err_msg.error_code); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&error_code_int)); offset += 2; if (err_msg.message.len > 0) { @memcpy(buffer[offset..offset + err_msg.message.len], err_msg.message); } }, .key_exchange_init => |kex| { // SECURITY: Safe bounds check with overflow protection // public_key(32) + signature(64) + identity_key(32) + session_nonce(32) + timestamp(8) = 168 bytes try checkBounds(buffer, offset, 168); @memcpy(buffer[offset..offset + 32], &kex.initiator_public_key); @memcpy(buffer[offset + 32..offset + 96], &kex.signature); @memcpy(buffer[offset + 96..offset + 128], &kex.identity_key); @memcpy(buffer[offset + 128..offset + 160], &kex.session_nonce); std.mem.writeInt(i64, buffer[offset + 160 ..][0..8], kex.timestamp, .little); }, .key_exchange_response => |kex| { // SECURITY: Safe bounds check with overflow protection // public_key(32) + signature(64) + identity_key(32) + timestamp(8) + initiator_session_nonce(32) = 168 bytes try checkBounds(buffer, offset, 168); @memcpy(buffer[offset..offset + 32], &kex.responder_public_key); @memcpy(buffer[offset + 32..offset + 96], &kex.signature); @memcpy(buffer[offset + 96..offset + 128], &kex.identity_key); std.mem.writeInt(i64, buffer[offset + 128 ..][0..8], kex.timestamp, .little); @memcpy(buffer[offset + 136..offset + 168], &kex.initiator_session_nonce); }, // SEC-H2: Key confirmation serialization .key_confirmation => |kc| { // confirmation_tag(32) = 32 bytes try checkBounds(buffer, offset, 32); @memcpy(buffer[offset..offset + 32], &kc.confirmation_tag); }, // DHT message serialization (basic implementation - can be enhanced later) .dht_find_node => |find| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(safeAdd(8, 32) orelse return SerializationError.InvalidLength, 32) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&find.request_id)); offset += 8; @memcpy(buffer[offset..offset + 32], &find.target_id); offset += 32; @memcpy(buffer[offset..offset + 32], &find.sender_id); }, .dht_find_node_response => |resp| { // SECURITY: Safe bounds check with overflow protection const nodes_len = std.math.cast(u32, resp.closest_nodes.len) orelse return SerializationError.MessageTooLarge; try checkBounds(buffer, offset, 12); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.request_id)); offset += 8; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&nodes_len)); offset += 4; // IMP-H3 FIX: Serialize each node with full node_id, address, and address_len for (resp.closest_nodes) |node| { try checkBounds(buffer, offset, 79); // 32 + 46 + 1 @memcpy(buffer[offset..offset + 32], &node.node_id); offset += 32; @memcpy(buffer[offset..offset + 46], &node.address); offset += 46; buffer[offset] = node.address_len; offset += 1; } // IP Reflection: variable-length encoding (len first, then data) const addr_len: usize = @min(resp.observed_addr_len, 18); try checkBounds(buffer, offset, 1 + addr_len); buffer[offset] = resp.observed_addr_len; offset += 1; if (addr_len > 0) { @memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]); offset += addr_len; } }, .dht_store => |store| { // SECURITY: Safe bounds check with overflow protection const value_len = std.math.cast(u32, store.value.len) orelse return SerializationError.MessageTooLarge; var required = safeAdd(8, 32) orelse return SerializationError.InvalidLength; required = safeAdd(required, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, store.value.len) orelse return SerializationError.InvalidLength; required = safeAdd(required, 4) orelse return SerializationError.InvalidLength; required = safeAdd(required, 32) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&store.request_id)); offset += 8; @memcpy(buffer[offset..offset + 32], &store.key); offset += 32; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&value_len)); offset += 4; if (store.value.len > 0) { @memcpy(buffer[offset..offset + store.value.len], store.value); offset += store.value.len; } @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&store.ttl)); offset += 4; @memcpy(buffer[offset..offset + 32], &store.sender_id); }, .dht_store_response => |resp| { // SECURITY: Safe bounds check with overflow protection // Variable-length encoding: 8 + 1 + 1 + addr_len const addr_len: usize = @min(resp.observed_addr_len, 18); try checkBounds(buffer, offset, 8 + 1 + 1 + addr_len); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.request_id)); offset += 8; buffer[offset] = if (resp.success) 1 else 0; offset += 1; // IP Reflection: variable-length encoding (len first, then data) buffer[offset] = resp.observed_addr_len; offset += 1; if (addr_len > 0) { @memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]); offset += addr_len; } }, .dht_find_value => |find| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(safeAdd(8, 32) orelse return SerializationError.InvalidLength, 32) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&find.request_id)); offset += 8; @memcpy(buffer[offset..offset + 32], &find.key); offset += 32; @memcpy(buffer[offset..offset + 32], &find.sender_id); }, .dht_find_value_response => |resp| { // SECURITY: Safe bounds check with overflow protection try checkBounds(buffer, offset, 9); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.request_id)); offset += 8; buffer[offset] = if (resp.found) 1 else 0; offset += 1; // Serialize optional value if (resp.value) |val| { const value_len = std.math.cast(u32, val.len) orelse return SerializationError.MessageTooLarge; const val_required = safeAdd(4, val.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, val_required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&value_len)); offset += 4; if (val.len > 0) { @memcpy(buffer[offset..offset + val.len], val); offset += val.len; } } else { try checkBounds(buffer, offset, 4); const zero: u32 = 0; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&zero)); offset += 4; } // Serialize closest nodes const nodes_len = std.math.cast(u32, resp.closest_nodes.len) orelse return SerializationError.MessageTooLarge; try checkBounds(buffer, offset, 4); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&nodes_len)); offset += 4; for (resp.closest_nodes) |node| { try checkBounds(buffer, offset, 79); // 32 + 46 + 1 @memcpy(buffer[offset..offset + 32], &node.node_id); offset += 32; @memcpy(buffer[offset..offset + 46], &node.address); offset += 46; buffer[offset] = node.address_len; offset += 1; } // IP Reflection: variable-length encoding (len first, then data) const addr_len: usize = @min(resp.observed_addr_len, 18); try checkBounds(buffer, offset, 1 + addr_len); buffer[offset] = resp.observed_addr_len; offset += 1; if (addr_len > 0) { @memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]); offset += addr_len; } }, .app_data => |app| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(2, app.data.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&app.app_id)); offset += 2; if (app.data.len > 0) { @memcpy(buffer[offset..offset + app.data.len], app.data); } }, .app_control => |ctrl| { // SECURITY: Safe bounds check with overflow protection const required = safeAdd(4, ctrl.params.len) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&ctrl.app_id)); offset += 2; @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&ctrl.command)); offset += 2; if (ctrl.params.len > 0) { @memcpy(buffer[offset..offset + ctrl.params.len], ctrl.params); } }, } } // MED-4 FIX: Updated deserialization to include signature fields // Signature fields are optional for backwards compatibility - older messages have zeroed signatures fn deserializeDiscoveryHello(self: *MessageSerializer, buffer: []const u8) !message.DiscoveryHello { _ = self; const base_size = 2 + 4 + @sizeOf(message.NetworkAddress); const signed_size = base_size + 64 + 32 + 8; // + signature + signer_id + timestamp if (buffer.len < base_size) return SerializationError.BufferTooSmall; var offset: usize = 0; const version = readLittle(u16, buffer[offset..offset + 2]); offset += 2; const capabilities = readLittle(u32, buffer[offset..offset + 4]); offset += 4; var address: message.NetworkAddress = undefined; @memcpy(std.mem.asBytes(&address), buffer[offset..][0..@sizeOf(message.NetworkAddress)]); offset += @sizeOf(message.NetworkAddress); // MED-4 FIX: Parse signature fields if present if (buffer.len >= signed_size) { var signature: [64]u8 = undefined; @memcpy(&signature, buffer[offset..][0..64]); offset += 64; var signer_id: [32]u8 = undefined; @memcpy(&signer_id, buffer[offset..][0..32]); offset += 32; const timestamp = readLittle(i64, buffer[offset..offset + 8]); return message.DiscoveryHello.initSigned(version, capabilities, address, signer_id, timestamp, signature); } return message.DiscoveryHello.init(version, capabilities, address); } fn deserializeDiscoveryResponse(self: *MessageSerializer, buffer: []const u8) !message.DiscoveryResponse { _ = self; const base_size = 8 + 4 + @sizeOf(message.NetworkAddress); const signed_size = base_size + 64 + 32 + 8; // + signature + signer_id + timestamp if (buffer.len < base_size) return SerializationError.BufferTooSmall; var offset: usize = 0; const original_id = readLittle(u64, buffer[offset..offset + 8]); offset += 8; const capabilities = readLittle(u32, buffer[offset..offset + 4]); offset += 4; var address: message.NetworkAddress = undefined; @memcpy(std.mem.asBytes(&address), buffer[offset..][0..@sizeOf(message.NetworkAddress)]); offset += @sizeOf(message.NetworkAddress); var result = message.DiscoveryResponse.init(original_id, capabilities, address); // MED-4 FIX: Parse signature fields if present if (buffer.len >= signed_size) { @memcpy(&result.signature, buffer[offset..][0..64]); offset += 64; @memcpy(&result.signer_id, buffer[offset..][0..32]); offset += 32; result.timestamp = readLittle(i64, buffer[offset..offset + 8]); } return result; } fn deserializeDiscoveryAnnounce(self: *MessageSerializer, buffer: []const u8) !message.DiscoveryAnnounce { _ = self; const base_size = 4 + @sizeOf(message.NetworkAddress) + 1; // capabilities + address + ttl const signed_size = base_size + 64 + 32 + 8; // + signature + signer_id + timestamp if (buffer.len < base_size) return SerializationError.BufferTooSmall; var offset: usize = 0; const capabilities = readLittle(u32, buffer[offset..offset + 4]); offset += 4; var address: message.NetworkAddress = undefined; @memcpy(std.mem.asBytes(&address), buffer[offset..][0..@sizeOf(message.NetworkAddress)]); offset += @sizeOf(message.NetworkAddress); const ttl = buffer[offset]; offset += 1; var result = message.DiscoveryAnnounce.initWithTtl(capabilities, address, ttl); // MED-4 FIX: Parse signature fields if present if (buffer.len >= signed_size) { @memcpy(&result.signature, buffer[offset..][0..64]); offset += 64; @memcpy(&result.signer_id, buffer[offset..][0..32]); offset += 32; result.timestamp = readLittle(i64, buffer[offset..offset + 8]); } return result; } fn deserializeTopologyQuery(self: *MessageSerializer, buffer: []const u8) !message.TopologyQuery { _ = self; if (buffer.len < 9) return SerializationError.BufferTooSmall; const query_id = readLittle(u64, buffer[0..8]); const topology_type = buffer[8]; return message.TopologyQuery.init(query_id, topology_type); } fn deserializeTopologyResponse(self: *MessageSerializer, buffer: []const u8) !message.TopologyResponse { _ = self; if (buffer.len < 8) return SerializationError.BufferTooSmall; const query_id = readLittle(u64, buffer[0..8]); const topology_data = buffer[8..]; // SECURITY: Validate topology data size against reasonable limits to prevent memory exhaustion if (topology_data.len > Limits.MAX_TOPOLOGY_DATA_SIZE) return SerializationError.TopologyDataTooLarge; return message.TopologyResponse.init(query_id, topology_data); } fn deserializeTopologyUpdate(self: *MessageSerializer, buffer: []const u8) !message.TopologyUpdate { _ = self; if (buffer.len < 4) return SerializationError.BufferTooSmall; const sequence = readLittle(u32, buffer[0..4]); const changes = buffer[4..]; // SECURITY: Validate changes data size against reasonable limits to prevent memory exhaustion if (changes.len > Limits.MAX_TOPOLOGY_DATA_SIZE) return SerializationError.TopologyDataTooLarge; return message.TopologyUpdate.initFromChanges(sequence, changes); } fn deserializeDataRequest(self: *MessageSerializer, buffer: []const u8) !message.DataRequest { _ = self; if (buffer.len < 24) return SerializationError.BufferTooSmall; var offset: usize = 0; const request_id = readLittle(u64, buffer[offset..offset + 8]); offset += 8; // Read and validate data_id length try checkBounds(buffer, offset, 4); const data_id_len = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // SECURITY: Validate data_id_len against reasonable limits to prevent memory exhaustion if (data_id_len > Limits.MAX_DATA_ID_LENGTH) return SerializationError.DataIdTooLong; // Validate against max message size first if (data_id_len > protocol.MAX_MESSAGE_SIZE) return SerializationError.MessageTooLarge; // CRITICAL FIX: Check offset bounds BEFORE subtraction to prevent underflow // Old vulnerable code: if (data_id_len > buffer.len - offset) // This would underflow if offset > buffer.len try checkBounds(buffer, offset, data_id_len); const data_id = buffer[offset..offset + data_id_len]; offset += data_id_len; // Ensure we have enough bytes for offset and size (use safe bounds check) try checkBounds(buffer, offset, 12); const offset_val = readLittle(u64, buffer[offset..offset + 8]); offset += 8; const size = readLittle(u32, buffer[offset..offset + 4]); return message.DataRequest.init(request_id, data_id, offset_val, size); } fn deserializeDataResponse(self: *MessageSerializer, buffer: []const u8) !message.DataResponse { _ = self; if (buffer.len < 8) return SerializationError.BufferTooSmall; var offset: usize = 0; const request_id = readLittle(u64, buffer[offset..offset + 8]); offset += 8; // Read and validate data_id length try checkBounds(buffer, offset, 4); const data_id_len = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // SECURITY: Validate data_id_len against reasonable limits to prevent memory exhaustion if (data_id_len > Limits.MAX_DATA_ID_LENGTH) return SerializationError.DataIdTooLong; // Validate against max message size first if (data_id_len > protocol.MAX_MESSAGE_SIZE) return SerializationError.MessageTooLarge; // CRITICAL FIX: Check offset bounds BEFORE subtraction to prevent underflow // Old vulnerable code: if (data_id_len > buffer.len - offset) // This would underflow if offset > buffer.len try checkBounds(buffer, offset, data_id_len); const data_id = buffer[offset..offset + data_id_len]; offset += data_id_len; // Read and validate data length try checkBounds(buffer, offset, 4); const data_len = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // SECURITY: Validate payload size against reasonable limits to prevent memory exhaustion if (data_len > Limits.MAX_PAYLOAD_SIZE) return SerializationError.PayloadTooLarge; // Validate against max message size first if (data_len > protocol.MAX_MESSAGE_SIZE) return SerializationError.MessageTooLarge; // CRITICAL FIX: Check offset bounds BEFORE subtraction to prevent underflow try checkBounds(buffer, offset, data_len); const data = buffer[offset..offset + data_len]; return message.DataResponse.init(request_id, data_id, data); } fn deserializeDataChunk(self: *MessageSerializer, buffer: []const u8) !message.DataChunk { _ = self; if (buffer.len < 8) return SerializationError.BufferTooSmall; var offset: usize = 0; const sequence = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // Read and validate data_id length try checkBounds(buffer, offset, 4); const data_id_len = readLittle(u32, buffer[offset..offset + 4]); offset += 4; // SECURITY: Validate data_id_len against reasonable limits to prevent memory exhaustion if (data_id_len > Limits.MAX_DATA_ID_LENGTH) return SerializationError.DataIdTooLong; // Validate against max message size first if (data_id_len > protocol.MAX_MESSAGE_SIZE) return SerializationError.MessageTooLarge; // CRITICAL FIX: Check offset bounds BEFORE subtraction to prevent underflow // Old vulnerable code: if (data_id_len > buffer.len - offset) // This would underflow if offset > buffer.len try checkBounds(buffer, offset, data_id_len); const data_id = buffer[offset..offset + data_id_len]; offset += data_id_len; // Ensure we have at least one byte for is_final flag try checkBounds(buffer, offset, 1); const is_final = buffer[offset] != 0; offset += 1; // Remaining bytes are chunk_data - validate offset is within bounds // CRITICAL FIX: Use checkBounds even for zero-length check if (offset > buffer.len) return SerializationError.BufferTooSmall; const chunk_data = buffer[offset..]; // SECURITY: Validate chunk_data size against reasonable limits to prevent memory exhaustion if (chunk_data.len > Limits.MAX_PAYLOAD_SIZE) return SerializationError.PayloadTooLarge; return message.DataChunk.init(sequence, data_id, chunk_data, is_final); } fn deserializeRouteQuery(self: *MessageSerializer, buffer: []const u8) !message.RouteQuery { _ = self; if (buffer.len < 8 + protocol.Network.NODE_ID_SIZE) return SerializationError.BufferTooSmall; const query_id = readLittle(u64, buffer[0..8]); var target: message.NodeId = undefined; @memcpy(&target, buffer[8..8 + protocol.Network.NODE_ID_SIZE]); return message.RouteQuery.init(query_id, target); } fn deserializeRouteResponse(self: *MessageSerializer, buffer: []const u8) !message.RouteResponse { _ = self; // HIGH-5 FIX: Updated format with security fields // Format: query_id(8) + has_next_hop(1) + [next_hop(32)] + signature(64) + signer_id(32) + timestamp(8) + origin(32) + route_info const min_size = 8 + 1 + 64 + 32 + 8 + 32; // Without next_hop if (buffer.len < min_size) return SerializationError.BufferTooSmall; var offset: usize = 0; const query_id = readLittle(u64, buffer[offset..][0..8]); offset += 8; const has_next_hop = buffer[offset] != 0; offset += 1; var next_hop: ?message.NodeId = null; if (has_next_hop) { if (buffer.len < min_size + 32) return SerializationError.BufferTooSmall; var hop: message.NodeId = undefined; @memcpy(&hop, buffer[offset..][0..32]); next_hop = hop; offset += 32; } var signature: [64]u8 = undefined; @memcpy(&signature, buffer[offset..][0..64]); offset += 64; var signer_id: message.NodeId = undefined; @memcpy(&signer_id, buffer[offset..][0..32]); offset += 32; const timestamp = readLittle(i64, buffer[offset..][0..8]); offset += 8; var origin: message.NodeId = undefined; @memcpy(&origin, buffer[offset..][0..32]); offset += 32; const route_info = buffer[offset..]; // SECURITY: Validate route info size against reasonable limits to prevent memory exhaustion if (route_info.len > Limits.MAX_ROUTE_INFO_SIZE) return SerializationError.RouteInfoTooLarge; return message.RouteResponse.initSigned(query_id, route_info, next_hop, signature, signer_id, timestamp, origin); } fn deserializeRouteUpdate(self: *MessageSerializer, buffer: []const u8) !message.RouteUpdate { _ = self; if (buffer.len < 4) return SerializationError.BufferTooSmall; const sequence = readLittle(u32, buffer[0..4]); const route_changes = buffer[4..]; // SECURITY: Validate route changes size against reasonable limits to prevent memory exhaustion if (route_changes.len > Limits.MAX_ROUTE_INFO_SIZE) return SerializationError.RouteInfoTooLarge; return message.RouteUpdate.init(sequence, route_changes); } fn deserializePing(self: *MessageSerializer, buffer: []const u8) !message.Ping { _ = self; if (buffer.len < 4) return SerializationError.BufferTooSmall; const sequence = readLittle(u32, buffer[0..4]); return message.Ping.init(sequence); } fn deserializePong(self: *MessageSerializer, buffer: []const u8) !message.Pong { _ = self; if (buffer.len < 8) return SerializationError.BufferTooSmall; const sequence = readLittle(u32, buffer[0..4]); const rtt = readLittle(u32, buffer[4..8]); return message.Pong.init(sequence, rtt); } fn deserializeError(self: *MessageSerializer, buffer: []const u8) !message.Error { _ = self; if (buffer.len < 9) return SerializationError.BufferTooSmall; var offset: usize = 0; const original_id_ptr = @as(?u64, readLittle(u64, buffer[offset..offset + 8])); offset += 8; const error_code_int = readLittle(u16, buffer[offset..offset + 2]); offset += 2; // CRIT-NEW-1 FIX: Safe enum conversion with bounds checking const error_code = std.meta.intToEnum(protocol.ErrorCode, error_code_int) catch { std.log.warn("Unknown error code 0x{x:0>4}, treating as unknown_error", .{error_code_int}); return message.Error.init(original_id_ptr, protocol.ErrorCode.unknown_error, buffer[offset..]); }; const error_message = buffer[offset..]; // SECURITY: Validate error message length against reasonable limits to prevent memory exhaustion if (error_message.len > Limits.MAX_ERROR_MESSAGE_LENGTH) return SerializationError.ErrorMessageTooLong; return message.Error.init(original_id_ptr, error_code, error_message); } fn deserializeKeyExchangeInit(self: *MessageSerializer, buffer: []const u8) !message.KeyExchangeInit { _ = self; // public_key(32) + signature(64) + identity_key(32) + session_nonce(32) + timestamp(8) = 168 bytes if (buffer.len < 168) return SerializationError.BufferTooSmall; var initiator_public_key: [32]u8 = undefined; var signature: [64]u8 = undefined; var identity_key: [32]u8 = undefined; var session_nonce: [32]u8 = undefined; @memcpy(&initiator_public_key, buffer[0..32]); @memcpy(&signature, buffer[32..96]); @memcpy(&identity_key, buffer[96..128]); @memcpy(&session_nonce, buffer[128..160]); const timestamp = std.mem.readInt(i64, buffer[160..168], .little); return message.KeyExchangeInit.init(initiator_public_key, signature, identity_key, session_nonce, timestamp); } fn deserializeKeyExchangeResponse(self: *MessageSerializer, buffer: []const u8) !message.KeyExchangeResponse { _ = self; // public_key(32) + signature(64) + identity_key(32) + timestamp(8) + initiator_session_nonce(32) = 168 bytes if (buffer.len < 168) return SerializationError.BufferTooSmall; var responder_public_key: [32]u8 = undefined; var signature: [64]u8 = undefined; var identity_key: [32]u8 = undefined; var initiator_session_nonce: [32]u8 = undefined; @memcpy(&responder_public_key, buffer[0..32]); @memcpy(&signature, buffer[32..96]); @memcpy(&identity_key, buffer[96..128]); const timestamp = std.mem.readInt(i64, buffer[128..136], .little); @memcpy(&initiator_session_nonce, buffer[136..168]); return message.KeyExchangeResponse.init(responder_public_key, signature, identity_key, timestamp, initiator_session_nonce); } /// SEC-H2 FIX: Deserialize key confirmation message fn deserializeKeyConfirmation(self: *MessageSerializer, buffer: []const u8) !message.KeyConfirmation { _ = self; // confirmation_tag(32) = 32 bytes if (buffer.len < 32) return SerializationError.BufferTooSmall; var confirmation_tag: [32]u8 = undefined; @memcpy(&confirmation_tag, buffer[0..32]); return message.KeyConfirmation.init(confirmation_tag); } fn deserializeAppData(self: *MessageSerializer, buffer: []const u8) !message.AppData { _ = self; if (buffer.len < 2) return SerializationError.BufferTooSmall; const app_id = readLittle(u16, buffer[0..2]); const app_data = buffer[2..]; // SECURITY: Validate app data size against reasonable limits to prevent memory exhaustion if (app_data.len > Limits.MAX_APP_DATA_SIZE) return SerializationError.AppDataTooLarge; return message.AppData.init(app_id, app_data); } fn deserializeAppControl(self: *MessageSerializer, buffer: []const u8) !message.AppControl { _ = self; if (buffer.len < 4) return SerializationError.BufferTooSmall; const app_id = readLittle(u16, buffer[0..2]); const command = readLittle(u16, buffer[2..4]); const params = buffer[4..]; // SECURITY: Validate params size against reasonable limits to prevent memory exhaustion if (params.len > Limits.MAX_APP_DATA_SIZE) return SerializationError.AppDataTooLarge; return message.AppControl.init(app_id, command, params); } }; // SEC-M9 FIX: Removed calculateChecksum and verifyChecksum functions. // These were wrappers around CRC32 which is redundant with HMAC integrity. // Message integrity is enforced via HMAC-SHA256 which provides both // integrity AND authentication, making CRC32 unnecessary. test "message serialization" { const allocator = std.testing.allocator; // Create crypto manager for authentication var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); // Create serializer with authentication var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); // Test ping message serialization const ping = message.Ping.init(123); const full_msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(full_msg, &buffer); try std.testing.expect(size > 0); try std.testing.expect(size < buffer.len); // Test deserialization (same serializer since it has the HMAC key) const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type); const full_msg_deserialized = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(protocol.MessageType.ping, full_msg_deserialized.getType()); } test "encrypted message serialization roundtrip" { const allocator = std.testing.allocator; // Create crypto manager with encryption key for peer var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x42} ** 32; const encryption_key = [_]u8{0xAB} ** 32; const hmac_key = [_]u8{0xCD} ** 32; try crypto_mgr.setKeyForPeer(peer_id, encryption_key); try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); // Create serializer with encryption enabled var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); // Create a ping message const ping = message.Ping.init(12345); const msg = message.Message{ .ping = ping }; // Serialize with encryption var buffer: [1024]u8 = undefined; const size = try serializer.serializeEncrypted(msg, &buffer); try std.testing.expect(size > 0); // Verify ENCRYPTED flag is set const header = try serializer.deserializeHeader(buffer[0..protocol.Serialization.HEADER_SIZE]); try std.testing.expect((header.flags & protocol.MessageFlags.ENCRYPTED) != 0); try std.testing.expect((header.flags & protocol.MessageFlags.AUTHENTICATED) != 0); // Deserialize with decryption var decrypted = try serializer.deserializeDecrypted(buffer[0..size]); defer decrypted.deinit(); // Verify we can parse the decrypted message try std.testing.expectEqual(protocol.MessageType.ping, decrypted.base.header.msg_type); const full_msg = try serializer.deserializeFull(decrypted.base); try std.testing.expectEqual(protocol.MessageType.ping, full_msg.getType()); try std.testing.expectEqual(@as(u32, 12345), full_msg.ping.sequence); } test "key exchange messages are not encrypted" { const allocator = std.testing.allocator; // Create crypto manager var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x11} ** 32; const encryption_key = [_]u8{0x22} ** 32; const hmac_key = [_]u8{0x33} ** 32; try crypto_mgr.setKeyForPeer(peer_id, encryption_key); try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); // Create serializer with encryption enabled var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); // Create a key exchange init message const public_key = [_]u8{0xFF} ** 32; const signature = [_]u8{0xAA} ** 64; const identity_key = [_]u8{0xBB} ** 32; const session_nonce = [_]u8{0xCC} ** 32; const timestamp = platform_time.timestamp(); const key_exchange = message.KeyExchangeInit.init(public_key, signature, identity_key, session_nonce, timestamp); const msg = message.Message{ .key_exchange_init = key_exchange }; // Serialize - should NOT be encrypted even with encryption enabled var buffer: [1024]u8 = undefined; const size = try serializer.serializeEncrypted(msg, &buffer); try std.testing.expect(size > 0); // Verify ENCRYPTED flag is NOT set (key exchange must be in plaintext) const header = try serializer.deserializeHeader(buffer[0..protocol.Serialization.HEADER_SIZE]); try std.testing.expect((header.flags & protocol.MessageFlags.ENCRYPTED) == 0); } test "decryption fails with wrong key" { const allocator = std.testing.allocator; // Create crypto manager for sender var sender_crypto = crypto.CryptoManager.init(allocator); defer sender_crypto.deinit(); const peer_id = [_]u8{0x99} ** 32; const encryption_key = [_]u8{0xAA} ** 32; const hmac_key = [_]u8{0xBB} ** 32; try sender_crypto.setKeyForPeer(peer_id, encryption_key); try sender_crypto.setHmacKeyForPeer(peer_id, hmac_key); var sender = MessageSerializer.initWithCrypto(allocator, &sender_crypto, peer_id); // Encrypt a message const ping = message.Ping.init(9999); const msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const size = try sender.serializeEncrypted(msg, &buffer); // Create receiver with WRONG key var receiver_crypto = crypto.CryptoManager.init(allocator); defer receiver_crypto.deinit(); const wrong_key = [_]u8{0xCC} ** 32; // Different key! try receiver_crypto.setKeyForPeer(peer_id, wrong_key); try receiver_crypto.setHmacKeyForPeer(peer_id, hmac_key); // Same HMAC key var receiver = MessageSerializer.initWithCrypto(allocator, &receiver_crypto, peer_id); // Decryption should fail const result = receiver.deserializeDecrypted(buffer[0..size]); try std.testing.expectError(SerializationError.DecryptionFailed, result); } test "safeAdd overflow protection" { // Normal addition should work try std.testing.expectEqual(@as(?usize, 10), safeAdd(5, 5)); try std.testing.expectEqual(@as(?usize, 0), safeAdd(0, 0)); try std.testing.expectEqual(@as(?usize, 100), safeAdd(50, 50)); // Overflow should return null const max = std.math.maxInt(usize); try std.testing.expect(safeAdd(max, 1) == null); try std.testing.expect(safeAdd(max, max) == null); try std.testing.expect(safeAdd(max / 2 + 1, max / 2 + 1) == null); } test "checkBounds validation" { const buffer: [100]u8 = undefined; // Valid bounds try checkBounds(&buffer, 0, 50); try checkBounds(&buffer, 0, 100); try checkBounds(&buffer, 50, 50); try checkBounds(&buffer, 99, 1); // Invalid: offset beyond buffer try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buffer, 101, 1)); // Invalid: required exceeds remaining try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buffer, 50, 51)); try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buffer, 0, 101)); // Large offset case - offset check happens first const max = std.math.maxInt(usize); try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buffer, max, 1)); } test "Limits accessor functions" { // Verify limit accessors return reasonable values try std.testing.expect(Limits.maxMessageSize() > 0); try std.testing.expect(Limits.maxPieceDataSize() > 0); // Verify compile-time constants try std.testing.expect(Limits.MAX_MESSAGE_SIZE > 0); try std.testing.expect(Limits.MAX_PAYLOAD_SIZE > 0); try std.testing.expect(Limits.MAX_DATA_ID_LENGTH > 0); try std.testing.expect(Limits.MAX_TOPOLOGY_DATA_SIZE > 0); try std.testing.expect(Limits.MAX_ROUTE_INFO_SIZE > 0); try std.testing.expect(Limits.MAX_ERROR_MESSAGE_LENGTH > 0); try std.testing.expect(Limits.MAX_APP_DATA_SIZE > 0); try std.testing.expect(Limits.MAX_PEER_LIST_SIZE > 0); try std.testing.expect(Limits.MAX_NODE_LIST_SIZE > 0); } test "MessageSerializer init variants" { const allocator = std.testing.allocator; // Basic init (will fail without crypto in production) const basic = MessageSerializer.init(allocator); try std.testing.expect(basic.crypto_manager == null); try std.testing.expect(!basic.is_test_mode); // Test mode init const test_serializer = MessageSerializer.initInsecureForTesting(allocator); try std.testing.expect(test_serializer.crypto_manager == null); try std.testing.expect(test_serializer.is_test_mode); } test "MessageSerializer setCryptoManager and setDestinationPeer" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); var serializer = MessageSerializer.init(allocator); try std.testing.expect(serializer.crypto_manager == null); // Set crypto manager serializer.setCryptoManager(&crypto_mgr); try std.testing.expect(serializer.crypto_manager != null); // Set destination peer const peer_id = [_]u8{0xAB} ** 32; serializer.setDestinationPeer(peer_id); try std.testing.expect(std.mem.eql(u8, &serializer.peer_id, &peer_id)); } test "MessageSerializer initFull" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const local_id = [_]u8{0x11} ** 32; const remote_id = [_]u8{0x22} ** 32; const serializer = MessageSerializer.initFull(allocator, &crypto_mgr, local_id, remote_id); try std.testing.expect(std.mem.eql(u8, &serializer.local_peer_id, &local_id)); try std.testing.expect(std.mem.eql(u8, &serializer.peer_id, &remote_id)); try std.testing.expect(serializer.crypto_manager != null); } test "serialize without crypto_manager fails in production mode" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); // Not in test mode and no crypto_manager const ping = message.Ping.init(123); const msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const result = serializer.serialize(msg, &buffer); try std.testing.expectError(SerializationError.NoCryptoManager, result); } test "deserialize without crypto_manager fails in production mode" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); const dummy_buffer: [100]u8 = [_]u8{0} ** 100; const result = serializer.deserialize(&dummy_buffer); try std.testing.expectError(SerializationError.NoCryptoManager, result); } test "serialize buffer too small" { const allocator = std.testing.allocator; var serializer = MessageSerializer.initInsecureForTesting(allocator); const ping = message.Ping.init(123); const msg = message.Message{ .ping = ping }; // Buffer too small var small_buffer: [10]u8 = undefined; const result = serializer.serialize(msg, &small_buffer); try std.testing.expectError(SerializationError.BufferTooSmall, result); } test "deserialize invalid magic number" { const allocator = std.testing.allocator; var serializer = MessageSerializer.initInsecureForTesting(allocator); // Create buffer with wrong magic number var buffer: [100]u8 = [_]u8{0} ** 100; // Set wrong magic buffer[0] = 0xFF; buffer[1] = 0xFF; buffer[2] = 0xFF; buffer[3] = 0xFF; // Invalid magic causes message type parsing to fail since header is garbled const result = serializer.deserialize(&buffer); try std.testing.expectError(SerializationError.InvalidMessageType, result); } test "deserialize buffer too small" { const allocator = std.testing.allocator; var serializer = MessageSerializer.initInsecureForTesting(allocator); // Buffer smaller than header const small_buffer: [5]u8 = [_]u8{0} ** 5; const result = serializer.deserialize(&small_buffer); try std.testing.expectError(SerializationError.BufferTooSmall, result); } test "pong message serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const pong = message.Pong.init(456, 100); const msg = message.Message{ .pong = pong }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.pong, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u32, 456), full_msg.pong.sequence); try std.testing.expectEqual(@as(u32, 100), full_msg.pong.rtt); } test "error message serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const err_msg = message.Error.init(42, protocol.ErrorCode.invalid_message, "Test error message"); const msg = message.Message{ .err = err_msg }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.err, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(protocol.ErrorCode.invalid_message, full_msg.err.error_code); } test "data request message serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const data_req = message.DataRequest{ .data_id = "test-data-id", .offset = 1000, .size = 4096, .request_id = 12345, }; const msg = message.Message{ .data_request = data_req }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.data_request, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u64, 1000), full_msg.data_request.offset); try std.testing.expectEqual(@as(u32, 4096), full_msg.data_request.size); try std.testing.expectEqual(@as(u64, 12345), full_msg.data_request.request_id); } test "data response message serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const test_data = "Hello, this is test data for response"; const data_resp = message.DataResponse{ .request_id = 54321, .data_id = "test-data-id", .data = test_data, .total_size = test_data.len, }; const msg = message.Message{ .data_response = data_resp }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.data_response, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u64, 54321), full_msg.data_response.request_id); // Note: total_size may not be preserved through serialization depending on wire format try std.testing.expect(full_msg.data_response.data.len > 0); } test "discovery hello message serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); var ip_addr: [16]u8 = [_]u8{0} ** 16; ip_addr[0] = 127; ip_addr[3] = 1; const hello = message.DiscoveryHello.init( 1, // version 0xFF, // capabilities message.NetworkAddress{ .ip = ip_addr, .port = 9999, }, ); const msg = message.Message{ .discovery_hello = hello }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.discovery_hello, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u16, 9999), full_msg.discovery_hello.address.port); try std.testing.expectEqual(@as(u32, 0xFF), full_msg.discovery_hello.capabilities); } test "getPayloadSizePublic returns correct sizes" { const allocator = std.testing.allocator; var serializer = MessageSerializer.initInsecureForTesting(allocator); // Ping has fixed size (4 bytes for sequence) const ping = message.Ping.init(123); const ping_msg = message.Message{ .ping = ping }; const ping_size = serializer.getPayloadSizePublic(ping_msg); try std.testing.expect(ping_size >= 4); // Pong has fixed size (4 bytes sequence + 4 bytes rtt) const pong = message.Pong.init(456, 100); const pong_msg = message.Message{ .pong = pong }; const pong_size = serializer.getPayloadSizePublic(pong_msg); try std.testing.expect(pong_size >= 8); } test "key exchange response serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const public_key = [_]u8{0x11} ** 32; const signature = [_]u8{0x22} ** 64; const identity_key = [_]u8{0x33} ** 32; const initiator_nonce = [_]u8{0x44} ** 32; const timestamp = platform_time.timestamp(); const key_resp = message.KeyExchangeResponse.init(public_key, signature, identity_key, timestamp, initiator_nonce); const msg = message.Message{ .key_exchange_response = key_resp }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.key_exchange_response, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expect(std.mem.eql(u8, &full_msg.key_exchange_response.responder_public_key, &public_key)); try std.testing.expect(std.mem.eql(u8, &full_msg.key_exchange_response.initiator_session_nonce, &initiator_nonce)); } test "key confirmation serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const confirmation_tag = [_]u8{0x44} ** 32; const key_conf = message.KeyConfirmation.init(confirmation_tag); const msg = message.Message{ .key_confirmation = key_conf }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.key_confirmation, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expect(std.mem.eql(u8, &full_msg.key_confirmation.confirmation_tag, &confirmation_tag)); } test "app data serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const app_data = message.AppData{ .app_id = 0x42, .data = "Custom application data payload", }; const msg = message.Message{ .app_data = app_data }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.app_data, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u16, 0x42), full_msg.app_data.app_id); } test "app control serialization roundtrip" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const app_ctrl = message.AppControl{ .app_id = 0x42, .command = 0x01, .params = "Control params", }; const msg = message.Message{ .app_control = app_ctrl }; var buffer: [1024]u8 = undefined; const size = try serializer.serialize(msg, &buffer); const base_msg = try serializer.deserialize(buffer[0..size]); try std.testing.expectEqual(protocol.MessageType.app_control, base_msg.header.msg_type); const full_msg = try serializer.deserializeFull(base_msg); try std.testing.expectEqual(@as(u16, 0x01), full_msg.app_control.command); try std.testing.expectEqual(@as(u16, 0x42), full_msg.app_control.app_id); } test "HMAC verification fails with wrong key" { const allocator = std.testing.allocator; // Sender crypto manager var sender_crypto = crypto.CryptoManager.init(allocator); defer sender_crypto.deinit(); const peer_id = [_]u8{0x01} ** 32; const hmac_key = [_]u8{0xAB} ** 32; try sender_crypto.setHmacKeyForPeer(peer_id, hmac_key); var sender = MessageSerializer.initWithCrypto(allocator, &sender_crypto, peer_id); // Serialize a message const ping = message.Ping.init(123); const msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const size = try sender.serialize(msg, &buffer); // Receiver with WRONG HMAC key var receiver_crypto = crypto.CryptoManager.init(allocator); defer receiver_crypto.deinit(); const wrong_hmac_key = [_]u8{0xCD} ** 32; try receiver_crypto.setHmacKeyForPeer(peer_id, wrong_hmac_key); var receiver = MessageSerializer.initWithCrypto(allocator, &receiver_crypto, peer_id); // Deserialization should fail due to HMAC mismatch const result = receiver.deserialize(buffer[0..size]); try std.testing.expectError(SerializationError.AuthenticationFailed, result); } test "serializeEncrypted requires crypto manager" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); const ping = message.Ping.init(123); const msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const result = serializer.serializeEncrypted(msg, &buffer); try std.testing.expectError(SerializationError.EncryptionRequired, result); } test "serializeEncrypted requires key for peer" { const allocator = std.testing.allocator; var crypto_mgr = crypto.CryptoManager.init(allocator); defer crypto_mgr.deinit(); const peer_id = [_]u8{0x01} ** 32; // Only set HMAC key, no encryption key const hmac_key = [_]u8{0xAB} ** 32; try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key); var serializer = MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id); const ping = message.Ping.init(123); const msg = message.Message{ .ping = ping }; var buffer: [1024]u8 = undefined; const result = serializer.serializeEncrypted(msg, &buffer); try std.testing.expectError(SerializationError.NoKeyForPeer, result); } test "readLittle: u32 little endian byte order" { const buf = [_]u8{ 0x04, 0x03, 0x02, 0x01 }; const val = readLittle(u32, &buf); try std.testing.expectEqual(@as(u32, 0x01020304), val); } test "readLittle: u16 little endian" { const buf = [_]u8{ 0xCD, 0xAB }; const val = readLittle(u16, &buf); try std.testing.expectEqual(@as(u16, 0xABCD), val); } test "readLittle: u64 little endian" { var buf: [8]u8 = undefined; std.mem.writeInt(u64, &buf, 0xDEADBEEFCAFEBABE, .little); const val = readLittle(u64, &buf); try std.testing.expectEqual(@as(u64, 0xDEADBEEFCAFEBABE), val); } test "safeAdd: normal addition" { try std.testing.expectEqual(@as(?usize, 5), safeAdd(2, 3)); try std.testing.expectEqual(@as(?usize, 0), safeAdd(0, 0)); } test "safeAdd: overflow returns null" { try std.testing.expect(safeAdd(std.math.maxInt(usize), 1) == null); try std.testing.expect(safeAdd(std.math.maxInt(usize), std.math.maxInt(usize)) == null); } test "safeAdd: boundary values" { const max = std.math.maxInt(usize); try std.testing.expectEqual(@as(?usize, max), safeAdd(max, 0)); try std.testing.expectEqual(@as(?usize, max), safeAdd(0, max)); try std.testing.expectEqual(@as(?usize, max), safeAdd(max - 1, 1)); } test "checkBounds: valid bounds" { const buf: [10]u8 = undefined; try checkBounds(&buf, 0, 10); try checkBounds(&buf, 5, 5); try checkBounds(&buf, 10, 0); try checkBounds(&buf, 0, 0); } test "checkBounds: offset beyond buffer" { const buf: [10]u8 = undefined; try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buf, 11, 0)); } test "checkBounds: end beyond buffer" { const buf: [10]u8 = undefined; try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buf, 5, 6)); } test "checkBounds: overflow in offset + required" { // offset must be <= buf.len for overflow check to be reached (offset check comes first) const buf: [10]u8 = undefined; try std.testing.expectError(SerializationError.InvalidLength, checkBounds(&buf, 5, std.math.maxInt(usize))); } test "checkBounds: empty buffer" { const buf: [0]u8 = .{}; try checkBounds(&buf, 0, 0); try std.testing.expectError(SerializationError.BufferTooSmall, checkBounds(&buf, 0, 1)); } test "deserializeHeader: buffer too small at various points" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); // Empty buffer try std.testing.expectError(SerializationError.BufferTooSmall, serializer.deserializeHeader(&[_]u8{})); // Only 3 bytes (need 4 for magic) try std.testing.expectError(SerializationError.BufferTooSmall, serializer.deserializeHeader(&[_]u8{ 0, 0, 0 })); } test "deserializeHeader: invalid message type" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); // Build a buffer with valid magic, version, but invalid msg_type (0xFF) var buf: [80]u8 = undefined; @memset(&buf, 0); // magic (4 bytes) std.mem.writeInt(u32, buf[0..4], protocol.Serialization.MAGIC_NUMBER, .little); // version (2 bytes) std.mem.writeInt(u16, buf[4..6], protocol.PROTOCOL_VERSION, .little); // invalid message type buf[6] = 0xFF; try std.testing.expectError(SerializationError.InvalidMessageType, serializer.deserializeHeader(&buf)); } test "deserializeHeader: invalid priority value" { const allocator = std.testing.allocator; var serializer = MessageSerializer.init(allocator); // Build buffer with valid fields up to priority, then invalid priority (5) var buf: [80]u8 = undefined; @memset(&buf, 0); std.mem.writeInt(u32, buf[0..4], protocol.Serialization.MAGIC_NUMBER, .little); std.mem.writeInt(u16, buf[4..6], protocol.PROTOCOL_VERSION, .little); buf[6] = 0; // ping message type buf[7] = 0; // flags // message ID (8 bytes) - offset 8 // source node ID (32 bytes) - offset 16 // dest node ID (32 bytes) - offset 48 // priority at offset 80... actually need a bigger buffer // Header size: 4+2+1+1+8+32+32+1+1+8+1 = 91 bytes var big_buf: [92]u8 = undefined; @memset(&big_buf, 0); std.mem.writeInt(u32, big_buf[0..4], protocol.Serialization.MAGIC_NUMBER, .little); std.mem.writeInt(u16, big_buf[4..6], protocol.PROTOCOL_VERSION, .little); big_buf[6] = 0; // ping big_buf[7] = 0; // flags // skip 8 bytes message ID, 32+32 bytes node IDs big_buf[80] = 5; // invalid priority (> 3) try std.testing.expectError(SerializationError.InvalidMessageType, serializer.deserializeHeader(&big_buf)); } test "Limits: compile-time constants are reasonable" { try std.testing.expect(Limits.MAX_MESSAGE_SIZE > 0); try std.testing.expect(Limits.MAX_PAYLOAD_SIZE > 0); try std.testing.expect(Limits.MAX_PAYLOAD_SIZE <= Limits.MAX_MESSAGE_SIZE); try std.testing.expect(Limits.MAX_DATA_ID_LENGTH <= Limits.MAX_PAYLOAD_SIZE); try std.testing.expect(Limits.MAX_ERROR_MESSAGE_LENGTH > 0); try std.testing.expect(Limits.MAX_TOPOLOGY_DATA_SIZE > 0); try std.testing.expect(Limits.MAX_ROUTE_INFO_SIZE > 0); } test "Limits: runtime accessors return nonzero values" { try std.testing.expect(Limits.maxMessageSize() > 0); try std.testing.expect(Limits.maxPieceDataSize() > 0); } test "SerializationError: distinct error values" { const e1 = SerializationError.BufferTooSmall; const e2 = SerializationError.InvalidMessageType; const e3 = SerializationError.PayloadTooLarge; const e4 = SerializationError.DataIdTooLong; const e5 = SerializationError.ChecksumMismatch; try std.testing.expect(e1 != e2); try std.testing.expect(e2 != e3); try std.testing.expect(e3 != e4); try std.testing.expect(e4 != e5); }