This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

View File

@@ -0,0 +1,219 @@
//! Allocation Limits and Size Validation Tests
//!
//! This test suite validates that protocol message handling enforces
//! strict size limits to prevent:
//! - Memory exhaustion attacks
//! - Integer overflow exploitation
//! - Excessive resource consumption
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const serializer = protocol.serializer;
const message = protocol.message;
const protocol_constants = protocol.protocol;
// Import limits
const MAX_MESSAGE_SIZE = protocol_constants.MAX_MESSAGE_SIZE;
const Limits = serializer.Limits;
// ============================================================================
// Limits Constants Tests
// ============================================================================
test "limits constants are defined" {
// Verify all limits are properly defined
try testing.expect(Limits.MAX_MESSAGE_SIZE > 0);
try testing.expect(Limits.MAX_PAYLOAD_SIZE > 0);
try testing.expect(Limits.MAX_DATA_ID_LENGTH > 0);
try testing.expect(Limits.MAX_PEER_LIST_SIZE > 0);
}
test "limits have reasonable values" {
// MAX_MESSAGE_SIZE should be reasonable (64MB max)
try testing.expect(Limits.MAX_MESSAGE_SIZE <= 64 * 1024 * 1024);
// MAX_PAYLOAD_SIZE should be reasonable (16MB)
try testing.expectEqual(@as(usize, 16 * 1024 * 1024), Limits.MAX_PAYLOAD_SIZE);
// MAX_PEER_LIST_SIZE should prevent excessive lists
try testing.expectEqual(@as(usize, 1000), Limits.MAX_PEER_LIST_SIZE);
// Data ID length should be bounded
try testing.expectEqual(@as(usize, 4096), Limits.MAX_DATA_ID_LENGTH);
}
test "limits hierarchy is correct" {
// MAX_DATA_ID_LENGTH < MAX_PAYLOAD_SIZE < MAX_MESSAGE_SIZE
try testing.expect(Limits.MAX_DATA_ID_LENGTH < Limits.MAX_PAYLOAD_SIZE);
try testing.expect(Limits.MAX_PAYLOAD_SIZE <= Limits.MAX_MESSAGE_SIZE);
}
// ============================================================================
// Serializer Size Validation Tests
// ============================================================================
test "serializer rejects buffer larger than MAX_MESSAGE_SIZE" {
// Verify that the MAX_MESSAGE_SIZE limit is set correctly
// The actual size enforcement happens at the message parsing level
try testing.expect(Limits.MAX_MESSAGE_SIZE > 0);
try testing.expect(Limits.MAX_MESSAGE_SIZE <= 64 * 1024 * 1024);
// Document that buffers larger than MAX_MESSAGE_SIZE should be rejected
// before being passed to the deserializer
}
test "MAX_MESSAGE_SIZE allows reasonable buffer sizes" {
// Verify that MAX_MESSAGE_SIZE is large enough for practical use
// but not excessively large
try testing.expect(Limits.MAX_MESSAGE_SIZE >= 1024); // At least 1KB
try testing.expect(Limits.MAX_MESSAGE_SIZE <= 64 * 1024 * 1024); // At most 64MB
// Verify the constant is what we expect (64MB)
try testing.expectEqual(@as(usize, 64 * 1024 * 1024), Limits.MAX_MESSAGE_SIZE);
}
test "serializer handles zero-length buffer" {
const allocator = testing.allocator;
// CRIT-NEW-9: Use test mode to allow null crypto_manager
var s = serializer.MessageSerializer.initInsecureForTesting(allocator);
const empty_buffer: []const u8 = &[_]u8{};
const result = s.deserialize(empty_buffer);
// Should fail with some error (buffer too small, not MessageTooLarge)
try testing.expectError(serializer.SerializationError.BufferTooSmall, result);
}
// ============================================================================
// Message Serialization Size Tests
// ============================================================================
test "ping message serialization size is bounded" {
const allocator = testing.allocator;
// CRIT-NEW-9: Use test mode to allow null crypto_manager
var s = serializer.MessageSerializer.initInsecureForTesting(allocator);
const ping = message.Ping.init(12345);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try s.serialize(msg, &buffer);
// Ping should be small (header ~182 bytes + small payload)
try testing.expect(size < 500);
try testing.expect(size <= Limits.MAX_MESSAGE_SIZE);
}
test "pong message serialization size is bounded" {
const allocator = testing.allocator;
// CRIT-NEW-9: Use test mode to allow null crypto_manager
var s = serializer.MessageSerializer.initInsecureForTesting(allocator);
const pong = message.Pong.init(12345, 100);
const msg = message.Message{ .pong = pong };
var buffer: [1024]u8 = undefined;
const size = try s.serialize(msg, &buffer);
// Pong should be small (header ~182 bytes + small payload)
try testing.expect(size < 500);
try testing.expect(size <= Limits.MAX_MESSAGE_SIZE);
}
// ============================================================================
// Security Tests - Overflow Prevention
// ============================================================================
test "size fields prevent integer overflow" {
// Test that u32 max values don't cause overflow
const max_u32: u32 = std.math.maxInt(u32);
// These operations should not overflow
const safe_check1 = @as(u64, max_u32) + 1;
try testing.expect(safe_check1 > max_u32);
// The Limits are set below u32 max to prevent overflow
try testing.expect(Limits.MAX_MESSAGE_SIZE < max_u32);
try testing.expect(Limits.MAX_PAYLOAD_SIZE < max_u32);
}
test "multiple allocations stay within limits" {
const allocator = testing.allocator;
// Even multiple MAX_DATA_ID_LENGTH allocations should be safe
const count = 10;
const total = Limits.MAX_DATA_ID_LENGTH * count;
// This should not overflow or cause issues
try testing.expect(total < Limits.MAX_MESSAGE_SIZE * count);
// We can safely allocate this much
const buffer = try allocator.alloc(u8, Limits.MAX_DATA_ID_LENGTH);
defer allocator.free(buffer);
try testing.expectEqual(Limits.MAX_DATA_ID_LENGTH, buffer.len);
}
// ============================================================================
// Handler Limits Tests
// ============================================================================
test "handler limits are defined" {
const HandlerLimits = protocol.handler.HandlerLimits;
try testing.expect(HandlerLimits.MAX_PENDING_MESSAGES > 0);
try testing.expect(HandlerLimits.MAX_HANDLER_REGISTRY_SIZE > 0);
}
test "handler limits have reasonable values" {
const HandlerLimits = protocol.handler.HandlerLimits;
// MAX_PENDING_MESSAGES should prevent queue exhaustion
try testing.expectEqual(@as(usize, 10000), HandlerLimits.MAX_PENDING_MESSAGES);
// MAX_HANDLER_REGISTRY_SIZE should be bounded
try testing.expectEqual(@as(usize, 1000), HandlerLimits.MAX_HANDLER_REGISTRY_SIZE);
}
// ============================================================================
// Documentation Test
// ============================================================================
test "document all enforced limits" {
// This test documents all the size limits enforced by the protocol
// Serialization limits
_ = Limits.MAX_MESSAGE_SIZE; // Maximum total message size
_ = Limits.MAX_PAYLOAD_SIZE; // Maximum payload data size
_ = Limits.MAX_DATA_ID_LENGTH; // Maximum data identifier length
_ = Limits.MAX_TOPOLOGY_DATA_SIZE; // Maximum topology data
_ = Limits.MAX_ROUTE_INFO_SIZE; // Maximum route info size
_ = Limits.MAX_ERROR_MESSAGE_LENGTH; // Maximum error message
_ = Limits.MAX_APP_DATA_SIZE; // Maximum application data
_ = Limits.MAX_PEER_LIST_SIZE; // Maximum peers in list
_ = Limits.MAX_NODE_LIST_SIZE; // Maximum nodes in list
// Handler limits
const HandlerLimits = protocol.handler.HandlerLimits;
_ = HandlerLimits.MAX_PENDING_MESSAGES;
_ = HandlerLimits.MAX_HANDLER_REGISTRY_SIZE;
// These limits prevent:
// 1. Memory exhaustion attacks
// 2. Integer overflow exploitation
// 3. Queue exhaustion DoS
// 4. Handler registry exhaustion
}
test "limits are consistent across modules" {
// Ensure limits are properly exported and accessible
const s_limits = serializer.Limits;
const h_limits = protocol.handler.HandlerLimits;
// All should be compile-time constants
comptime {
_ = s_limits.MAX_MESSAGE_SIZE;
_ = s_limits.MAX_PAYLOAD_SIZE;
_ = h_limits.MAX_PENDING_MESSAGES;
}
}

View File

@@ -0,0 +1,444 @@
//! Comprehensive tests for cryptographic operations
//! Tests encryption/decryption with various sizes, key rotation, concurrency, memory cleanup,
//! nonce uniqueness, tampered ciphertext detection, and side-channel considerations
const std = @import("std");
const testing = std.testing;
const crypto_mod = @import("protocol").crypto;
test "crypto: encrypt decrypt roundtrip with zero bytes" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "crypto: encrypt decrypt roundtrip with 1 byte" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{3} ** 32;
const key = [_]u8{4} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "X";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "crypto: encrypt decrypt roundtrip with 16 bytes" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{5} ** 32;
const key = [_]u8{6} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "0123456789ABCDEF"; // Exactly 16 bytes
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "crypto: encrypt decrypt roundtrip with 1KB data" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{7} ** 32;
const key = [_]u8{8} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = [_]u8{'A'} ** 1024;
const ciphertext = try crypto.encrypt(peer_id, &plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualSlices(u8, &plaintext, decrypted);
}
test "crypto: encrypt decrypt roundtrip with 1MB data" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{9} ** 32;
const key = [_]u8{10} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = try allocator.alloc(u8, 1024 * 1024);
defer allocator.free(plaintext);
@memset(plaintext, 'B');
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualSlices(u8, plaintext, decrypted);
}
test "crypto: key rotation" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{11} ** 32;
const key1 = [_]u8{12} ** 32;
const key2 = [_]u8{13} ** 32;
// Set initial key
try crypto.setKeyForPeer(peer_id, key1);
const plaintext = "Test message";
const ciphertext1 = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext1);
// Rotate to new key
try crypto.setKeyForPeer(peer_id, key2);
// Old ciphertext should fail with new key
const result = crypto.decrypt(peer_id, ciphertext1);
try testing.expectError(crypto_mod.CryptoError.DecryptionFailed, result);
// New encryption should work with new key
const ciphertext2 = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext2);
const decrypted = try crypto.decrypt(peer_id, ciphertext2);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "crypto: concurrent encryption with same peer" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{14} ** 32;
const key = [_]u8{15} ** 32;
try crypto.setKeyForPeer(peer_id, key);
// Encrypt multiple messages concurrently (simulated by sequential calls)
const msg1 = "Message 1";
const msg2 = "Message 2";
const msg3 = "Message 3";
const cipher1 = try crypto.encrypt(peer_id, msg1);
defer allocator.free(cipher1);
const cipher2 = try crypto.encrypt(peer_id, msg2);
defer allocator.free(cipher2);
const cipher3 = try crypto.encrypt(peer_id, msg3);
defer allocator.free(cipher3);
// All should decrypt correctly
const plain1 = try crypto.decrypt(peer_id, cipher1);
defer allocator.free(plain1);
const plain2 = try crypto.decrypt(peer_id, cipher2);
defer allocator.free(plain2);
const plain3 = try crypto.decrypt(peer_id, cipher3);
defer allocator.free(plain3);
try testing.expectEqualStrings(msg1, plain1);
try testing.expectEqualStrings(msg2, plain2);
try testing.expectEqualStrings(msg3, plain3);
}
test "crypto: nonce uniqueness verification" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{16} ** 32;
const key = [_]u8{17} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Repeated message";
// Generate 10000 encryptions and check nonce uniqueness
var nonces = std.AutoHashMap([12]u8, void).init(allocator);
defer nonces.deinit();
var i: usize = 0;
while (i < 10000) : (i += 1) {
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Extract nonce (first 12 bytes)
var nonce: [12]u8 = undefined;
@memcpy(&nonce, ciphertext[0..12]);
// Verify uniqueness
try testing.expect(!nonces.contains(nonce));
try nonces.put(nonce, {});
}
try testing.expectEqual(@as(usize, 10000), nonces.count());
}
test "crypto: unknown peer rejection" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const unknown_peer = [_]u8{99} ** 32;
const plaintext = "Secret";
// Encrypt should fail for unknown peer
const result = crypto.encrypt(unknown_peer, plaintext);
try testing.expectError(crypto_mod.CryptoError.NoKeyForPeer, result);
}
test "crypto: tampered ciphertext detection - single byte" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{18} ** 32;
const key = [_]u8{19} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Sensitive data";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with one byte in the middle
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[20] ^= 0xFF;
const result = crypto.decrypt(peer_id, tampered);
try testing.expectError(crypto_mod.CryptoError.DecryptionFailed, result);
}
test "crypto: tampered ciphertext detection - multiple bytes" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{20} ** 32;
const key = [_]u8{21} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Important message";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with multiple bytes
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[15] ^= 0x12;
tampered[16] ^= 0x34;
tampered[17] ^= 0x56;
const result = crypto.decrypt(peer_id, tampered);
try testing.expectError(crypto_mod.CryptoError.DecryptionFailed, result);
}
test "crypto: partial tag tampering detection" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{22} ** 32;
const key = [_]u8{23} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Tagged message";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with tag (last 16 bytes)
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
const tag_start = tampered.len - 16;
tampered[tag_start] ^= 0x01;
const result = crypto.decrypt(peer_id, tampered);
try testing.expectError(crypto_mod.CryptoError.DecryptionFailed, result);
}
test "crypto: ciphertext length manipulation rejection" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{24} ** 32;
const key = [_]u8{25} ** 32;
try crypto.setKeyForPeer(peer_id, key);
// Try to decrypt truncated ciphertext (too short)
const short_cipher = [_]u8{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Less than 28 bytes minimum
const result = crypto.decrypt(peer_id, &short_cipher);
try testing.expectError(crypto_mod.CryptoError.InvalidCiphertext, result);
}
test "crypto: different plaintexts produce different ciphertexts" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{26} ** 32;
const key = [_]u8{27} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const msg1 = "Message A";
const msg2 = "Message B";
const cipher1 = try crypto.encrypt(peer_id, msg1);
defer allocator.free(cipher1);
const cipher2 = try crypto.encrypt(peer_id, msg2);
defer allocator.free(cipher2);
// Ciphertexts should be different
try testing.expect(!std.mem.eql(u8, cipher1, cipher2));
}
test "crypto: same plaintext produces different ciphertexts (nonce randomness)" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{28} ** 32;
const key = [_]u8{29} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Same message";
const cipher1 = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(cipher1);
const cipher2 = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(cipher2);
// Ciphertexts should be different due to different nonces
try testing.expect(!std.mem.eql(u8, cipher1, cipher2));
// But both should decrypt to same plaintext
const plain1 = try crypto.decrypt(peer_id, cipher1);
defer allocator.free(plain1);
const plain2 = try crypto.decrypt(peer_id, cipher2);
defer allocator.free(plain2);
try testing.expectEqualStrings(plaintext, plain1);
try testing.expectEqualStrings(plaintext, plain2);
}
test "crypto: memory cleanup verification" {
const allocator = testing.allocator;
// Track allocations
const initial_allocated = @intFromPtr(allocator);
_ = initial_allocated;
{
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{30} ** 32;
const key = [_]u8{31} ** 32;
try crypto.setKeyForPeer(peer_id, key);
// Perform multiple encryptions/decryptions
var i: usize = 0;
while (i < 100) : (i += 1) {
const plaintext = "Temporary data";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try crypto.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
}
// All intermediate allocations should be freed
}
// After deinit, all memory should be cleaned up
// Testing allocator will catch any leaks
}
test "crypto: different keys produce different ciphertexts" {
const allocator = testing.allocator;
var crypto1 = crypto_mod.CryptoManager.init(allocator);
defer crypto1.deinit();
var crypto2 = crypto_mod.CryptoManager.init(allocator);
defer crypto2.deinit();
const peer_id = [_]u8{32} ** 32;
const key1 = [_]u8{33} ** 32;
const key2 = [_]u8{34} ** 32;
try crypto1.setKeyForPeer(peer_id, key1);
try crypto2.setKeyForPeer(peer_id, key2);
const plaintext = "Common message";
// Encrypt with both keys (forcing same nonce would be ideal but not exposed)
const cipher1 = try crypto1.encrypt(peer_id, plaintext);
defer allocator.free(cipher1);
const cipher2 = try crypto2.encrypt(peer_id, plaintext);
defer allocator.free(cipher2);
// Ciphertexts should differ (even if nonces happened to match, which is extremely unlikely)
try testing.expect(!std.mem.eql(u8, cipher1, cipher2));
// Cross-decryption should fail
const result = crypto1.decrypt(peer_id, cipher2);
try testing.expectError(crypto_mod.CryptoError.DecryptionFailed, result);
}
test "crypto: ciphertext format verification" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{35} ** 32;
const key = [_]u8{36} ** 32;
try crypto.setKeyForPeer(peer_id, key);
const plaintext = "Format test";
const ciphertext = try crypto.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Verify format: nonce(12) + ciphertext(len) + tag(16)
const expected_len = 12 + plaintext.len + 16;
try testing.expectEqual(expected_len, ciphertext.len);
}
test "crypto: local key generation randomness" {
const allocator = testing.allocator;
var crypto1 = crypto_mod.CryptoManager.init(allocator);
defer crypto1.deinit();
var crypto2 = crypto_mod.CryptoManager.init(allocator);
defer crypto2.deinit();
// Local keys should be different
try testing.expect(!std.mem.eql(u8, &crypto1.local_key, &crypto2.local_key));
}

View File

@@ -0,0 +1,576 @@
//! Comprehensive integer overflow vulnerability tests for deserializers
//!
//! This test suite validates that all deserialize functions in the protocol
//! are protected against integer overflow attacks, including:
//! - Underflow in buffer.len - offset calculations
//! - Overflow in offset + length calculations
//! - Malicious length fields designed to trigger overflows
//! - Edge cases with usize max values
const std = @import("std");
const testing = std.testing;
// Import from the actual source paths
const protocol_mod = @import("../../src/protocol/protocol.zig");
const message = @import("../../src/protocol/message.zig");
const serializer = @import("../../src/protocol/serializer.zig");
const transfer_mod = @import("../../src/files/transfer.zig");
/// Test helper to create a serializer
/// CRIT-NEW-9: Use test mode to allow null crypto_manager
fn createSerializer() serializer.MessageSerializer {
return serializer.MessageSerializer.initInsecureForTesting(testing.allocator);
}
// ============================================================================
// CRITICAL: DataRequest Overflow Tests
// ============================================================================
test "deserializeDataRequest: underflow protection with offset > buffer.len" {
var s = createSerializer();
// Create a malicious buffer where:
// - request_id: 8 bytes (valid)
// - data_id_len: 4 bytes claiming a huge value (0xFFFFFFFF)
// - This would cause buffer.len - offset to underflow if not protected
var buffer: [16]u8 = undefined;
// Request ID
std.mem.writeInt(u64, buffer[0..8], 12345, .little);
// Malicious data_id_len = 0xFFFFFFFF (max u32)
std.mem.writeInt(u32, buffer[8..12], 0xFFFFFFFF, .little);
// The deserializer should catch this and return an error
const result = s.deserializeDataRequest(&buffer);
try testing.expectError(serializer.SerializationError.InvalidLength, result);
}
test "deserializeDataRequest: overflow in offset + data_id_len" {
var s = createSerializer();
// Create buffer with a large data_id_len that would overflow when added to offset
var buffer: [24]u8 = undefined;
// Request ID
std.mem.writeInt(u64, buffer[0..8], 12345, .little);
// Malicious data_id_len that exceeds protocol limits
std.mem.writeInt(u32, buffer[8..12], protocol_mod.MAX_MESSAGE_SIZE + 1, .little);
const result = s.deserializeDataRequest(&buffer);
try testing.expectError(serializer.SerializationError.MessageTooLarge, result);
}
test "deserializeDataRequest: valid small message" {
var s = createSerializer();
// Create a valid small message
var buffer: [32]u8 = undefined;
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// offset_val = 0
std.mem.writeInt(u64, buffer[offset..][0..8], 0, .little);
offset += 8;
// size = 1024
std.mem.writeInt(u32, buffer[offset..][0..4], 1024, .little);
offset += 4;
const result = try s.deserializeDataRequest(buffer[0..offset]);
try testing.expectEqual(@as(u64, 12345), result.request_id);
try testing.expectEqualSlices(u8, "test", result.data_id);
try testing.expectEqual(@as(u64, 0), result.offset);
try testing.expectEqual(@as(u32, 1024), result.size);
}
test "deserializeDataRequest: buffer too small for header" {
var s = createSerializer();
var buffer: [20]u8 = undefined;
const result = s.deserializeDataRequest(&buffer);
try testing.expectError(serializer.SerializationError.BufferTooSmall, result);
}
test "deserializeDataRequest: zero-length data_id" {
var s = createSerializer();
var buffer: [24]u8 = undefined;
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len = 0
std.mem.writeInt(u32, buffer[offset..][0..4], 0, .little);
offset += 4;
// offset_val = 0
std.mem.writeInt(u64, buffer[offset..][0..8], 0, .little);
offset += 8;
// size = 1024
std.mem.writeInt(u32, buffer[offset..][0..4], 1024, .little);
offset += 4;
const result = try s.deserializeDataRequest(buffer[0..offset]);
try testing.expectEqual(@as(usize, 0), result.data_id.len);
}
// ============================================================================
// CRITICAL: DataResponse Overflow Tests
// ============================================================================
test "deserializeDataResponse: double underflow protection" {
var s = createSerializer();
// Create a malicious buffer with two large length fields
var buffer: [20]u8 = undefined;
// Request ID
std.mem.writeInt(u64, buffer[0..8], 12345, .little);
// Malicious data_id_len = 0xFFFFFFFF
std.mem.writeInt(u32, buffer[8..12], 0xFFFFFFFF, .little);
const result = s.deserializeDataResponse(&buffer);
try testing.expectError(serializer.SerializationError.MessageTooLarge, result);
}
test "deserializeDataResponse: overflow in data_len" {
var s = createSerializer();
var buffer: [24]u8 = undefined;
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// Malicious data_len = max message size + 1
std.mem.writeInt(u32, buffer[offset..][0..4], protocol_mod.MAX_MESSAGE_SIZE + 1, .little);
offset += 4;
const result = s.deserializeDataResponse(buffer[0..offset]);
try testing.expectError(serializer.SerializationError.MessageTooLarge, result);
}
test "deserializeDataResponse: valid message with data" {
var s = createSerializer();
var buffer: [32]u8 = undefined;
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// data_len = 8
std.mem.writeInt(u32, buffer[offset..][0..4], 8, .little);
offset += 4;
// data = "response"
@memcpy(buffer[offset..][0..8], "response");
offset += 8;
const result = try s.deserializeDataResponse(buffer[0..offset]);
try testing.expectEqual(@as(u64, 12345), result.request_id);
try testing.expectEqualSlices(u8, "test", result.data_id);
try testing.expectEqualSlices(u8, "response", result.data);
}
test "deserializeDataResponse: empty data field" {
var s = createSerializer();
var buffer: [20]u8 = undefined;
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// data_len = 0
std.mem.writeInt(u32, buffer[offset..][0..4], 0, .little);
offset += 4;
const result = try s.deserializeDataResponse(buffer[0..offset]);
try testing.expectEqual(@as(usize, 0), result.data.len);
}
// ============================================================================
// CRITICAL: DataChunk Overflow Tests
// ============================================================================
test "deserializeDataChunk: underflow in data_id_len calculation" {
var s = createSerializer();
var buffer: [12]u8 = undefined;
// Sequence
std.mem.writeInt(u32, buffer[0..4], 1, .little);
// Malicious data_id_len = 0xFFFFFFFF
std.mem.writeInt(u32, buffer[4..8], 0xFFFFFFFF, .little);
const result = s.deserializeDataChunk(&buffer);
try testing.expectError(serializer.SerializationError.MessageTooLarge, result);
}
test "deserializeDataChunk: valid chunk with final flag" {
var s = createSerializer();
var buffer: [25]u8 = undefined;
var offset: usize = 0;
// Sequence
std.mem.writeInt(u32, buffer[offset..][0..4], 1, .little);
offset += 4;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// is_final = true
buffer[offset] = 1;
offset += 1;
// chunk_data = "data here"
@memcpy(buffer[offset..][0..9], "data here");
offset += 9;
const result = try s.deserializeDataChunk(buffer[0..offset]);
try testing.expectEqual(@as(u32, 1), result.sequence);
try testing.expectEqualSlices(u8, "test", result.data_id);
try testing.expectEqual(true, result.is_final);
try testing.expectEqualSlices(u8, "data here", result.chunk_data);
}
test "deserializeDataChunk: zero-length chunk_data" {
var s = createSerializer();
var buffer: [16]u8 = undefined;
var offset: usize = 0;
// Sequence
std.mem.writeInt(u32, buffer[offset..][0..4], 1, .little);
offset += 4;
// data_id_len = 4
std.mem.writeInt(u32, buffer[offset..][0..4], 4, .little);
offset += 4;
// data_id = "test"
@memcpy(buffer[offset..][0..4], "test");
offset += 4;
// is_final = false
buffer[offset] = 0;
offset += 1;
// No chunk_data
const result = try s.deserializeDataChunk(buffer[0..offset]);
try testing.expectEqual(@as(usize, 0), result.chunk_data.len);
}
// ============================================================================
// Edge Case Tests: Boundary Conditions
// ============================================================================
test "deserializeDataRequest: near-max valid data_id_len" {
var s = createSerializer();
// Use a reasonably large but valid data_id_len
const data_id_len: u32 = 1024;
const buffer_size = 24 + data_id_len;
var buffer = try testing.allocator.alloc(u8, buffer_size);
defer testing.allocator.free(buffer);
var offset: usize = 0;
// Request ID
std.mem.writeInt(u64, buffer[offset..][0..8], 12345, .little);
offset += 8;
// data_id_len
std.mem.writeInt(u32, buffer[offset..][0..4], data_id_len, .little);
offset += 4;
// data_id (filled with 'x')
@memset(buffer[offset..][0..data_id_len], 'x');
offset += data_id_len;
// offset_val = 0
std.mem.writeInt(u64, buffer[offset..][0..8], 0, .little);
offset += 8;
// size = 1024
std.mem.writeInt(u32, buffer[offset..][0..4], 1024, .little);
offset += 4;
const result = try s.deserializeDataRequest(buffer[0..offset]);
try testing.expectEqual(@as(u64, 12345), result.request_id);
try testing.expectEqual(data_id_len, result.data_id.len);
}
test "checkBounds: detects offset > buffer.len" {
var buffer: [10]u8 = undefined;
// This should fail because offset (15) > buffer.len (10)
const result = serializer.checkBounds(&buffer, 15, 5);
try testing.expectError(serializer.SerializationError.BufferTooSmall, result);
}
test "checkBounds: detects overflow in offset + required" {
var buffer: [10]u8 = undefined;
// This should fail due to overflow in addition
const result = serializer.checkBounds(&buffer, std.math.maxInt(usize) - 5, 10);
try testing.expectError(serializer.SerializationError.InvalidLength, result);
}
test "checkBounds: allows valid bounds" {
var buffer: [10]u8 = undefined;
// This should succeed: offset=5, required=5, total=10
try serializer.checkBounds(&buffer, 5, 5);
}
test "safeAdd: detects overflow" {
// This should return null due to overflow
const result = serializer.safeAdd(std.math.maxInt(usize), 1);
try testing.expect(result == null);
}
test "safeAdd: allows valid addition" {
const result = serializer.safeAdd(100, 200);
try testing.expect(result != null);
try testing.expectEqual(@as(usize, 300), result.?);
}
// ============================================================================
// Fuzz-like Tests: Random Malformed Input
// ============================================================================
test "deserializeDataRequest: random garbage data" {
var s = createSerializer();
var prng = std.Random.DefaultPrng.init(0);
const random = prng.random();
// Try 100 random malformed messages
var i: usize = 0;
while (i < 100) : (i += 1) {
var buffer: [256]u8 = undefined;
random.bytes(&buffer);
// All of these should either succeed or return an error
// None should crash or cause undefined behavior
_ = s.deserializeDataRequest(&buffer);
}
}
test "deserializeDataResponse: random garbage data" {
var s = createSerializer();
var prng = std.Random.DefaultPrng.init(42);
const random = prng.random();
var i: usize = 0;
while (i < 100) : (i += 1) {
var buffer: [256]u8 = undefined;
random.bytes(&buffer);
_ = s.deserializeDataResponse(&buffer);
}
}
test "deserializeDataChunk: random garbage data" {
var s = createSerializer();
var prng = std.Random.DefaultPrng.init(123);
const random = prng.random();
var i: usize = 0;
while (i < 100) : (i += 1) {
var buffer: [256]u8 = undefined;
random.bytes(&buffer);
_ = s.deserializeDataChunk(&buffer);
}
}
// ============================================================================
// Transfer Message Overflow Tests
// ============================================================================
test "TransferMessage serialize: overflow in total_size calculation" {
const allocator = testing.allocator;
// Create message with lengths that would overflow when added
// This is a theoretical test - in practice, allocation would fail first
const huge_peer_id = try allocator.alloc(u8, 1024 * 1024); // 1MB
defer allocator.free(huge_peer_id);
@memset(huge_peer_id, 'x');
const huge_data = try allocator.alloc(u8, 1024 * 1024); // 1MB
defer allocator.free(huge_data);
@memset(huge_data, 'y');
const msg = transfer_mod.TransferMessage{
.message_type = .piece_data,
.message_id = 1,
.peer_id = huge_peer_id,
.data = huge_data,
.timestamp = 0,
};
// This should succeed because we're under MAX_MESSAGE_SIZE
const serialized = try msg.serialize(allocator);
defer allocator.free(serialized);
try testing.expect(serialized.len > 0);
}
test "TransferMessage deserialize: overflow protection in combined_len" {
const allocator = testing.allocator;
// Create a malicious buffer with peer_id_len and data_len that would overflow when added
var buffer: [19]u8 = undefined;
var offset: usize = 0;
// Message type
buffer[offset] = @intFromEnum(transfer_mod.MessageType.handshake);
offset += 1;
// Message ID
std.mem.writeInt(u32, buffer[offset..][0..4], 1, .big);
offset += 4;
// peer_id_len = 0x7FFFFFFF (half of u32 max)
std.mem.writeInt(u16, buffer[offset..][0..2], 0x7FFF, .big);
offset += 2;
// timestamp
std.mem.writeInt(i64, buffer[offset..][0..8], 0, .big);
offset += 8;
// data_len = 0x7FFFFFFF (would overflow when added to peer_id_len)
std.mem.writeInt(u32, buffer[offset..][0..4], 0x7FFFFFFF, .big);
offset += 4;
const result = transfer_mod.TransferMessage.deserialize(&buffer, allocator);
try testing.expectError(error.InvalidData, result);
}
test "TransferMessage deserialize: underflow in buffer bounds check" {
const allocator = testing.allocator;
var buffer: [19]u8 = undefined;
var offset: usize = 0;
// Message type
buffer[offset] = @intFromEnum(transfer_mod.MessageType.handshake);
offset += 1;
// Message ID
std.mem.writeInt(u32, buffer[offset..][0..4], 1, .big);
offset += 4;
// peer_id_len = 100
std.mem.writeInt(u16, buffer[offset..][0..2], 100, .big);
offset += 2;
// timestamp
std.mem.writeInt(i64, buffer[offset..][0..8], 0, .big);
offset += 8;
// data_len = 100
std.mem.writeInt(u32, buffer[offset..][0..4], 100, .big);
offset += 4;
// Buffer is too small for the claimed lengths
const result = transfer_mod.TransferMessage.deserialize(&buffer, allocator);
try testing.expectError(error.InvalidData, result);
}
// ============================================================================
// Summary Test
// ============================================================================
test "overflow protection summary" {
// This test documents all the overflow vulnerabilities that have been fixed:
//
// 1. deserializeDataRequest (lines 609-641):
// - FIXED: buffer.len - offset underflow when offset > buffer.len
// - FIXED: offset + data_id_len overflow
// - Uses checkBounds() for safe validation
//
// 2. deserializeDataResponse (lines 642-680):
// - FIXED: buffer.len - offset underflow (twice: for data_id and data)
// - FIXED: offset + data_id_len overflow
// - FIXED: offset + data_len overflow
// - Uses checkBounds() for safe validation
//
// 3. deserializeDataChunk (lines 683-717):
// - FIXED: buffer.len - offset underflow
// - FIXED: offset + data_id_len overflow
// - Uses checkBounds() for safe validation
//
// 4. TransferMessage.serialize (transfer.zig line 63-68):
// - FIXED: HEADER_SIZE + peer_id.len + data.len overflow
// - Uses std.math.add for safe arithmetic
//
// 5. TransferMessage.deserialize (transfer.zig line 141-150):
// - FIXED: peer_id_len + data_len overflow
// - FIXED: offset + combined_len underflow/overflow
// - Uses std.math.add for safe arithmetic
//
// All fixes use the following pattern:
// - Check offset > buffer.len BEFORE subtraction
// - Use safeAdd() or std.math.add() to detect overflow
// - Use checkBounds() helper for common pattern
// - Validate against MAX_MESSAGE_SIZE limits
}

View File

@@ -0,0 +1,326 @@
//! Integration tests for message encryption in the serialization pipeline
const std = @import("std");
const testing = std.testing;
// Import from protocol module
const protocol_mod = @import("protocol");
const crypto = protocol_mod.crypto;
const serializer = protocol_mod.serializer;
const message = protocol_mod.message;
const protocol = protocol_mod.protocol;
test "message roundtrip with encryption enabled" {
const allocator = testing.allocator;
// Set up crypto managers for two peers
var crypto_mgr_a = crypto.CryptoManager.init(allocator);
defer crypto_mgr_a.deinit();
var crypto_mgr_b = crypto.CryptoManager.init(allocator);
defer crypto_mgr_b.deinit();
// Create peer IDs
const peer_a_id = [_]u8{0xAA} ** 32;
const peer_b_id = [_]u8{0xBB} ** 32;
// Exchange keys - in real scenario, this would be done via key exchange protocol
const key_a = crypto_mgr_a.local_key;
const key_b = crypto_mgr_b.local_key;
// Set encryption keys
try crypto_mgr_a.setKeyForPeer(peer_b_id, key_b);
try crypto_mgr_b.setKeyForPeer(peer_a_id, key_a);
// Set HMAC keys (required for message authentication)
const hmac_key = [_]u8{0x55} ** 32;
try crypto_mgr_a.setHmacKeyForPeer(peer_b_id, hmac_key);
try crypto_mgr_b.setHmacKeyForPeer(peer_a_id, hmac_key);
// Create serializer with encryption enabled for peer A (sending to peer B)
// initFull takes: allocator, crypto_manager, enable_encryption, local_peer_id, remote_peer_id
var ser_a = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_a, peer_a_id, peer_b_id);
// Create serializer with encryption enabled for peer B (sending to peer A)
var ser_b = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_b, peer_b_id, peer_a_id);
// Create a test message
const ping = message.Ping.init(12345);
const msg = message.Message{ .ping = ping };
// Serialize with encryption (A -> B)
var send_buffer: [2048]u8 = undefined;
const serialized_size = try ser_a.serialize(msg, &send_buffer);
try testing.expect(serialized_size > 0);
try testing.expect(serialized_size <= send_buffer.len);
// Deserialize and decrypt on B's side
const base_msg = try ser_b.deserialize(send_buffer[0..serialized_size]);
defer if (base_msg.isEncrypted()) allocator.free(base_msg.payload);
// Verify the message was decrypted correctly
try testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
// Deserialize the full message
const full_msg = try ser_b.deserializeFull(base_msg);
try testing.expectEqual(protocol.MessageType.ping, full_msg.getType());
try testing.expectEqual(@as(u32, 12345), full_msg.ping.sequence);
}
test "encrypted messages have ENCRYPTED flag set" {
const allocator = testing.allocator;
// Set up crypto manager
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
// Create peer ID for destination (peer_b)
const peer_b_id = [_]u8{0xBB} ** 32;
// Set encryption key for peer B
const key_b = [_]u8{0x42} ** 32;
try crypto_mgr.setKeyForPeer(peer_b_id, key_b);
// Set HMAC key for peer B (required for authentication)
const hmac_key = [_]u8{0x55} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_b_id, hmac_key);
// Create serializer with encryption enabled - peer_id is the DESTINATION peer (peer_b) for key lookup
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_b_id);
// Create a test message with destination = peer_b_id
const ping = message.Ping.init(999);
const msg = message.Message{ .ping = ping };
// Serialize with encryption (use serializeEncrypted for actual encryption)
var send_buffer: [2048]u8 = undefined;
const serialized_size = try ser.serializeEncrypted(msg, &send_buffer);
// Deserialize to check encryption flag (only the serialized portion)
const base_msg = try ser.deserialize(send_buffer[0..serialized_size]);
// Verify ENCRYPTED flag is set
try testing.expect((base_msg.header.flags & protocol.MessageFlags.ENCRYPTED) != 0);
try testing.expect(base_msg.isEncrypted());
}
test "decryption failure on tampered ciphertext" {
const allocator = testing.allocator;
// Set up crypto managers
var crypto_mgr_a = crypto.CryptoManager.init(allocator);
defer crypto_mgr_a.deinit();
var crypto_mgr_b = crypto.CryptoManager.init(allocator);
defer crypto_mgr_b.deinit();
// Create peer IDs
const peer_a_id = [_]u8{0xAA} ** 32;
const peer_b_id = [_]u8{0xBB} ** 32;
// Exchange encryption keys
const key_a = crypto_mgr_a.local_key;
const key_b = crypto_mgr_b.local_key;
try crypto_mgr_a.setKeyForPeer(peer_b_id, key_b);
try crypto_mgr_b.setKeyForPeer(peer_a_id, key_a);
// Set HMAC keys for both peers
const hmac_key = [_]u8{0x77} ** 32;
try crypto_mgr_a.setHmacKeyForPeer(peer_b_id, hmac_key);
try crypto_mgr_b.setHmacKeyForPeer(peer_a_id, hmac_key);
// Create serializers - initFull(allocator, crypto_manager, enable_encryption, local_peer_id, remote_peer_id)
var ser_a = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_a, peer_a_id, peer_b_id);
var ser_b = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_b, peer_b_id, peer_a_id);
// Create and serialize a message
const ping = message.Ping.init(777);
const msg = message.Message{ .ping = ping };
var send_buffer: [2048]u8 = undefined;
const serialized_size = try ser_a.serialize(msg, &send_buffer);
// Tamper with the ciphertext (modify a byte in the payload)
const payload_start = protocol.Serialization.HEADER_SIZE + @sizeOf(message.MessageHeader);
if (payload_start < serialized_size) {
send_buffer[payload_start + 10] ^= 0xFF; // Flip bits
}
// Attempt to deserialize - should fail due to tampered ciphertext
// Tampering causes HMAC authentication to fail first
const result = ser_b.deserialize(send_buffer[0..serialized_size]);
try testing.expectError(serializer.SerializationError.AuthenticationFailed, result);
}
test "authentication is mandatory and works correctly" {
const allocator = testing.allocator;
// Set up crypto manager with HMAC key for authentication
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{0xAA} ** 32;
const hmac_key = [_]u8{0x55} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
// Create serializer WITH authentication (mandatory now)
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
// Create a test message
const ping = message.Ping.init(555);
const msg = message.Message{ .ping = ping };
// Serialize with authentication
var send_buffer: [2048]u8 = undefined;
const serialized_size = try ser.serialize(msg, &send_buffer);
try testing.expect(serialized_size > 0);
// Deserialize (authentication is verified)
const base_msg = try ser.deserialize(send_buffer[0..serialized_size]);
// Verify message was authenticated
try testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
// Verify message content
const full_msg = try ser.deserializeFull(base_msg);
try testing.expectEqual(protocol.MessageType.ping, full_msg.getType());
try testing.expectEqual(@as(u32, 555), full_msg.ping.sequence);
}
test "encryption enabled but no encryption key for peer - uses HMAC only" {
const allocator = testing.allocator;
// Set up crypto manager with HMAC key but no encryption key
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
// Destination peer ID
const peer_b_id = [_]u8{0xBB} ** 32;
// Set HMAC key but no encryption key
const hmac_key = [_]u8{0x55} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_b_id, hmac_key);
// Create serializer with encryption enabled but no encryption key
// peer_id is the DESTINATION peer (peer_b) for key lookup
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_b_id);
// Create a test message
const ping = message.Ping.init(333);
const msg = message.Message{ .ping = ping };
// Serialize - should work but without encryption (no encryption key)
var send_buffer: [2048]u8 = undefined;
const serialized_size = try ser.serialize(msg, &send_buffer);
// Deserialize to check flag - should NOT be encrypted (but is authenticated)
const base_msg = try ser.deserialize(send_buffer[0..serialized_size]);
try testing.expect(!base_msg.isEncrypted());
try testing.expect((base_msg.header.flags & protocol.MessageFlags.ENCRYPTED) == 0);
}
test "roundtrip with different message types" {
const allocator = testing.allocator;
// Set up crypto managers
var crypto_mgr_a = crypto.CryptoManager.init(allocator);
defer crypto_mgr_a.deinit();
var crypto_mgr_b = crypto.CryptoManager.init(allocator);
defer crypto_mgr_b.deinit();
const peer_a_id = [_]u8{0xAA} ** 32;
const peer_b_id = [_]u8{0xBB} ** 32;
// Set encryption keys
const key_a = crypto_mgr_a.local_key;
const key_b = crypto_mgr_b.local_key;
try crypto_mgr_a.setKeyForPeer(peer_b_id, key_b);
try crypto_mgr_b.setKeyForPeer(peer_a_id, key_a);
// Set HMAC keys for message authentication
const hmac_key = [_]u8{0x88} ** 32;
try crypto_mgr_a.setHmacKeyForPeer(peer_b_id, hmac_key);
try crypto_mgr_b.setHmacKeyForPeer(peer_a_id, hmac_key);
// initFull(allocator, crypto_manager, enable_encryption, local_peer_id, remote_peer_id)
var ser_a = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_a, peer_a_id, peer_b_id);
var ser_b = serializer.MessageSerializer.initFull(allocator, &crypto_mgr_b, peer_b_id, peer_a_id);
// Test with Pong message
{
const pong = message.Pong.init(123, 456);
const msg = message.Message{ .pong = pong };
var buffer: [2048]u8 = undefined;
const size = try ser_a.serialize(msg, &buffer);
const base_msg = try ser_b.deserialize(buffer[0..size]);
defer if (base_msg.isEncrypted()) allocator.free(base_msg.payload);
const full_msg = try ser_b.deserializeFull(base_msg);
try testing.expectEqual(protocol.MessageType.pong, full_msg.getType());
try testing.expectEqual(@as(u32, 123), full_msg.pong.sequence);
try testing.expectEqual(@as(u32, 456), full_msg.pong.rtt);
}
// Test with TopologyQuery message
{
const query = message.TopologyQuery.init(789, 5);
const msg = message.Message{ .topology_query = query };
var buffer: [2048]u8 = undefined;
const size = try ser_a.serialize(msg, &buffer);
const base_msg = try ser_b.deserialize(buffer[0..size]);
defer if (base_msg.isEncrypted()) allocator.free(base_msg.payload);
const full_msg = try ser_b.deserializeFull(base_msg);
try testing.expectEqual(protocol.MessageType.topology_query, full_msg.getType());
try testing.expectEqual(@as(u64, 789), full_msg.topology_query.query_id);
try testing.expectEqual(@as(u8, 5), full_msg.topology_query.topology_type);
}
}
test "encrypted payload is larger than plaintext" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
// Destination peer ID
const peer_b_id = [_]u8{0xBB} ** 32;
// Set encryption key for peer B
const key_b = [_]u8{0x42} ** 32;
try crypto_mgr.setKeyForPeer(peer_b_id, key_b);
// Set HMAC key for peer B
const hmac_key = [_]u8{0x99} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_b_id, hmac_key);
// Serialize with encryption - peer_id is the DESTINATION peer (peer_b) for key lookup
var ser_encrypted = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_b_id);
// Serialize without encryption
// CRIT-NEW-9: Use test mode to allow null crypto_manager for comparison
var ser_plain = serializer.MessageSerializer.initInsecureForTesting(allocator);
const ping = message.Ping.init(111);
const msg = message.Message{ .ping = ping };
var encrypted_buffer: [2048]u8 = undefined;
var plain_buffer: [2048]u8 = undefined;
// Use serializeEncrypted to actually encrypt (not just authenticate)
const encrypted_size = try ser_encrypted.serializeEncrypted(msg, &encrypted_buffer);
const plain_size = try ser_plain.serialize(msg, &plain_buffer);
// Encrypted size should be larger due to nonce (12) + tag (16) + HMAC (32) = 60 extra bytes
try testing.expect(encrypted_size > plain_size);
try testing.expectEqual(plain_size + 60, encrypted_size);
}

View File

@@ -0,0 +1,514 @@
//! Message handler framework tests
const std = @import("std");
const protocol = @import("../../src/protocol/protocol.zig");
const message = @import("../../src/protocol/message.zig");
const handler = @import("../../src/protocol/handler.zig");
test "handler context initialization" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
try std.testing.expectEqual(@as(u64, 0), metrics.messages_processed);
try std.testing.expectEqual(@as(u64, 0), metrics.messages_failed);
try std.testing.expectEqual(@as(u16, 0), metrics.handlers_registered);
try std.testing.expectEqual(@as(f64, 0.0), metrics.average_processing_time);
// Test metrics recording
metrics.recordMessageProcessed(0.1);
try std.testing.expectEqual(@as(u64, 1), metrics.messages_processed);
try std.testing.expectEqual(@as(f64, 0.1), metrics.average_processing_time);
metrics.recordMessageFailed();
try std.testing.expectEqual(@as(u64, 1), metrics.messages_failed);
try std.testing.expectEqual(@as(f64, 0.5), metrics.getSuccessRate());
// Test context creation
var context = handler.HandlerContext.init(allocator, &metrics);
try std.testing.expect(context.allocator == allocator);
try std.testing.expect(context.metrics == &metrics);
try std.testing.expectEqual(null, context.router);
context.setRouter(@as(*anyopaque, @ptrCast(&context)));
try std.testing.expect(context.router != null);
}
test "handler metrics tracking" {
var metrics = handler.HandlerMetrics.init();
// Initial state
try std.testing.expectEqual(@as(u64, 0), metrics.messages_processed);
try std.testing.expectEqual(@as(u64, 0), metrics.messages_failed);
try std.testing.expectEqual(@as(f64, 1.0), metrics.getSuccessRate());
// Record processed messages
metrics.recordMessageProcessed(0.1);
metrics.recordMessageProcessed(0.2);
metrics.recordMessageProcessed(0.3);
try std.testing.expectEqual(@as(u64, 3), metrics.messages_processed);
try std.testing.expect(metrics.average_processing_time > 0.0);
// Record failed messages
metrics.recordMessageFailed();
metrics.recordMessageFailed();
try std.testing.expectEqual(@as(u64, 2), metrics.messages_failed);
try std.testing.expectEqual(@as(f64, 3.0/5.0), metrics.getSuccessRate());
// Test average calculation
metrics.recordMessageProcessed(0.4);
try std.testing.expect(metrics.average_processing_time > 0.2); // Should be weighted average
}
test "message handler creation" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var test_handler = handler.MessageHandler.init(
struct {
fn testFunc(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc,
&context,
.ping,
);
try std.testing.expectEqual(protocol.MessageType.ping, test_handler.msg_type);
try std.testing.expectEqual(&context, test_handler.context);
try std.testing.expectEqual(@as(u8, 0), test_handler.priority);
}
test "handler registry initialization" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
try std.testing.expectEqual(@as(usize, 0), registry.handlers.count());
try std.testing.expect(registry.allocator == allocator);
const context = registry.getContext();
try std.testing.expect(context != null);
}
test "handler registration" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var handler1 = handler.MessageHandler.init(
struct {
fn testFunc1(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc1,
&context,
.ping,
);
var handler2 = handler.MessageHandler.init(
struct {
fn testFunc2(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc2,
&context,
.ping,
);
// Register first handler
try registry.registerHandler(.ping, handler1);
try std.testing.expectEqual(@as(usize, 1), registry.handlers.count());
try std.testing.expectEqual(@as(u16, 1), registry.context.metrics.handlers_registered);
// Register second handler for same message type
try registry.registerHandler(.ping, handler2);
try std.testing.expectEqual(@as(usize, 1), registry.handlers.count()); // Still one key
try std.testing.expectEqual(@as(u16, 2), registry.context.metrics.handlers_registered);
// Register handler for different message type
var handler3 = handler.MessageHandler.init(
struct {
fn testFunc3(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc3,
&context,
.pong,
);
try registry.registerHandler(.pong, handler3);
try std.testing.expectEqual(@as(usize, 2), registry.handlers.count());
try std.testing.expectEqual(@as(u16, 3), registry.context.metrics.handlers_registered);
}
test "handler unregistration" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var handler1 = handler.MessageHandler.init(
struct {
fn testFunc(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc,
&context,
.ping,
);
var handler2 = handler.MessageHandler.init(
struct {
fn testFunc(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testFunc,
&context,
.ping,
);
// Register handlers
try registry.registerHandler(.ping, handler1);
try registry.registerHandler(.ping, handler2);
// Unregister all handlers for ping
registry.unregisterHandlers(.ping);
try std.testing.expectEqual(@as(usize, 0), registry.handlers.count());
try std.testing.expectEqual(@as(u16, 0), registry.context.metrics.handlers_registered);
}
test "message processing" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var called = false;
var handler_instance = handler.MessageHandler.init(
struct {
fn testFunc(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
const context_ptr = @as(*handler.HandlerContext, @ptrCast(@alignCast(ctx)));
context_ptr.metrics.recordMessageProcessed(0.0);
called = true;
}
}.testFunc,
&context,
.ping,
);
try registry.registerHandler(.ping, handler_instance);
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
try std.testing.expect(called);
try std.testing.expectEqual(@as(u64, 1), context.metrics.messages_processed);
}
test "error handling in message processing" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var handler_instance = handler.MessageHandler.init(
struct {
fn errorFunc(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
const context_ptr = @as(*handler.HandlerContext, @ptrCast(@alignCast(ctx)));
context_ptr.metrics.recordMessageFailed();
return error.TestError;
}
}.errorFunc,
&context,
.ping,
);
try registry.registerHandler(.ping, handler_instance);
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try std.testing.expectError(error.TestError, registry.processMessage(msg));
try std.testing.expectEqual(@as(u64, 1), context.metrics.messages_failed);
}
test "multiple handlers processing" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var call_count: u8 = 0;
var handler1 = handler.MessageHandler.init(
struct {
fn func1(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
call_count += 1;
}
}.func1,
&context,
.ping,
);
var handler2 = handler.MessageHandler.init(
struct {
fn func2(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
call_count += 10;
}
}.func2,
&context,
.ping,
);
try registry.registerHandler(.ping, handler1);
try registry.registerHandler(.ping, handler2);
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
try std.testing.expectEqual(@as(u8, 11), call_count); // Both handlers should be called
}
test "handler priority ordering" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var execution_order = std.ArrayList(u8).init(allocator);
defer execution_order.deinit();
var handler1 = handler.MessageHandler.init(
struct {
fn func1(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
const order_ptr = @as(*std.ArrayList(u8), @ptrCast(@alignCast(ctx)));
order_ptr.append(1) catch {};
}
}.func1,
&context,
.ping,
);
handler1.priority = 1; // Lower priority
var handler2 = handler.MessageHandler.init(
struct {
fn func2(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
const order_ptr = @as(*std.ArrayList(u8), @ptrCast(@alignCast(ctx)));
order_ptr.append(2) catch {};
}
}.func2,
&context,
.ping,
);
handler2.priority = 2; // Higher priority
try registry.registerHandler(.ping, handler1);
try registry.registerHandler(.ping, handler2);
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
// Higher priority handler should be called first
try std.testing.expectEqual(@as(usize, 2), execution_order.items.len);
try std.testing.expectEqual(@as(u8, 2), execution_order.items[0]); // High priority first
try std.testing.expectEqual(@as(u8, 1), execution_order.items[1]); // Low priority second
}
test "discovery handler" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var discovery_handler = handler.DiscoveryHandler.init();
// Test hello handling
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
try discovery_handler.handleHello(hello, &context);
// Test response handling
const response = message.DiscoveryResponse.init(123, 0x02, .{
.ip = .{192, 168, 1, 1} ** 4,
.port = 9090,
});
try discovery_handler.handleResponse(response, &context);
// Test announce handling
const announce = message.DiscoveryAnnounce.init(0x03, .{
.ip = .{10, 0, 0, 1} ** 4,
.port = 7070,
});
try discovery_handler.handleAnnounce(announce, &context);
}
test "topology handler" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var topology_handler = handler.TopologyHandler.init();
// Test query handling
const query = message.TopologyQuery.init(456, 1);
try topology_handler.handleQuery(query, &context);
// Test response handling
const response = message.TopologyResponse.init(456, "topology data");
try topology_handler.handleResponse(response, &context);
// Test update handling
const update = message.TopologyUpdate.init(1000, "topology changes");
try topology_handler.handleUpdate(update, &context);
}
test "data handler" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var data_handler = handler.DataHandler.init();
// Test request handling
const request = message.DataRequest.init(789, "data123", 1024, 4096);
try data_handler.handleRequest(request, &context);
// Test response handling
const response = message.DataResponse.init(789, "data123", "response data");
try data_handler.handleResponse(response, &context);
// Test chunk handling
const chunk = message.DataChunk.init(1, "data123", "chunk data", false);
try data_handler.handleChunk(chunk, &context);
const final_chunk = message.DataChunk.init(2, "data123", "final chunk", true);
try data_handler.handleChunk(final_chunk, &context);
}
test "control handler" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var control_handler = handler.ControlHandler.init();
// Test ping handling
const ping = message.Ping.init(999);
try control_handler.handlePing(ping, &context);
// Test pong handling
const pong = message.Pong.init(999, 150);
try control_handler.handlePong(pong, &context);
// Test error handling
const error_msg = message.Error.init(888, .invalid_message, "test error");
try control_handler.handleError(error_msg, &context);
}
test "app handler" {
const allocator = std.testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var app_handler = handler.AppHandler.init();
// Test app data handling
const app_data = message.AppData.init(1000, "app data content");
try app_handler.handleAppData(app_data, &context);
// Test app control handling
const app_control = message.AppControl.init(1000, 2000, "control params");
try app_handler.handleAppControl(app_control, &context);
}
test "handler builder" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var builder = handler.HandlerBuilder.init(&registry);
// Initially no handlers registered
try std.testing.expectEqual(@as(u16, 0), registry.context.metrics.handlers_registered);
// Note: This test would require implementing the registerDefaultHandlers method
// For now, we'll just test that the builder is created properly
try std.testing.expect(builder.registry == &registry);
}
test "async message processor initialization" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var processor = handler.AsyncMessageProcessor.init(allocator, &registry);
try std.testing.expect(processor.allocator == allocator);
try std.testing.expect(processor.registry == &registry);
try std.testing.expectEqual(@as(usize, 0), processor.queue.items.len);
try std.testing.expectEqual(@as(usize, 0), processor.workers.items.len);
try std.testing.expect(processor.shutdown.load(.monotonic) == false);
}
test "async message queue" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
var processor = handler.AsyncMessageProcessor.init(allocator, &registry);
defer processor.deinit();
// Queue a message
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try processor.queueMessage(msg);
try std.testing.expectEqual(@as(usize, 1), processor.queue.items.len);
// Queue another message
const pong = message.Pong.init(456, 100);
const msg2 = message.Message{ .pong = pong };
try processor.queueMessage(msg2);
try std.testing.expectEqual(@as(usize, 2), processor.queue.items.len);
}

View File

@@ -0,0 +1,267 @@
//! Comprehensive tests for complete protocol handler implementations
//! Tests that all handlers actually process and send responses
const std = @import("std");
const testing = std.testing;
const handler = @import("../../src/protocol/handler.zig");
const handler_impl = @import("../../src/protocol/handler_impl.zig");
const message = @import("../../src/protocol/message.zig");
const protocol = @import("../../src/protocol/protocol.zig");
test "handleDiscoveryHello sends response" {
const allocator = testing.allocator;
// Setup handler context
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
// Create discovery hello message
const hello = message.DiscoveryHello{
.version = protocol.PROTOCOL_VERSION,
.capabilities = 0x0F,
.address = .{
.ip = [_]u8{127} ++ [_]u8{0} ++ [_]u8{0} ++ [_]u8{1},
.port = 8888,
},
};
// Test handler (without full network setup, this will return NoNetworkSender error)
const result = handler_impl.handleDiscoveryHello(hello, &context);
// Verify it attempts to send (will fail without network_sender, but that's expected)
try testing.expectError(error.NoNetworkSender, result);
}
test "handlePing sends pong response" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{5} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
// Create a ping times map (required by handlePing)
var ping_times = std.AutoHashMap(u32, i64).init(allocator);
defer ping_times.deinit();
const ping = message.Ping{
.sequence = 789,
};
// Test handler
const result = handler_impl.handlePing(ping, &context, &ping_times);
// Should attempt to send pong (will fail without network_sender)
try testing.expectError(error.NoNetworkSender, result);
}
test "handlePong updates metrics" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{6} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
// Create a ping times map
var ping_times = std.AutoHashMap(u32, i64).init(allocator);
defer ping_times.deinit();
const pong = message.Pong{
.sequence = 789,
.rtt = 42,
};
// Test handler (should complete without peer_manager)
try handler_impl.handlePong(pong, &context, &ping_times);
// Verify metrics were updated
try testing.expectEqual(@as(u64, 1), metrics.messages_processed.load(.monotonic));
}
test "handleError logs and updates metrics" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{7} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
const error_msg = message.Error{
.error_code = .routing_error,
.message = "Test error message",
.original_id = 999,
};
// Test handler
try handler_impl.handleError(error_msg, &context);
// Verify error metrics were updated
try testing.expectEqual(@as(u64, 1), metrics.messages_failed.load(.monotonic));
}
test "handleDataRequest attempts to send response" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{8} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
var data_id: [32]u8 = [_]u8{0xAB} ** 32;
const request = message.DataRequest{
.request_id = 111,
.data_id = &data_id,
.offset = 0,
.size = 16384,
};
// Test handler (will error without file_manager)
const result = handler_impl.handleDataRequest(request, &context);
// Should return error due to missing file manager
try testing.expectError(error.FileManagerNotConfigured, result);
}
test "handleDataResponse processes data" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{9} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
var data_id: [32]u8 = [_]u8{0xCD} ** 32;
var test_data: [100]u8 = [_]u8{0xFF} ** 100;
const response = message.DataResponse{
.request_id = 111,
.data_id = &data_id,
.data = &test_data,
.total_size = null,
};
// Test handler (will error without request_tracker - new behavior)
const result = handler_impl.handleDataResponse(response, &context);
// Should return error due to missing request tracker
try testing.expectError(error.InvalidData, result);
}
test "handleRouteQuery sends route response" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var source_id: message.NodeId = [_]u8{3} ** protocol.Network.NODE_ID_SIZE;
context.setSource(source_id);
var target: message.NodeId = [_]u8{10} ** protocol.Network.NODE_ID_SIZE;
const query = message.RouteQuery{
.query_id = 456,
.target = target,
};
// Test handler (will error without routing_table)
const result = handler_impl.handleRouteQuery(query, &context);
// Should attempt to send response (will fail without network_sender or routing_table)
try testing.expect(result == error.NoNetworkSender or result == void{});
}
test "Handler context sendResponse validates network_sender" {
const allocator = testing.allocator;
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var dest_id: message.NodeId = [_]u8{12} ** protocol.Network.NODE_ID_SIZE;
const ping_msg = message.Message{
.ping = message.Ping{ .sequence = 123 },
};
// Try to send without network_sender - should error
const result = context.sendResponse(dest_id, ping_msg);
try testing.expectError(error.NoNetworkSender, result);
}
test "Ping/Pong roundtrip flow" {
const allocator = testing.allocator;
// Setup context
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var peer_id: message.NodeId = [_]u8{13} ** protocol.Network.NODE_ID_SIZE;
context.setSource(peer_id);
var ping_times = std.AutoHashMap(u32, i64).init(allocator);
defer ping_times.deinit();
// Receive ping
const ping = message.Ping{ .sequence = 999 };
// Process ping (will error without network_sender, but validates flow)
const ping_result = handler_impl.handlePing(ping, &context, &ping_times);
try testing.expectError(error.NoNetworkSender, ping_result);
// Receive pong (simulated response)
const pong = message.Pong{ .sequence = 999, .rtt = 25 };
// Process pong
try handler_impl.handlePong(pong, &context, &ping_times);
// Verify processing completed
try testing.expectEqual(@as(u64, 1), metrics.messages_processed.load(.monotonic));
}
test "Discovery handshake flow" {
const allocator = testing.allocator;
// Setup context
var metrics = handler.HandlerMetrics.init();
var context = handler.HandlerContext.init(allocator, &metrics);
var peer_id: message.NodeId = [_]u8{14} ** protocol.Network.NODE_ID_SIZE;
context.setSource(peer_id);
// Step 1: Receive Hello
const hello = message.DiscoveryHello{
.version = protocol.PROTOCOL_VERSION,
.capabilities = 0x0F,
.address = .{
.ip = [_]u8{192} ++ [_]u8{168} ++ [_]u8{1} ++ [_]u8{100},
.port = 9000,
},
};
const hello_result = handler_impl.handleDiscoveryHello(hello, &context);
try testing.expectError(error.NoNetworkSender, hello_result);
}
test "All handler implementations are accessible" {
// This test verifies that all handler functions are accessible
_ = handler_impl.handleDiscoveryHello;
_ = handler_impl.handlePing;
_ = handler_impl.handlePong;
_ = handler_impl.handleError;
_ = handler_impl.handleDataRequest;
_ = handler_impl.handleDataResponse;
_ = handler_impl.handleDataChunk;
_ = handler_impl.handleRouteQuery;
_ = handler_impl.handleRouteUpdate;
_ = handler_impl.handleKeyExchangeInit;
_ = handler_impl.handleKeyExchangeResponse;
}

View File

@@ -0,0 +1,369 @@
//! Comprehensive tests for message handler framework
//! Tests handler registration, priority ordering, dispatch, error propagation, and metrics
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const message = protocol.message;
const handler_mod = protocol.handler;
test "handler: register single handler" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const handler = handler_mod.MessageHandler.init(
struct {
fn testHandler(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
}
}.testHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler);
try testing.expectEqual(@as(u16, 1), registry.context.metrics.handlers_registered);
}
test "handler: register multiple handlers for same type" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const handler1 = handler_mod.MessageHandler.init(
struct {
fn handler1(_: message.Message, _: *anyopaque) !void {}
}.handler1,
registry.getContext(),
.ping,
);
const handler2 = handler_mod.MessageHandler.init(
struct {
fn handler2(_: message.Message, _: *anyopaque) !void {}
}.handler2,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler1);
try registry.registerHandler(.ping, handler2);
try testing.expectEqual(@as(u16, 2), registry.context.metrics.handlers_registered);
}
test "handler: priority ordering - high before normal" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
var execution_order = std.ArrayList(u8).init(allocator);
defer execution_order.deinit();
var handler_high = handler_mod.MessageHandler.init(
struct {
fn highHandler(_: message.Message, ctx: *anyopaque) !void {
const order = @as(*std.ArrayList(u8), @ptrCast(@alignCast(ctx)));
try order.append(2); // High priority = 2
}
}.highHandler,
&execution_order,
.ping,
);
handler_high.priority = 2;
var handler_normal = handler_mod.MessageHandler.init(
struct {
fn normalHandler(_: message.Message, ctx: *anyopaque) !void {
const order = @as(*std.ArrayList(u8), @ptrCast(@alignCast(ctx)));
try order.append(1); // Normal priority = 1
}
}.normalHandler,
&execution_order,
.ping,
);
handler_normal.priority = 1;
// Register in reverse order to test sorting
try registry.registerHandler(.ping, handler_normal);
try registry.registerHandler(.ping, handler_high);
const ping = message.Ping.init(100);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
// High priority (2) should execute before normal (1)
try testing.expectEqual(@as(usize, 2), execution_order.items.len);
try testing.expectEqual(@as(u8, 2), execution_order.items[0]);
try testing.expectEqual(@as(u8, 1), execution_order.items[1]);
}
test "handler: message dispatch to correct handler" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
var ping_called = false;
var pong_called = false;
const ping_handler = handler_mod.MessageHandler.init(
struct {
fn handlePing(_: message.Message, ctx: *anyopaque) !void {
const called = @as(*bool, @ptrCast(@alignCast(ctx)));
called.* = true;
}
}.handlePing,
&ping_called,
.ping,
);
const pong_handler = handler_mod.MessageHandler.init(
struct {
fn handlePong(_: message.Message, ctx: *anyopaque) !void {
const called = @as(*bool, @ptrCast(@alignCast(ctx)));
called.* = true;
}
}.handlePong,
&pong_called,
.pong,
);
try registry.registerHandler(.ping, ping_handler);
try registry.registerHandler(.pong, pong_handler);
// Send ping message
const ping = message.Ping.init(111);
const ping_msg = message.Message{ .ping = ping };
try registry.processMessage(ping_msg);
try testing.expect(ping_called);
try testing.expect(!pong_called);
}
test "handler: unknown message type handling" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// No handlers registered
const ping = message.Ping.init(222);
const msg = message.Message{ .ping = ping };
// Should not error, just silently ignore
try registry.processMessage(msg);
}
test "handler: error propagation from handler" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const error_handler = handler_mod.MessageHandler.init(
struct {
fn failingHandler(_: message.Message, _: *anyopaque) !void {
return error.TestError;
}
}.failingHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, error_handler);
const ping = message.Ping.init(333);
const msg = message.Message{ .ping = ping };
const result = registry.processMessage(msg);
try testing.expectError(error.TestError, result);
// Metrics should reflect failure
try testing.expectEqual(@as(u64, 1), registry.context.metrics.messages_failed);
}
test "handler: metrics accuracy - messages processed" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const handler = handler_mod.MessageHandler.init(
struct {
fn simpleHandler(_: message.Message, _: *anyopaque) !void {}
}.simpleHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler);
// Process 10 messages
var i: usize = 0;
while (i < 10) : (i += 1) {
const ping = message.Ping.init(@as(u32, @intCast(i)));
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
}
try testing.expectEqual(@as(u64, 10), registry.context.metrics.messages_processed);
try testing.expectEqual(@as(u64, 0), registry.context.metrics.messages_failed);
}
test "handler: metrics success rate calculation" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
var counter: u32 = 0;
const handler = handler_mod.MessageHandler.init(
struct {
fn maybeFailHandler(_: message.Message, ctx: *anyopaque) !void {
const count = @as(*u32, @ptrCast(@alignCast(ctx)));
count.* += 1;
// Fail every other call
if (count.* % 2 == 0) {
return error.TestError;
}
}
}.maybeFailHandler,
&counter,
.ping,
);
try registry.registerHandler(.ping, handler);
// Process 10 messages (5 should succeed, 5 should fail)
var i: usize = 0;
while (i < 10) : (i += 1) {
const ping = message.Ping.init(@as(u32, @intCast(i)));
const msg = message.Message{ .ping = ping };
_ = registry.processMessage(msg) catch {};
}
const success_rate = registry.context.metrics.getSuccessRate();
try testing.expect(success_rate > 0.4 and success_rate < 0.6); // Approximately 0.5
}
test "handler: unregister handlers" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const handler = handler_mod.MessageHandler.init(
struct {
fn testHandler(_: message.Message, _: *anyopaque) !void {}
}.testHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler);
try testing.expectEqual(@as(u16, 1), registry.context.metrics.handlers_registered);
registry.unregisterHandlers(.ping);
try testing.expectEqual(@as(u16, 0), registry.context.metrics.handlers_registered);
}
test "handler: context access in handler" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
var data: u32 = 42;
const handler = handler_mod.MessageHandler.init(
struct {
fn contextHandler(_: message.Message, ctx: *anyopaque) !void {
const value = @as(*u32, @ptrCast(@alignCast(ctx)));
value.* += 10;
}
}.contextHandler,
&data,
.ping,
);
try registry.registerHandler(.ping, handler);
const ping = message.Ping.init(444);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
try testing.expectEqual(@as(u32, 52), data);
}
test "handler: multiple message types with different handlers" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
var ping_count: u32 = 0;
var pong_count: u32 = 0;
const ping_handler = handler_mod.MessageHandler.init(
struct {
fn handlePing(_: message.Message, ctx: *anyopaque) !void {
const count = @as(*u32, @ptrCast(@alignCast(ctx)));
count.* += 1;
}
}.handlePing,
&ping_count,
.ping,
);
const pong_handler = handler_mod.MessageHandler.init(
struct {
fn handlePong(_: message.Message, ctx: *anyopaque) !void {
const count = @as(*u32, @ptrCast(@alignCast(ctx)));
count.* += 1;
}
}.handlePong,
&pong_count,
.pong,
);
try registry.registerHandler(.ping, ping_handler);
try registry.registerHandler(.pong, pong_handler);
// Process mix of messages
var i: usize = 0;
while (i < 5) : (i += 1) {
const ping = message.Ping.init(@as(u32, @intCast(i)));
const ping_msg = message.Message{ .ping = ping };
try registry.processMessage(ping_msg);
const pong = message.Pong.init(@as(u32, @intCast(i)), 10);
const pong_msg = message.Message{ .pong = pong };
try registry.processMessage(pong_msg);
}
try testing.expectEqual(@as(u32, 5), ping_count);
try testing.expectEqual(@as(u32, 5), pong_count);
}
test "handler: average processing time tracking" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const handler = handler_mod.MessageHandler.init(
struct {
fn slowHandler(_: message.Message, _: *anyopaque) !void {
std.time.sleep(std.time.ns_per_ms * 1); // 1ms delay
}
}.slowHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler);
const ping = message.Ping.init(555);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
// Average processing time should be > 0
try testing.expect(registry.context.metrics.average_processing_time >= 0.0);
}

View File

@@ -0,0 +1,581 @@
//! Comprehensive tests for Diffie-Hellman key exchange implementation
//! Tests the full key exchange handshake between peers
const std = @import("std");
const crypto_mod = @import("protocol").crypto;
const message_mod = @import("protocol").message;
const testing = std.testing;
test "KeyExchange: generate key pair" {
const kp = try crypto_mod.KeyExchange.generateKeyPair();
// Verify keys are not all zeros
var public_zero = true;
var secret_zero = true;
for (kp.public) |byte| {
if (byte != 0) {
public_zero = false;
break;
}
}
for (kp.secret) |byte| {
if (byte != 0) {
secret_zero = false;
break;
}
}
try testing.expect(!public_zero);
try testing.expect(!secret_zero);
}
test "KeyExchange: compute shared secret" {
// Generate two key pairs
const alice_kp = try crypto_mod.KeyExchange.generateKeyPair();
const bob_kp = try crypto_mod.KeyExchange.generateKeyPair();
// Compute shared secrets
const alice_shared = try crypto_mod.KeyExchange.computeSharedSecret(alice_kp.secret, bob_kp.public);
const bob_shared = try crypto_mod.KeyExchange.computeSharedSecret(bob_kp.secret, alice_kp.public);
// Both should derive the same shared secret
try testing.expectEqualSlices(u8, &alice_shared, &bob_shared);
// Shared secret should not be all zeros
var is_zero = true;
for (alice_shared) |byte| {
if (byte != 0) {
is_zero = false;
break;
}
}
try testing.expect(!is_zero);
}
test "KeyExchange: reject all-zero public key" {
const kp = try crypto_mod.KeyExchange.generateKeyPair();
const zero_key = [_]u8{0} ** 32;
try testing.expectError(
crypto_mod.CryptoError.InvalidPublicKey,
crypto_mod.KeyExchange.computeSharedSecret(kp.secret, zero_key),
);
}
test "KeyExchange: derive keys from shared secret" {
const shared_secret = [_]u8{0xAB} ** 32;
const our_public = [_]u8{0x01} ** 32;
const their_public = [_]u8{0x02} ** 32;
const session_nonce = [_]u8{0x42} ** 32;
const keys = try crypto_mod.KeyExchange.deriveKeys(shared_secret, our_public, their_public, session_nonce);
// Verify keys are not all zeros
var enc_zero = true;
var hmac_zero = true;
for (keys.encryption_key) |byte| {
if (byte != 0) {
enc_zero = false;
break;
}
}
for (keys.hmac_key) |byte| {
if (byte != 0) {
hmac_zero = false;
break;
}
}
try testing.expect(!enc_zero);
try testing.expect(!hmac_zero);
// Encryption and HMAC keys should be different
try testing.expect(!std.mem.eql(u8, &keys.encryption_key, &keys.hmac_key));
}
test "KeyExchange: derived keys are deterministic" {
const shared_secret = [_]u8{0x42} ** 32;
const our_public = [_]u8{0x01} ** 32;
const their_public = [_]u8{0x02} ** 32;
const session_nonce = [_]u8{0x99} ** 32;
const keys1 = try crypto_mod.KeyExchange.deriveKeys(shared_secret, our_public, their_public, session_nonce);
const keys2 = try crypto_mod.KeyExchange.deriveKeys(shared_secret, our_public, their_public, session_nonce);
// Same inputs should produce same derived keys
try testing.expectEqualSlices(u8, &keys1.encryption_key, &keys2.encryption_key);
try testing.expectEqualSlices(u8, &keys1.hmac_key, &keys2.hmac_key);
}
test "KeyExchange: different shared secrets produce different keys" {
const shared_secret1 = [_]u8{0x11} ** 32;
const shared_secret2 = [_]u8{0x22} ** 32;
const our_public = [_]u8{0x01} ** 32;
const their_public = [_]u8{0x02} ** 32;
const session_nonce = [_]u8{0x42} ** 32;
const keys1 = try crypto_mod.KeyExchange.deriveKeys(shared_secret1, our_public, their_public, session_nonce);
const keys2 = try crypto_mod.KeyExchange.deriveKeys(shared_secret2, our_public, their_public, session_nonce);
// Different shared secrets should produce different keys
try testing.expect(!std.mem.eql(u8, &keys1.encryption_key, &keys2.encryption_key));
try testing.expect(!std.mem.eql(u8, &keys1.hmac_key, &keys2.hmac_key));
}
test "CryptoManager: full key exchange handshake" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Alice initiates key exchange (with signature)
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
try testing.expect(alice_crypto.isKeyExchangeInProgress(bob_id));
// Bob responds to key exchange (verifying Alice's signature and timestamp)
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try testing.expect(bob_crypto.hasKeyForPeer(alice_id));
// Alice completes key exchange (verifying Bob's signature, timestamp, and session nonce echo)
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
try testing.expect(alice_crypto.hasKeyForPeer(bob_id));
try testing.expect(!alice_crypto.isKeyExchangeInProgress(bob_id));
// Both peers should have keys for each other
try testing.expect(alice_crypto.hasKeyForPeer(bob_id));
try testing.expect(bob_crypto.hasKeyForPeer(alice_id));
}
test "CryptoManager: derived encryption keys work" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Perform key exchange with signatures
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
// Test encryption/decryption with derived keys
const plaintext = "Hello, secure world!";
// Alice encrypts for Bob
const ciphertext = try alice_crypto.encrypt(bob_id, plaintext);
defer allocator.free(ciphertext);
// Bob decrypts from Alice
const decrypted = try bob_crypto.decrypt(alice_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "CryptoManager: both peers derive same shared secret" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Perform key exchange with signatures
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
// Both should be able to communicate securely
const alice_msg = "From Alice";
const bob_msg = "From Bob";
// Alice -> Bob
const alice_ciphertext = try alice_crypto.encrypt(bob_id, alice_msg);
defer allocator.free(alice_ciphertext);
const bob_plaintext = try bob_crypto.decrypt(alice_id, alice_ciphertext);
defer allocator.free(bob_plaintext);
try testing.expectEqualStrings(alice_msg, bob_plaintext);
// Bob -> Alice
const bob_ciphertext = try bob_crypto.encrypt(alice_id, bob_msg);
defer allocator.free(bob_ciphertext);
const alice_plaintext = try alice_crypto.decrypt(bob_id, bob_ciphertext);
defer allocator.free(alice_plaintext);
try testing.expectEqualStrings(bob_msg, alice_plaintext);
}
test "CryptoManager: key exchange in progress prevents duplicate initiation" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{1} ** 32;
// First initiation should succeed
_ = try crypto.initiateKeyExchange(peer_id);
// Second initiation should fail
try testing.expectError(
crypto_mod.CryptoError.KeyExchangeInProgress,
crypto.initiateKeyExchange(peer_id),
);
}
test "CryptoManager: complete without initiate fails" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
const peer_id = [_]u8{1} ** 32;
const fake_public_key = [_]u8{0x42} ** 32;
const fake_signature = [_]u8{0} ** 64;
const fake_identity_key = [_]u8{0x42} ** 32;
// Completing without initiating should fail
const fake_timestamp: i64 = std.time.timestamp();
const fake_session_nonce = [_]u8{0} ** 32;
try testing.expectError(
crypto_mod.CryptoError.NoKeyExchangeInProgress,
crypto.completeKeyExchange(peer_id, fake_public_key, fake_signature, fake_identity_key, fake_timestamp, fake_session_nonce),
);
}
test "CryptoManager: simultaneous key exchange resolution" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = alice_crypto.local_key;
const bob_id = bob_crypto.local_key;
// Both initiate simultaneously
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const bob_init = try bob_crypto.initiateKeyExchange(alice_id);
// One should become responder based on peer ID comparison
// The one with lower peer ID becomes responder
const alice_is_lower = std.mem.lessThan(u8, &alice_id, &bob_id);
if (alice_is_lower) {
// Alice becomes responder
const alice_response = try alice_crypto.respondToKeyExchange(
bob_id,
bob_init.public_key,
bob_init.signature,
bob_init.identity_key,
bob_init.session_nonce,
bob_init.timestamp,
);
try bob_crypto.completeKeyExchange(
alice_id,
alice_response.public_key,
alice_response.signature,
alice_response.identity_key,
alice_response.timestamp,
alice_response.initiator_session_nonce,
);
} else {
// Bob becomes responder
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
}
// Both should end up with keys
try testing.expect(alice_crypto.hasKeyForPeer(bob_id));
try testing.expect(bob_crypto.hasKeyForPeer(alice_id));
}
test "CryptoManager: HMAC keys are also derived" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Perform key exchange with signatures
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
// Both should have HMAC keys
const alice_hmac = try alice_crypto.getHmacKeyForPeer(bob_id);
const bob_hmac = try bob_crypto.getHmacKeyForPeer(alice_id);
// HMAC keys should not be all zeros
var alice_zero = true;
var bob_zero = true;
for (alice_hmac) |byte| {
if (byte != 0) {
alice_zero = false;
break;
}
}
for (bob_hmac) |byte| {
if (byte != 0) {
bob_zero = false;
break;
}
}
try testing.expect(!alice_zero);
try testing.expect(!bob_zero);
// Both should have derived the same HMAC key
try testing.expectEqualSlices(u8, &alice_hmac, &bob_hmac);
}
test "Message: KeyExchangeInit creation" {
const public_key = [_]u8{0x42} ** 32;
const signature = [_]u8{0xAB} ** 64;
const identity_key = [_]u8{0xCD} ** 32;
const session_nonce = [_]u8{0x99} ** 32;
const msg = message_mod.KeyExchangeInit.init(public_key, signature, identity_key, session_nonce);
try testing.expectEqualSlices(u8, &public_key, &msg.initiator_public_key);
try testing.expectEqualSlices(u8, &signature, &msg.signature);
try testing.expectEqualSlices(u8, &identity_key, &msg.identity_key);
try testing.expectEqualSlices(u8, &session_nonce, &msg.session_nonce);
try testing.expectEqual(message_mod.KeyExchangeInit.msg_type, .key_exchange_init);
}
test "Message: KeyExchangeResponse creation" {
const public_key = [_]u8{0x84} ** 32;
const signature = [_]u8{0xEF} ** 64;
const identity_key = [_]u8{0x12} ** 32;
const msg = message_mod.KeyExchangeResponse.init(public_key, signature, identity_key);
try testing.expectEqualSlices(u8, &public_key, &msg.responder_public_key);
try testing.expectEqualSlices(u8, &signature, &msg.signature);
try testing.expectEqualSlices(u8, &identity_key, &msg.identity_key);
try testing.expectEqual(message_mod.KeyExchangeResponse.msg_type, .key_exchange_response);
}
test "Integration: full handshake with message types" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Step 1: Alice initiates (with signature and timestamp)
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const init_msg = message_mod.KeyExchangeInit.init(
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
// Step 2: Bob receives init and responds (verifying Alice's signature and timestamp)
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
init_msg.initiator_public_key,
init_msg.signature,
init_msg.identity_key,
init_msg.session_nonce,
init_msg.timestamp,
);
const response_msg = message_mod.KeyExchangeResponse.init(
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
// Step 3: Alice receives response and completes (verifying Bob's signature, timestamp, and nonce echo)
try alice_crypto.completeKeyExchange(
bob_id,
response_msg.responder_public_key,
response_msg.signature,
response_msg.identity_key,
response_msg.timestamp,
response_msg.initiator_session_nonce,
);
// Verify both have keys
try testing.expect(alice_crypto.hasKeyForPeer(bob_id));
try testing.expect(bob_crypto.hasKeyForPeer(alice_id));
// Verify encrypted communication works
const test_data = "Secure message after key exchange";
const encrypted = try alice_crypto.encrypt(bob_id, test_data);
defer allocator.free(encrypted);
const decrypted = try bob_crypto.decrypt(alice_id, encrypted);
defer allocator.free(decrypted);
try testing.expectEqualStrings(test_data, decrypted);
}
test "Security: different key pairs produce different shared secrets" {
// Generate two independent key exchanges
const kp1_alice = try crypto_mod.KeyExchange.generateKeyPair();
const kp1_bob = try crypto_mod.KeyExchange.generateKeyPair();
const kp2_alice = try crypto_mod.KeyExchange.generateKeyPair();
const kp2_bob = try crypto_mod.KeyExchange.generateKeyPair();
// Compute shared secrets
const shared1 = try crypto_mod.KeyExchange.computeSharedSecret(kp1_alice.secret, kp1_bob.public);
const shared2 = try crypto_mod.KeyExchange.computeSharedSecret(kp2_alice.secret, kp2_bob.public);
// Different key pairs should produce different shared secrets
try testing.expect(!std.mem.eql(u8, &shared1, &shared2));
}
test "Security: tampering with ciphertext fails after key exchange" {
const allocator = testing.allocator;
var alice_crypto = crypto_mod.CryptoManager.init(allocator);
defer alice_crypto.deinit();
var bob_crypto = crypto_mod.CryptoManager.init(allocator);
defer bob_crypto.deinit();
const alice_id = [_]u8{1} ** 32;
const bob_id = [_]u8{2} ** 32;
// Perform key exchange with signatures
const alice_init = try alice_crypto.initiateKeyExchange(bob_id);
const bob_response = try bob_crypto.respondToKeyExchange(
alice_id,
alice_init.public_key,
alice_init.signature,
alice_init.identity_key,
alice_init.session_nonce,
alice_init.timestamp,
);
try alice_crypto.completeKeyExchange(
bob_id,
bob_response.public_key,
bob_response.signature,
bob_response.identity_key,
bob_response.timestamp,
bob_response.initiator_session_nonce,
);
// Encrypt a message
const plaintext = "Secret message";
const ciphertext = try alice_crypto.encrypt(bob_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with the ciphertext
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[20] ^= 0xFF;
// Bob should detect tampering
try testing.expectError(
crypto_mod.CryptoError.DecryptionFailed,
bob_crypto.decrypt(alice_id, tampered),
);
}

View File

@@ -0,0 +1,404 @@
//! Protocol tests
const std = @import("std");
const protocol = @import("../src/protocol/protocol.zig");
const message = @import("../src/protocol/message.zig");
const serializer = @import("../src/protocol/serializer.zig");
const router = @import("../src/protocol/router.zig");
const handler = @import("../src/protocol/handler.zig");
test "protocol constants validation" {
try std.testing.expect(protocol.ProtocolHelpers.isValidMessageType(.ping));
try std.testing.expect(protocol.ProtocolHelpers.isValidMessageType(.discovery_hello));
try std.testing.expect(!protocol.ProtocolHelpers.isReservedMessageType(.ping));
try std.testing.expect(protocol.ProtocolHelpers.isReservedMessageType(@as(protocol.MessageType, @enumFromInt(0xF0))));
try std.testing.expect(protocol.ProtocolHelpers.isAppMessageType(.app_data));
try std.testing.expect(!protocol.ProtocolHelpers.isAppMessageType(.ping));
try std.testing.expect(protocol.ProtocolHelpers.isVersionCompatible(1));
try std.testing.expect(!protocol.ProtocolHelpers.isVersionCompatible(2));
try std.testing.expectEqualStrings("control", protocol.ProtocolHelpers.getMessageCategory(.ping));
try std.testing.expectEqualStrings("app", protocol.ProtocolHelpers.getMessageCategory(.app_data));
try std.testing.expectEqualStrings("discovery", protocol.ProtocolHelpers.getMessageCategory(.discovery_hello));
try std.testing.expectEqual(@as(u16, protocol.MAX_MESSAGE_SIZE), protocol.ProtocolHelpers.getMessageSizeLimit(.data_chunk));
try std.testing.expectEqual(@as(u16, 8192), protocol.ProtocolHelpers.getMessageSizeLimit(.ping));
}
test "message types and structures" {
const allocator = std.testing.allocator;
// Test message header creation
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
try std.testing.expectEqual(protocol.MessageType.ping, header.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 123), header.id);
try std.testing.expect(header.source[0] == 1);
try std.testing.expect(header.dest[0] == 2);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, header.version);
try std.testing.expectEqual(protocol.Serialization.MAGIC_NUMBER, header.magic);
// Test base message operations
var base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.getType());
try std.testing.expectEqual(@as(message.MessageId, 123), base_msg.getId());
try std.testing.expectEqual(source, base_msg.getSource());
try std.testing.expectEqual(dest, base_msg.getDest());
try std.testing.expect(!base_msg.isBroadcast());
try std.testing.expect(!base_msg.isEncrypted());
base_msg.header.flags |= protocol.MessageFlags.BROADCAST;
try std.testing.expect(base_msg.isBroadcast());
base_msg.header.flags |= protocol.MessageFlags.ENCRYPTED;
try std.testing.expect(base_msg.isEncrypted());
// Test TTL decrement
try std.testing.expect(base_msg.decrementTTL());
try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS - 1), base_msg.header.ttl);
// Test TTL exhausted
base_msg.header.ttl = 0;
try std.testing.expect(!base_msg.decrementTTL());
// Test message builder
var builder = message.MessageBuilder.init(allocator);
const ping_msg = try builder.createMessage(.ping, source, dest);
try std.testing.expectEqual(protocol.MessageType.ping, ping_msg.getType());
// Test specific message types
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, hello.version);
try std.testing.expectEqual(@as(u32, 0x01), hello.capabilities);
const ping = message.Ping.init(456);
try std.testing.expectEqual(@as(u32, 456), ping.sequence);
const pong = message.Pong.init(456, 100);
try std.testing.expectEqual(@as(u32, 456), pong.sequence);
try std.testing.expectEqual(@as(u32, 100), pong.rtt);
}
test "message serialization and deserialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
// Test ping message serialization
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &buffer);
try std.testing.expect(size > 0);
try std.testing.expect(size < buffer.len);
try std.testing.expect(size >= protocol.Serialization.HEADER_SIZE + @sizeOf(message.MessageHeader));
// Test deserialization
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 123), base_msg.header.id);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, base_msg.header.version);
try std.testing.expectEqual(protocol.Serialization.MAGIC_NUMBER, base_msg.header.magic);
const full_msg_deserialized = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(protocol.MessageType.ping, full_msg_deserialized.getType());
// Test hello message serialization
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
const hello_msg = message.Message{ .discovery_hello = hello };
var hello_buffer: [1024]u8 = undefined;
const hello_size = try serializer_instance.serialize(hello_msg, &hello_buffer);
try std.testing.expect(hello_size > 0);
const hello_base_msg = try serializer_instance.deserialize(&hello_buffer[0..hello_size]);
try std.testing.expectEqual(protocol.MessageType.discovery_hello, hello_base_msg.header.msg_type);
const hello_full_msg = try serializer_instance.deserializeFull(hello_base_msg);
try std.testing.expectEqual(protocol.MessageType.discovery_hello, hello_full_msg.getType());
// Test error cases
try std.testing.expectError(serializer.SerializationError.BufferTooSmall,
serializer_instance.deserialize(&buffer[0..5]));
try std.testing.expectError(serializer.SerializationError.InvalidMagicNumber,
serializer_instance.deserialize(&[_]u8{ 0x00, 0x01, 0x02, 0x03 }));
// Test checksum calculation
const checksum = serializer.calculateChecksum(&buffer[0..size]);
try std.testing.expect(serializer.verifyChecksum(&buffer[0..size], checksum));
// Test with invalid checksum
buffer[0] +%= 1;
try std.testing.expect(!serializer.verifyChecksum(&buffer[0..size], checksum));
}
test "message routing" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
// Test basic routing
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Route should fail since no route exists
const route_result = routing_instance.routeMessage(base_msg);
try std.testing.expect(!route_result.success);
try std.testing.expectEqual(protocol.ErrorCode.routing_error, route_result.error.?);
// Add a route
try routing_instance.addRoute(dest, dest, 1);
// Route should succeed now
const route_result2 = routing_instance.routeMessage(base_msg);
try std.testing.expect(route_result2.success);
try std.testing.expectEqual(dest, route_result2.next_hop.?);
try std.testing.expectEqual(@as(u32, 1), route_result2.cost.?);
// Test broadcast messages
var broadcast_header = header;
broadcast_header.flags |= protocol.MessageFlags.BROADCAST;
const broadcast_msg = message.BaseMessage{ .header = broadcast_header, .payload = &.{} };
const broadcast_result = routing_instance.routeMessage(broadcast_msg);
try std.testing.expect(broadcast_result.success);
try std.testing.expectEqual(null, broadcast_result.next_hop); // Broadcast to all
// Test local messages
var local_header = header;
@memset(&local_header.dest, 0); // All zeros means local
const local_msg = message.BaseMessage{ .header = local_header, .payload = &.{} };
const local_result = routing_instance.routeMessage(local_msg);
try std.testing.expect(local_result.success);
try std.testing.expectEqual(null, local_result.next_hop); // Local delivery
// Test route management
try std.testing.expect(routing_instance.isReachable(dest));
try std.testing.expectEqual(dest, routing_instance.getNextHop(dest).?);
routing_instance.removeRoute(dest);
try std.testing.expect(!routing_instance.isReachable(dest));
try std.testing.expectEqual(null, routing_instance.getNextHop(dest));
// Test metrics
const metrics = routing_instance.getMetrics();
try std.testing.expect(metrics.total_routes > 0);
try std.testing.expect(metrics.successful_lookups > 0);
try std.testing.expect(metrics.failed_lookups > 0);
const stats = routing_instance.getRouteStats();
try std.testing.expect(stats.total > 0);
try std.testing.expect(stats.success_rate >= 0.0 and stats.success_rate <= 1.0);
// Test distance vector routing
var dv_router = router.DistanceVectorRouter.init(&routing_instance);
var neighbor_routes = std.ArrayList(router.RouteEntry).init(allocator);
defer neighbor_routes.deinit();
var neighbor_dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor_dest[0] = 3;
try neighbor_routes.append(router.RouteEntry{
.destination = neighbor_dest,
.next_hop = neighbor_dest,
.cost = 1,
.last_updated = std.time.timestamp(),
.is_valid = true,
});
try dv_router.processUpdate(source, neighbor_routes.items);
// Test route invalidation
routing_instance.invalidateRoute(dest);
try std.testing.expect(!routing_instance.isReachable(dest));
}
test "message handler framework" {
const allocator = std.testing.allocator;
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
// Test handler registration
var handler_instance = handler.MessageHandler.init(
struct {
fn testHandler(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
// Simple test handler
}
}.testHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler_instance);
try std.testing.expectEqual(@as(u16, 1), registry.context.metrics.handlers_registered);
// Test message processing
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
try registry.processMessage(msg);
try std.testing.expectEqual(@as(u64, 1), registry.context.metrics.messages_processed);
try std.testing.expectEqual(@as(u64, 0), registry.context.metrics.messages_failed);
try std.testing.expectEqual(@as(f64, 1.0), registry.context.metrics.getSuccessRate());
// Test multiple handlers for same message type
var handler2 = handler.MessageHandler.init(
struct {
fn testHandler2(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
// Another test handler
}
}.testHandler2,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, handler2);
try std.testing.expectEqual(@as(u16, 2), registry.context.metrics.handlers_registered);
try registry.processMessage(msg);
try std.testing.expectEqual(@as(u64, 2), registry.context.metrics.messages_processed);
// Test handler unregistration
registry.unregisterHandlers(.ping);
try std.testing.expectEqual(@as(u16, 0), registry.context.metrics.handlers_registered);
// Test error handling
var error_handler = handler.MessageHandler.init(
struct {
fn errorHandler(msg: message.Message, ctx: *anyopaque) !void {
_ = msg;
_ = ctx;
return error.TestError;
}
}.errorHandler,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, error_handler);
try std.testing.expectError(error.TestError, registry.processMessage(msg));
try std.testing.expectEqual(@as(u64, 1), registry.context.metrics.messages_failed);
// Test specific handlers
var discovery_handler = handler.DiscoveryHandler.init();
var context = registry.getContext();
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
try discovery_handler.handleHello(hello, context);
const ping_msg = message.Ping.init(456);
try discovery_handler.handlePing(ping_msg, context);
const pong_msg = message.Pong.init(456, 100);
try discovery_handler.handlePong(pong_msg, context);
// Test handler builder
var builder = handler.HandlerBuilder.init(&registry);
try builder.registerDefaultHandlers();
// Test async message processor
var async_processor = handler.AsyncMessageProcessor.init(allocator, &registry);
defer async_processor.deinit();
try async_processor.startWorkers(2);
const test_msg = message.Message{ .ping = message.Ping.init(789) };
try async_processor.queueMessage(test_msg);
// Give workers time to process
std.time.sleep(std.time.ns_per_ms * 100);
}
test "protocol integration test" {
const allocator = std.testing.allocator;
// Create all components
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var registry = try handler.HandlerRegistry.init(allocator);
defer registry.deinit();
// Set up a simple network
var node1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
node1[0] = 1;
var node2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
node2[0] = 2;
// Add routes
try routing_instance.addRoute(node2, node2, 1);
// Create and process a ping message
const ping = message.Ping.init(123);
const ping_msg = message.Message{ .ping = ping };
// Serialize the message
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(ping_msg, &buffer);
// Deserialize the message
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
// Route the message
const route_result = routing_instance.routeMessage(base_msg);
try std.testing.expect(route_result.success);
// Process the message
const full_msg = try serializer_instance.deserializeFull(base_msg);
try registry.processMessage(full_msg);
// Test complete round trip with pong response
const pong = message.Pong.init(123, 50);
const pong_msg = message.Message{ .pong = pong };
const pong_size = try serializer_instance.serialize(pong_msg, &buffer);
const pong_base_msg = try serializer_instance.deserialize(&buffer[0..pong_size]);
const pong_full_msg = try serializer_instance.deserializeFull(pong_base_msg);
try registry.processMessage(pong_full_msg);
// Verify metrics
const handler_metrics = registry.context.metrics;
try std.testing.expect(handler_metrics.messages_processed >= 2);
const router_metrics = routing_instance.getMetrics();
try std.testing.expect(router_metrics.successful_lookups > 0);
}

View File

@@ -0,0 +1,347 @@
//! Message structures tests
const std = @import("std");
const protocol = @import("../../src/protocol/protocol.zig");
const message = @import("../../src/protocol/message.zig");
test "message header creation" {
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
try std.testing.expectEqual(protocol.MessageType.ping, header.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 123), header.id);
try std.testing.expectEqual(source, header.source);
try std.testing.expectEqual(dest, header.dest);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, header.version);
try std.testing.expectEqual(protocol.Serialization.MAGIC_NUMBER, header.magic);
try std.testing.expectEqual(protocol.Priority.normal, header.priority);
try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS), header.ttl);
try std.testing.expect(header.timestamp > 0);
try std.testing.expectEqual(@as(u8, 0), header.flags);
try std.testing.expectEqual(@as(u8, 0), header.reserved);
}
test "base message operations" {
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const payload = "test payload";
const base_msg = message.BaseMessage{ .header = header, .payload = payload };
// Test getters
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.getType());
try std.testing.expectEqual(@as(message.MessageId, 123), base_msg.getId());
try std.testing.expectEqual(source, base_msg.getSource());
try std.testing.expectEqual(dest, base_msg.getDest());
try std.testing.expectEqual(payload, base_msg.payload);
// Test flag checks
try std.testing.expect(!base_msg.isBroadcast());
try std.testing.expect(!base_msg.isEncrypted());
// Set flags and test again
base_msg.header.flags |= protocol.MessageFlags.BROADCAST;
try std.testing.expect(base_msg.isBroadcast());
base_msg.header.flags |= protocol.MessageFlags.ENCRYPTED;
try std.testing.expect(base_msg.isEncrypted());
base_msg.header.flags &= ~protocol.MessageFlags.BROADCAST;
try std.testing.expect(!base_msg.isBroadcast());
}
test "ttl operations" {
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
var header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Test normal TTL decrement
try std.testing.expect(base_msg.decrementTTL());
try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS - 1), base_msg.header.ttl);
// Test multiple decrements
var msg = base_msg;
var decrements: u8 = 0;
while (msg.decrementTTL()) {
decrements += 1;
}
try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS - 1), decrements);
try std.testing.expectEqual(@as(u8, 0), msg.header.ttl);
// Test TTL exhausted
msg.header.ttl = 0;
try std.testing.expect(!msg.decrementTTL());
}
test "discovery messages" {
// Test DiscoveryHello
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
try std.testing.expectEqual(protocol.MessageType.discovery_hello, hello.msg_type);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, hello.version);
try std.testing.expectEqual(@as(u32, 0x01), hello.capabilities);
try std.testing.expectEqual(@as(u16, 8080), hello.address.port);
// Test DiscoveryResponse
var known_nodes: [2]message.NodeId = undefined;
known_nodes[0][0] = 3;
known_nodes[1][0] = 4;
const response = message.DiscoveryResponse.init(456, 0x02, .{
.ip = .{192, 168, 1, 1} ** 4,
.port = 9090,
});
try std.testing.expectEqual(protocol.MessageType.discovery_response, response.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 456), response.original_id);
try std.testing.expectEqual(@as(u32, 0x02), response.capabilities);
try std.testing.expectEqual(@as(u16, 9090), response.address.port);
// Test DiscoveryAnnounce
const announce = message.DiscoveryAnnounce.init(0x03, .{
.ip = .{10, 0, 0, 1} ** 4,
.port = 7070,
});
try std.testing.expectEqual(protocol.MessageType.discovery_announce, announce.msg_type);
try std.testing.expectEqual(@as(u32, 0x03), announce.capabilities);
try std.testing.expectEqual(@as(u16, 7070), announce.address.port);
}
test "topology messages" {
// Test TopologyQuery
const query = message.TopologyQuery.init(789, 1);
try std.testing.expectEqual(protocol.MessageType.topology_query, query.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 789), query.query_id);
try std.testing.expectEqual(@as(u8, 1), query.topology_type);
// Test TopologyResponse
const topology_data = "topology information";
const response = message.TopologyResponse.init(789, topology_data);
try std.testing.expectEqual(protocol.MessageType.topology_response, response.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 789), response.query_id);
try std.testing.expectEqual(topology_data, response.topology_data);
// Test TopologyUpdate
const changes = "topology changes";
const update = message.TopologyUpdate.init(1000, changes);
try std.testing.expectEqual(protocol.MessageType.topology_update, update.msg_type);
try std.testing.expectEqual(@as(u32, 1000), update.sequence);
try std.testing.expectEqual(changes, update.changes);
}
test "data messages" {
// Test DataRequest
const data_id = "file123";
const request = message.DataRequest.init(111, data_id, 1024, 4096);
try std.testing.expectEqual(protocol.MessageType.data_request, request.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 111), request.request_id);
try std.testing.expectEqual(data_id, request.data_id);
try std.testing.expectEqual(@as(u64, 1024), request.offset);
try std.testing.expectEqual(@as(u32, 4096), request.size);
// Test DataResponse
const data = "response data";
const response = message.DataResponse.init(111, data_id, data);
try std.testing.expectEqual(protocol.MessageType.data_response, response.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 111), response.request_id);
try std.testing.expectEqual(data_id, response.data_id);
try std.testing.expectEqual(data, response.data);
try std.testing.expectEqual(null, response.total_size);
// Test DataChunk
const chunk_data = "chunk data here";
const chunk = message.DataChunk.init(5, data_id, chunk_data, false);
try std.testing.expectEqual(protocol.MessageType.data_chunk, chunk.msg_type);
try std.testing.expectEqual(@as(u32, 5), chunk.sequence);
try std.testing.expectEqual(data_id, chunk.data_id);
try std.testing.expectEqual(chunk_data, chunk.chunk_data);
try std.testing.expectEqual(false, chunk.is_final);
// Test final chunk
const final_chunk = message.DataChunk.init(5, data_id, chunk_data, true);
try std.testing.expectEqual(true, final_chunk.is_final);
}
test "routing messages" {
// Test RouteQuery
var target: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
target[0] = 5;
const query = message.RouteQuery.init(222, target);
try std.testing.expectEqual(protocol.MessageType.route_query, query.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 222), query.query_id);
try std.testing.expectEqual(target, query.target);
// Test RouteResponse
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 6;
const route_info = "route information";
const response = message.RouteResponse.init(222, route_info);
try std.testing.expectEqual(protocol.MessageType.route_response, response.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 222), response.query_id);
try std.testing.expectEqual(route_info, response.route_info);
try std.testing.expectEqual(null, response.next_hop);
// Test RouteUpdate
const route_changes = "route changes";
const update = message.RouteUpdate.init(2000, route_changes);
try std.testing.expectEqual(protocol.MessageType.route_update, update.msg_type);
try std.testing.expectEqual(@as(u32, 2000), update.sequence);
try std.testing.expectEqual(route_changes, update.route_changes);
}
test "control messages" {
// Test Ping
const ping = message.Ping.init(333);
try std.testing.expectEqual(protocol.MessageType.ping, ping.msg_type);
try std.testing.expectEqual(@as(u32, 333), ping.sequence);
// Test Pong
const pong = message.Pong.init(333, 150);
try std.testing.expectEqual(protocol.MessageType.pong, pong.msg_type);
try std.testing.expectEqual(@as(u32, 333), pong.sequence);
try std.testing.expectEqual(@as(u32, 150), pong.rtt);
// Test Error
const error_msg = "error message";
const error = message.Error.init(444, .invalid_message, error_msg);
try std.testing.expectEqual(protocol.MessageType.error, error.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 444), error.original_id.?);
try std.testing.expectEqual(protocol.ErrorCode.invalid_message, error.error_code);
try std.testing.expectEqual(error_msg, error.message);
// Test Error without original ID
const error_no_id = message.Error.init(null, .unknown_error, error_msg);
try std.testing.expectEqual(null, error_no_id.original_id);
}
test "application messages" {
// Test AppData
const app_data = "application data";
const app_msg = message.AppData.init(1000, app_data);
try std.testing.expectEqual(protocol.MessageType.app_data, app_msg.msg_type);
try std.testing.expectEqual(@as(u16, 1000), app_msg.app_id);
try std.testing.expectEqual(app_data, app_msg.data);
// Test AppControl
const params = "control parameters";
const control_msg = message.AppControl.init(1000, 2000, params);
try std.testing.expectEqual(protocol.MessageType.app_control, control_msg.msg_type);
try std.testing.expectEqual(@as(u16, 1000), control_msg.app_id);
try std.testing.expectEqual(@as(u16, 2000), control_msg.command);
try std.testing.expectEqual(params, control_msg.params);
}
test "message union operations" {
// Test message type detection
const ping = message.Ping.init(555);
const ping_msg = message.Message{ .ping = ping };
try std.testing.expectEqual(protocol.MessageType.ping, ping_msg.getType());
try std.testing.expectEqual(@as(message.MessageId, 555), ping_msg.getId().?);
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
const hello_msg = message.Message{ .discovery_hello = hello };
try std.testing.expectEqual(protocol.MessageType.discovery_hello, hello_msg.getType());
try std.testing.expectEqual(null, hello_msg.getId());
// Test different message types
const messages = [_]message.Message{
message.Message{ .ping = message.Ping.init(1) },
message.Message{ .pong = message.Pong.init(1, 100) },
message.Message{ .error = message.Error.init(null, .none, "") },
};
try std.testing.expectEqual(protocol.MessageType.ping, messages[0].getType());
try std.testing.expectEqual(protocol.MessageType.pong, messages[1].getType());
try std.testing.expectEqual(protocol.MessageType.error, messages[2].getType());
}
test "message builder" {
const allocator = std.testing.allocator;
var builder = message.MessageBuilder.init(allocator);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
// Test ping message creation
const ping_msg = try builder.createMessage(.ping, source, dest);
try std.testing.expectEqual(protocol.MessageType.ping, ping_msg.getType());
// Test hello message creation
const hello_msg = try builder.createMessage(.discovery_hello, source, dest);
try std.testing.expectEqual(protocol.MessageType.discovery_hello, hello_msg.getType());
// Test unsupported message type
try std.testing.expectError(error.UnsupportedMessageType,
builder.createMessage(.data_chunk, source, dest));
}
test "network address" {
const addr = message.NetworkAddress{
.ip = .{192, 168, 1, 100} ** 4,
.port = 8080,
};
try std.testing.expectEqual(@as(u16, 8080), addr.port);
// Test formatting
var buffer: [50]u8 = undefined;
const formatted = std.fmt.bufPrint(&buffer, "{}", .{addr}) catch "error";
try std.testing.expect(buffer[0] != 0); // Should have content
}
test "message ID generation" {
const allocator = std.testing.allocator;
var builder = message.MessageBuilder.init(allocator);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
// Create multiple messages and check IDs are different
const msg1 = try builder.createMessage(.ping, source, dest);
const msg2 = try builder.createMessage(.ping, source, dest);
try std.testing.expect(msg1.getId().? != msg2.getId().?);
// IDs should be non-zero
try std.testing.expect(msg1.getId().? > 0);
try std.testing.expect(msg2.getId().? > 0);
}

View File

@@ -0,0 +1,405 @@
//! Tests for HMAC message authentication
const std = @import("std");
const protocol_mod = @import("protocol");
const crypto = protocol_mod.crypto;
const protocol = protocol_mod.protocol;
const message = protocol_mod.message;
const serializer = protocol_mod.serializer;
test "hmac computation produces consistent output" {
const key = [_]u8{0x42} ** 32;
const data = "Test message for HMAC";
const mac1 = crypto.HmacAuthenticator.computeHmac(key, data);
const mac2 = crypto.HmacAuthenticator.computeHmac(key, data);
try std.testing.expectEqualSlices(u8, &mac1, &mac2);
}
test "hmac verification succeeds with correct mac" {
const key = [_]u8{0xAB} ** 32;
const data = "Hello, authenticated world!";
const mac = crypto.HmacAuthenticator.computeHmac(key, data);
try std.testing.expect(crypto.HmacAuthenticator.verifyHmac(key, data, mac));
}
test "hmac verification fails with tampered data" {
const key = [_]u8{0xCD} ** 32;
const data = "Original message";
const mac = crypto.HmacAuthenticator.computeHmac(key, data);
// Tamper with data
const tampered = "Modified message";
try std.testing.expect(!crypto.HmacAuthenticator.verifyHmac(key, tampered, mac));
}
test "hmac verification fails with wrong key" {
const key1 = [_]u8{0x11} ** 32;
const key2 = [_]u8{0x22} ** 32;
const data = "Secret data";
const mac = crypto.HmacAuthenticator.computeHmac(key1, data);
try std.testing.expect(!crypto.HmacAuthenticator.verifyHmac(key2, data, mac));
}
test "hmac verification fails with tampered mac" {
const key = [_]u8{0x33} ** 32;
const data = "Important message";
const mac = crypto.HmacAuthenticator.computeHmac(key, data);
// Tamper with MAC
var tampered_mac = mac;
tampered_mac[0] ^= 0xFF;
tampered_mac[15] ^= 0xAA;
try std.testing.expect(!crypto.HmacAuthenticator.verifyHmac(key, data, tampered_mac));
}
test "different data produces different hmacs" {
const key = [_]u8{0x44} ** 32;
const data1 = "Message one";
const data2 = "Message two";
const mac1 = crypto.HmacAuthenticator.computeHmac(key, data1);
const mac2 = crypto.HmacAuthenticator.computeHmac(key, data2);
try std.testing.expect(!std.mem.eql(u8, &mac1, &mac2));
}
test "authenticated message serialization and deserialization" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
// Set up peer IDs and HMAC keys
const peer1_id = [_]u8{1} ** 32;
const peer2_id = [_]u8{2} ** 32;
const hmac_key = [_]u8{0xAB} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer1_id, hmac_key);
try crypto_mgr.setHmacKeyForPeer(peer2_id, hmac_key);
// Create serializer with crypto support
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer1_id);
// Create a test message
const ping = message.Ping.init(42);
const msg = message.Message{ .ping = ping };
// Serialize with authentication
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// Should be larger than base message due to HMAC
try std.testing.expect(size > protocol.Serialization.HEADER_SIZE);
// Deserialize and verify
const base_msg = try ser.deserialize(buffer[0..size]);
// Check that AUTHENTICATED flag is set
try std.testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
// Message type should match
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
}
test "authenticated message fails with tampered data" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const hmac_key = [_]u8{0xCD} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
// Create and serialize message
const ping = message.Ping.init(123);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// Tamper with the message data (but not the HMAC)
// Change some byte in the middle of the message
if (size > 100) {
buffer[100] ^= 0xFF;
}
// Deserialization should fail due to HMAC mismatch
try std.testing.expectError(
serializer.SerializationError.AuthenticationFailed,
ser.deserialize(buffer[0..size])
);
}
test "authenticated message fails with tampered hmac" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{3} ** 32;
const hmac_key = [_]u8{0xEF} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
const ping = message.Ping.init(456);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// Tamper with the HMAC at the end
buffer[size - 1] ^= 0xFF;
buffer[size - 16] ^= 0xAA;
// Should fail authentication
try std.testing.expectError(
serializer.SerializationError.AuthenticationFailed,
ser.deserialize(buffer[0..size])
);
}
test "authenticated message fails with wrong hmac key" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{4} ** 32;
const correct_key = [_]u8{0x11} ** 32;
const wrong_key = [_]u8{0x22} ** 32;
// Serialize with correct key
try crypto_mgr.setHmacKeyForPeer(peer_id, correct_key);
var ser_send = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
const ping = message.Ping.init(789);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser_send.serialize(msg, &buffer);
// Try to deserialize with wrong key
var crypto_mgr2 = crypto.CryptoManager.init(allocator);
defer crypto_mgr2.deinit();
try crypto_mgr2.setHmacKeyForPeer(peer_id, wrong_key);
var ser_recv = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr2, peer_id);
// Should fail due to key mismatch
try std.testing.expectError(
serializer.SerializationError.AuthenticationFailed,
ser_recv.deserialize(buffer[0..size])
);
}
test "authentication is now mandatory - serializer requires crypto manager" {
const allocator = std.testing.allocator;
// Set up crypto manager for authentication (now required)
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{0x99} ** 32;
const hmac_key = [_]u8{0x88} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
const ping = message.Ping.init(999);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// Deserialize should work with proper authentication
const base_msg = try ser.deserialize(buffer[0..size]);
// Check that AUTHENTICATED flag IS set (authentication is mandatory)
try std.testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
}
test "hmac key management in crypto manager" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{5} ** 32;
const hmac_key = [_]u8{0x55} ** 32;
// Set HMAC key
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
// Retrieve HMAC key
const retrieved_key = try crypto_mgr.getHmacKeyForPeer(peer_id);
try std.testing.expectEqualSlices(u8, &hmac_key, &retrieved_key);
// Should fail for unknown peer
const unknown_peer = [_]u8{99} ** 32;
try std.testing.expectError(
crypto.CryptoError.NoHmacKeyForPeer,
crypto_mgr.getHmacKeyForPeer(unknown_peer)
);
}
test "multiple peers with different hmac keys" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer1 = [_]u8{1} ** 32;
const peer2 = [_]u8{2} ** 32;
const peer3 = [_]u8{3} ** 32;
const key1 = [_]u8{0x11} ** 32;
const key2 = [_]u8{0x22} ** 32;
const key3 = [_]u8{0x33} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer1, key1);
try crypto_mgr.setHmacKeyForPeer(peer2, key2);
try crypto_mgr.setHmacKeyForPeer(peer3, key3);
// Verify each peer has correct key
const retrieved1 = try crypto_mgr.getHmacKeyForPeer(peer1);
const retrieved2 = try crypto_mgr.getHmacKeyForPeer(peer2);
const retrieved3 = try crypto_mgr.getHmacKeyForPeer(peer3);
try std.testing.expectEqualSlices(u8, &key1, &retrieved1);
try std.testing.expectEqualSlices(u8, &key2, &retrieved2);
try std.testing.expectEqualSlices(u8, &key3, &retrieved3);
// Keys should be different
try std.testing.expect(!std.mem.eql(u8, &retrieved1, &retrieved2));
try std.testing.expect(!std.mem.eql(u8, &retrieved2, &retrieved3));
}
test "hmac authentication with different message types" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{7} ** 32;
const hmac_key = [_]u8{0x77} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
// Test with Ping
{
const ping = message.Ping.init(111);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
const base_msg = try ser.deserialize(buffer[0..size]);
try std.testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
}
// Test with Pong
{
const pong = message.Pong.init(222, 1000);
const msg = message.Message{ .pong = pong };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
const base_msg = try ser.deserialize(buffer[0..size]);
try std.testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
try std.testing.expectEqual(protocol.MessageType.pong, base_msg.header.msg_type);
}
}
test "hmac protects message integrity end-to-end" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const sender_id = [_]u8{10} ** 32;
const shared_key = [_]u8{0xAB} ** 32;
// Register the HMAC key for the sender (whom we'll receive from)
try crypto_mgr.setHmacKeyForPeer(sender_id, shared_key);
// Sender serializes - uses their own ID as the source in header
var ser_sender = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, sender_id);
const ping = message.Ping.init(555);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser_sender.serialize(msg, &buffer);
// Receiver deserializes - peer_id is sender_id since that's whose message we're receiving
// The receiver looks up HMAC key for sender_id and verifies the header source matches sender_id
var ser_receiver = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, sender_id);
const received_msg = try ser_receiver.deserialize(buffer[0..size]);
// Verify message was authenticated and intact
try std.testing.expect((received_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
try std.testing.expectEqual(protocol.MessageType.ping, received_msg.header.msg_type);
}
test "replay attack detection - hmac alone does not prevent replay" {
// This test documents that HMAC protects integrity but NOT replay attacks
// A valid message with valid HMAC can be replayed
// Future enhancement: add sequence numbers or timestamps to prevent replay
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{8} ** 32;
const hmac_key = [_]u8{0x88} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
const ping = message.Ping.init(333);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// First reception - should succeed
const msg1 = try ser.deserialize(buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.ping, msg1.header.msg_type);
// "Replay" the same message - HMAC will still be valid
const msg2 = try ser.deserialize(buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.ping, msg2.header.msg_type);
// Both messages pass authentication (replay not detected by HMAC alone)
try std.testing.expect((msg1.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
try std.testing.expect((msg2.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
}
test "hmac with empty payload" {
const allocator = std.testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
const peer_id = [_]u8{9} ** 32;
const hmac_key = [_]u8{0x99} ** 32;
try crypto_mgr.setHmacKeyForPeer(peer_id, hmac_key);
var ser = serializer.MessageSerializer.initWithCrypto(allocator, &crypto_mgr, peer_id);
// Ping message has minimal payload
const ping = message.Ping.init(0);
const msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try ser.serialize(msg, &buffer);
// Should still authenticate correctly
const base_msg = try ser.deserialize(buffer[0..size]);
try std.testing.expect((base_msg.header.flags & protocol.MessageFlags.AUTHENTICATED) != 0);
}

View File

@@ -0,0 +1,458 @@
//! Nonce Exhaustion and Key Rotation Tests
//!
//! This test suite validates critical nonce exhaustion protection in ChaCha20-Poly1305 encryption.
//! Nonce reuse is catastrophic for stream ciphers - it allows attackers to recover the keystream
//! and decrypt all messages encrypted with the same key.
//!
//! Tests cover:
//! 1. Nonce exhaustion detection at threshold
//! 2. Encryption failure when nonce limit reached
//! 3. Automatic key rotation triggers
//! 4. Previous key fallback during rotation
//! 5. Generation counter prevents cross-rotation reuse
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const encryption = protocol.encryption;
const crypto = protocol.crypto;
const EncryptionKey = encryption.EncryptionKey;
const EncryptionManager = encryption.EncryptionManager;
// ============================================================================
// Critical: Nonce Exhaustion Detection
// ============================================================================
test "nonce exhaustion triggers error at threshold" {
var key = EncryptionKey.init([_]u8{0xAA} ** 32, 1);
// Set counter near threshold (u32 max - 1000)
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(EncryptionKey.NONCE_ROTATION_THRESHOLD - 10, .release);
// Should still work for the next 10 nonces
var i: usize = 0;
while (i < 10) : (i += 1) {
_ = try key.getNextNonce();
}
// Now at threshold - next call should fail
const result = key.getNextNonce();
try testing.expectError(crypto.CryptoError.NonceExhaustion, result);
// Verify needs_rotation flag is set
try testing.expect(key.needs_rotation);
}
test "encryption fails safely at nonce limit" {
var key = EncryptionKey.init([_]u8{0xBB} ** 32, 1);
// Force nonce to exactly the threshold
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(EncryptionKey.NONCE_ROTATION_THRESHOLD, .release);
// Attempt to get nonce - should fail immediately
const result = key.getNextNonce();
try testing.expectError(crypto.CryptoError.NonceExhaustion, result);
}
test "nonce counter never wraps with saturating addition" {
var key = EncryptionKey.init([_]u8{0xCC} ** 32, 1);
// Set counter to near u64 max (unrealistic but tests overflow protection)
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(std.math.maxInt(u64) - 10, .release);
// Even if threshold check fails, counter should saturate not wrap
// This should fail due to threshold check
const result = key.getNextNonce();
try testing.expectError(crypto.CryptoError.NonceExhaustion, result);
// SECURITY FIX: When nonce exhaustion occurs, the key is zeroized
// This is correct behavior - key material should be cleared to prevent
// any further use of an exhausted key.
// Counter is 0 because key.zeroize() was called on exhaustion
// CRIT-NEW-16 FIX: Use atomic load
try testing.expectEqual(@as(u64, 0), key.nonce_counter.load(.acquire));
try testing.expect(key.needs_rotation);
}
test "nonce format combines generation, counter, and random" {
var key = EncryptionKey.init([_]u8{0xDD} ** 32, 42);
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(1337, .release);
const nonce = try key.getNextNonce();
// Verify generation is in first 4 bytes
const generation = std.mem.readInt(u32, nonce[0..4], .little);
try testing.expectEqual(@as(u32, 42), generation);
// Verify counter is in next 4 bytes
const counter = std.mem.readInt(u32, nonce[4..8], .little);
try testing.expectEqual(@as(u32, 1337), counter);
// Last 4 bytes are random - just verify they exist
try testing.expectEqual(@as(usize, 12), nonce.len);
}
test "consecutive nonces are unique" {
var key = EncryptionKey.init([_]u8{0xEE} ** 32, 1);
// Generate 100 nonces and verify they're all unique
var nonces: [100][12]u8 = undefined;
for (&nonces) |*nonce| {
nonce.* = try key.getNextNonce();
}
// Check each pair is different
for (nonces[0..99], 0..) |nonce1, i| {
for (nonces[i + 1 ..]) |nonce2| {
try testing.expect(!std.mem.eql(u8, &nonce1, &nonce2));
}
}
}
// ============================================================================
// Key Rotation Logic
// ============================================================================
test "key rotation triggered by age" {
var key = EncryptionKey.init([_]u8{0xFF} ** 32, 1);
// Artificially age the key
key.created_at = std.time.timestamp() - 7200; // 2 hours old
// Should require rotation (default max age is 1 hour = 3600s)
const should_rotate = key.shouldRotate(3600, 1_000_000);
try testing.expect(should_rotate);
}
test "key rotation triggered by message count" {
var key = EncryptionKey.init([_]u8{0x00} ** 32, 1);
// Set counter above rotation threshold
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(1_000_001, .release);
// Should require rotation (default max messages is 1M)
const should_rotate = key.shouldRotate(3600, 1_000_000);
try testing.expect(should_rotate);
}
test "key rotation triggered by nonce exhaustion flag" {
var key = EncryptionKey.init([_]u8{0x11} ** 32, 1);
// Set the needs_rotation flag
key.needs_rotation = true;
// Should require rotation even if age and counter are fine
const should_rotate = key.shouldRotate(3600, 1_000_000);
try testing.expect(should_rotate);
}
test "key rotation triggered by approaching u32 limit" {
var key = EncryptionKey.init([_]u8{0x22} ** 32, 1);
// Set counter to threshold
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(EncryptionKey.NONCE_ROTATION_THRESHOLD, .release);
// Should require rotation
const should_rotate = key.shouldRotate(3600, 1_000_000);
try testing.expect(should_rotate);
}
test "fresh key does not need rotation" {
const key = EncryptionKey.init([_]u8{0x33} ** 32, 1);
// Fresh key should not need rotation
const should_rotate = key.shouldRotate(3600, 1_000_000);
try testing.expect(!should_rotate);
}
// ============================================================================
// EncryptionManager Integration
// ============================================================================
test "encryption manager prevents encryption at nonce exhaustion" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0x44} ** 32;
const key = [_]u8{0x55} ** 32;
// Add key for peer
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Manually set nonce counter to threshold
const key_ptr = try enc_mgr.getKeyForPeer(peer_id);
// CRIT-NEW-16 FIX: Use atomic store
key_ptr.nonce_counter.store(EncryptionKey.NONCE_ROTATION_THRESHOLD, .release);
// Attempting to get key should now fail
const result = enc_mgr.getKeyForPeer(peer_id);
try testing.expectError(crypto.CryptoError.NonceExhaustion, result);
}
test "encryption manager key rotation increments generation" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0x66} ** 32;
const key = [_]u8{0x77} ** 32;
// Add key for peer
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Get initial generation
const key_before = try enc_mgr.getKeyForPeer(peer_id);
const gen_before = key_before.generation;
// Rotate key
try enc_mgr.rotateKeyForPeer(peer_id);
// Get new generation
const key_after = try enc_mgr.getKeyForPeer(peer_id);
const gen_after = key_after.generation;
// Generation should have incremented
try testing.expectEqual(gen_before + 1, gen_after);
// Nonce counter should be reset
// CRIT-NEW-16 FIX: Use atomic load
try testing.expectEqual(@as(u64, 0), key_after.nonce_counter.load(.acquire));
}
test "encryption manager rotation stores previous key" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0x88} ** 32;
const key = [_]u8{0x99} ** 32;
// Add key for peer
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Get the current key value
const key_before = try enc_mgr.getKeyForPeer(peer_id);
const old_key = key_before.key;
// Rotate key
try enc_mgr.rotateKeyForPeer(peer_id);
// Check that previous_key is set
const key_after = try enc_mgr.getKeyForPeer(peer_id);
try testing.expect(key_after.previous_key != null);
// The previous key should match the old key
// Note: Due to HKDF, we can't easily verify this without knowing the derivation
// But we can verify it's non-null and different from current
try testing.expect(!std.mem.eql(u8, &key_after.key, &old_key));
}
test "encryption manager prevents double rotation without setup" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0xAA} ** 32;
// Attempt to rotate key for non-existent peer
const result = enc_mgr.rotateKeyForPeer(peer_id);
try testing.expectError(crypto.CryptoError.NoKeyForPeer, result);
}
test "encryption manager hasKeyForPeer check" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id1 = [_]u8{0xBB} ** 32;
const peer_id2 = [_]u8{0xCC} ** 32;
const key = [_]u8{0xDD} ** 32;
// Initially should not have any keys
try testing.expect(!enc_mgr.hasKeyForPeer(peer_id1));
try testing.expect(!enc_mgr.hasKeyForPeer(peer_id2));
// Add key for peer1
try enc_mgr.setKeyForPeer(peer_id1, key, 1);
// Now should have key for peer1 but not peer2
try testing.expect(enc_mgr.hasKeyForPeer(peer_id1));
try testing.expect(!enc_mgr.hasKeyForPeer(peer_id2));
}
test "encryption manager removeKeyForPeer" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0xEE} ** 32;
const key = [_]u8{0xFF} ** 32;
// Add key
try enc_mgr.setKeyForPeer(peer_id, key, 1);
try testing.expect(enc_mgr.hasKeyForPeer(peer_id));
// Remove key
enc_mgr.removeKeyForPeer(peer_id);
try testing.expect(!enc_mgr.hasKeyForPeer(peer_id));
// Attempting to get removed key should fail
const result = enc_mgr.getKeyForPeer(peer_id);
try testing.expectError(crypto.CryptoError.NoKeyForPeer, result);
}
// ============================================================================
// Edge Cases and Stress Tests
// ============================================================================
test "multiple rotations work correctly" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{0x00} ** 32;
const key = [_]u8{0x11} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Perform multiple rotations
for (0..5) |i| {
try enc_mgr.rotateKeyForPeer(peer_id);
const current_key = try enc_mgr.getKeyForPeer(peer_id);
try testing.expectEqual(@as(u64, i + 2), current_key.generation);
// CRIT-NEW-16 FIX: Use atomic load
try testing.expectEqual(@as(u64, 0), current_key.nonce_counter.load(.acquire));
}
}
test "nonce exhaustion with realistic message load" {
var key = EncryptionKey.init([_]u8{0x22} ** 32, 1);
// Simulate sending messages until near threshold
const messages_to_send = EncryptionKey.NONCE_ROTATION_THRESHOLD - 100;
// Set counter to simulate already having sent many messages
// CRIT-NEW-16 FIX: Use atomic store
key.nonce_counter.store(messages_to_send, .release);
// Should still work for 100 more
for (0..100) |_| {
_ = try key.getNextNonce();
}
// Now should fail
const result = key.getNextNonce();
try testing.expectError(crypto.CryptoError.NonceExhaustion, result);
}
test "generation prevents nonce reuse across rotations" {
var key1 = EncryptionKey.init([_]u8{0x33} ** 32, 1);
var key2 = EncryptionKey.init([_]u8{0x33} ** 32, 2);
// Same counter value
// CRIT-NEW-16 FIX: Use atomic store
key1.nonce_counter.store(100, .release);
key2.nonce_counter.store(100, .release);
const nonce1 = try key1.getNextNonce();
const nonce2 = try key2.getNextNonce();
// Nonces should be different due to different generation
try testing.expect(!std.mem.eql(u8, &nonce1, &nonce2));
// Verify generations are different
const gen1 = std.mem.readInt(u32, nonce1[0..4], .little);
const gen2 = std.mem.readInt(u32, nonce2[0..4], .little);
try testing.expectEqual(@as(u32, 1), gen1);
try testing.expectEqual(@as(u32, 2), gen2);
}
test "max key age configurable" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
// Set custom max age (30 minutes = 1800 seconds)
enc_mgr.max_key_age = 1800;
const peer_id = [_]u8{0x44} ** 32;
const key = [_]u8{0x55} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const key_ptr = try enc_mgr.getKeyForPeer(peer_id);
// Age it to 31 minutes
key_ptr.created_at = std.time.timestamp() - 1860;
// Should need rotation with custom max age
try testing.expect(key_ptr.shouldRotate(enc_mgr.max_key_age, enc_mgr.max_messages_per_key));
}
test "max messages per key configurable" {
const allocator = testing.allocator;
var crypto_mgr = crypto.CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
// Set custom max messages (100k)
enc_mgr.max_messages_per_key = 100_000;
const peer_id = [_]u8{0x66} ** 32;
const key = [_]u8{0x77} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const key_ptr = try enc_mgr.getKeyForPeer(peer_id);
// Send 100,001 messages
// CRIT-NEW-16 FIX: Use atomic store
key_ptr.nonce_counter.store(100_001, .release);
// Should need rotation with custom max messages
try testing.expect(key_ptr.shouldRotate(enc_mgr.max_key_age, enc_mgr.max_messages_per_key));
}

View File

@@ -0,0 +1,122 @@
//! Protocol definitions and constants tests
const std = @import("std");
const protocol = @import("../../src/protocol/protocol.zig");
test "protocol constants" {
try std.testing.expectEqual(@as(u16, 1), protocol.PROTOCOL_VERSION);
try std.testing.expectEqual(@as(u16, 65536), protocol.MAX_MESSAGE_SIZE);
try std.testing.expectEqual(@as(u32, 0x4D524C54), protocol.Serialization.MAGIC_NUMBER);
}
test "message type validation" {
// Test valid message types
try std.testing.expect(protocol.ProtocolHelpers.isValidMessageType(.discovery_hello));
try std.testing.expect(protocol.ProtocolHelpers.isValidMessageType(.ping));
try std.testing.expect(protocol.ProtocolHelpers.isValidMessageType(.app_data));
// Test reserved message types
try std.testing.expect(protocol.ProtocolHelpers.isReservedMessageType(@as(protocol.MessageType, @enumFromInt(0xF0))));
try std.testing.expect(protocol.ProtocolHelpers.isReservedMessageType(@as(protocol.MessageType, @enumFromInt(0xFF))));
try std.testing.expect(!protocol.ProtocolHelpers.isReservedMessageType(.ping));
// Test application message types
try std.testing.expect(protocol.ProtocolHelpers.isAppMessageType(.app_data));
try std.testing.expect(protocol.ProtocolHelpers.isAppMessageType(.app_control));
try std.testing.expect(!protocol.ProtocolHelpers.isAppMessageType(.ping));
try std.testing.expect(!protocol.ProtocolHelpers.isAppMessageType(.discovery_hello));
}
test "version compatibility" {
try std.testing.expect(protocol.ProtocolHelpers.isVersionCompatible(1));
try std.testing.expect(protocol.ProtocolHelpers.isVersionCompatible(0));
try std.testing.expect(!protocol.ProtocolHelpers.isVersionCompatible(2));
try std.testing.expect(!protocol.ProtocolHelpers.isVersionCompatible(255));
}
test "message categories" {
try std.testing.expectEqualStrings("discovery", protocol.ProtocolHelpers.getMessageCategory(.discovery_hello));
try std.testing.expectEqualStrings("discovery", protocol.ProtocolHelpers.getMessageCategory(.discovery_response));
try std.testing.expectEqualStrings("discovery", protocol.ProtocolHelpers.getMessageCategory(.discovery_announce));
try std.testing.expectEqualStrings("topology", protocol.ProtocolHelpers.getMessageCategory(.topology_query));
try std.testing.expectEqualStrings("topology", protocol.ProtocolHelpers.getMessageCategory(.topology_response));
try std.testing.expectEqualStrings("topology", protocol.ProtocolHelpers.getMessageCategory(.topology_update));
try std.testing.expectEqualStrings("data", protocol.ProtocolHelpers.getMessageCategory(.data_request));
try std.testing.expectEqualStrings("data", protocol.ProtocolHelpers.getMessageCategory(.data_response));
try std.testing.expectEqualStrings("data", protocol.ProtocolHelpers.getMessageCategory(.data_chunk));
try std.testing.expectEqualStrings("routing", protocol.ProtocolHelpers.getMessageCategory(.route_query));
try std.testing.expectEqualStrings("routing", protocol.ProtocolHelpers.getMessageCategory(.route_response));
try std.testing.expectEqualStrings("routing", protocol.ProtocolHelpers.getMessageCategory(.route_update));
try std.testing.expectEqualStrings("control", protocol.ProtocolHelpers.getMessageCategory(.ping));
try std.testing.expectEqualStrings("control", protocol.ProtocolHelpers.getMessageCategory(.pong));
try std.testing.expectEqualStrings("control", protocol.ProtocolHelpers.getMessageCategory(.error));
try std.testing.expectEqualStrings("app", protocol.ProtocolHelpers.getMessageCategory(.app_data));
try std.testing.expectEqualStrings("app", protocol.ProtocolHelpers.getMessageCategory(.app_control));
}
test "message size limits" {
// Data messages should have larger limits
try std.testing.expectEqual(@as(u16, protocol.MAX_MESSAGE_SIZE),
protocol.ProtocolHelpers.getMessageSizeLimit(.data_chunk));
try std.testing.expectEqual(@as(u16, protocol.MAX_MESSAGE_SIZE),
protocol.ProtocolHelpers.getMessageSizeLimit(.data_response));
// Other message types should have smaller limits
try std.testing.expectEqual(@as(u16, 8192),
protocol.ProtocolHelpers.getMessageSizeLimit(.ping));
try std.testing.expectEqual(@as(u16, 8192),
protocol.ProtocolHelpers.getMessageSizeLimit(.discovery_hello));
try std.testing.expectEqual(@as(u16, 8192),
protocol.ProtocolHelpers.getMessageSizeLimit(.topology_query));
}
test "error codes" {
try std.testing.expectEqual(protocol.ErrorCode.none, @as(protocol.ErrorCode, @enumFromInt(0x0000)));
try std.testing.expectEqual(protocol.ErrorCode.invalid_message, @as(protocol.ErrorCode, @enumFromInt(0x0001)));
try std.testing.expectEqual(protocol.ErrorCode.unknown_error, @as(protocol.ErrorCode, @enumFromInt(0xFFFF)));
}
test "timeouts and limits" {
try std.testing.expectEqual(@as(u32, 5000), protocol.Timeouts.MESSAGE_ACK);
try std.testing.expectEqual(@as(u32, 10000), protocol.Timeouts.ROUTE_QUERY);
try std.testing.expectEqual(@as(u32, 15000), protocol.Timeouts.DISCOVERY);
try std.testing.expectEqual(@as(u32, 30000), protocol.Timeouts.HEARTBEAT);
try std.testing.expectEqual(@as(u8, 16), protocol.Limits.MAX_HOPS);
try std.testing.expectEqual(@as(u3, 3), protocol.Limits.MAX_RETRY_COUNT);
try std.testing.expectEqual(@as(u16, 256), protocol.Limits.MAX_HANDLERS);
try std.testing.expectEqual(@as(usize, 1000), protocol.Limits.ROUTE_CACHE_SIZE);
}
test "network constants" {
try std.testing.expectEqual(@as(u16, 65535), protocol.Network.MAX_NODES);
try std.testing.expectEqual(@as(u8, 32), protocol.Network.NODE_ID_SIZE);
try std.testing.expectEqual(@as(u8, 16), protocol.Network.ADDRESS_SIZE);
try std.testing.expectEqual(@as(u16, 2), protocol.Network.PORT_SIZE);
}
test "message flags" {
try std.testing.expectEqual(@as(u8, 0x00), protocol.MessageFlags.NONE);
try std.testing.expectEqual(@as(u8, 0x01), protocol.MessageFlags.ENCRYPTED);
try std.testing.expectEqual(@as(u8, 0x02), protocol.MessageFlags.COMPRESSED);
try std.testing.expectEqual(@as(u8, 0x04), protocol.MessageFlags.PRIORITY);
try std.testing.expectEqual(@as(u8, 0x08), protocol.MessageFlags.BROADCAST);
try std.testing.expectEqual(@as(u8, 0x10), protocol.MessageFlags.RELIABLE);
}
test "priorities" {
try std.testing.expectEqual(@as(u2, 0), @intFromEnum(protocol.Priority.low));
try std.testing.expectEqual(@as(u2, 1), @intFromEnum(protocol.Priority.normal));
try std.testing.expectEqual(@as(u2, 2), @intFromEnum(protocol.Priority.high));
try std.testing.expectEqual(@as(u2, 3), @intFromEnum(protocol.Priority.critical));
}
test "serialization constants" {
try std.testing.expectEqual(@as(usize, 12), protocol.Serialization.HEADER_SIZE);
try std.testing.expectEqual(@as(u32, 0x4D524C54), protocol.Serialization.MAGIC_NUMBER);
// SEC-M9 FIX: Removed CHECKSUM_ALGORITHM test - HMAC handles integrity now
}

View File

@@ -0,0 +1,410 @@
//! Comprehensive integration tests for replay protection in message handlers
//! This file tests that replay protection is properly wired into the message handling pipeline
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const handler_mod = protocol.handler;
const message_mod = protocol.message;
const replay_protection = protocol.replay_protection;
/// Test that duplicate message IDs are rejected
test "replay protection: duplicate message_id is rejected" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// Create a simple ping message
const ping = message_mod.Ping.init(12345);
const msg = message_mod.Message{ .ping = ping };
// Set source peer for context
const peer_id: message_mod.NodeId = [_]u8{1} ** 32;
registry.context.source_peer_id = peer_id;
// First message should succeed
try registry.processMessage(msg);
// Immediate replay should fail (same message ID, timestamp, nonce)
const result = registry.processMessage(msg);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, result);
}
/// Test that old timestamps are rejected
test "replay protection: old timestamp is rejected" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// Configure replay protector with short TTL for testing
registry.replay_protector.configure(null, 1, null); // 1 second TTL
const peer_id: message_mod.NodeId = [_]u8{2} ** 32;
registry.context.source_peer_id = peer_id;
// Create message with very old timestamp
const old_timestamp = std.time.timestamp() - 7200; // 2 hours ago
// Directly test the replay protector with old timestamp
const result = registry.replay_protector.checkMessage(
12345,
old_timestamp,
1000,
0,
peer_id,
);
try testing.expectError(replay_protection.ReplayError.TimestampTooOld, result);
}
/// Test that future timestamps are rejected
test "replay protection: future timestamp is rejected" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{3} ** 32;
// Create message with future timestamp (beyond clock skew tolerance)
const future_timestamp = std.time.timestamp() + 600; // 10 minutes in future
// Test directly via replay protector
const result = registry.replay_protector.checkMessage(
12345,
future_timestamp,
1000,
0,
peer_id,
);
try testing.expectError(replay_protection.ReplayError.TimestampTooFarInFuture, result);
}
/// Test that valid messages pass through replay protection
test "replay protection: valid messages pass through" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{4} ** 32;
registry.context.source_peer_id = peer_id;
// Create different ping messages with different IDs
const ping1 = message_mod.Ping.init(100);
const ping2 = message_mod.Ping.init(200);
const ping3 = message_mod.Ping.init(300);
const msg1 = message_mod.Message{ .ping = ping1 };
const msg2 = message_mod.Message{ .ping = ping2 };
const msg3 = message_mod.Message{ .ping = ping3 };
// All messages should succeed
try registry.processMessage(msg1);
try registry.processMessage(msg2);
try registry.processMessage(msg3);
// Verify metrics
try testing.expectEqual(@as(u64, 3), registry.context.metrics.messages_processed);
try testing.expectEqual(@as(u64, 0), registry.context.metrics.messages_failed);
}
/// Test cleanup removes old entries
test "replay protection: cleanup removes old entries" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// Configure with very short TTL for testing
registry.replay_protector.configure(null, 1, null); // 1 second TTL
const peer_id: message_mod.NodeId = [_]u8{5} ** 32;
// Add some messages with old timestamps
const old_time = std.time.timestamp() - 2;
_ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id);
_ = try registry.replay_protector.checkMessage(2, old_time, 1001, 2, peer_id);
var stats = registry.getReplayStats();
try testing.expect(stats.tracked_messages > 0);
// Force cleanup
registry.cleanupReplayProtection();
// Old messages should be cleaned up
stats = registry.getReplayStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_messages);
}
/// Test per-peer sequence tracking works
test "replay protection: per-peer sequence tracking" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer1: message_mod.NodeId = [_]u8{6} ** 32;
const peer2: message_mod.NodeId = [_]u8{7} ** 32;
const current_time = std.time.timestamp();
// Peer 1 sends messages in order
try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1);
try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer1);
try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 3, peer1);
// Peer 2 can use same sequences independently
try registry.replay_protector.checkMessage(10, current_time, 2000, 1, peer2);
try registry.replay_protector.checkMessage(11, current_time + 1, 2001, 2, peer2);
// Both peers tracked
const stats = registry.getReplayStats();
try testing.expectEqual(@as(usize, 2), stats.tracked_peers);
// Replay from peer1 should fail
const result = registry.replay_protector.checkMessage(4, current_time + 3, 1003, 2, peer1);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, result);
}
/// Test nonce uniqueness enforcement
test "replay protection: nonce uniqueness" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{8} ** 32;
const current_time = std.time.timestamp();
// First message with nonce 5000
try registry.replay_protector.checkMessage(100, current_time, 5000, 0, peer_id);
// Different message ID but same nonce should fail
const result = registry.replay_protector.checkMessage(101, current_time + 1, 5000, 0, peer_id);
try testing.expectError(replay_protection.ReplayError.DuplicateNonce, result);
}
/// Test out-of-order messages within sliding window
test "replay protection: out-of-order messages within window" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{9} ** 32;
const current_time = std.time.timestamp();
// Send sequence 1, 2, 5, then 3 (out of order but within window)
try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer_id);
try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer_id);
try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 5, peer_id);
// Message 3 (out of order) should be accepted
try registry.replay_protector.checkMessage(4, current_time + 3, 1003, 3, peer_id);
}
/// Test sequences too old (outside window) are rejected
test "replay protection: sequences too old are rejected" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{10} ** 32;
const current_time = std.time.timestamp();
// Send sequence 100 (establishes baseline)
try registry.replay_protector.checkMessage(1, current_time, 1000, 100, peer_id);
// Try to send sequence 1 (too old, outside 64-message window)
const result = registry.replay_protector.checkMessage(2, current_time + 1, 1001, 1, peer_id);
try testing.expectError(replay_protection.ReplayError.SequenceTooOld, result);
}
/// Test peer sequence reset functionality
test "replay protection: peer sequence reset" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{11} ** 32;
const current_time = std.time.timestamp();
// Send some messages
try registry.replay_protector.checkMessage(1, current_time, 1000, 5, peer_id);
try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 6, peer_id);
// Reset peer sequence (simulating reconnection)
try registry.resetPeerReplayState(peer_id);
// Should be able to start from sequence 1 again
try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 1, peer_id);
}
/// Test integration: message processing with replay protection enabled
test "replay protection: full integration test" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{12} ** 32;
registry.context.source_peer_id = peer_id;
// Register a simple handler that counts messages
var message_count: u32 = 0;
const TestContext = struct {
count: *u32,
};
var test_ctx = TestContext{ .count = &message_count };
const test_handler = handler_mod.MessageHandler.init(
struct {
fn handler(msg: message_mod.Message, ctx: *anyopaque) !void {
_ = msg;
const test_context = @as(*TestContext, @ptrCast(@alignCast(ctx)));
test_context.count.* += 1;
}
}.handler,
&test_ctx,
.ping,
);
try registry.registerHandler(.ping, test_handler);
// Send valid messages
const ping1 = message_mod.Ping.init(1);
const ping2 = message_mod.Ping.init(2);
const msg1 = message_mod.Message{ .ping = ping1 };
const msg2 = message_mod.Message{ .ping = ping2 };
try registry.processMessage(msg1);
try registry.processMessage(msg2);
// Handler should have been called twice
try testing.expectEqual(@as(u32, 2), message_count);
// Try to replay msg1 - should be rejected and handler should NOT be called
const replay_result = registry.processMessage(msg1);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, replay_result);
// Message count should still be 2 (handler not called for replay)
try testing.expectEqual(@as(u32, 2), message_count);
}
/// Test statistics reporting
test "replay protection: statistics reporting" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer1: message_mod.NodeId = [_]u8{13} ** 32;
const peer2: message_mod.NodeId = [_]u8{14} ** 32;
const current_time = std.time.timestamp();
// Add some messages
try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1);
try registry.replay_protector.checkMessage(2, current_time, 2000, 1, peer2);
const stats = registry.getReplayStats();
// Should have tracked messages, nonces, and peers
try testing.expect(stats.tracked_messages >= 2);
try testing.expect(stats.tracked_nonces >= 2);
try testing.expectEqual(@as(usize, 2), stats.tracked_peers);
}
/// Test automatic cleanup during checkMessage
test "replay protection: automatic cleanup during check" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// Set very short cleanup interval (0 = immediate)
registry.replay_protector.configure(null, 0, 0); // 0 second TTL, 0 second cleanup interval
const peer_id: message_mod.NodeId = [_]u8{15} ** 32;
// Add old message (already stale with 0 TTL)
const old_time = std.time.timestamp() - 1;
_ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id);
// Brief wait to ensure cleanup can trigger
std.time.sleep(50 * std.time.ns_per_ms);
// Add new message (should trigger automatic cleanup)
const current_time = std.time.timestamp();
try registry.replay_protector.checkMessage(2, current_time, 2000, 2, peer_id);
// Old message should have been cleaned up automatically
const stats = registry.getReplayStats();
try testing.expect(stats.tracked_messages <= 1);
}
/// Test multiple message types with replay protection
test "replay protection: multiple message types" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
const peer_id: message_mod.NodeId = [_]u8{16} ** 32;
registry.context.source_peer_id = peer_id;
// Create different message types
const ping = message_mod.Ping.init(100);
const pong = message_mod.Pong{ .sequence = 200, .rtt = 10 };
const ping_msg = message_mod.Message{ .ping = ping };
const pong_msg = message_mod.Message{ .pong = pong };
// All different message types should be processed
try registry.processMessage(ping_msg);
try registry.processMessage(pong_msg);
// Same message replayed should fail
const result1 = registry.processMessage(ping_msg);
const result2 = registry.processMessage(pong_msg);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, result1);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, result2);
}
/// Test that replay protection is mandatory by default
test "replay protection: enabled by default (security requirement)" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// SECURITY: Replay protection MUST be enabled by default
try testing.expect(registry.require_replay_protection);
const peer_id: message_mod.NodeId = [_]u8{17} ** 32;
registry.context.source_peer_id = peer_id;
// Create and send a message
const ping = message_mod.Ping.init(500);
const msg = message_mod.Message{ .ping = ping };
try registry.processMessage(msg);
// Replay should be rejected when protection is enabled (default)
const replay_result = registry.processMessage(msg);
try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, replay_result);
}
/// Test that replay protection can be explicitly disabled for testing only
test "replay protection: can be disabled for testing (SECURITY WARNING)" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// SECURITY WARNING: Only disable for testing purposes - production MUST have this enabled
registry.require_replay_protection = false;
const peer_id: message_mod.NodeId = [_]u8{18} ** 32;
registry.context.source_peer_id = peer_id;
// Create and send a message
const ping = message_mod.Ping.init(600);
const msg = message_mod.Message{ .ping = ping };
try registry.processMessage(msg);
// Replay should be ACCEPTED when protection is disabled (only for testing)
try registry.processMessage(msg);
// Verify both messages were processed (replay not blocked)
try testing.expectEqual(@as(u64, 2), registry.context.metrics.messages_processed);
}

View File

@@ -0,0 +1,570 @@
//! Comprehensive tests for replay protection module
//!
//! Tests memory limits, edge cases, and code paths not covered
//! by the inline tests in replay_protection.zig.
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const ReplayProtector = protocol.replay_protection.ReplayProtector;
const ReplayError = protocol.replay_protection.ReplayError;
const MemoryError = protocol.replay_protection.MemoryError;
const ReplayStats = protocol.replay_protection.ReplayStats;
// ============================================================================
// Basic Initialization Tests
// ============================================================================
test "ReplayProtector: init with default values" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
// Verify default configuration (HIGH-3 tighter defaults)
try testing.expectEqual(@as(i64, 5), protector.max_clock_skew);
try testing.expectEqual(@as(i64, 10), protector.message_ttl);
try testing.expectEqual(@as(i64, 30), protector.cleanup_interval);
// Verify empty state
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_messages);
try testing.expectEqual(@as(usize, 0), stats.tracked_nonces);
try testing.expectEqual(@as(usize, 0), stats.tracked_peers);
}
test "ReplayProtector: constants are properly defined" {
// Verify security constants
try testing.expectEqual(@as(usize, 600_000), ReplayProtector.MAX_TRACKED_MESSAGES);
try testing.expectEqual(@as(usize, 10_000), ReplayProtector.MAX_TRACKED_PEERS);
try testing.expectEqual(@as(usize, 600_000), ReplayProtector.MAX_TRACKED_NONCES);
}
// ============================================================================
// Configuration Tests
// ============================================================================
test "ReplayProtector: configure with partial values" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
// Configure only clock skew
protector.configure(10, null, null);
try testing.expectEqual(@as(i64, 10), protector.max_clock_skew);
try testing.expectEqual(@as(i64, 10), protector.message_ttl); // unchanged
// Configure only TTL
protector.configure(null, 60, null);
try testing.expectEqual(@as(i64, 10), protector.max_clock_skew); // unchanged
try testing.expectEqual(@as(i64, 60), protector.message_ttl);
// Configure only cleanup interval
protector.configure(null, null, 120);
try testing.expectEqual(@as(i64, 120), protector.cleanup_interval);
}
test "ReplayProtector: configure with all null values" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const orig_skew = protector.max_clock_skew;
const orig_ttl = protector.message_ttl;
const orig_interval = protector.cleanup_interval;
// Configure with all nulls should not change anything
protector.configure(null, null, null);
try testing.expectEqual(orig_skew, protector.max_clock_skew);
try testing.expectEqual(orig_ttl, protector.message_ttl);
try testing.expectEqual(orig_interval, protector.cleanup_interval);
}
// ============================================================================
// Timestamp Validation Edge Cases
// ============================================================================
test "ReplayProtector: timestamp at exact TTL boundary" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{1} ** 32;
// Message at exactly TTL boundary (10 seconds old with 10s TTL)
// validateTimestamp uses (time_diff < -message_ttl), so exactly at boundary is accepted
const boundary_timestamp = current_time - protector.message_ttl;
try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id);
// Message just past TTL boundary should be rejected
const past_boundary = current_time - protector.message_ttl - 1;
const result = protector.checkMessage(2, past_boundary, 1001, 0, peer_id);
try testing.expectError(ReplayError.TimestampTooOld, result);
}
test "ReplayProtector: timestamp just within TTL" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{1} ** 32;
// Message just within TTL boundary
const valid_timestamp = current_time - protector.message_ttl + 1;
try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id);
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 1), stats.tracked_messages);
}
test "ReplayProtector: timestamp at exact clock skew boundary" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{1} ** 32;
// Message at exactly clock skew boundary (5 seconds in future with 5s skew)
// This should be accepted
const boundary_timestamp = current_time + protector.max_clock_skew;
try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id);
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 1), stats.tracked_messages);
}
test "ReplayProtector: timestamp just beyond clock skew" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{1} ** 32;
// Message just beyond clock skew boundary
const future_timestamp = current_time + protector.max_clock_skew + 1;
const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id);
try testing.expectError(ReplayError.TimestampTooFarInFuture, result);
}
// ============================================================================
// Nonce Edge Cases (isDuplicateNonce)
// ============================================================================
test "ReplayProtector: nonce with very future timestamp rejected" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{2} ** 32;
// First, send a message with a timestamp far in the future (> 60s)
// This tests the isDuplicateNonce future timestamp rejection path
const far_future = current_time + 120; // 2 minutes in future
// This will be rejected by validateTimestamp first (TimestampTooFarInFuture)
const result = protector.checkMessage(1, far_future, 2000, 0, peer_id);
try testing.expectError(ReplayError.TimestampTooFarInFuture, result);
}
test "ReplayProtector: nonce reuse after TTL expiry allowed" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
// Use short TTL for testing
protector.configure(null, 1, null);
const base_time = std.time.timestamp();
const peer_id = [_]u8{3} ** 32;
// Add a message with nonce 3000
try protector.checkMessage(1, base_time, 3000, 0, peer_id);
// Force cleanup with future time to expire the nonce
protector.cleanup(base_time + 10);
// Now nonce 3000 should be allowed again (with new message ID and timestamp)
// Note: we need a valid timestamp relative to real current time
const new_time = std.time.timestamp();
try protector.checkMessage(2, new_time, 3000, 0, peer_id);
}
// ============================================================================
// Sequence Number Edge Cases
// ============================================================================
test "ReplayProtector: sequence 0 is always accepted" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{4} ** 32;
// Sequence 0 is reserved for non-ordered messages
try protector.checkMessage(1, current_time, 4000, 0, peer_id);
try protector.checkMessage(2, current_time + 1, 4001, 0, peer_id);
try protector.checkMessage(3, current_time + 2, 4002, 0, peer_id);
// No peer should be tracked for sequence 0 messages
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_peers);
}
test "ReplayProtector: sequence at window boundary" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{5} ** 32;
// Send sequence 100
try protector.checkMessage(1, current_time, 5000, 100, peer_id);
// Sequence 37 is at position 63 (100 - 37 = 63), which is the last bit in the window
try protector.checkMessage(2, current_time + 1, 5001, 37, peer_id);
// Sequence 36 is at position 64, which is outside the window (WINDOW_SIZE = 64)
const result = protector.checkMessage(3, current_time + 2, 5002, 36, peer_id);
try testing.expectError(ReplayError.SequenceTooOld, result);
}
test "ReplayProtector: sequence replay in sliding window" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{6} ** 32;
// Send sequences 1, 5, then 3 (out of order)
try protector.checkMessage(1, current_time, 6000, 1, peer_id);
try protector.checkMessage(2, current_time + 1, 6001, 5, peer_id);
try protector.checkMessage(3, current_time + 2, 6002, 3, peer_id);
// Replay sequence 3 should fail (InvalidSequence - already in window)
const result = protector.checkMessage(4, current_time + 3, 6003, 3, peer_id);
try testing.expectError(ReplayError.InvalidSequence, result);
}
test "ReplayProtector: sequence exactly at last_sequence" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{7} ** 32;
// Send sequence 10
try protector.checkMessage(1, current_time, 7000, 10, peer_id);
// Send sequence 10 again (duplicate)
const result = protector.checkMessage(2, current_time + 1, 7001, 10, peer_id);
try testing.expectError(ReplayError.DuplicateMessageId, result);
}
test "ReplayProtector: large sequence jump resets window" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{8} ** 32;
// Send sequence 10
try protector.checkMessage(1, current_time, 8000, 10, peer_id);
// Large jump to 1000 (> WINDOW_SIZE=64)
try protector.checkMessage(2, current_time + 1, 8001, 1000, peer_id);
// Sequence 5 is now way too old (1000 - 5 = 995 > 64)
const result = protector.checkMessage(3, current_time + 2, 8002, 5, peer_id);
try testing.expectError(ReplayError.SequenceTooOld, result);
}
// ============================================================================
// Cleanup Tests
// ============================================================================
test "ReplayProtector: forceCleanup removes expired entries" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
protector.configure(null, 1, null); // 1 second TTL
const base_time = std.time.timestamp();
const peer_id = [_]u8{9} ** 32;
// Add messages
try protector.checkMessage(1, base_time, 9000, 0, peer_id);
try protector.checkMessage(2, base_time, 9001, 0, peer_id);
var stats = protector.getStats();
try testing.expectEqual(@as(usize, 2), stats.tracked_messages);
try testing.expectEqual(@as(usize, 2), stats.tracked_nonces);
// Wait briefly and force cleanup
std.Thread.sleep(2 * std.time.ns_per_s);
protector.forceCleanup();
stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_messages);
try testing.expectEqual(@as(usize, 0), stats.tracked_nonces);
}
test "ReplayProtector: cleanup preserves recent entries" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{10} ** 32;
// Add messages with current timestamp
try protector.checkMessage(1, current_time, 10000, 1, peer_id);
try protector.checkMessage(2, current_time, 10001, 2, peer_id);
var stats = protector.getStats();
try testing.expectEqual(@as(usize, 2), stats.tracked_messages);
try testing.expectEqual(@as(usize, 1), stats.tracked_peers);
// Cleanup with current time should preserve recent entries
protector.cleanup(current_time);
stats = protector.getStats();
try testing.expectEqual(@as(usize, 2), stats.tracked_messages);
try testing.expectEqual(@as(usize, 1), stats.tracked_peers);
}
test "ReplayProtector: peer cleanup after 24 hours" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const base_time = std.time.timestamp();
const peer_id = [_]u8{11} ** 32;
// Add a peer
try protector.checkMessage(1, base_time, 11000, 1, peer_id);
var stats = protector.getStats();
try testing.expectEqual(@as(usize, 1), stats.tracked_peers);
// Cleanup with time 25 hours in future should remove the peer
const future_time = base_time + (25 * 3600);
protector.cleanup(future_time);
stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_peers);
}
// ============================================================================
// Reset Tests
// ============================================================================
test "ReplayProtector: resetPeerSequence for unknown peer" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const unknown_peer = [_]u8{12} ** 32;
// Reset for unknown peer should not error
try protector.resetPeerSequence(unknown_peer);
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 0), stats.tracked_peers);
}
test "ReplayProtector: resetPeerSequence allows restarting sequence" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{13} ** 32;
// Build up sequence to 100 (so that 1 is outside WINDOW_SIZE of 64)
try protector.checkMessage(1, current_time, 13000, 100, peer_id);
// Sequence 1 would normally be too old (100 - 1 = 99 > 64)
const result = protector.checkMessage(2, current_time + 1, 13001, 1, peer_id);
try testing.expectError(ReplayError.SequenceTooOld, result);
// Reset the peer
try protector.resetPeerSequence(peer_id);
// Now sequence 1 should work
try protector.checkMessage(3, current_time + 2, 13002, 1, peer_id);
}
// ============================================================================
// Multiple Peer Tests
// ============================================================================
test "ReplayProtector: independent sequence tracking per peer" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_a = [_]u8{0xAA} ** 32;
const peer_b = [_]u8{0xBB} ** 32;
// Peer A at sequence 100
try protector.checkMessage(1, current_time, 14000, 100, peer_a);
// Peer B can still use sequence 1
try protector.checkMessage(2, current_time + 1, 14001, 1, peer_b);
// Peer A can advance to 101
try protector.checkMessage(3, current_time + 2, 14002, 101, peer_a);
// Peer B can advance to 2
try protector.checkMessage(4, current_time + 3, 14003, 2, peer_b);
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 2), stats.tracked_peers);
}
test "ReplayProtector: same message ID different peers" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_a = [_]u8{0xCC} ** 32;
const peer_b = [_]u8{0xDD} ** 32;
// Peer A sends message ID 42
try protector.checkMessage(42, current_time, 15000, 1, peer_a);
// Peer B tries same message ID - should fail (message IDs are global)
const result = protector.checkMessage(42, current_time + 1, 15001, 1, peer_b);
try testing.expectError(ReplayError.DuplicateMessageId, result);
}
// ============================================================================
// Stats Tests
// ============================================================================
test "ReplayProtector: stats reflect correct counts" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
// Add messages from 3 different peers
for (0..3) |i| {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, @as(u8, @intCast(i + 1)));
const msg_id: u64 = @as(u64, @intCast(i)) * 100;
const nonce: u64 = 16000 + @as(u64, @intCast(i));
try protector.checkMessage(msg_id, current_time, nonce, @as(u64, @intCast(i + 1)), peer_id);
}
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 3), stats.tracked_messages);
try testing.expectEqual(@as(usize, 3), stats.tracked_nonces);
try testing.expectEqual(@as(usize, 3), stats.tracked_peers);
}
// ============================================================================
// Error Type Tests
// ============================================================================
test "ReplayError: all error types exist" {
// Verify error types can be used in switch statements
const errors = [_]ReplayError{
ReplayError.TimestampTooOld,
ReplayError.TimestampTooFarInFuture,
ReplayError.DuplicateMessageId,
ReplayError.InvalidSequence,
ReplayError.DuplicateNonce,
ReplayError.SequenceTooOld,
};
try testing.expectEqual(@as(usize, 6), errors.len);
}
test "MemoryError: all error types exist" {
const errors = [_]MemoryError{
MemoryError.TooManyMessages,
MemoryError.TooManyPeers,
MemoryError.TooManyNonces,
};
try testing.expectEqual(@as(usize, 3), errors.len);
}
// ============================================================================
// Boundary and Edge Cases
// ============================================================================
test "ReplayProtector: message with zero nonce" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{17} ** 32;
// Nonce 0 should work
try protector.checkMessage(1, current_time, 0, 0, peer_id);
// Duplicate nonce 0 should fail
const result = protector.checkMessage(2, current_time + 1, 0, 0, peer_id);
try testing.expectError(ReplayError.DuplicateNonce, result);
}
test "ReplayProtector: message with max u64 values" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{18} ** 32;
// Max u64 message ID and nonce
try protector.checkMessage(std.math.maxInt(u64), current_time, std.math.maxInt(u64) - 1, 1, peer_id);
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 1), stats.tracked_messages);
}
test "ReplayProtector: rapid message processing" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
const current_time = std.time.timestamp();
const peer_id = [_]u8{19} ** 32;
// Process 100 messages rapidly
for (0..100) |i| {
const msg_id: u64 = 19000 + @as(u64, @intCast(i));
const nonce: u64 = 190000 + @as(u64, @intCast(i));
const seq: u64 = @as(u64, @intCast(i + 1));
try protector.checkMessage(msg_id, current_time, nonce, seq, peer_id);
}
const stats = protector.getStats();
try testing.expectEqual(@as(usize, 100), stats.tracked_messages);
try testing.expectEqual(@as(usize, 100), stats.tracked_nonces);
}
// ============================================================================
// Cleanup Interval Tests
// ============================================================================
test "ReplayProtector: periodic cleanup triggered by checkMessage" {
var protector = ReplayProtector.init(testing.allocator);
defer protector.deinit();
// Set very short cleanup interval and TTL
protector.configure(null, 1, 1);
const base_time = std.time.timestamp();
const peer_id = [_]u8{20} ** 32;
// Add initial message
try protector.checkMessage(1, base_time, 20000, 0, peer_id);
var stats = protector.getStats();
try testing.expectEqual(@as(usize, 1), stats.tracked_messages);
// Wait for cleanup interval to pass
std.Thread.sleep(2 * std.time.ns_per_s);
// New message should trigger periodic cleanup
try protector.checkMessage(2, std.time.timestamp(), 20001, 0, peer_id);
stats = protector.getStats();
// Old message should be cleaned up, only new one remains
try testing.expectEqual(@as(usize, 1), stats.tracked_messages);
}

View File

@@ -0,0 +1,413 @@
//! Message routing tests
const std = @import("std");
const protocol = @import("../../src/protocol/protocol.zig");
const message = @import("../../src/protocol/message.zig");
const router = @import("../../src/protocol/router.zig");
test "router initialization" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
try std.testing.expect(routing_instance.allocator == allocator);
try std.testing.expectEqual(@as(usize, 0), routing_instance.routes.count());
try std.testing.expectEqual(@as(usize, 0), routing_instance.pending_queries.count());
const metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(usize, 0), metrics.total_routes);
try std.testing.expectEqual(@as(usize, 0), metrics.active_routes);
try std.testing.expectEqual(@as(u64, 0), metrics.failed_lookups);
try std.testing.expectEqual(@as(u64, 0), metrics.successful_lookups);
try std.testing.expectEqual(@as(f64, 0.0), metrics.average_lookup_time);
}
test "basic message routing" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// No route exists, should fail
const route_result = routing_instance.routeMessage(base_msg);
try std.testing.expect(!route_result.success);
try std.testing.expectEqual(protocol.ErrorCode.routing_error, route_result.error.?);
try std.testing.expectEqual(null, route_result.next_hop);
try std.testing.expectEqual(null, route_result.cost);
// Add a route
try routing_instance.addRoute(dest, dest, 1);
// Route should succeed now
const route_result2 = routing_instance.routeMessage(base_msg);
try std.testing.expect(route_result2.success);
try std.testing.expectEqual(dest, route_result2.next_hop.?);
try std.testing.expectEqual(@as(u32, 1), route_result2.cost.?);
try std.testing.expectEqual(null, route_result2.error);
}
test "route management" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest1[0] = 2;
var dest2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest2[0] = 3;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 4;
// Add multiple routes
try routing_instance.addRoute(dest1, next_hop, 1);
try routing_instance.addRoute(dest2, next_hop, 2);
try std.testing.expectEqual(@as(usize, 2), routing_instance.routes.count());
var metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(usize, 2), metrics.total_routes);
try std.testing.expectEqual(@as(usize, 2), metrics.active_routes);
// Test route queries
try std.testing.expect(routing_instance.isReachable(dest1));
try std.testing.expect(routing_instance.isReachable(dest2));
try std.testing.expectEqual(next_hop, routing_instance.getNextHop(dest1).?);
try std.testing.expectEqual(next_hop, routing_instance.getNextHop(dest2).?);
// Remove a route
routing_instance.removeRoute(dest1);
try std.testing.expect(!routing_instance.isReachable(dest1));
try std.testing.expect(routing_instance.isReachable(dest2));
try std.testing.expectEqual(null, routing_instance.getNextHop(dest1));
try std.testing.expectEqual(next_hop, routing_instance.getNextHop(dest2).?);
metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(usize, 1), metrics.active_routes);
}
test "route invalidation" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 3;
// Add route
try routing_instance.addRoute(dest, next_hop, 1);
try std.testing.expect(routing_instance.isReachable(dest));
// Invalidate route
routing_instance.invalidateRoute(dest);
try std.testing.expect(!routing_instance.isReachable(dest));
try std.testing.expectEqual(null, routing_instance.getNextHop(dest));
const metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(usize, 0), metrics.active_routes);
}
test "broadcast message handling" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
var header = message.MessageHeader.init(.ping, 123, source, dest);
header.flags |= protocol.MessageFlags.BROADCAST;
const broadcast_msg = message.BaseMessage{ .header = header, .payload = &.{} };
const route_result = routing_instance.routeMessage(broadcast_msg);
try std.testing.expect(route_result.success);
try std.testing.expectEqual(null, route_result.next_hop); // Broadcast to all
try std.testing.expectEqual(@as(u32, 1), route_result.cost.?);
try std.testing.expectEqual(null, route_result.error);
}
test "local message handling" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE; // All zeros = local
const header = message.MessageHeader.init(.ping, 123, source, dest);
const local_msg = message.BaseMessage{ .header = header, .payload = &.{} };
const route_result = routing_instance.routeMessage(local_msg);
try std.testing.expect(route_result.success);
try std.testing.expectEqual(null, route_result.next_hop); // Local delivery
try std.testing.expectEqual(@as(u32, 0), route_result.cost.?);
try std.testing.expectEqual(null, route_result.error);
}
test "route discovery" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Initiate route discovery
const query_result = routing_instance.routeMessage(base_msg);
try std.testing.expect(!query_result.success);
// Should have added to pending queries
try std.testing.expectEqual(@as(usize, 1), routing_instance.pending_queries.count());
}
test "route response handling" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 3;
// Add pending query
try routing_instance.pending_queries.put(123, dest);
// Handle route response
const response = message.RouteResponse.init(123, "route info");
try routing_instance.handleRouteResponse(response);
// Should have updated routing table
try std.testing.expect(routing_instance.isReachable(dest));
try std.testing.expectEqual(next_hop, routing_instance.getNextHop(dest).?);
// Pending query should be removed
try std.testing.expectEqual(@as(usize, 0), routing_instance.pending_queries.count());
}
test "route cleanup" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest1[0] = 2;
var dest2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest2[0] = 3;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 4;
// Add routes with current timestamp
try routing_instance.addRoute(dest1, next_hop, 1);
try routing_instance.addRoute(dest2, next_hop, 1);
// Clean up routes older than 1 second (shouldn't affect fresh routes)
routing_instance.cleanupExpiredRoutes(1);
try std.testing.expect(routing_instance.isReachable(dest1));
try std.testing.expect(routing_instance.isReachable(dest2));
// Clean up routes older than 0 seconds (should affect all routes)
routing_instance.cleanupExpiredRoutes(0);
try std.testing.expect(!routing_instance.isReachable(dest1));
try std.testing.expect(!routing_instance.isReachable(dest2));
}
test "route statistics" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 3;
// Add route
try routing_instance.addRoute(dest, next_hop, 1);
// Generate some lookups
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Successful lookup
_ = routing_instance.routeMessage(base_msg);
// Failed lookup (remove route)
routing_instance.removeRoute(dest);
_ = routing_instance.routeMessage(base_msg);
const stats = routing_instance.getRouteStats();
try std.testing.expectEqual(@as(usize, 1), stats.total);
try std.testing.expectEqual(@as(usize, 0), stats.active);
try std.testing.expectEqual(@as(usize, 0), stats.pending);
try std.testing.expect(stats.success_rate >= 0.0 and stats.success_rate <= 1.0);
}
test "distance vector routing" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dv_router = router.DistanceVectorRouter.init(&routing_instance);
var neighbor: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor[0] = 2;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 3;
var neighbor_routes = std.ArrayList(router.RouteEntry).init(allocator);
defer neighbor_routes.deinit();
try neighbor_routes.append(router.RouteEntry{
.destination = dest,
.next_hop = dest,
.cost = 1,
.last_updated = std.time.timestamp(),
.is_valid = true,
});
// Process distance vector update
try dv_router.processUpdate(neighbor, neighbor_routes.items);
// Should have learned route through neighbor
try std.testing.expect(routing_instance.isReachable(dest));
const next_hop = routing_instance.getNextHop(dest);
try std.testing.expect(next_hop != null);
// Test sending distance vector
const routes = try dv_router.sendDistanceVector(neighbor);
defer routes.deinit();
try std.testing.expect(routes.items.len > 0);
}
test "link state routing initialization" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var ls_router = router.LinkStateRouter.init(&routing_instance, allocator);
defer ls_router.deinit();
try std.testing.expectEqual(@as(usize, 0), ls_router.topology_map.count());
}
test "link state advertisement processing" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var ls_router = router.LinkStateRouter.init(&routing_instance, allocator);
defer ls_router.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var neighbors = std.ArrayList(message.NodeId).init(allocator);
defer neighbors.deinit();
var neighbor1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor1[0] = 2;
var neighbor2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor2[0] = 3;
try neighbors.append(neighbor1);
try neighbors.append(neighbor2);
// Process LSA
try ls_router.processLSA(source, neighbors.items);
try std.testing.expectEqual(@as(usize, 1), ls_router.topology_map.count());
const source_neighbors = ls_router.topology_map.get(source);
try std.testing.expect(source_neighbors != null);
try std.testing.expectEqual(@as(usize, 2), source_neighbors.?.items.len);
}
test "get all routes" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var dest1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest1[0] = 2;
var dest2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest2[0] = 3;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 4;
try routing_instance.addRoute(dest1, next_hop, 1);
try routing_instance.addRoute(dest2, next_hop, 2);
const all_routes = routing_instance.getAllRoutes();
defer all_routes.deinit();
try std.testing.expectEqual(@as(usize, 2), all_routes.items.len);
// Routes should be in the list
var found_routes = 0;
for (all_routes.items) |route| {
if (std.mem.eql(u8, &route.destination, &dest1) or
std.mem.eql(u8, &route.destination, &dest2)) {
found_routes += 1;
}
}
try std.testing.expectEqual(@as(usize, 2), found_routes);
}
test "metrics tracking" {
const allocator = std.testing.allocator;
var routing_instance = router.MessageRouter.init(allocator);
defer routing_instance.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Initial metrics
var metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(u64, 0), metrics.successful_lookups);
try std.testing.expectEqual(@as(u64, 0), metrics.failed_lookups);
try std.testing.expectEqual(@as(f64, 0.0), metrics.average_lookup_time);
// Failed lookup
_ = routing_instance.routeMessage(base_msg);
metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(u64, 0), metrics.successful_lookups);
try std.testing.expectEqual(@as(u64, 1), metrics.failed_lookups);
// Add route and successful lookup
try routing_instance.addRoute(dest, dest, 1);
_ = routing_instance.routeMessage(base_msg);
metrics = routing_instance.getMetrics();
try std.testing.expectEqual(@as(u64, 1), metrics.successful_lookups);
try std.testing.expectEqual(@as(u64, 1), metrics.failed_lookups);
try std.testing.expect(metrics.average_lookup_time >= 0.0);
}

View File

@@ -0,0 +1,326 @@
//! Comprehensive tests for message routing functionality
//! Tests routing to known/unknown destinations, route expiration, updates, concurrency, and metrics
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const message = protocol.message;
const router_mod = protocol.router;
test "router: route message to known destination" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
// Add route to destination
try router.addRoute(dest, dest, 1);
// Create message
const header = message.MessageHeader.init(.ping, 123, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Route should succeed
const result = router.routeMessage(base_msg);
try testing.expect(result.success);
try testing.expectEqual(dest, result.next_hop.?);
try testing.expectEqual(@as(u32, 1), result.cost.?);
}
test "router: route message to unknown destination initiates discovery" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 99; // Unknown destination
const header = message.MessageHeader.init(.ping, 456, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Route should fail (no route exists)
const result = router.routeMessage(base_msg);
try testing.expect(!result.success);
try testing.expectEqual(protocol.protocol.ErrorCode.routing_error, result.err.?);
}
test "router: add and retrieve route" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 5;
var next_hop: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
next_hop[0] = 3;
try router.addRoute(dest, next_hop, 2);
const retrieved_hop = router.getNextHop(dest);
try testing.expect(retrieved_hop != null);
try testing.expectEqual(next_hop, retrieved_hop.?);
}
test "router: route expiration after max age" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 7;
try router.addRoute(dest, dest, 1);
// Verify route exists
try testing.expect(router.isReachable(dest));
// Clean up expired routes with 0 second max age (expire immediately)
router.cleanupExpiredRoutes(0);
// Route should still exist but marked as invalid
try testing.expect(!router.isReachable(dest));
}
test "router: route update with better cost" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 8;
var hop1: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
hop1[0] = 10;
var hop2: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
hop2[0] = 11;
// Add initial route with cost 5
try router.addRoute(dest, hop1, 5);
var next_hop = router.getNextHop(dest);
try testing.expectEqual(hop1, next_hop.?);
// Add better route with cost 2
try router.addRoute(dest, hop2, 2);
next_hop = router.getNextHop(dest);
try testing.expectEqual(hop2, next_hop.?);
}
test "router: route update preserves worse cost" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 9;
var hop1: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
hop1[0] = 12;
var hop2: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
hop2[0] = 13;
// Add initial route with cost 2
try router.addRoute(dest, hop1, 2);
// Try to add worse route with cost 5 (should be ignored)
try router.addRoute(dest, hop2, 5);
const next_hop = router.getNextHop(dest);
try testing.expectEqual(hop1, next_hop.?);
}
test "router: remove route" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 15;
try router.addRoute(dest, dest, 1);
try testing.expect(router.isReachable(dest));
router.removeRoute(dest);
try testing.expect(!router.isReachable(dest));
}
test "router: invalidate route" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 16;
try router.addRoute(dest, dest, 1);
try testing.expect(router.isReachable(dest));
router.invalidateRoute(dest);
try testing.expect(!router.isReachable(dest));
// Route still exists but marked invalid
const metrics = router.getMetrics();
try testing.expect(metrics.total_routes > 0);
}
test "router: metrics accuracy under load" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
// Add 100 routes
var i: u8 = 0;
while (i < 100) : (i += 1) {
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = i;
try router.addRoute(dest, dest, @as(u32, i));
}
const metrics = router.getMetrics();
try testing.expectEqual(@as(usize, 100), metrics.total_routes);
try testing.expectEqual(@as(usize, 100), metrics.active_routes);
}
test "router: successful lookup metrics" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
try router.addRoute(dest, dest, 1);
const header = message.MessageHeader.init(.ping, 789, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
_ = router.routeMessage(base_msg);
const metrics = router.getMetrics();
try testing.expectEqual(@as(u64, 1), metrics.successful_lookups);
try testing.expectEqual(@as(u64, 0), metrics.failed_lookups);
}
test "router: failed lookup metrics" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 99; // Unknown
const header = message.MessageHeader.init(.ping, 999, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
_ = router.routeMessage(base_msg);
const metrics = router.getMetrics();
try testing.expectEqual(@as(u64, 0), metrics.successful_lookups);
try testing.expectEqual(@as(u64, 1), metrics.failed_lookups);
}
test "router: broadcast message handling" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
var header = message.MessageHeader.init(.ping, 111, source, dest);
header.flags |= protocol.protocol.MessageFlags.BROADCAST;
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
const result = router.routeMessage(base_msg);
try testing.expect(result.success);
}
test "router: local message detection" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE; // All zeros = local
const header = message.MessageHeader.init(.ping, 222, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
const result = router.routeMessage(base_msg);
try testing.expect(result.success);
try testing.expect(result.next_hop == null); // Local, no next hop
}
test "router: route stats accuracy" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
// Add some routes
var i: u8 = 0;
while (i < 10) : (i += 1) {
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = i;
try router.addRoute(dest, dest, 1);
}
// Invalidate half
i = 0;
while (i < 5) : (i += 1) {
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = i;
router.invalidateRoute(dest);
}
const stats = router.getRouteStats();
try testing.expectEqual(@as(usize, 10), stats.total);
try testing.expectEqual(@as(usize, 5), stats.active);
}
test "router: add neighbor" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var neighbor: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
neighbor[0] = 20;
try router.addNeighbor(neighbor);
try testing.expectEqual(@as(usize, 1), router.neighbors.items.len);
}
test "router: route response handling" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var dest: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
dest[0] = 30;
var next_hop: message.NodeId = .{0} ** protocol.protocol.Network.NODE_ID_SIZE;
next_hop[0] = 31;
const query_id: u64 = 5555;
// Add to pending queries
try router.pending_queries.put(query_id, dest);
// Create route response
var response = message.RouteResponse.init(query_id, "route_info");
response.next_hop = next_hop;
// Handle response
try router.handleRouteResponse(response);
// Route should now exist
const retrieved_hop = router.getNextHop(dest);
try testing.expectEqual(next_hop, retrieved_hop.?);
}

View File

@@ -0,0 +1,544 @@
//! Comprehensive routing security tests
//! Tests route authentication, limits, TTL enforcement, and stale route eviction
const std = @import("std");
const testing = std.testing;
const router_mod = @import("../../src/protocol/router.zig");
const message = @import("../../src/protocol/message.zig");
const protocol = @import("../../src/protocol/protocol.zig");
const routing_mod = @import("../../src/network/routing.zig");
const peer_mod = @import("../../src/network/peer.zig");
const core = @import("core");
// Test that unsigned routes to non-directly-connected peers are rejected
test "unsigned routes rejected for non-directly-connected peers" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Try to add route without signature (should fail)
const result = router.addRoute(destination, next_hop, 5);
try testing.expectError(error.UnsignedRoute, result);
}
// Test that unsigned routes to directly-connected peers are accepted
test "unsigned routes accepted for directly-connected peers" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark destination as directly connected
try router.directly_connected_peers.put(destination, void{});
// Add route without signature (should succeed)
try router.addRoute(destination, next_hop, 5);
// Verify route was added
try testing.expect(router.isReachable(destination));
}
// Test that invalid signatures are rejected
test "invalid signatures rejected" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
var invalid_signer: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
invalid_signer[0] = 99; // Not the destination, not a trusted relay
// Create signature with invalid signer
const sig = router_mod.RouteSignature{
.signer_id = invalid_signer,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp(),
};
// Try to add route with invalid signature (should fail)
const result = router.addRouteWithSignature(destination, next_hop, 5, sig);
try testing.expectError(error.InvalidSignature, result);
}
// Test that signatures from destination are accepted
test "signatures from destination accepted" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Create signature signed by destination itself
const sig = router_mod.RouteSignature{
.signer_id = destination,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp(),
};
// Add route with valid signature (should succeed)
try router.addRouteWithSignature(destination, next_hop, 5, sig);
// Verify route was added
try testing.expect(router.isReachable(destination));
}
// Test that signatures from trusted relays are accepted
test "signatures from trusted relays accepted" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var trusted_relay: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
trusted_relay[0] = 3;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark relay as directly connected (trusted)
try router.directly_connected_peers.put(trusted_relay, void{});
// Create signature signed by trusted relay
const sig = router_mod.RouteSignature{
.signer_id = trusted_relay,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp(),
};
// Add route with signature from trusted relay (should succeed)
try router.addRouteWithSignature(destination, next_hop, 5, sig);
// Verify route was added
try testing.expect(router.isReachable(destination));
}
// Test that zero-cost routes are rejected
test "zero-cost routes rejected" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark as directly connected to bypass signature requirement
try router.directly_connected_peers.put(destination, void{});
// Try to add route with zero cost (should fail)
const result = router.addRoute(destination, next_hop, 0);
try testing.expectError(error.InvalidRouteCost, result);
}
// Test that excessively high-cost routes are rejected
test "high-cost routes rejected" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark as directly connected to bypass signature requirement
try router.directly_connected_peers.put(destination, void{});
// Try to add route with excessive cost (should fail)
const result = router.addRoute(destination, next_hop, 1001);
try testing.expectError(error.InvalidRouteCost, result);
}
// Test that valid-cost routes are accepted
test "valid-cost routes accepted" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark as directly connected to bypass signature requirement
try router.directly_connected_peers.put(destination, void{});
// Add routes with valid costs
try router.addRoute(destination, next_hop, 1);
try testing.expect(router.isReachable(destination));
// Update with different cost
try router.addRoute(destination, next_hop, 500);
try testing.expect(router.isReachable(destination));
try router.addRoute(destination, next_hop, 1000);
try testing.expect(router.isReachable(destination));
}
// Test routing table size limits
test "routing table size limits enforced" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
// Set a small limit for testing
router.max_routes = 10;
// Add routes up to the limit
var i: u8 = 0;
while (i < 10) : (i += 1) {
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = i;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = i + 100;
// Mark as directly connected
try router.directly_connected_peers.put(destination, void{});
try router.addRoute(destination, next_hop, 5);
}
// Verify we have 10 routes
try testing.expectEqual(@as(usize, 10), router.routes.count());
// Add one more route - should evict LRU
var new_dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
new_dest[0] = 99;
var new_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
new_hop[0] = 199;
try router.directly_connected_peers.put(new_dest, void{});
try router.addRoute(new_dest, new_hop, 5);
// Should still have 10 routes (one was evicted)
try testing.expectEqual(@as(usize, 10), router.routes.count());
// New route should be present
try testing.expect(router.isReachable(new_dest));
}
// Test per-destination route limits
test "per-destination route limits enforced" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
router.max_routes_per_destination = 2;
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
// Mark as directly connected
try router.directly_connected_peers.put(destination, void{});
// Add first route
var next_hop1: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop1[0] = 10;
try router.addRoute(destination, next_hop1, 5);
// Add second route (different next hop, same destination)
var next_hop2: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop2[0] = 20;
try router.addRoute(destination, next_hop2, 10);
// Try to add third route with worse cost - should fail
var next_hop3: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop3[0] = 30;
const result = router.addRoute(destination, next_hop3, 15);
try testing.expectError(error.RouteNotBetter, result);
// Add third route with better cost - should replace worst
var next_hop4: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop4[0] = 40;
try router.addRoute(destination, next_hop4, 3);
// Should still be reachable
try testing.expect(router.isReachable(destination));
}
// Test TTL enforcement
test "TTL enforcement in routeMessage" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
// Create message with TTL = 0
var header = message.MessageHeader.init(.ping, 123, source, dest);
header.ttl = 0;
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Route should fail due to expired TTL
const route_result = router.routeMessage(base_msg);
try testing.expect(!route_result.success);
try testing.expectEqual(protocol.ErrorCode.routing_error, route_result.err.?);
}
// Test TTL allows routing when > 0
test "TTL allows routing when greater than zero" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
// Add route
try router.directly_connected_peers.put(dest, void{});
try router.addRoute(dest, dest, 1);
// Create message with TTL > 0
var header = message.MessageHeader.init(.ping, 123, source, dest);
header.ttl = 5;
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Route should succeed
const route_result = router.routeMessage(base_msg);
try testing.expect(route_result.success);
}
// Test stale route eviction
test "stale routes evicted by cleanupStaleRoutes" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
// Set zero max age for instant staleness (fast testing)
router.max_route_age = 0;
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Mark as directly connected
try router.directly_connected_peers.put(destination, void{});
// Add route
try router.addRoute(destination, next_hop, 5);
try testing.expect(router.isReachable(destination));
// Brief wait then cleanup (route is instantly stale with max_route_age=0)
std.time.sleep(50 * std.time.ns_per_ms);
// Clean up stale routes
router.cleanupStaleRoutes();
// Route should be invalidated
try testing.expect(!router.isReachable(destination));
}
// Test signature timestamp validation
test "signature timestamp validation" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var destination: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
destination[0] = 1;
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
// Create signature with very old timestamp
const old_sig = router_mod.RouteSignature{
.signer_id = destination,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp() - 600, // 10 minutes old
};
// Should be rejected due to old timestamp
const result1 = router.addRouteWithSignature(destination, next_hop, 5, old_sig);
try testing.expectError(error.InvalidSignature, result1);
// Create signature with future timestamp
const future_sig = router_mod.RouteSignature{
.signer_id = destination,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp() + 120, // 2 minutes in the future
};
// Should be rejected due to future timestamp
const result2 = router.addRouteWithSignature(destination, next_hop, 5, future_sig);
try testing.expectError(error.InvalidSignature, result2);
// Create signature with valid timestamp
const valid_sig = router_mod.RouteSignature{
.signer_id = destination,
.signature = [_]u8{0} ** 64,
.timestamp = std.time.timestamp(),
};
// Should succeed
try router.addRouteWithSignature(destination, next_hop, 5, valid_sig);
try testing.expect(router.isReachable(destination));
}
// Test Kademlia routing table size limits
test "Kademlia routing table enforces size limits" {
const allocator = testing.allocator;
const local_id = peer_mod.PeerId.init();
var config = routing_mod.RoutingConfig{};
config.max_total_peers = 5; // Small limit for testing
var routing_table = routing_mod.KademliaRoutingTable.initWithConfig(allocator, local_id, config);
defer routing_table.deinit();
// Add peers up to the limit
var i: u8 = 0;
while (i < 5) : (i += 1) {
const peer_id = peer_mod.PeerId.init();
const address = core.Address.init();
var peer = try allocator.create(peer_mod.Peer);
peer.* = peer_mod.Peer.init(peer_id, address);
defer allocator.destroy(peer);
var position = try allocator.create(routing_mod.NodePosition);
position.* = routing_mod.NodePosition.init(allocator, peer_id);
defer {
position.deinit();
allocator.destroy(position);
}
try routing_table.addPeer(peer, position);
}
// Verify we have 5 peers
try testing.expectEqual(@as(usize, 5), routing_table.total_peers.load(.monotonic));
// Try to add one more - should fail
const peer_id = peer_mod.PeerId.init();
const address = core.Address.init();
var peer = try allocator.create(peer_mod.Peer);
peer.* = peer_mod.Peer.init(peer_id, address);
defer allocator.destroy(peer);
var position = try allocator.create(routing_mod.NodePosition);
position.* = routing_mod.NodePosition.init(allocator, peer_id);
defer {
position.deinit();
allocator.destroy(position);
}
const result = routing_table.addPeer(peer, position);
try testing.expectError(error.RoutingTableFull, result);
}
// Test Kademlia stale route eviction
test "Kademlia routing table evicts stale routes" {
const allocator = testing.allocator;
const local_id = peer_mod.PeerId.init();
var config = routing_mod.RoutingConfig{};
config.max_route_age = 0; // 0 = instant staleness for fast testing
var routing_table = routing_mod.KademliaRoutingTable.initWithConfig(allocator, local_id, config);
defer routing_table.deinit();
// Add a peer
const peer_id = peer_mod.PeerId.init();
const address = core.Address.init();
var peer = try allocator.create(peer_mod.Peer);
peer.* = peer_mod.Peer.init(peer_id, address);
defer allocator.destroy(peer);
var position = try allocator.create(routing_mod.NodePosition);
position.* = routing_mod.NodePosition.init(allocator, peer_id);
defer {
position.deinit();
allocator.destroy(position);
}
try routing_table.addPeer(peer, position);
try testing.expectEqual(@as(usize, 1), routing_table.total_peers.load(.monotonic));
// Brief wait then cleanup (route is instantly stale with max_route_age=0)
std.time.sleep(50 * std.time.ns_per_ms);
// Clean up stale routes
try routing_table.cleanupStaleRoutes();
// Peer should be removed
try testing.expectEqual(@as(usize, 0), routing_table.total_peers.load(.monotonic));
}
// Test addNeighbor marks peer as directly connected
test "addNeighbor marks peer as directly connected" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var neighbor: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor[0] = 1;
// Add neighbor
try router.addNeighbor(neighbor);
// Verify neighbor is in directly_connected_peers
try testing.expect(router.directly_connected_peers.contains(neighbor));
// Verify neighbor can add routes without signatures
var next_hop: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
next_hop[0] = 2;
try router.addRoute(neighbor, next_hop, 5);
try testing.expect(router.isReachable(neighbor));
}
// Test removeNeighbor removes peer from directly connected
test "removeNeighbor removes peer from directly connected" {
const allocator = testing.allocator;
var router = router_mod.MessageRouter.init(allocator);
defer router.deinit();
var neighbor: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
neighbor[0] = 1;
// Add neighbor
try router.addNeighbor(neighbor);
try testing.expect(router.directly_connected_peers.contains(neighbor));
// Remove neighbor
router.removeNeighbor(neighbor);
// Verify neighbor is not in directly_connected_peers
try testing.expect(!router.directly_connected_peers.contains(neighbor));
}

View File

@@ -0,0 +1,764 @@
//! Security Tests for P2P Protocol
//! Tests encryption, authentication, and message integrity
//!
//! NOTE: These tests use EncryptionManager (the production encryption path)
//! instead of CryptoManager.encrypt() which is deprecated due to nonce reuse risk.
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const CryptoManager = protocol.crypto.CryptoManager;
const CryptoError = protocol.crypto.CryptoError;
const EncryptionManager = protocol.encryption.EncryptionManager;
test "encryption roundtrip with various message sizes" {
const allocator = testing.allocator;
// Create crypto manager (required by EncryptionManager)
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1); // generation = 1
// Test various message sizes
const sizes = [_]usize{ 1, 16, 64, 256, 1024, 4096 };
for (sizes) |size| {
const plaintext = try allocator.alloc(u8, size);
defer allocator.free(plaintext);
std.crypto.random.bytes(plaintext);
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try enc_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualSlices(u8, plaintext, decrypted);
}
}
test "decryption fails on tampered ciphertext" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Test 1: Tamper with authentication tag
{
const plaintext = "Secret message for tag tamper test";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[tampered.len - 1] ^= 0xFF;
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
// Test 2: Tamper with ciphertext body (using new encryption to avoid nonce replay)
{
const plaintext = "Secret message for body tamper test";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
if (tampered.len > 20) {
tampered[20] ^= 0xFF;
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
}
// Test 3: Tamper with nonce (random bytes) - affects decryption but not generation check
// Note: Tampering nonce bytes 0-3 (generation) may cause NonceReplay if it creates an older generation
{
const plaintext = "Secret message for nonce tamper test";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
// Tamper with the random portion of nonce (bytes 8-11) to avoid generation check issues
tampered[10] ^= 0xFF;
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
}
test "encryption with unknown peer fails" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const unknown_peer = [_]u8{99} ** 32;
const plaintext = "Test message";
try testing.expectError(CryptoError.NoKeyForPeer, enc_mgr.encrypt(unknown_peer, plaintext));
}
test "invalid ciphertext sizes rejected" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Test ciphertexts that are too small (need at least nonce + tag)
const too_small = [_]u8{0} ** 10;
try testing.expectError(CryptoError.InvalidCiphertext, enc_mgr.decrypt(peer_id, &too_small));
// Minimum valid size is 12 (nonce) + 16 (tag) = 28 bytes
const min_size = [_]u8{0} ** 27;
try testing.expectError(CryptoError.InvalidCiphertext, enc_mgr.decrypt(peer_id, &min_size));
}
test "nonce counter increments correctly" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "Test message for nonce testing";
// Encrypt multiple messages
var ciphertexts: [5][]u8 = undefined;
for (&ciphertexts) |*ct| {
ct.* = try enc_mgr.encrypt(peer_id, plaintext);
}
defer for (ciphertexts) |ct| allocator.free(ct);
// All ciphertexts should be different (different nonces)
for (ciphertexts, 0..) |ct1, i| {
for (ciphertexts[i + 1 ..]) |ct2| {
try testing.expect(!std.mem.eql(u8, ct1, ct2));
}
}
// But all should decrypt to the same plaintext
for (ciphertexts) |ct| {
const decrypted = try enc_mgr.decrypt(peer_id, ct);
defer allocator.free(decrypted);
try testing.expectEqualSlices(u8, plaintext, decrypted);
}
}
test "key rotation maintains decryption compatibility" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key1 = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key1, 1);
// Encrypt with old key
const plaintext = "Message before rotation";
const ct_old = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct_old);
// Rotate key
try enc_mgr.rotateKeyForPeer(peer_id);
// New messages should work
const ct_new = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct_new);
const decrypted_new = try enc_mgr.decrypt(peer_id, ct_new);
defer allocator.free(decrypted_new);
try testing.expectEqualSlices(u8, plaintext, decrypted_new);
// Old messages should still work (previous key fallback)
const decrypted_old = try enc_mgr.decrypt(peer_id, ct_old);
defer allocator.free(decrypted_old);
try testing.expectEqualSlices(u8, plaintext, decrypted_old);
}
test "AAD prevents context confusion attack" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 0);
// Encrypt with 'file_transfer' context
const plaintext = "Secret file data";
const ciphertext = try enc_mgr.encryptWithContext(peer_id, plaintext, .file_transfer);
defer allocator.free(ciphertext);
// Trying to decrypt with wrong context should fail
// This prevents message type confusion attacks
try testing.expectError(
CryptoError.DecryptionFailed,
enc_mgr.decryptWithContext(peer_id, ciphertext, .data),
);
try testing.expectError(
CryptoError.DecryptionFailed,
enc_mgr.decryptWithContext(peer_id, ciphertext, .control),
);
// Decrypt with correct context should succeed
const decrypted = try enc_mgr.decryptWithContext(peer_id, ciphertext, .file_transfer);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "AAD prevents peer swapping attack" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_a = [_]u8{1} ** 32;
const peer_b = [_]u8{2} ** 32;
const key = [_]u8{3} ** 32;
// Set same key for both peers (simulates attacker relaying messages)
try enc_mgr.setKeyForPeer(peer_a, key, 0);
try enc_mgr.setKeyForPeer(peer_b, key, 0);
// Encrypt message for peer_a
const plaintext = "Message for peer A";
const ciphertext = try enc_mgr.encrypt(peer_a, plaintext);
defer allocator.free(ciphertext);
// Trying to decrypt as peer_b should fail
// This prevents message swapping attacks even with same key
try testing.expectError(
CryptoError.DecryptionFailed,
enc_mgr.decrypt(peer_b, ciphertext),
);
// Decrypt as peer_a should succeed
const decrypted = try enc_mgr.decrypt(peer_a, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
// =============================================================================
// Additional Security Tests - Core Requirements
// =============================================================================
// REMOVED: CryptoManager.encrypt() has been removed for security
// Use EncryptionManager from encryption.zig instead for counter-based nonces
test "tampered ciphertext detected - modify tag" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "Sensitive data that must not be modified";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with authentication tag (last 16 bytes)
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[tampered.len - 1] ^= 0xFF;
// Should fail with DecryptionFailed
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
test "tampered ciphertext detected - modify nonce" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "Data protected by AEAD";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with nonce (first 12 bytes)
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
tampered[5] ^= 0xFF;
// Should fail with DecryptionFailed
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
test "tampered ciphertext detected - modify payload" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "Long message with substantial payload content for testing";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Tamper with payload (middle bytes)
var tampered = try allocator.dupe(u8, ciphertext);
defer allocator.free(tampered);
const middle_idx = 12 + (plaintext.len / 2);
tampered[middle_idx] ^= 0xFF;
// Should fail with DecryptionFailed
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, tampered));
}
test "message ID uniqueness - no collisions in 10000 IDs" {
const MessageBuilder = protocol.message.MessageBuilder;
var ids = std.AutoHashMap(u64, void).init(testing.allocator);
defer ids.deinit();
var i: usize = 0;
while (i < 10000) : (i += 1) {
const builder = MessageBuilder.init(testing.allocator);
const id = builder.generateMessageId();
// Verify no collision
try testing.expect(ids.get(id) == null);
try ids.put(id, {});
}
}
test "message ID uniqueness - high entropy distribution" {
const MessageBuilder = protocol.message.MessageBuilder;
const builder = MessageBuilder.init(testing.allocator);
// Track bit distribution in generated IDs
var bit_set_counts: [64]usize = [_]usize{0} ** 64;
var i: usize = 0;
while (i < 1000) : (i += 1) {
const id = builder.generateMessageId();
// Count set bits in each position
var bit_pos: usize = 0;
while (bit_pos < 64) : (bit_pos += 1) {
if ((id >> @intCast(bit_pos)) & 1 == 1) {
bit_set_counts[bit_pos] += 1;
}
}
}
// Each bit should be set roughly 50% of the time (300-700 out of 1000)
// This verifies we're using cryptographic randomness, not weak randomness
// Using wider bounds (30-70%) to avoid statistical false positives
for (bit_set_counts) |count| {
try testing.expect(count >= 300); // At least 30%
try testing.expect(count <= 700); // At most 70%
}
}
test "message ID uniqueness - concurrent generation" {
const MessageBuilder = protocol.message.MessageBuilder;
var ids = std.AutoHashMap(u64, void).init(testing.allocator);
defer ids.deinit();
// Generate IDs rapidly in succession to test for time-based collisions
const builder = MessageBuilder.init(testing.allocator);
var i: usize = 0;
while (i < 5000) : (i += 1) {
const id = builder.generateMessageId();
try testing.expect(ids.get(id) == null);
try ids.put(id, {});
}
}
test "authentication failure - wrong key decryption" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key1 = [_]u8{2} ** 32;
const key2 = [_]u8{3} ** 32; // Different key
// Set up encryption with key1
try enc_mgr.setKeyForPeer(peer_id, key1, 1);
const plaintext = "Secret encrypted with key1";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Replace key with key2
try enc_mgr.setKeyForPeer(peer_id, key2, 1);
// Decryption should fail - wrong key
try testing.expectError(CryptoError.DecryptionFailed, enc_mgr.decrypt(peer_id, ciphertext));
}
test "authentication failure - no key for peer" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const unknown_peer = [_]u8{99} ** 32;
const plaintext = "This should fail";
// Attempt to encrypt without registering key
try testing.expectError(CryptoError.NoKeyForPeer, enc_mgr.encrypt(unknown_peer, plaintext));
}
test "authentication failure - HMAC verification" {
const HmacAuthenticator = protocol.crypto.HmacAuthenticator;
const key = [_]u8{0xAB} ** 32;
const wrong_key = [_]u8{0xCD} ** 32;
const data = "Data to authenticate";
// Compute HMAC with correct key
const mac = HmacAuthenticator.computeHmac(key, data);
// Verification with correct key should succeed
try testing.expect(HmacAuthenticator.verifyHmac(key, data, mac));
// Verification with wrong key should fail
try testing.expect(!HmacAuthenticator.verifyHmac(wrong_key, data, mac));
// Verification with modified data should fail
const tampered_data = "Data to authenticate!";
try testing.expect(!HmacAuthenticator.verifyHmac(key, tampered_data, mac));
// Verification with modified MAC should fail
var tampered_mac = mac;
tampered_mac[0] ^= 0xFF;
try testing.expect(!HmacAuthenticator.verifyHmac(key, data, tampered_mac));
}
// =============================================================================
// Edge Case Tests
// =============================================================================
test "edge case - empty data encryption" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Encrypt empty data
const plaintext = "";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Should still have nonce + tag (28 bytes minimum)
try testing.expectEqual(@as(usize, 28), ciphertext.len);
// Should decrypt to empty
const decrypted = try enc_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
test "edge case - maximum size data encryption" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
// Test with maximum allowed message size (65535 bytes - limit enforced by encryption)
const large_size = 65535;
const plaintext = try allocator.alloc(u8, large_size);
defer allocator.free(plaintext);
// Fill with pattern for verification
for (plaintext, 0..) |*byte, i| {
byte.* = @as(u8, @truncate(i));
}
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
const decrypted = try enc_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualSlices(u8, plaintext, decrypted);
}
test "edge case - single byte data encryption" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "X";
const ciphertext = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ciphertext);
// Should be nonce(12) + data(1) + tag(16) = 29 bytes
try testing.expectEqual(@as(usize, 29), ciphertext.len);
const decrypted = try enc_mgr.decrypt(peer_id, ciphertext);
defer allocator.free(decrypted);
try testing.expectEqualStrings(plaintext, decrypted);
}
// =============================================================================
// Advanced Security Tests
// =============================================================================
test "security - key material properly zeroized on deinit" {
const allocator = testing.allocator;
// Create a peer key we can track
const peer_id = [_]u8{42} ** 32;
const key = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ** 8;
{
var crypto_mgr = CryptoManager.init(allocator);
try crypto_mgr.setKeyForPeer(peer_id, key);
// Verify key is registered
try testing.expect(crypto_mgr.hasKeyForPeer(peer_id));
// deinit should zeroize all keys
crypto_mgr.deinit();
// Note: We can't directly verify memory was zeroized without unsafe operations,
// but this test ensures the zeroization code path is exercised
}
}
test "security - nonce reuse prevention across rotations" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 0);
var all_nonces = std.AutoHashMap([12]u8, void).init(allocator);
defer all_nonces.deinit();
const plaintext = "Test message";
// Generate some messages before rotation
var i: usize = 0;
while (i < 50) : (i += 1) {
const ct = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct);
const nonce = ct[0..12].*;
try testing.expect(!all_nonces.contains(nonce));
try all_nonces.put(nonce, {});
}
// Rotate key
try enc_mgr.rotateKeyForPeer(peer_id);
// Generate messages after rotation - nonces should still be unique
i = 0;
while (i < 50) : (i += 1) {
const ct = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct);
const nonce = ct[0..12].*;
try testing.expect(!all_nonces.contains(nonce));
try all_nonces.put(nonce, {});
}
}
test "security - replay attack prevention via nonce uniqueness" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext = "Same message encrypted multiple times";
// Encrypt the same message three times
const ct1 = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct1);
const ct2 = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct2);
const ct3 = try enc_mgr.encrypt(peer_id, plaintext);
defer allocator.free(ct3);
// All ciphertexts should be different (different nonces)
try testing.expect(!std.mem.eql(u8, ct1, ct2));
try testing.expect(!std.mem.eql(u8, ct1, ct3));
try testing.expect(!std.mem.eql(u8, ct2, ct3));
// Extract nonces and verify they're all different
const nonce1 = ct1[0..12].*;
const nonce2 = ct2[0..12].*;
const nonce3 = ct3[0..12].*;
try testing.expect(!std.mem.eql(u8, &nonce1, &nonce2));
try testing.expect(!std.mem.eql(u8, &nonce1, &nonce3));
try testing.expect(!std.mem.eql(u8, &nonce2, &nonce3));
// But all should decrypt to the same plaintext
const dec1 = try enc_mgr.decrypt(peer_id, ct1);
defer allocator.free(dec1);
const dec2 = try enc_mgr.decrypt(peer_id, ct2);
defer allocator.free(dec2);
const dec3 = try enc_mgr.decrypt(peer_id, ct3);
defer allocator.free(dec3);
try testing.expectEqualStrings(plaintext, dec1);
try testing.expectEqualStrings(plaintext, dec2);
try testing.expectEqualStrings(plaintext, dec3);
}
test "security - different plaintext produces different ciphertext" {
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext1 = "Message A";
const plaintext2 = "Message B";
const ct1 = try enc_mgr.encrypt(peer_id, plaintext1);
defer allocator.free(ct1);
const ct2 = try enc_mgr.encrypt(peer_id, plaintext2);
defer allocator.free(ct2);
// Ciphertexts should be different
try testing.expect(!std.mem.eql(u8, ct1, ct2));
// And decrypt correctly
const dec1 = try enc_mgr.decrypt(peer_id, ct1);
defer allocator.free(dec1);
const dec2 = try enc_mgr.decrypt(peer_id, ct2);
defer allocator.free(dec2);
try testing.expectEqualStrings(plaintext1, dec1);
try testing.expectEqualStrings(plaintext2, dec2);
}
test "security - ciphertext length reveals plaintext length" {
// This is an inherent property of AEAD - verify and document it
const allocator = testing.allocator;
var crypto_mgr = CryptoManager.init(allocator);
defer crypto_mgr.deinit();
var enc_mgr = EncryptionManager.init(allocator, &crypto_mgr);
defer enc_mgr.deinit();
const peer_id = [_]u8{1} ** 32;
const key = [_]u8{2} ** 32;
try enc_mgr.setKeyForPeer(peer_id, key, 1);
const plaintext_short = "Hi";
const plaintext_long = "Hello, World!";
const ct_short = try enc_mgr.encrypt(peer_id, plaintext_short);
defer allocator.free(ct_short);
const ct_long = try enc_mgr.encrypt(peer_id, plaintext_long);
defer allocator.free(ct_long);
// Ciphertext length = nonce(12) + plaintext.len + tag(16)
try testing.expectEqual(12 + plaintext_short.len + 16, ct_short.len);
try testing.expectEqual(12 + plaintext_long.len + 16, ct_long.len);
// Length difference reveals plaintext length difference
const length_diff = ct_long.len - ct_short.len;
try testing.expectEqual(plaintext_long.len - plaintext_short.len, length_diff);
}

View File

@@ -0,0 +1,328 @@
//! Message serialization tests
const std = @import("std");
const protocol = @import("../../src/protocol/protocol.zig");
const message = @import("../../src/protocol/message.zig");
const serializer = @import("../../src/protocol/serializer.zig");
// SEC-M9 FIX: Removed CRC32 tests - CRC32 was redundant with HMAC-SHA256 integrity.
// Message integrity is now provided by HMAC which is tested in the HMAC tests.
// HMAC provides both integrity AND authentication, making CRC32 unnecessary.
test "serializer helper functions" {
// Test safeAdd overflow protection
const max_val = std.math.maxInt(usize);
try std.testing.expect(serializer.safeAdd(max_val, 1) == null);
try std.testing.expect(serializer.safeAdd(100, 200) != null);
try std.testing.expectEqual(@as(?usize, 300), serializer.safeAdd(100, 200));
// Test checkBounds
const buffer = [_]u8{0} ** 100;
try serializer.checkBounds(&buffer, 0, 50);
try serializer.checkBounds(&buffer, 50, 50);
try std.testing.expectError(serializer.SerializationError.BufferTooSmall, serializer.checkBounds(&buffer, 50, 51));
try std.testing.expectError(serializer.SerializationError.BufferTooSmall, serializer.checkBounds(&buffer, 101, 0));
}
test "serializer initialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
try std.testing.expect(serializer_instance.allocator == allocator);
}
test "ping message serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &buffer);
// Should write positive number of bytes
try std.testing.expect(size > 0);
try std.testing.expect(size <= buffer.len);
// Should be at least header size
try std.testing.expect(size >= protocol.Serialization.HEADER_SIZE + @sizeOf(message.MessageHeader));
// Should fit in buffer
try std.testing.expect(size <= buffer.len);
}
test "ping message deserialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const ping = message.Ping.init(456);
const full_msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &buffer);
// Deserialize base message
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
try std.testing.expectEqual(@as(message.MessageId, 456), base_msg.header.id);
try std.testing.expectEqual(source, base_msg.header.source);
try std.testing.expectEqual(dest, base_msg.header.dest);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, base_msg.header.version);
try std.testing.expectEqual(protocol.Serialization.MAGIC_NUMBER, base_msg.header.magic);
// Deserialize full message
const full_msg_deserialized = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(protocol.MessageType.ping, full_msg_deserialized.getType());
const ping_deserialized = switch (full_msg_deserialized) {
.ping => |p| p,
else => return error.UnexpectedMessageType,
};
try std.testing.expectEqual(@as(u32, 456), ping_deserialized.sequence);
}
test "hello message serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
});
const hello_msg = message.Message{ .discovery_hello = hello };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(hello_msg, &buffer);
try std.testing.expect(size > 0);
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.discovery_hello, base_msg.header.msg_type);
const full_msg_deserialized = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(protocol.MessageType.discovery_hello, full_msg_deserialized.getType());
}
test "pong message serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const pong = message.Pong.init(789, 150);
const pong_msg = message.Message{ .pong = pong };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(pong_msg, &buffer);
try std.testing.expect(size > 0);
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.pong, base_msg.header.msg_type);
const full_msg_deserialized = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(protocol.MessageType.pong, full_msg_deserialized.getType());
const pong_deserialized = switch (full_msg_deserialized) {
.pong => |p| p,
else => return error.UnexpectedMessageType,
};
try std.testing.expectEqual(@as(u32, 789), pong_deserialized.sequence);
try std.testing.expectEqual(@as(u32, 150), pong_deserialized.rtt);
}
test "error message serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const error_msg = message.Error.init(999, .invalid_message, "test error");
const error_full_msg = message.Message{ .error = error_msg };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(error_full_msg, &buffer);
try std.testing.expect(size > 0);
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
try std.testing.expectEqual(protocol.MessageType.error, base_msg.header.msg_type);
const full_msg_deserialized = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(protocol.MessageType.error, full_msg_deserialized.getType());
}
test "serialization error handling" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
var small_buffer: [5]u8 = undefined;
// Buffer too small for header
try std.testing.expectError(serializer.SerializationError.BufferTooSmall,
serializer_instance.serialize(full_msg, &small_buffer));
// Deserialization with invalid magic number
var invalid_buffer = [_]u8{ 0x00, 0x01, 0x02, 0x03 };
try std.testing.expectError(serializer.SerializationError.InvalidMagicNumber,
serializer_instance.deserialize(&invalid_buffer));
// Deserialization with too small buffer
try std.testing.expectError(serializer.SerializationError.BufferTooSmall,
serializer_instance.deserialize(&invalid_buffer[0..2]));
}
test "message integrity" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &buffer);
// Calculate and verify checksum
const checksum = serializer.calculateChecksum(&buffer[0..size]);
try std.testing.expect(serializer.verifyChecksum(&buffer[0..size], checksum));
// Verify that modifying data breaks checksum
buffer[0] +%= 1;
try std.testing.expect(!serializer.verifyChecksum(&buffer[0..size], checksum));
}
test "round trip serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const original_ping = message.Ping.init(12345);
const original_msg = message.Message{ .ping = original_ping };
// Serialize
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(original_msg, &buffer);
// Deserialize
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
const deserialized_msg = try serializer_instance.deserializeFull(base_msg);
// Verify round trip
try std.testing.expectEqual(protocol.MessageType.ping, deserialized_msg.getType());
const deserialized_ping = switch (deserialized_msg) {
.ping => |p| p,
else => return error.UnexpectedMessageType,
};
try std.testing.expectEqual(original_ping.sequence, deserialized_ping.sequence);
}
test "multiple message types serialization" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
var source: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = 1;
var dest: message.NodeId = .{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = 2;
const messages = [_]message.Message{
message.Message{ .ping = message.Ping.init(1) },
message.Message{ .pong = message.Pong.init(2, 100) },
message.Message{ .discovery_hello = message.DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0x01, .{
.ip = .{127, 0, 0, 1} ** 4,
.port = 8080,
})},
message.Message{ .error = message.Error.init(3, .unknown_error, "test") },
};
var buffer: [1024]u8 = undefined;
for (messages, 0..) |original_msg, i| {
const size = try serializer_instance.serialize(original_msg, &buffer);
try std.testing.expect(size > 0);
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
const deserialized_msg = try serializer_instance.deserializeFull(base_msg);
try std.testing.expectEqual(original_msg.getType(), deserialized_msg.getType());
}
}
test "serialization buffer management" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
// Test with exactly the right buffer size
var exact_buffer: [200]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &exact_buffer);
try std.testing.expect(size > 0);
// Test with larger buffer
var large_buffer: [1024]u8 = undefined;
const large_size = try serializer_instance.serialize(full_msg, &large_buffer);
try std.testing.expectEqual(size, large_size);
// Test serialization doesn't write beyond claimed size
try std.testing.expect(large_buffer[size] != 0 or size == large_buffer.len); // Might be zero if at end
}
test "message header validation" {
const allocator = std.testing.allocator;
var serializer_instance = serializer.MessageSerializer.init(allocator);
defer serializer_instance.allocator.destroy(&serializer_instance);
const ping = message.Ping.init(123);
const full_msg = message.Message{ .ping = ping };
var buffer: [1024]u8 = undefined;
const size = try serializer_instance.serialize(full_msg, &buffer);
const base_msg = try serializer_instance.deserialize(&buffer[0..size]);
// Validate all header fields
try std.testing.expectEqual(protocol.Serialization.MAGIC_NUMBER, base_msg.header.magic);
try std.testing.expectEqual(protocol.PROTOCOL_VERSION, base_msg.header.version);
try std.testing.expectEqual(protocol.MessageType.ping, base_msg.header.msg_type);
try std.testing.expectEqual(@as(u8, 0), base_msg.header.flags);
try std.testing.expect(base_msg.header.id > 0);
try std.testing.expectEqual(protocol.Priority.normal, base_msg.header.priority);
try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS), base_msg.header.ttl);
try std.testing.expect(base_msg.header.timestamp > 0);
try std.testing.expectEqual(@as(u8, 0), base_msg.header.reserved);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
//! Comprehensive thread safety tests for the protocol module
//! Tests concurrent access to MessageRouter, CryptoManager, and HandlerRegistry
const std = @import("std");
const testing = std.testing;
const protocol = @import("../../src/protocol/protocol.zig");
const router_mod = @import("../../src/protocol/router.zig");
const crypto_mod = @import("../../src/protocol/crypto.zig");
const handler_mod = @import("../../src/protocol/handler.zig");
const message = @import("../../src/protocol/message.zig");
const NUM_THREADS = 8;
const OPERATIONS_PER_THREAD = 1000;
/// Test concurrent message routing
test "concurrent message routing" {
const allocator = testing.allocator;
var msg_router = router_mod.MessageRouter.init(allocator);
defer msg_router.deinit();
// Setup some initial routes
var dest1: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE;
var dest2: message.NodeId = [_]u8{2} ** protocol.Network.NODE_ID_SIZE;
var dest3: message.NodeId = [_]u8{3} ** protocol.Network.NODE_ID_SIZE;
try msg_router.addRoute(dest1, dest1, 1);
try msg_router.addRoute(dest2, dest2, 2);
try msg_router.addRoute(dest3, dest3, 3);
// Spawn multiple threads that perform routing operations
var threads: [NUM_THREADS]std.Thread = undefined;
const ThreadContext = struct {
router: *router_mod.MessageRouter,
thread_id: usize,
};
const routingThread = struct {
fn run(ctx: ThreadContext) void {
var source: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE;
source[0] = @as(u8, @intCast(ctx.thread_id));
var i: usize = 0;
while (i < OPERATIONS_PER_THREAD) : (i += 1) {
// Rotate through destinations
const dest_idx = i % 3;
var dest: message.NodeId = undefined;
if (dest_idx == 0) {
dest = [_]u8{1} ** protocol.Network.NODE_ID_SIZE;
} else if (dest_idx == 1) {
dest = [_]u8{2} ** protocol.Network.NODE_ID_SIZE;
} else {
dest = [_]u8{3} ** protocol.Network.NODE_ID_SIZE;
}
const header = message.MessageHeader.init(.ping, i, source, dest);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
// Perform routing
const result = ctx.router.routeMessage(base_msg);
_ = result;
// Also test other read operations
_ = ctx.router.isReachable(dest);
_ = ctx.router.getNextHop(dest);
// Occasionally add/remove routes
if (i % 100 == 0) {
var temp_dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE;
temp_dest[0] = @as(u8, @intCast((ctx.thread_id + i) % 256));
ctx.router.addRoute(temp_dest, dest, 5) catch {};
}
if (i % 150 == 0) {
var temp_dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE;
temp_dest[0] = @as(u8, @intCast((ctx.thread_id + i - 50) % 256));
ctx.router.removeRoute(temp_dest);
}
}
}
}.run;
// Spawn threads
for (&threads, 0..) |*thread, i| {
const ctx = ThreadContext{ .router = &msg_router, .thread_id = i };
thread.* = try std.Thread.spawn(.{}, routingThread, .{ctx});
}
// Wait for all threads
for (threads) |thread| {
thread.join();
}
// Verify metrics
const metrics = msg_router.getMetrics();
const total_ops = NUM_THREADS * OPERATIONS_PER_THREAD;
// Should have processed many lookups
try testing.expect(metrics.successful_lookups > 0);
try testing.expect(metrics.successful_lookups + metrics.failed_lookups == total_ops);
// Should have added routes
try testing.expect(metrics.total_routes > 3);
std.debug.print("\nRouting Test Results:\n", .{});
std.debug.print(" Total Routes: {}\n", .{metrics.total_routes});
std.debug.print(" Active Routes: {}\n", .{metrics.active_routes});
std.debug.print(" Successful Lookups: {}\n", .{metrics.successful_lookups});
std.debug.print(" Failed Lookups: {}\n", .{metrics.failed_lookups});
std.debug.print(" Avg Lookup Time: {d:.6}s\n", .{metrics.average_lookup_time});
}
/// Test concurrent encryption/decryption
test "concurrent encryption and decryption" {
const allocator = testing.allocator;
var crypto = crypto_mod.CryptoManager.init(allocator);
defer crypto.deinit();
// Setup peer keys
const peer1_id = [_]u8{1} ** 32;
const peer1_key = [_]u8{0x11} ** 32;
const peer2_id = [_]u8{2} ** 32;
const peer2_key = [_]u8{0x22} ** 32;
try crypto.setKeyForPeer(peer1_id, peer1_key);
try crypto.setKeyForPeer(peer2_id, peer2_key);
var threads: [NUM_THREADS]std.Thread = undefined;
const ThreadContext = struct {
crypto_mgr: *crypto_mod.CryptoManager,
thread_id: usize,
alloc: std.mem.Allocator,
};
const cryptoThread = struct {
fn run(ctx: ThreadContext) void {
var i: usize = 0;
while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) { // Fewer ops due to encryption cost
// Alternate between peers
const peer_id = if (i % 2 == 0) [_]u8{1} ** 32 else [_]u8{2} ** 32;
// Create message
var message_buf: [128]u8 = undefined;
const msg = std.fmt.bufPrint(&message_buf, "Thread {} message {}", .{ ctx.thread_id, i }) catch unreachable;
// Encrypt
const ciphertext = ctx.crypto_mgr.encrypt(peer_id, msg) catch |err| {
std.debug.print("Encrypt error: {}\n", .{err});
continue;
};
defer ctx.alloc.free(ciphertext);
// Decrypt
const plaintext = ctx.crypto_mgr.decrypt(peer_id, ciphertext) catch |err| {
std.debug.print("Decrypt error: {}\n", .{err});
continue;
};
defer ctx.alloc.free(plaintext);
// Verify
if (!std.mem.eql(u8, msg, plaintext)) {
std.debug.print("Decryption mismatch!\n", .{});
}
}
}
}.run;
// Spawn threads
for (&threads, 0..) |*thread, i| {
const ctx = ThreadContext{
.crypto_mgr = &crypto,
.thread_id = i,
.alloc = allocator,
};
thread.* = try std.Thread.spawn(.{}, cryptoThread, .{ctx});
}
// Wait for all threads
for (threads) |thread| {
thread.join();
}
std.debug.print("\nCrypto Test: Successfully completed {} concurrent encrypt/decrypt operations\n", .{NUM_THREADS * (OPERATIONS_PER_THREAD / 10)});
}
/// Test concurrent handler registration and message processing
test "concurrent handler operations" {
const allocator = testing.allocator;
var registry = try handler_mod.HandlerRegistry.init(allocator);
defer registry.deinit();
// Register some initial handlers
const test_handler_fn = struct {
fn handler(msg: message.Message, ctx: *anyopaque) !void {
const context = @as(*handler_mod.HandlerContext, @ptrCast(@alignCast(ctx)));
_ = msg;
context.metrics.recordMessageProcessed(0.001);
}
}.handler;
// Register handlers for different message types
const ping_handler = handler_mod.MessageHandler.init(
test_handler_fn,
registry.getContext(),
.ping,
);
try registry.registerHandler(.ping, ping_handler);
const pong_handler = handler_mod.MessageHandler.init(
test_handler_fn,
registry.getContext(),
.pong,
);
try registry.registerHandler(.pong, pong_handler);
var threads: [NUM_THREADS]std.Thread = undefined;
const ThreadContext = struct {
reg: *handler_mod.HandlerRegistry,
thread_id: usize,
};
const handlerThread = struct {
fn run(ctx: ThreadContext) void {
var i: usize = 0;
while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) {
// Create and process messages
const msg_type: protocol.MessageType = if (i % 2 == 0) .ping else .pong;
const msg = if (msg_type == .ping)
message.Message{ .ping = message.Ping.init(@as(u32, @intCast(i))) }
else
message.Message{ .pong = message.Pong.init(@as(u32, @intCast(i)), 10) };
// Process message
ctx.reg.processMessage(msg) catch |err| {
std.debug.print("Handler error: {}\n", .{err});
};
// Occasionally register new handlers (with different priorities)
if (i % 50 == 0 and ctx.thread_id == 0) {
var new_handler = handler_mod.MessageHandler.init(
struct {
fn h(m: message.Message, c: *anyopaque) !void {
_ = m;
_ = c;
}
}.h,
ctx.reg.getContext(),
msg_type,
);
new_handler.priority = @as(u8, @intCast(i % 10));
ctx.reg.registerHandler(msg_type, new_handler) catch {};
}
}
}
}.run;
// Spawn threads
for (&threads, 0..) |*thread, i| {
const ctx = ThreadContext{ .reg = &registry, .thread_id = i };
thread.* = try std.Thread.spawn(.{}, handlerThread, .{ctx});
}
// Wait for all threads
for (threads) |thread| {
thread.join();
}
// Verify metrics
const processed = registry.getContext().metrics.messages_processed;
const failed = registry.getContext().metrics.messages_failed;
try testing.expect(processed > 0);
std.debug.print("\nHandler Test Results:\n", .{});
std.debug.print(" Messages Processed: {}\n", .{processed});
std.debug.print(" Messages Failed: {}\n", .{failed});
std.debug.print(" Handlers Registered: {}\n", .{registry.getContext().metrics.handlers_registered});
std.debug.print(" Success Rate: {d:.2}%\n", .{registry.getContext().metrics.getSuccessRate() * 100});
}
/// Test metrics accuracy under concurrent access
test "metrics accuracy under concurrent access" {
const allocator = testing.allocator;
var msg_router = router_mod.MessageRouter.init(allocator);
defer msg_router.deinit();
// Add a single route
var dest: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE;
try msg_router.addRoute(dest, dest, 1);
var threads: [NUM_THREADS]std.Thread = undefined;
const expected_successful = NUM_THREADS * OPERATIONS_PER_THREAD;
const ThreadContext = struct {
router: *router_mod.MessageRouter,
};
const metricsThread = struct {
fn run(ctx: ThreadContext) void {
var source: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE;
var dest_val: message.NodeId = [_]u8{1} ** protocol.Network.NODE_ID_SIZE;
var i: usize = 0;
while (i < OPERATIONS_PER_THREAD) : (i += 1) {
const header = message.MessageHeader.init(.ping, i, source, dest_val);
const base_msg = message.BaseMessage{ .header = header, .payload = &.{} };
const result = ctx.router.routeMessage(base_msg);
_ = result;
}
}
}.run;
// Spawn threads
for (&threads) |*thread| {
const ctx = ThreadContext{ .router = &msg_router };
thread.* = try std.Thread.spawn(.{}, metricsThread, .{ctx});
}
// Wait for all threads
for (threads) |thread| {
thread.join();
}
// Verify metrics are accurate
const metrics = msg_router.getMetrics();
std.debug.print("\nMetrics Accuracy Test:\n", .{});
std.debug.print(" Expected Successful Lookups: {}\n", .{expected_successful});
std.debug.print(" Actual Successful Lookups: {}\n", .{metrics.successful_lookups});
std.debug.print(" Difference: {}\n", .{
if (metrics.successful_lookups > expected_successful)
metrics.successful_lookups - expected_successful
else
expected_successful - metrics.successful_lookups,
});
// All lookups should be successful since route exists
try testing.expectEqual(expected_successful, metrics.successful_lookups);
try testing.expectEqual(@as(u64, 0), metrics.failed_lookups);
}
/// Test route table operations under high contention
test "route table under high contention" {
const allocator = testing.allocator;
var msg_router = router_mod.MessageRouter.init(allocator);
defer msg_router.deinit();
var threads: [NUM_THREADS]std.Thread = undefined;
const ThreadContext = struct {
router: *router_mod.MessageRouter,
thread_id: usize,
};
const contentionThread = struct {
fn run(ctx: ThreadContext) void {
var i: usize = 0;
while (i < OPERATIONS_PER_THREAD / 10) : (i += 1) {
var dest: message.NodeId = [_]u8{0} ** protocol.Network.NODE_ID_SIZE;
dest[0] = @as(u8, @intCast((ctx.thread_id + i) % 100));
// Mix of operations
switch (i % 5) {
0 => {
// Add route
ctx.router.addRoute(dest, dest, @as(u32, @intCast(i % 10))) catch {};
},
1 => {
// Check reachability
_ = ctx.router.isReachable(dest);
},
2 => {
// Get next hop
_ = ctx.router.getNextHop(dest);
},
3 => {
// Invalidate route
ctx.router.invalidateRoute(dest);
},
4 => {
// Remove route
ctx.router.removeRoute(dest);
},
else => unreachable,
}
// Occasionally get all routes
if (i % 100 == 0) {
var routes = ctx.router.getAllRoutes();
routes.deinit();
}
// Occasionally get stats
if (i % 50 == 0) {
_ = ctx.router.getRouteStats();
}
}
}
}.run;
// Spawn threads
for (&threads, 0..) |*thread, i| {
const ctx = ThreadContext{ .router = &msg_router, .thread_id = i };
thread.* = try std.Thread.spawn(.{}, contentionThread, .{ctx});
}
// Wait for all threads
for (threads) |thread| {
thread.join();
}
const stats = msg_router.getRouteStats();
std.debug.print("\nContention Test Results:\n", .{});
std.debug.print(" Total Routes: {}\n", .{stats.total});
std.debug.print(" Active Routes: {}\n", .{stats.active});
std.debug.print(" Pending Queries: {}\n", .{stats.pending});
// Should have some routes added
try testing.expect(stats.total > 0);
}