bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

View File

@@ -0,0 +1,528 @@
//! IP Reflection (Bundled STUN) Variable-Length Encoding Tests
//!
//! Tests the variable-length encoding optimization for observed_addr in DHT responses.
//! Format: [len:1][addr:0-18] where len determines how many bytes follow.
//!
//! Address types:
//! - IPv4: 6 bytes (4 IP + 2 port)
//! - IPv6: 18 bytes (16 IP + 2 port)
//! - None: 0 bytes
const std = @import("std");
const testing = std.testing;
const protocol = @import("protocol");
const message = protocol.message;
// Import the DHT module for simple binary format testing
const dht = @import("p2p").dht;
// =============================================================================
// Test Helpers
// =============================================================================
fn makeIPv4Addr(ip: [4]u8, port: u16) struct { addr: [18]u8, len: u8 } {
var addr: [18]u8 = [_]u8{0} ** 18;
@memcpy(addr[0..4], &ip);
addr[4] = @truncate(port >> 8);
addr[5] = @truncate(port);
return .{ .addr = addr, .len = 6 };
}
fn makeIPv6Addr(ip: [16]u8, port: u16) struct { addr: [18]u8, len: u8 } {
var addr: [18]u8 = undefined;
@memcpy(addr[0..16], &ip);
addr[16] = @truncate(port >> 8);
addr[17] = @truncate(port);
return .{ .addr = addr, .len = 18 };
}
// =============================================================================
// STORE_RESPONSE Tests
// =============================================================================
test "IP Reflection: STORE_RESPONSE with no address" {
const allocator = testing.allocator;
// Create response with no observed address
const resp = message.DhtStoreResponse{
.request_id = 12345,
.success = true,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
const msg = message.Message{ .dht_store_response = resp };
// Serialize using DHT simple binary format
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Expected: type(1) + request_id(8) + success(1) + len(1) = 11 bytes
try testing.expectEqual(@as(usize, 11), len);
// Verify the length byte is 0
try testing.expectEqual(@as(u8, 0), buffer[10]);
// Deserialize and verify round-trip
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
const decoded = result.dht_store_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(resp.success, decoded.success);
try testing.expectEqual(@as(u8, 0), decoded.observed_addr_len);
}
test "IP Reflection: STORE_RESPONSE with IPv4 address" {
const allocator = testing.allocator;
// Create IPv4 address: 192.168.1.100:8080
const ipv4 = makeIPv4Addr(.{ 192, 168, 1, 100 }, 8080);
const resp = message.DhtStoreResponse.initWithObserved(12345, true, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_store_response = resp };
// Serialize
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Expected: type(1) + request_id(8) + success(1) + len(1) + addr(6) = 17 bytes
try testing.expectEqual(@as(usize, 17), len);
// Verify the length byte
try testing.expectEqual(@as(u8, 6), buffer[10]);
// Verify the IP address bytes
try testing.expectEqual(@as(u8, 192), buffer[11]);
try testing.expectEqual(@as(u8, 168), buffer[12]);
try testing.expectEqual(@as(u8, 1), buffer[13]);
try testing.expectEqual(@as(u8, 100), buffer[14]);
// Deserialize and verify round-trip
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
const decoded = result.dht_store_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(resp.success, decoded.success);
try testing.expectEqual(@as(u8, 6), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, ipv4.addr[0..6], decoded.observed_addr[0..6]);
}
test "IP Reflection: STORE_RESPONSE with IPv6 address" {
const allocator = testing.allocator;
// Create IPv6 address: 2001:db8::1 port 443
const ipv6 = makeIPv6Addr(.{ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 443);
const resp = message.DhtStoreResponse.initWithObserved(12345, false, ipv6.addr, ipv6.len);
const msg = message.Message{ .dht_store_response = resp };
// Serialize
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Expected: type(1) + request_id(8) + success(1) + len(1) + addr(18) = 29 bytes
try testing.expectEqual(@as(usize, 29), len);
// Verify the length byte
try testing.expectEqual(@as(u8, 18), buffer[10]);
// Deserialize and verify round-trip
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
const decoded = result.dht_store_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(resp.success, decoded.success);
try testing.expectEqual(@as(u8, 18), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, &ipv6.addr, &decoded.observed_addr);
}
// =============================================================================
// FIND_NODE_RESPONSE Tests
// =============================================================================
test "IP Reflection: FIND_NODE_RESPONSE with no address, no nodes" {
const allocator = testing.allocator;
const resp = message.DhtFindNodeResponse{
.request_id = 99999,
.closest_nodes = &[_]message.DhtFindNodeResponse.NodeInfo{},
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
const msg = message.Message{ .dht_find_node_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Expected: type(1) + request_id(8) + node_count(4) + len(1) = 14 bytes
try testing.expectEqual(@as(usize, 14), len);
// Deserialize and verify
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
defer allocator.free(result.dht_find_node_response.closest_nodes);
const decoded = result.dht_find_node_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(@as(usize, 0), decoded.closest_nodes.len);
try testing.expectEqual(@as(u8, 0), decoded.observed_addr_len);
}
test "IP Reflection: FIND_NODE_RESPONSE with IPv4 address and nodes" {
const allocator = testing.allocator;
const ipv4 = makeIPv4Addr(.{ 10, 0, 0, 1 }, 9999);
const NodeInfo = message.DhtFindNodeResponse.NodeInfo;
const nodes = [_]NodeInfo{
.{ .node_id = [_]u8{0xAA} ** 32, .address = [_]u8{0} ** 46, .address_len = 6 },
.{ .node_id = [_]u8{0xBB} ** 32, .address = [_]u8{0} ** 46, .address_len = 18 },
};
const resp = message.DhtFindNodeResponse.initWithObserved(12345, &nodes, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_find_node_response = resp };
var buffer: [512]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Expected: type(1) + request_id(8) + node_count(4) + 2*node(79) + len(1) + addr(6) = 178 bytes
try testing.expectEqual(@as(usize, 178), len);
// Deserialize and verify
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
defer allocator.free(result.dht_find_node_response.closest_nodes);
const decoded = result.dht_find_node_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(@as(usize, 2), decoded.closest_nodes.len);
try testing.expectEqual(@as(u8, 6), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, ipv4.addr[0..6], decoded.observed_addr[0..6]);
// Verify node data preserved
try testing.expectEqualSlices(u8, &nodes[0].node_id, &decoded.closest_nodes[0].node_id);
try testing.expectEqualSlices(u8, &nodes[1].node_id, &decoded.closest_nodes[1].node_id);
}
// =============================================================================
// FIND_VALUE_RESPONSE Tests
// =============================================================================
test "IP Reflection: FIND_VALUE_RESPONSE with value and IPv4" {
const allocator = testing.allocator;
const ipv4 = makeIPv4Addr(.{ 172, 16, 0, 1 }, 5000);
const resp = message.DhtFindValueResponse.initWithObserved(
12345,
true,
"test value data",
&[_]message.DhtFindNodeResponse.NodeInfo{},
ipv4.addr,
ipv4.len,
);
const msg = message.Message{ .dht_find_value_response = resp };
var buffer: [512]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Deserialize and verify
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
defer {
if (result.dht_find_value_response.value) |v| allocator.free(v);
allocator.free(result.dht_find_value_response.closest_nodes);
}
const decoded = result.dht_find_value_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(true, decoded.found);
try testing.expectEqualStrings("test value data", decoded.value.?);
try testing.expectEqual(@as(u8, 6), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, ipv4.addr[0..6], decoded.observed_addr[0..6]);
}
test "IP Reflection: FIND_VALUE_RESPONSE not found with IPv6" {
const allocator = testing.allocator;
const ipv6 = makeIPv6Addr(.{ 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 8443);
const NodeInfo = message.DhtFindNodeResponse.NodeInfo;
const nodes = [_]NodeInfo{
.{ .node_id = [_]u8{0xCC} ** 32, .address = [_]u8{0} ** 46, .address_len = 6 },
};
const resp = message.DhtFindValueResponse.initWithObserved(
54321,
false,
null,
&nodes,
ipv6.addr,
ipv6.len,
);
const msg = message.Message{ .dht_find_value_response = resp };
var buffer: [512]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Deserialize and verify
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
defer {
if (result.dht_find_value_response.value) |v| allocator.free(v);
allocator.free(result.dht_find_value_response.closest_nodes);
}
const decoded = result.dht_find_value_response;
try testing.expectEqual(resp.request_id, decoded.request_id);
try testing.expectEqual(false, decoded.found);
try testing.expect(decoded.value == null);
try testing.expectEqual(@as(usize, 1), decoded.closest_nodes.len);
try testing.expectEqual(@as(u8, 18), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, &ipv6.addr, &decoded.observed_addr);
}
// =============================================================================
// Edge Cases
// =============================================================================
test "IP Reflection: boundary length values" {
const allocator = testing.allocator;
// Test with length = 1 (unusual but valid)
{
var addr: [18]u8 = [_]u8{0} ** 18;
addr[0] = 0x42;
const resp = message.DhtStoreResponse.initWithObserved(1, true, addr, 1);
const msg = message.Message{ .dht_store_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// type(1) + request_id(8) + success(1) + len(1) + addr(1) = 12 bytes
try testing.expectEqual(@as(usize, 12), len);
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
try testing.expectEqual(@as(u8, 1), result.dht_store_response.observed_addr_len);
try testing.expectEqual(@as(u8, 0x42), result.dht_store_response.observed_addr[0]);
}
// Test with length = 17 (between IPv4 and IPv6)
{
var addr: [18]u8 = undefined;
for (&addr, 0..) |*b, i| {
b.* = @truncate(i);
}
const resp = message.DhtStoreResponse.initWithObserved(2, false, addr, 17);
const msg = message.Message{ .dht_store_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// type(1) + request_id(8) + success(1) + len(1) + addr(17) = 28 bytes
try testing.expectEqual(@as(usize, 28), len);
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
return error.DeserializationFailed;
};
try testing.expectEqual(@as(u8, 17), result.dht_store_response.observed_addr_len);
try testing.expectEqualSlices(u8, addr[0..17], result.dht_store_response.observed_addr[0..17]);
}
}
test "IP Reflection: real-world IPv4 addresses" {
const allocator = testing.allocator;
const test_cases = [_]struct { ip: [4]u8, port: u16, name: []const u8 }{
.{ .ip = .{ 8, 8, 8, 8 }, .port = 53, .name = "Google DNS" },
.{ .ip = .{ 1, 1, 1, 1 }, .port = 443, .name = "Cloudflare" },
.{ .ip = .{ 192, 168, 0, 1 }, .port = 80, .name = "Local router" },
.{ .ip = .{ 10, 255, 255, 255 }, .port = 65535, .name = "Max private" },
.{ .ip = .{ 0, 0, 0, 0 }, .port = 0, .name = "Zero address" },
.{ .ip = .{ 255, 255, 255, 255 }, .port = 65535, .name = "Broadcast max" },
};
for (test_cases) |tc| {
const ipv4 = makeIPv4Addr(tc.ip, tc.port);
const resp = message.DhtStoreResponse.initWithObserved(12345, true, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_store_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
std.debug.print("Failed to serialize: {s}\n", .{tc.name});
return error.SerializationFailed;
};
const result = dht.deserializeDhtMessage(buffer[0..len], allocator) orelse {
std.debug.print("Failed to deserialize: {s}\n", .{tc.name});
return error.DeserializationFailed;
};
const decoded = result.dht_store_response;
try testing.expectEqual(@as(u8, 6), decoded.observed_addr_len);
try testing.expectEqualSlices(u8, &tc.ip, decoded.observed_addr[0..4]);
// Verify port (big-endian)
const decoded_port = (@as(u16, decoded.observed_addr[4]) << 8) | decoded.observed_addr[5];
try testing.expectEqual(tc.port, decoded_port);
}
}
test "IP Reflection: payload size calculation" {
// Test that getPayloadSize correctly calculates variable-length sizes
const serializer = @import("protocol").serializer;
// No address: 8 + 1 + 1 = 10 bytes
{
const resp = message.DhtStoreResponse{
.request_id = 1,
.success = true,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
const msg = message.Message{ .dht_store_response = resp };
var ser = serializer.MessageSerializer.initInsecureForTesting(testing.allocator);
try testing.expectEqual(@as(usize, 10), ser.getPayloadSizePublic(msg));
}
// IPv4: 8 + 1 + 1 + 6 = 16 bytes
{
const ipv4 = makeIPv4Addr(.{ 1, 2, 3, 4 }, 1234);
const resp = message.DhtStoreResponse.initWithObserved(1, true, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_store_response = resp };
var ser = serializer.MessageSerializer.initInsecureForTesting(testing.allocator);
try testing.expectEqual(@as(usize, 16), ser.getPayloadSizePublic(msg));
}
// IPv6: 8 + 1 + 1 + 18 = 28 bytes
{
const ipv6 = makeIPv6Addr([_]u8{0} ** 16, 443);
const resp = message.DhtStoreResponse.initWithObserved(1, true, ipv6.addr, ipv6.len);
const msg = message.Message{ .dht_store_response = resp };
var ser = serializer.MessageSerializer.initInsecureForTesting(testing.allocator);
try testing.expectEqual(@as(usize, 28), ser.getPayloadSizePublic(msg));
}
}
test "IP Reflection: truncation of invalid lengths" {
// Test that lengths > 18 are safely handled (capped at 18)
// Manually create a message with invalid length (will be capped during serialization)
var addr: [18]u8 = undefined;
for (&addr, 0..) |*b, i| {
b.* = @truncate(i + 1);
}
// Create with len=255 (invalid, should be capped at 18)
const resp = message.DhtStoreResponse{
.request_id = 99999,
.success = true,
.observed_addr = addr,
.observed_addr_len = 255, // Invalid, will be capped
};
const msg = message.Message{ .dht_store_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Should serialize max 18 bytes of address data
// type(1) + request_id(8) + success(1) + len(1) + addr(18) = 29 bytes
try testing.expectEqual(@as(usize, 29), len);
// The length byte should still be 255 (we preserve original value)
try testing.expectEqual(@as(u8, 255), buffer[10]);
// But only 18 bytes of actual data should be written
// Verify the first 18 bytes match
try testing.expectEqualSlices(u8, addr[0..18], buffer[11..29]);
}
test "IP Reflection: minimum buffer size requirements" {
// Test that serialization fails gracefully with too-small buffers
const ipv4 = makeIPv4Addr(.{ 1, 2, 3, 4 }, 1234);
const resp = message.DhtStoreResponse.initWithObserved(1, true, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_store_response = resp };
// Buffer too small (need 17 bytes for IPv4 STORE_RESPONSE)
{
var small_buffer: [16]u8 = undefined;
const result = dht.serializeDhtMessage(msg, &small_buffer);
try testing.expect(result == null);
}
// Exact size should work
{
var exact_buffer: [17]u8 = undefined;
const result = dht.serializeDhtMessage(msg, &exact_buffer);
try testing.expect(result != null);
try testing.expectEqual(@as(usize, 17), result.?);
}
}
test "IP Reflection: deserialization with truncated data" {
const allocator = testing.allocator;
// Create valid serialized data
const ipv4 = makeIPv4Addr(.{ 1, 2, 3, 4 }, 1234);
const resp = message.DhtStoreResponse.initWithObserved(1, true, ipv4.addr, ipv4.len);
const msg = message.Message{ .dht_store_response = resp };
var buffer: [256]u8 = undefined;
const len = dht.serializeDhtMessage(msg, &buffer) orelse {
return error.SerializationFailed;
};
// Try to deserialize with progressively truncated data
// Should fail gracefully (return null) for incomplete data
// Missing address data (have length byte but no address)
{
const result = dht.deserializeDhtMessage(buffer[0..11], allocator);
try testing.expect(result == null);
}
// Partial address data
{
const result = dht.deserializeDhtMessage(buffer[0..14], allocator);
try testing.expect(result == null);
}
// Complete data should work
{
const result = dht.deserializeDhtMessage(buffer[0..len], allocator);
try testing.expect(result != null);
}
}

View File

@@ -795,13 +795,19 @@ test "getPayloadSize DHT messages" {
// Just verify it returns a reasonable value (> 0)
try testing.expect(ser.getPayloadSizePublic(fnr_msg) > 0);
// DHT store_response: 8 + 1 = 9
// DHT store_response with variable-length encoding:
// With observed_addr_len=0: 8 + 1 + 1 = 10 (request_id + success + len byte only)
const store_resp = message.DhtStoreResponse{
.request_id = 1,
.success = true,
};
const sr_msg = message.Message{ .dht_store_response = store_resp };
try testing.expectEqual(@as(usize, 9), ser.getPayloadSizePublic(sr_msg));
try testing.expectEqual(@as(usize, 10), ser.getPayloadSizePublic(sr_msg));
// DHT store_response with IPv4 address (6 bytes): 8 + 1 + 1 + 6 = 16
const store_resp_ipv4 = message.DhtStoreResponse.initWithObserved(1, true, [_]u8{ 192, 168, 1, 1, 0x1F, 0x90 } ++ [_]u8{0} ** 12, 6);
const sr_msg_ipv4 = message.Message{ .dht_store_response = store_resp_ipv4 };
try testing.expectEqual(@as(usize, 16), ser.getPayloadSizePublic(sr_msg_ipv4));
// DHT find_value: 8 + 32 + 32 = 72
const find_value = message.DhtFindValue{