Files
zigp2p/src/protocol/router.zig
2026-02-06 21:03:59 -03:00

1703 lines
63 KiB
Zig

//! Message routing logic
//!
//! CRIT-NEW-17 FIX: Lock Ordering
//! ==============================
//! This module's locks are at Level 3 in the global hierarchy.
//! See src/network/network_manager.zig for the complete lock ordering.
//!
//! Lock levels in this module:
//! - pending_queries_lock: Level 3
//! - metrics_lock: Level 0
//! - neighbors_lock: Level 3
//! - peers_lock: Level 3
//!
//! IMPORTANT: Never acquire lower-level locks (0-2) while holding Level 3 locks,
//! unless they are within the same transaction (e.g., acquiring metrics_lock is safe
//! because it's Level 0).
const std = @import("std");
const core = @import("core");
const protocol = @import("protocol.zig");
const message = @import("message.zig");
const serializer = @import("serializer.zig");
/// IMP-H4 FIX: Error type for signature operations (instead of returning null)
pub const SignatureError = error{
/// The provided Ed25519 secret key bytes are invalid
InvalidSecretKey,
/// Failed to derive key pair from secret key
KeyPairCreationFailed,
/// Ed25519 signing operation failed
SigningFailed,
/// Secret key is too short (must be 64 bytes)
SecretKeyTooShort,
/// The provided Ed25519 public key is invalid for verification
InvalidPublicKey,
/// Signature verification failed (signature doesn't match)
VerificationFailed,
};
/// Route signature for authentication
pub const RouteSignature = struct {
origin: message.NodeId, // Origin node (who the route is to)
signer_id: message.NodeId,
signature: [64]u8, // Ed25519 signature
timestamp: i64,
};
/// Routing table entry
const RouteEntry = struct {
destination: message.NodeId,
next_hop: message.NodeId,
cost: u32,
last_updated: i64,
is_valid: bool,
signature: ?RouteSignature, // Optional signature for route authentication
};
/// Route query result
pub const RouteResult = struct {
success: bool,
next_hop: ?message.NodeId,
cost: ?u32,
err: ?protocol.ErrorCode,
};
/// Routing metrics
pub const RoutingMetrics = struct {
total_routes: usize,
active_routes: usize,
failed_lookups: u64,
successful_lookups: u64,
average_lookup_time: f64,
};
/// Network sender interface for sending messages
pub const NetworkSender = struct {
send_fn: *const fn (ctx: *anyopaque, destination: message.NodeId, data: []const u8) anyerror!void,
ctx: *anyopaque,
pub fn send(self: NetworkSender, destination: message.NodeId, data: []const u8) !void {
return self.send_fn(self.ctx, destination, data);
}
};
/// Message router
pub const MessageRouter = struct {
/// Maximum pending route discovery queries to prevent DoS
pub const MAX_PENDING_QUERIES: usize = 1000;
/// Timeout for pending queries in seconds
pub const QUERY_TIMEOUT_SECONDS: i64 = 30;
/// Entry in pending queries with timestamp for timeout cleanup
pub const PendingQueryEntry = struct {
destination: message.NodeId,
timestamp: i64,
};
allocator: std.mem.Allocator,
routes: std.AutoHashMap(message.NodeId, RouteEntry),
pending_queries: std.AutoHashMap(message.MessageId, PendingQueryEntry),
metrics: RoutingMetrics,
neighbors: std.ArrayList(message.NodeId),
network_sender: ?NetworkSender,
/// Local node ID for identifying messages destined for this node
local_node_id: message.NodeId,
// Security and limits
max_routes: u32 = 10000,
max_routes_per_destination: u8 = 3,
directly_connected_peers: std.AutoHashMap(message.NodeId, void),
// Cryptographic key registry for signature verification
peer_public_keys: std.AutoHashMap(message.NodeId, [32]u8),
// Route age limits
max_route_age: i64 = 3600, // 1 hour in seconds
// Thread safety: Protect all shared state
// Use RwLock for route_table (read-heavy operation)
// Use Mutex for pending_queries and other maps
route_table_lock: std.Thread.RwLock = .{},
pending_queries_lock: std.Thread.Mutex = .{},
metrics_lock: std.Thread.Mutex = .{},
// THR-1 FIX: Lock ordering documentation to prevent deadlock
// LOCK ORDERING (must be acquired in this order to prevent deadlock):
// 1. neighbors_lock
// 2. peers_lock
// When acquiring both locks, ALWAYS acquire neighbors_lock first.
// Never acquire neighbors_lock while holding peers_lock.
neighbors_lock: std.Thread.Mutex = .{},
peers_lock: std.Thread.Mutex = .{}, // Protects directly_connected_peers and peer_public_keys
// SECURITY: Signed routes are MANDATORY (compile-time enforced)
/// Route signatures prevent route poisoning attacks and are always required
pub const REQUIRE_SIGNED_ROUTES: bool = true;
/// IMP-CRIT-2 FIX: Init now requires local_node_id for proper message routing
pub fn init(allocator: std.mem.Allocator, local_node_id: message.NodeId) MessageRouter {
return .{
.allocator = allocator,
.routes = std.AutoHashMap(message.NodeId, RouteEntry).init(allocator),
.pending_queries = std.AutoHashMap(message.MessageId, PendingQueryEntry).init(allocator),
.metrics = .{
.total_routes = 0,
.active_routes = 0,
.failed_lookups = 0,
.successful_lookups = 0,
.average_lookup_time = 0.0,
},
.neighbors = .{},
.network_sender = null,
.directly_connected_peers = std.AutoHashMap(message.NodeId, void).init(allocator),
.peer_public_keys = std.AutoHashMap(message.NodeId, [32]u8).init(allocator),
.local_node_id = local_node_id,
};
}
pub fn deinit(self: *MessageRouter) void {
self.routes.deinit();
self.pending_queries.deinit();
self.neighbors.deinit(self.allocator);
self.directly_connected_peers.deinit();
self.peer_public_keys.deinit();
}
/// Cleanup timed out pending queries - MUST hold pending_queries_lock
fn cleanupTimedOutQueriesLocked(self: *MessageRouter) void {
const now = std.time.timestamp();
var keys_to_remove: std.ArrayListUnmanaged(message.MessageId) = .{};
defer keys_to_remove.deinit(self.allocator);
// Collect keys to remove (can't modify while iterating)
var iter = self.pending_queries.iterator();
while (iter.next()) |entry| {
const age = now - entry.value_ptr.timestamp;
if (age > QUERY_TIMEOUT_SECONDS) {
keys_to_remove.append(self.allocator, entry.key_ptr.*) catch {
// If we can't track it, log and continue
std.log.warn("Failed to track timed out query for removal", .{});
continue;
};
}
}
// Remove collected keys
const removed_count = keys_to_remove.items.len;
for (keys_to_remove.items) |key| {
_ = self.pending_queries.remove(key);
}
if (removed_count > 0) {
std.log.debug("Cleaned up {d} timed out pending queries", .{removed_count});
}
}
/// Public method to cleanup timed out queries (acquires lock)
pub fn cleanupTimedOutQueries(self: *MessageRouter) void {
self.pending_queries_lock.lock();
defer self.pending_queries_lock.unlock();
self.cleanupTimedOutQueriesLocked();
}
/// Route a message to its destination
pub fn routeMessage(self: *MessageRouter, base_msg: message.BaseMessage) RouteResult {
const start_time = std.time.timestamp();
defer {
const elapsed = @as(f64, @floatFromInt(std.time.timestamp() - start_time));
self.metrics_lock.lock();
self.metrics.average_lookup_time = (self.metrics.average_lookup_time * 0.9) + (elapsed * 0.1);
self.metrics_lock.unlock();
}
// Check TTL before forwarding
if (base_msg.header.ttl == 0) {
std.log.warn("Message dropped: TTL expired", .{});
self.metrics_lock.lock();
self.metrics.failed_lookups += 1;
self.metrics_lock.unlock();
return RouteResult{
.success = false,
.next_hop = null,
.cost = null,
.err = .routing_error,
};
}
// Check if message should be processed locally
if (self.isLocalMessage(base_msg)) {
return RouteResult{
.success = true,
.next_hop = null,
.cost = 0,
.err = null,
};
}
// Handle broadcast messages
if (base_msg.isBroadcast()) {
return self.handleBroadcast(base_msg);
}
// Look up route to destination (read lock)
const dest = base_msg.getDest();
self.route_table_lock.lockShared();
const route_opt = self.routes.get(dest);
self.route_table_lock.unlockShared();
if (route_opt) |route| {
if (route.is_valid) {
self.metrics_lock.lock();
self.metrics.successful_lookups += 1;
self.metrics_lock.unlock();
return RouteResult{
.success = true,
.next_hop = route.next_hop,
.cost = route.cost,
.err = null,
};
}
}
// Initiate route discovery if no route exists
const query_result = self.initiateRouteDiscovery(dest, base_msg.getId());
if (query_result) {
return RouteResult{
.success = false,
.next_hop = null,
.cost = null,
.err = .routing_error,
};
}
self.metrics_lock.lock();
self.metrics.failed_lookups += 1;
self.metrics_lock.unlock();
return RouteResult{
.success = false,
.next_hop = null,
.cost = null,
.err = .routing_error,
};
}
/// Verify route signature using Ed25519 cryptographic verification
/// This overload takes a RouteEntry and extracts the needed fields
pub fn verifyRouteSignature(self: *MessageRouter, route_entry: RouteEntry) bool {
const sig = route_entry.signature orelse {
std.log.warn("Route has no signature", .{});
return false;
};
return self.verifySignatureComponents(
route_entry.destination,
route_entry.next_hop,
route_entry.cost,
sig,
);
}
/// Verify route signature using individual components
/// Used when we need to verify before creating the RouteEntry
pub fn verifySignatureComponents(
self: *MessageRouter,
destination: message.NodeId,
next_hop: message.NodeId,
cost: u32,
sig: RouteSignature,
) bool {
// Verify timestamp is recent (SECURITY: reduced from 5 minutes to 60 seconds)
const now = std.time.timestamp();
const max_sig_age: i64 = 60; // 60 seconds
if (now - sig.timestamp > max_sig_age or sig.timestamp > now + 60) {
std.log.warn("Route signature timestamp out of acceptable range", .{});
return false;
}
// Verify signer is destination or trusted relay (timing-safe comparison)
const is_destination = std.crypto.timing_safe.eql([32]u8, sig.signer_id, destination);
self.peers_lock.lock();
const is_trusted_relay = self.directly_connected_peers.contains(sig.signer_id);
self.peers_lock.unlock();
if (!is_destination and !is_trusted_relay) {
std.log.warn("Route signer is neither destination nor trusted relay", .{});
return false;
}
// Look up the signer's public key
self.peers_lock.lock();
const public_key = self.peer_public_keys.get(sig.signer_id);
self.peers_lock.unlock();
if (public_key == null) {
std.log.warn("No public key registered for signer", .{});
return false;
}
// Construct the signed data: origin + destination + next_hop + cost + timestamp
const signed_data = self.constructSignedData(
sig.origin,
destination,
next_hop,
cost,
sig.timestamp,
);
// Verify the Ed25519 signature using Zig 0.15 API
const Ed25519 = std.crypto.sign.Ed25519;
const signature = Ed25519.Signature.fromBytes(sig.signature);
// Convert public key bytes to Ed25519.PublicKey
const pub_key = Ed25519.PublicKey.fromBytes(public_key.?) catch {
std.log.warn("Invalid Ed25519 public key format", .{});
return false;
};
signature.verify(&signed_data, pub_key) catch {
std.log.warn("Ed25519 signature verification failed", .{});
return false;
};
return true;
}
/// Construct the data that should be signed for route authentication
/// Includes: origin + destination + next_hop + cost + timestamp
fn constructSignedData(
self: *MessageRouter,
origin: message.NodeId,
destination: message.NodeId,
next_hop: message.NodeId,
cost: u32,
timestamp: i64,
) [32 + 32 + 32 + 4 + 8]u8 {
_ = self;
var data: [32 + 32 + 32 + 4 + 8]u8 = undefined;
var offset: usize = 0;
// Add origin (32 bytes)
@memcpy(data[offset..][0..32], &origin);
offset += 32;
// Add destination (32 bytes)
@memcpy(data[offset..][0..32], &destination);
offset += 32;
// Add next_hop (32 bytes)
@memcpy(data[offset..][0..32], &next_hop);
offset += 32;
// Add cost (4 bytes, big-endian)
std.mem.writeInt(u32, data[offset..][0..4], cost, .big);
offset += 4;
// Add timestamp (8 bytes, big-endian)
std.mem.writeInt(i64, data[offset..][0..8], timestamp, .big);
return data;
}
/// Add a route to the routing table with security checks
pub fn addRoute(self: *MessageRouter, destination: message.NodeId, next_hop: message.NodeId, cost: u32) !void {
try self.addRouteWithSignature(destination, next_hop, cost, null);
}
/// Add a route to the routing table with optional signature
pub fn addRouteWithSignature(
self: *MessageRouter,
destination: message.NodeId,
next_hop: message.NodeId,
cost: u32,
signature: ?RouteSignature,
) !void {
// Validate cost (prevent zero-cost and count-to-infinity attacks)
const min_cost: u32 = 1;
const max_cost: u32 = 1000;
if (cost < min_cost or cost > max_cost) {
std.log.warn("Route cost {} out of valid range [{}, {}]", .{ cost, min_cost, max_cost });
return error.InvalidRouteCost;
}
// Check if route requires signature verification
self.peers_lock.lock();
const is_directly_connected = self.directly_connected_peers.contains(destination);
self.peers_lock.unlock();
if (signature) |sig| {
// If signature provided, verify it using all route components
if (!self.verifySignatureComponents(destination, next_hop, cost, sig)) {
std.log.warn("Route signature verification failed", .{});
return error.InvalidSignature;
}
} else if (!is_directly_connected) {
// Reject unsigned routes for non-directly-connected destinations
std.log.warn("Unsigned route rejected for non-directly-connected peer", .{});
return error.UnsignedRoute;
}
// Acquire write lock for route table modification
self.route_table_lock.lock();
defer self.route_table_lock.unlock();
// Check total routes limit
if (self.routes.count() >= self.max_routes) {
// Evict least recently used route
try self.evictLRURoute();
}
// Count alternative routes to this destination
var alt_routes: u8 = 0;
var it = self.routes.iterator();
while (it.next()) |entry| {
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, entry.value_ptr.destination, destination)) {
alt_routes += 1;
}
}
// Check per-destination route limit
if (alt_routes >= self.max_routes_per_destination) {
// Find and remove the worst alternative route
var worst_cost: u32 = 0;
var worst_dest: ?message.NodeId = null;
it = self.routes.iterator();
while (it.next()) |entry| {
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, entry.value_ptr.destination, destination)) {
if (entry.value_ptr.cost > worst_cost) {
worst_cost = entry.value_ptr.cost;
worst_dest = entry.key_ptr.*;
}
}
}
if (worst_dest) |wd| {
if (cost < worst_cost) {
// Remove worst route to make room for better one
self.removeRouteUnlocked(wd);
} else {
// New route is not better than existing ones
return error.RouteNotBetter;
}
}
}
const entry = RouteEntry{
.destination = destination,
.next_hop = next_hop,
.cost = cost,
.last_updated = std.time.timestamp(),
.is_valid = true,
.signature = signature,
};
if (self.routes.get(destination)) |existing| {
// Update existing route if it's better or the existing one is invalid
if (!existing.is_valid or cost < existing.cost) {
try self.routes.put(destination, entry);
self.metrics_lock.lock();
self.metrics.active_routes += if (!existing.is_valid) 1 else 0;
self.metrics_lock.unlock();
}
} else {
try self.routes.put(destination, entry);
self.metrics_lock.lock();
self.metrics.total_routes += 1;
self.metrics.active_routes += 1;
self.metrics_lock.unlock();
}
}
/// Evict the least recently used route (caller must hold route_table_lock)
fn evictLRURoute(self: *MessageRouter) !void {
var oldest_time: i64 = std.time.timestamp();
var oldest_dest: ?message.NodeId = null;
var it = self.routes.iterator();
while (it.next()) |entry| {
if (entry.value_ptr.last_updated < oldest_time) {
oldest_time = entry.value_ptr.last_updated;
oldest_dest = entry.key_ptr.*;
}
}
if (oldest_dest) |dest| {
std.log.info("Evicting LRU route to make room for new route", .{});
self.removeRouteUnlocked(dest);
} else {
return error.NoRoutesToEvict;
}
}
/// Remove a route from the routing table (internal, caller must hold lock)
fn removeRouteUnlocked(self: *MessageRouter, destination: message.NodeId) void {
if (self.routes.fetchRemove(destination)) |entry| {
if (entry.value.is_valid) {
self.metrics_lock.lock();
self.metrics.active_routes -= 1;
self.metrics_lock.unlock();
}
}
}
/// Remove a route from the routing table
pub fn removeRoute(self: *MessageRouter, destination: message.NodeId) void {
self.route_table_lock.lock();
defer self.route_table_lock.unlock();
self.removeRouteUnlocked(destination);
}
/// Mark a route as invalid
pub fn invalidateRoute(self: *MessageRouter, destination: message.NodeId) void {
self.route_table_lock.lock();
defer self.route_table_lock.unlock();
if (self.routes.getEntry(destination)) |entry| {
entry.value_ptr.is_valid = false;
entry.value_ptr.last_updated = std.time.timestamp();
self.metrics_lock.lock();
self.metrics.active_routes -= 1;
self.metrics_lock.unlock();
}
}
/// Get routing metrics
pub fn getMetrics(self: *MessageRouter) RoutingMetrics {
self.metrics_lock.lock();
defer self.metrics_lock.unlock();
return self.metrics;
}
/// Get the next hop for a destination
pub fn getNextHop(self: *MessageRouter, destination: message.NodeId) ?message.NodeId {
self.route_table_lock.lockShared();
defer self.route_table_lock.unlockShared();
if (self.routes.get(destination)) |route| {
return if (route.is_valid) route.next_hop else null;
}
return null;
}
/// Add a neighbor to the router
/// THR-1 FIX: Lock ordering is neighbors_lock -> peers_lock (documented above)
pub fn addNeighbor(self: *MessageRouter, neighbor: message.NodeId) !void {
// THR-1: Acquire locks in documented order: neighbors_lock first, then peers_lock
self.neighbors_lock.lock();
defer self.neighbors_lock.unlock();
try self.neighbors.append(self.allocator, neighbor);
// Mark neighbor as directly connected for signature verification
// THR-1: peers_lock acquired while holding neighbors_lock (correct order)
self.peers_lock.lock();
defer self.peers_lock.unlock();
try self.directly_connected_peers.put(neighbor, void{});
}
/// Remove a neighbor from the router
/// THR-1 FIX: Lock ordering is neighbors_lock -> peers_lock (documented above)
pub fn removeNeighbor(self: *MessageRouter, neighbor: message.NodeId) void {
// THR-1: Acquire locks in documented order: neighbors_lock first, then peers_lock
self.neighbors_lock.lock();
defer self.neighbors_lock.unlock();
// Remove from neighbors list
var i: usize = 0;
while (i < self.neighbors.items.len) {
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, self.neighbors.items[i], neighbor)) {
_ = self.neighbors.orderedRemove(i);
break;
}
i += 1;
}
// Remove from directly connected peers
// THR-1: peers_lock acquired while holding neighbors_lock (correct order)
self.peers_lock.lock();
defer self.peers_lock.unlock();
_ = self.directly_connected_peers.remove(neighbor);
}
/// Set the network sender
pub fn setNetworkSender(self: *MessageRouter, sender: NetworkSender) void {
self.network_sender = sender;
}
/// Register a peer's Ed25519 public key for signature verification
pub fn registerPeerPublicKey(self: *MessageRouter, peer_id: message.NodeId, public_key: [32]u8) !void {
self.peers_lock.lock();
defer self.peers_lock.unlock();
try self.peer_public_keys.put(peer_id, public_key);
}
/// Remove a peer's public key
pub fn removePeerPublicKey(self: *MessageRouter, peer_id: message.NodeId) void {
self.peers_lock.lock();
defer self.peers_lock.unlock();
_ = self.peer_public_keys.remove(peer_id);
}
/// IMP-H4 FIX: Create a signed route entry using Ed25519
/// This is used by nodes to advertise their routes with cryptographic proof
/// Now returns proper errors instead of null for better diagnostics
pub fn createSignedRoute(
self: *MessageRouter,
origin: message.NodeId,
destination: message.NodeId,
next_hop: message.NodeId,
cost: u32,
signer_secret_key: [64]u8, // Ed25519 secret key (includes public key in last 32 bytes)
) SignatureError!RouteSignature {
const timestamp = std.time.timestamp();
// Construct the data to sign - now includes origin
const signed_data = self.constructSignedData(origin, destination, next_hop, cost, timestamp);
// Sign with Ed25519 using Zig 0.15 API
const Ed25519 = std.crypto.sign.Ed25519;
const secret_key = Ed25519.SecretKey.fromBytes(signer_secret_key) catch {
std.log.warn("Invalid Ed25519 secret key bytes", .{});
return SignatureError.InvalidSecretKey;
};
const key_pair = Ed25519.KeyPair.fromSecretKey(secret_key) catch {
std.log.warn("Failed to create key pair from secret key", .{});
return SignatureError.KeyPairCreationFailed;
};
const signature = key_pair.sign(&signed_data, null) catch {
std.log.warn("Ed25519 signing failed", .{});
return SignatureError.SigningFailed;
};
// Extract signer ID from public key (public key is derived from secret key)
var signer_id: message.NodeId = undefined;
@memcpy(&signer_id, &key_pair.public_key.toBytes());
return RouteSignature{
.origin = origin,
.signer_id = signer_id,
.signature = signature.toBytes(),
.timestamp = timestamp,
};
}
/// IMP-CRIT-2 FIX: Check if a message is for local processing
/// Returns true if destination matches our local_node_id or is all zeros (broadcast)
fn isLocalMessage(self: *MessageRouter, base_msg: message.BaseMessage) bool {
const dest = base_msg.getDest();
// Check if destination matches our local node ID
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, dest, self.local_node_id)) {
return true;
}
// Also accept all-zeros as local (broadcast/unspecified destination)
for (dest) |byte| {
if (byte != 0) return false;
}
return true;
}
/// IMP-CRIT-2 FIX: Handle broadcast messages by forwarding to all neighbors
/// Sends the raw message payload to each neighbor via network_sender
fn handleBroadcast(self: *MessageRouter, base_msg: message.BaseMessage) RouteResult {
const sender = self.network_sender orelse {
std.log.warn("Broadcast failed: no network sender configured", .{});
return RouteResult{
.success = false,
.next_hop = null,
.cost = null,
.err = .routing_error,
};
};
// Get the source to avoid sending back to originator
const source = base_msg.getSource();
// Lock neighbors for iteration
self.neighbors_lock.lock();
defer self.neighbors_lock.unlock();
var sent_count: usize = 0;
var fail_count: usize = 0;
for (self.neighbors.items) |neighbor| {
// Don't send back to the message source
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, neighbor, source)) {
continue;
}
// Send the raw payload - the receiver will handle parsing
sender.send(neighbor, base_msg.payload) catch |err| {
std.log.warn("Broadcast to neighbor failed: {}", .{err});
fail_count += 1;
continue;
};
sent_count += 1;
}
if (sent_count == 0 and fail_count == 0) {
// No neighbors to send to (excluding source)
std.log.debug("Broadcast: no neighbors to forward to", .{});
}
return RouteResult{
.success = sent_count > 0 or fail_count == 0, // Success if sent to anyone or no neighbors
.next_hop = null, // Broadcast has no single next hop
.cost = 1,
.err = null,
};
}
/// Initiate route discovery
fn initiateRouteDiscovery(self: *MessageRouter, destination: message.NodeId, msg_id: message.MessageId) bool {
// Add to pending queries
self.pending_queries_lock.lock();
// Cleanup timed out queries first to make room
self.cleanupTimedOutQueriesLocked();
// Enforce size limit to prevent DoS
if (self.pending_queries.count() >= MAX_PENDING_QUERIES) {
self.pending_queries_lock.unlock();
std.log.warn("SECURITY: Pending queries at capacity, rejecting new query", .{});
return false;
}
self.pending_queries.put(msg_id, .{
.destination = destination,
.timestamp = std.time.timestamp(),
}) catch |err| {
self.pending_queries_lock.unlock();
std.log.err("Failed to track route discovery query: {}", .{err});
return false;
};
self.pending_queries_lock.unlock();
// Create RouteQuery message
const query = message.Message{
.route_query = message.RouteQuery.init(msg_id, destination),
};
// Allocate on heap instead of stack to avoid overflow
const buffer = self.allocator.alloc(u8, protocol.MAX_MESSAGE_SIZE) catch |err| {
std.log.err("Failed to allocate buffer for route query: {}", .{err});
return false;
};
defer self.allocator.free(buffer);
// Route discovery uses internal serialization - actual authentication happens at network layer
// The NetworkSender is responsible for secure transmission
var ser = serializer.MessageSerializer.initInsecureForTesting(self.allocator);
const len = ser.serialize(query, buffer) catch |err| {
std.log.err("Failed to serialize route discovery query: {}", .{err});
return false;
};
// Send to all neighbors (read lock)
self.neighbors_lock.lock();
const neighbors = self.neighbors.items;
var sent_count: usize = 0;
for (neighbors) |neighbor| {
if (self.network_sender) |sender| {
sender.send(neighbor, buffer[0..len]) catch |err| {
std.log.warn("Failed to send route query to neighbor: {}", .{err});
continue;
};
sent_count += 1;
}
}
self.neighbors_lock.unlock();
if (sent_count == 0) {
std.log.warn("Route discovery failed: no neighbors reachable", .{});
return false;
}
return true;
}
/// Handle route query response
/// SECURITY: Verifies signature before accepting route
/// HIGH-5 FIX: Now uses timestamp and origin from response for proper verification
pub fn handleRouteResponse(self: *MessageRouter, response: message.RouteResponse) !void {
const original_query_id = response.query_id;
// Remove from pending queries
self.pending_queries_lock.lock();
const entry_opt = if (self.pending_queries.fetchRemove(original_query_id)) |kv| kv.value else null;
self.pending_queries_lock.unlock();
if (entry_opt) |entry| {
const dest = entry.destination;
// Update routing table with the response
if (response.next_hop) |next_hop| {
// SECURITY: Always verify signature (compile-time enforced)
comptime {
if (!REQUIRE_SIGNED_ROUTES) {
@compileError("SECURITY: Route signatures must be enabled");
}
}
// Check if signature is all zeros (unsigned)
var is_unsigned = true;
for (response.signature) |byte| {
if (byte != 0) {
is_unsigned = false;
break;
}
}
if (is_unsigned) {
core.log.err("SECURITY: Rejecting unsigned route response", .{});
return error.UnsignedRoute;
}
// HIGH-5 FIX: Verify timestamp is not zero (missing)
if (response.timestamp == 0) {
core.log.err("SECURITY: Rejecting route response with missing timestamp", .{});
return error.InvalidTimestamp;
}
// HIGH-5 FIX: Verify origin is not empty
var origin_is_empty = true;
for (response.origin) |byte| {
if (byte != 0) {
origin_is_empty = false;
break;
}
}
if (origin_is_empty) {
core.log.err("SECURITY: Rejecting route response with missing origin", .{});
return error.InvalidOrigin;
}
// HIGH-5 FIX: Verify destination matches expected
// SECURITY: Timing-safe comparison for cryptographic verification
if (!std.crypto.timing_safe.eql([32]u8, response.origin, dest)) {
core.log.err("SECURITY: Route response origin doesn't match expected destination", .{});
return error.OriginMismatch;
}
// HIGH-5 FIX: Create RouteSignature using response's timestamp and origin
const sig = RouteSignature{
.origin = response.origin,
.signer_id = response.signer_id,
.signature = response.signature,
.timestamp = response.timestamp,
};
// Add route with signature verification
try self.addRouteWithSignature(dest, next_hop, 1, sig);
}
}
}
/// Clean up expired routes (uses max_route_age from router config)
pub fn cleanupExpiredRoutes(self: *MessageRouter, max_age: i64) void {
const current_time = std.time.timestamp();
var expired_destinations: std.ArrayList(message.NodeId) = .{};
defer expired_destinations.deinit(self.allocator);
// Acquire write lock for cleanup
self.route_table_lock.lock();
// Pre-allocate capacity based on current route count
expired_destinations.ensureTotalCapacity(self.allocator, self.routes.count()) catch |err| {
std.log.err("Failed to pre-allocate cleanup list (capacity {}): {}", .{ self.routes.count(), err });
// Continue with dynamic allocation fallback
};
var cleanup_failures: usize = 0;
var it = self.routes.iterator();
while (it.next()) |entry| {
const route = entry.value_ptr;
if (current_time - route.last_updated > max_age) {
route.is_valid = false;
expired_destinations.append(self.allocator, entry.key_ptr.*) catch |err| {
std.log.err("Failed to track expired route during cleanup: {}", .{err});
cleanup_failures += 1;
continue;
};
}
}
// Invalidate expired routes (already holding lock)
for (expired_destinations.items) |dest| {
if (self.routes.getEntry(dest)) |entry| {
entry.value_ptr.is_valid = false;
self.metrics_lock.lock();
self.metrics.active_routes -= 1;
self.metrics_lock.unlock();
}
}
self.route_table_lock.unlock();
if (cleanup_failures > 0) {
std.log.warn("Route cleanup encountered {} failures", .{cleanup_failures});
}
}
/// Clean up stale routes using the router's configured max age
pub fn cleanupStaleRoutes(self: *MessageRouter) void {
self.cleanupExpiredRoutes(self.max_route_age);
}
/// Get all known routes
pub fn getAllRoutes(self: *MessageRouter) std.ArrayList(RouteEntry) {
var routes: std.ArrayList(RouteEntry) = .{};
self.route_table_lock.lockShared();
defer self.route_table_lock.unlockShared();
// Pre-allocate capacity based on current route count
routes.ensureTotalCapacity(self.allocator, self.routes.count()) catch |err| {
std.log.err("Failed to pre-allocate routes list (capacity {}): {}", .{ self.routes.count(), err });
// Continue with dynamic allocation fallback
};
var append_failures: usize = 0;
var it = self.routes.iterator();
while (it.next()) |entry| {
routes.append(self.allocator, entry.value_ptr.*) catch |err| {
std.log.err("Failed to add route to list: {}", .{err});
append_failures += 1;
continue;
};
}
if (append_failures > 0) {
std.log.warn("Route collection encountered {} failures", .{append_failures});
}
return routes;
}
/// Check if a destination is reachable
pub fn isReachable(self: *MessageRouter, destination: message.NodeId) bool {
self.route_table_lock.lockShared();
defer self.route_table_lock.unlockShared();
if (self.routes.get(destination)) |route| {
return route.is_valid;
}
return false;
}
/// Get route statistics
pub fn getRouteStats(self: *MessageRouter) struct {
total: usize,
active: usize,
pending: usize,
success_rate: f64,
} {
self.metrics_lock.lock();
const total = self.metrics.total_routes;
const active = self.metrics.active_routes;
const total_queries = self.metrics.successful_lookups + self.metrics.failed_lookups;
const success_rate = if (total_queries > 0)
@as(f64, @floatFromInt(self.metrics.successful_lookups)) / @as(f64, @floatFromInt(total_queries))
else
0.0;
self.metrics_lock.unlock();
self.pending_queries_lock.lock();
const pending = self.pending_queries.count();
self.pending_queries_lock.unlock();
return .{
.total = total,
.active = active,
.pending = pending,
.success_rate = success_rate,
};
}
};
/// Distance Vector routing algorithm implementation
pub const DistanceVectorRouter = struct {
router: *MessageRouter,
pub fn init(router: *MessageRouter) DistanceVectorRouter {
return .{ .router = router };
}
/// Maximum routes to process from a single distance vector update
pub const MAX_DV_UPDATE_ROUTES: usize = 1000;
/// Process distance vector update
pub fn processUpdate(self: *DistanceVectorRouter, neighbor_id: message.NodeId, neighbor_routes: []const RouteEntry) !void {
// SECURITY: Limit routes to prevent CPU exhaustion from malicious DV updates
const routes_to_process = if (neighbor_routes.len > MAX_DV_UPDATE_ROUTES) blk: {
std.log.warn("SECURITY: DV update from peer has {} routes, limiting to {}", .{ neighbor_routes.len, MAX_DV_UPDATE_ROUTES });
break :blk neighbor_routes[0..MAX_DV_UPDATE_ROUTES];
} else neighbor_routes;
// Add/update neighbor route
try self.router.addRoute(neighbor_id, neighbor_id, 1);
// Process neighbor's routes
for (routes_to_process) |route| {
// Skip routes to self or neighbor
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, route.destination, neighbor_id)) continue;
const new_cost = route.cost + 1; // Add cost to reach neighbor
// Update route if better than current
if (self.router.routes.get(route.destination)) |existing| {
if (!existing.is_valid or new_cost < existing.cost) {
try self.router.addRoute(route.destination, neighbor_id, new_cost);
}
} else {
try self.router.addRoute(route.destination, neighbor_id, new_cost);
}
}
}
/// Send distance vector to neighbor
pub fn sendDistanceVector(self: *DistanceVectorRouter, neighbor_id: message.NodeId) !std.ArrayList(RouteEntry) {
var routes: std.ArrayList(RouteEntry) = .{};
errdefer routes.deinit(self.router.allocator);
var it = self.router.routes.iterator();
while (it.next()) |entry| {
const route = entry.value_ptr;
if (route.is_valid and route.next_hop != neighbor_id) {
// ERR-M5 FIX: Propagate error instead of silently continuing
// OOM during distance vector construction should be reported to caller
try routes.append(self.router.allocator, route.*);
}
}
return routes;
}
};
/// Link State routing algorithm implementation
pub const LinkStateRouter = struct {
/// Maximum topology entries to prevent DoS via LSA flooding
pub const MAX_TOPOLOGY_ENTRIES: usize = 10000;
router: *MessageRouter,
topology_map: std.AutoHashMap(message.NodeId, std.ArrayList(message.NodeId)),
pub fn init(router: *MessageRouter, allocator: std.mem.Allocator) LinkStateRouter {
return .{
.router = router,
.topology_map = std.AutoHashMap(message.NodeId, std.ArrayList(message.NodeId)).init(allocator),
};
}
pub fn deinit(self: *LinkStateRouter) void {
self.topology_map.deinit();
}
/// Process link state advertisement
pub fn processLSA(self: *LinkStateRouter, source: message.NodeId, links: []const message.NodeId) !void {
// Update topology map
if (self.topology_map.getEntry(source)) |entry| {
entry.value_ptr.clearRetainingCapacity();
// Pre-allocate for links
entry.value_ptr.ensureTotalCapacity(self.router.allocator, links.len) catch |err| {
std.log.err("Failed to pre-allocate topology links (capacity {}): {}", .{ links.len, err });
};
var link_failures: usize = 0;
for (links) |link| {
entry.value_ptr.append(self.router.allocator, link) catch |err| {
std.log.err("Failed to append link to topology: {}", .{err});
link_failures += 1;
continue;
};
}
if (link_failures > 0) {
std.log.warn("LSA processing encountered {} link append failures", .{link_failures});
}
} else {
// SECURITY: Enforce topology map limit to prevent DoS via LSA flooding
if (self.topology_map.count() >= MAX_TOPOLOGY_ENTRIES) {
std.log.warn("SECURITY: topology_map at capacity ({}), rejecting new LSA", .{MAX_TOPOLOGY_ENTRIES});
return error.OutOfMemory;
}
var neighbors: std.ArrayList(message.NodeId) = .{};
// Pre-allocate for links
neighbors.ensureTotalCapacity(self.router.allocator, links.len) catch |err| {
std.log.err("Failed to pre-allocate neighbor list (capacity {}): {}", .{ links.len, err });
};
var link_failures: usize = 0;
for (links) |link| {
neighbors.append(self.router.allocator, link) catch |err| {
std.log.err("Failed to append neighbor: {}", .{err});
link_failures += 1;
continue;
};
}
if (link_failures > 0) {
std.log.warn("LSA neighbor creation encountered {} failures", .{link_failures});
}
try self.topology_map.put(source, neighbors);
}
// Recalculate routes using Dijkstra's algorithm
try self.recalculateRoutes();
}
/// Recalculate all routes using Dijkstra's algorithm
fn recalculateRoutes(self: *LinkStateRouter) !void {
// Clear existing routes
var destinations: std.ArrayList(message.NodeId) = .{};
defer destinations.deinit(self.router.allocator);
// Pre-allocate for current routes
destinations.ensureTotalCapacity(self.router.allocator, self.router.routes.count()) catch |err| {
std.log.err("Failed to pre-allocate destinations list (capacity {}): {}", .{ self.router.routes.count(), err });
};
var dest_failures: usize = 0;
var it = self.router.routes.iterator();
while (it.next()) |entry| {
destinations.append(self.router.allocator, entry.key_ptr.*) catch |err| {
std.log.err("Failed to collect route destination: {}", .{err});
dest_failures += 1;
continue;
};
}
if (dest_failures > 0) {
std.log.warn("Route recalculation destination collection encountered {} failures", .{dest_failures});
}
for (destinations.items) |dest| {
self.router.removeRoute(dest);
}
// Run Dijkstra's algorithm from all known sources
var sources: std.ArrayList(message.NodeId) = .{};
defer sources.deinit(self.router.allocator);
// Pre-allocate for topology sources
sources.ensureTotalCapacity(self.router.allocator, self.topology_map.count()) catch |err| {
std.log.err("Failed to pre-allocate sources list (capacity {}): {}", .{ self.topology_map.count(), err });
};
var src_failures: usize = 0;
var src_it = self.topology_map.keyIterator();
while (src_it.next()) |source| {
sources.append(self.router.allocator, source.*) catch |err| {
std.log.err("Failed to collect topology source: {}", .{err});
src_failures += 1;
continue;
};
}
if (src_failures > 0) {
std.log.warn("Route recalculation source collection encountered {} failures", .{src_failures});
}
for (sources.items) |source| {
try self.dijkstra(source);
}
}
/// Dijkstra's algorithm for shortest path
fn dijkstra(self: *LinkStateRouter, source: message.NodeId) !void {
var distances = std.AutoHashMap(message.NodeId, u32).init(self.router.allocator);
var previous = std.AutoHashMap(message.NodeId, message.NodeId).init(self.router.allocator);
var visited = std.AutoHashMap(message.NodeId, void).init(self.router.allocator);
defer {
distances.deinit();
previous.deinit();
visited.deinit();
}
// Initialize distances
try distances.put(source, 0);
// Process all nodes
while (true) {
// Find unvisited node with minimum distance
var current: ?message.NodeId = null;
var min_distance: u32 = std.math.maxInt(u32);
var dist_it = distances.iterator();
while (dist_it.next()) |entry| {
if (visited.contains(entry.key_ptr.*)) continue;
if (entry.value_ptr.* < min_distance) {
min_distance = entry.value_ptr.*;
current = entry.key_ptr.*;
}
}
if (current == null) break; // No more reachable nodes
const current_node = current.?;
try visited.put(current_node, void{});
// Get neighbors
const neighbors = self.topology_map.get(current_node) orelse continue;
// Update distances to neighbors
for (neighbors.items) |neighbor| {
const new_distance = distances.get(current_node).? + 1;
if (distances.get(neighbor)) |existing| {
if (new_distance < existing) {
try distances.put(neighbor, new_distance);
try previous.put(neighbor, current_node);
}
} else {
try distances.put(neighbor, new_distance);
try previous.put(neighbor, current_node);
}
}
}
// Build routing table from shortest paths
var dest_it = distances.iterator();
while (dest_it.next()) |entry| {
const dest = entry.key_ptr.*;
const distance = entry.value_ptr.*;
if (dest == source) continue; // Skip self
// Find next hop
var next_hop = dest;
var current = dest;
while (previous.get(current)) |prev| {
next_hop = current;
current = prev;
// SECURITY: Timing-safe comparison for node ID
if (std.crypto.timing_safe.eql([32]u8, current, source)) break;
}
try self.router.addRoute(dest, next_hop, distance);
}
}
};
test "message routing" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.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 = router.routeMessage(base_msg);
try std.testing.expect(!route_result.success);
// First add dest as a neighbor (directly connected peer)
// This is required because unsigned routes are only accepted for direct neighbors
try router.addNeighbor(dest);
// Add a route
try router.addRoute(dest, dest, 1);
// Route should succeed now
const route_result2 = router.routeMessage(base_msg);
try std.testing.expect(route_result2.success);
try std.testing.expectEqual(dest, route_result2.next_hop.?);
// Test metrics
const metrics = router.getMetrics();
try std.testing.expect(metrics.total_routes > 0);
try std.testing.expect(metrics.successful_lookups > 0);
}
test "Ed25519 signature verification - valid signature" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Register the peer's public key
try router.registerPeerPublicKey(peer_id, key_pair.public_key.bytes);
// Mark peer as directly connected (trusted relay)
try router.directly_connected_peers.put(peer_id, void{});
// Create origin, destination and next_hop
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a signed route (IMP-H4: now returns error instead of null)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Verify the signature
const is_valid = router.verifySignatureComponents(dest, next_hop, cost, sig);
try std.testing.expect(is_valid);
}
test "Ed25519 signature verification - invalid signature rejected" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Register the peer's public key
try router.registerPeerPublicKey(peer_id, key_pair.public_key.bytes);
// Mark peer as directly connected
try router.directly_connected_peers.put(peer_id, void{});
// Create origin, destination and next_hop
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a valid signed route (IMP-H4: now returns error instead of null)
var sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Tamper with the signature
sig.signature[0] ^= 0xFF;
sig.signature[10] ^= 0xAB;
// Verify should fail
const is_valid = router.verifySignatureComponents(dest, next_hop, cost, sig);
try std.testing.expect(!is_valid);
}
test "Ed25519 signature verification - unknown signer rejected" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Mark peer as directly connected but DON'T register public key
try router.directly_connected_peers.put(peer_id, void{});
// Create origin, destination and next_hop
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a signed route (IMP-H4: now returns error instead of null)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Verify should fail - no public key registered
const is_valid = router.verifySignatureComponents(dest, next_hop, cost, sig);
try std.testing.expect(!is_valid);
}
test "Ed25519 signature verification - untrusted signer rejected" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Register public key but DON'T mark as directly connected
try router.registerPeerPublicKey(peer_id, key_pair.public_key.bytes);
// Create origin and destination different from signer (signer is not destination)
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a signed route (IMP-H4: now returns error instead of null)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Verify should fail - signer is neither destination nor trusted relay
const is_valid = router.verifySignatureComponents(dest, next_hop, cost, sig);
try std.testing.expect(!is_valid);
}
test "Ed25519 signature verification - destination can sign own routes" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the destination
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up destination ID from public key (destination signs its own route)
var dest: message.NodeId = undefined;
@memcpy(&dest, &key_pair.public_key.bytes);
// Register the destination's public key
try router.registerPeerPublicKey(dest, key_pair.public_key.bytes);
// Note: We don't add dest to directly_connected_peers
// The destination should be allowed to sign its own route
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a signed route where signer == destination (IMP-H4: now returns error)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Verify should succeed - destination is signing its own route
const is_valid = router.verifySignatureComponents(dest, next_hop, cost, sig);
try std.testing.expect(is_valid);
}
test "Ed25519 signature verification - wrong data fails" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Register and trust the peer
try router.registerPeerPublicKey(peer_id, key_pair.public_key.bytes);
try router.directly_connected_peers.put(peer_id, void{});
// Create origin, destination and next_hop
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a signed route (IMP-H4: now returns error instead of null)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Try to verify with different cost - should fail
const is_valid = router.verifySignatureComponents(dest, next_hop, 10, sig);
try std.testing.expect(!is_valid);
}
test "addRouteWithSignature requires valid signature for non-neighbors" {
const allocator = std.testing.allocator;
// IMP-CRIT-2: Use test local_node_id
const test_local_id: message.NodeId = .{0xFF} ** 32;
var router = MessageRouter.init(allocator, test_local_id);
defer router.deinit();
// Generate Ed25519 key pair for the signer
const Ed25519 = std.crypto.sign.Ed25519;
const key_pair = Ed25519.KeyPair.generate();
// Set up peer ID from public key
var peer_id: message.NodeId = undefined;
@memcpy(&peer_id, &key_pair.public_key.bytes);
// Register and trust the peer
try router.registerPeerPublicKey(peer_id, key_pair.public_key.bytes);
try router.directly_connected_peers.put(peer_id, void{});
// Create origin, destination and next_hop
var origin: message.NodeId = .{0} ** 32;
origin[0] = 0;
var dest: message.NodeId = .{0} ** 32;
dest[0] = 1;
var next_hop: message.NodeId = .{0} ** 32;
next_hop[0] = 2;
const cost: u32 = 5;
// Create a valid signed route (IMP-H4: now returns error instead of null)
const sig = router.createSignedRoute(origin, dest, next_hop, cost, key_pair.secret_key.bytes) catch |err| {
std.debug.print("createSignedRoute failed: {}\n", .{err});
try std.testing.expect(false); // Should not fail with valid key
return;
};
// Should succeed with valid signature
try router.addRouteWithSignature(dest, next_hop, cost, sig);
try std.testing.expect(router.isReachable(dest));
// Try to add unsigned route to non-neighbor - should fail
var dest2: message.NodeId = .{0} ** 32;
dest2[0] = 3;
const result = router.addRouteWithSignature(dest2, next_hop, cost, null);
try std.testing.expectError(error.UnsignedRoute, result);
}
test "MessageRouter: init and deinit" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0x11} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
try std.testing.expectEqual(local_id, router.local_node_id);
}
test "MessageRouter: addRoute and isReachable" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0x22} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
const dest: message.NodeId = [_]u8{0x33} ** 32;
const next_hop: message.NodeId = [_]u8{0x44} ** 32;
// Register dest as directly connected to allow unsigned routes
try router.directly_connected_peers.put(dest, void{});
// Add route
try router.addRoute(dest, next_hop, 10);
// Should be reachable now
try std.testing.expect(router.isReachable(dest));
}
test "MessageRouter: removeRoute" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0x55} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
const dest: message.NodeId = [_]u8{0x66} ** 32;
const next_hop: message.NodeId = [_]u8{0x77} ** 32;
// Register dest as directly connected to allow unsigned routes
try router.directly_connected_peers.put(dest, void{});
// Add and then remove
try router.addRoute(dest, next_hop, 10);
try std.testing.expect(router.isReachable(dest));
router.removeRoute(dest);
try std.testing.expect(!router.isReachable(dest));
}
test "MessageRouter: getRouteStats" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0x88} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
const stats = router.getRouteStats();
// Initial state
try std.testing.expectEqual(@as(usize, 0), stats.pending);
try std.testing.expectEqual(@as(f64, 0.0), stats.success_rate);
}
test "MessageRouter: getNextHop returns null for unknown dest" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0xBB} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
const unknown_dest: message.NodeId = [_]u8{0xCC} ** 32;
try std.testing.expect(router.getNextHop(unknown_dest) == null);
}
test "MessageRouter: getMetrics" {
const allocator = std.testing.allocator;
const local_id: message.NodeId = [_]u8{0xDD} ** 32;
var router = MessageRouter.init(allocator, local_id);
defer router.deinit();
const metrics = router.getMetrics();
try std.testing.expectEqual(@as(u32, 0), metrics.total_routes);
try std.testing.expectEqual(@as(u32, 0), metrics.failed_lookups);
try std.testing.expectEqual(@as(u32, 0), metrics.successful_lookups);
}