Files
zigp2p/tests/protocol/test_routing_security.zig
2026-02-06 21:03:59 -03:00

545 lines
19 KiB
Zig

//! 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));
}