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,382 @@
//! Mock STUN Server for Testing
//!
//! Provides a localhost STUN server that responds with XOR-MAPPED-ADDRESS
//! to exercise NAT traversal code paths without external dependencies.
const std = @import("std");
const posix = std.posix;
const mem = std.mem;
const Allocator = mem.Allocator;
const core = @import("core");
const Address = core.Address;
const Socket = core.Socket;
pub const STUN_MAGIC_COOKIE: u32 = 0x2112A442;
pub const STUN_BINDING_REQUEST: u16 = 0x0001;
pub const STUN_BINDING_RESPONSE: u16 = 0x0101;
pub const STUN_ATTR_MAPPED_ADDRESS: u16 = 0x0001;
pub const STUN_ATTR_XOR_MAPPED_ADDRESS: u16 = 0x0020;
pub const STUN_HEADER_SIZE: usize = 20;
/// Mock STUN server that responds on localhost
pub const MockStunServer = struct {
allocator: Allocator,
socket: ?*Socket,
bound_port: u16,
running: std.atomic.Value(bool),
thread: ?std.Thread,
// Configurable response
response_address: Address,
should_respond: bool,
delay_ms: u32,
requests_received: std.atomic.Value(u32),
const Self = @This();
pub fn init(allocator: Allocator) Self {
return Self{
.allocator = allocator,
.socket = null,
.bound_port = 0,
.running = std.atomic.Value(bool).init(false),
.thread = null,
.response_address = Address.ipv4(.{ 203, 0, 113, 100 }, 12345),
.should_respond = true,
.delay_ms = 0,
.requests_received = std.atomic.Value(u32).init(0),
};
}
pub fn deinit(self: *Self) void {
self.stop();
if (self.socket) |sock| {
sock.deinit();
self.allocator.destroy(sock);
self.socket = null;
}
}
/// Set the address to return in XOR-MAPPED-ADDRESS
pub fn setResponseAddress(self: *Self, addr: Address) void {
self.response_address = addr;
}
/// Set whether to respond (for timeout testing)
pub fn setShouldRespond(self: *Self, should: bool) void {
self.should_respond = should;
}
/// Set response delay in milliseconds
pub fn setResponseDelay(self: *Self, delay_ms: u32) void {
self.delay_ms = delay_ms;
}
/// Get number of requests received
pub fn getRequestCount(self: *Self) u32 {
return self.requests_received.load(.acquire);
}
/// Start the mock server on a random available port
pub fn start(self: *Self) !u16 {
const sock = self.allocator.create(Socket) catch return error.OutOfMemory;
errdefer self.allocator.destroy(sock);
sock.* = Socket.init(.udp, self.allocator) catch return error.SocketError;
errdefer sock.deinit();
// Bind to any available port on localhost
const bind_addr = Address.ipv4(.{ 127, 0, 0, 1 }, 0);
sock.bind(bind_addr) catch return error.BindError;
// Get the actual bound port using getsockname
var addr_storage: posix.sockaddr.in = std.mem.zeroes(posix.sockaddr.in);
var addr_len: posix.socklen_t = @sizeOf(posix.sockaddr.in);
posix.getsockname(sock.fd, @ptrCast(&addr_storage), &addr_len) catch return error.BindError;
self.bound_port = std.mem.bigToNative(u16, addr_storage.port);
if (self.bound_port == 0) {
return error.BindError;
}
self.socket = sock;
self.running.store(true, .release);
// Start server thread
self.thread = std.Thread.spawn(.{}, serverLoop, .{self}) catch return error.ThreadError;
return self.bound_port;
}
/// Stop the mock server
pub fn stop(self: *Self) void {
self.running.store(false, .release);
if (self.thread) |t| {
t.join();
self.thread = null;
}
}
/// Get the server address for clients to connect to
pub fn getServerAddress(self: *Self) Address {
return Address.ipv4(.{ 127, 0, 0, 1 }, self.bound_port);
}
fn serverLoop(self: *Self) void {
var buffer: [512]u8 = undefined;
while (self.running.load(.acquire)) {
if (self.socket) |sock| {
// Use poll to wait for data with 100ms timeout
var fds = [1]posix.pollfd{
.{
.fd = sock.fd,
.events = posix.POLL.IN,
.revents = 0,
},
};
const poll_result = posix.poll(&fds, 100) catch 0;
if (poll_result > 0 and (fds[0].revents & posix.POLL.IN) != 0) {
// Data available
const result = sock.receiveFrom(&buffer);
if (result) |recv| {
_ = self.requests_received.fetchAdd(1, .monotonic);
if (self.should_respond) {
if (self.delay_ms > 0) {
std.Thread.sleep(self.delay_ms * std.time.ns_per_ms);
}
self.handleRequest(sock, recv.address, buffer[0..recv.size]) catch {};
}
} else |_| {
// Receive error, continue
}
}
// Timeout or no data, continue loop
} else {
break;
}
}
}
fn handleRequest(self: *Self, sock: *Socket, from: Address, data: []const u8) !void {
if (data.len < STUN_HEADER_SIZE) return;
// Parse STUN header
const msg_type = std.mem.readInt(u16, data[0..2], .big);
if (msg_type != STUN_BINDING_REQUEST) return;
const magic = std.mem.readInt(u32, data[4..8], .big);
if (magic != STUN_MAGIC_COOKIE) return;
const transaction_id = data[8..20];
// Build response
var response: [64]u8 = undefined;
const response_len = self.buildResponse(&response, transaction_id, from);
_ = sock.sendTo(response[0..response_len], from) catch {};
}
fn buildResponse(self: *Self, buffer: []u8, transaction_id: []const u8, client_addr: Address) usize {
// Message type: Binding Response
std.mem.writeInt(u16, buffer[0..2], STUN_BINDING_RESPONSE, .big);
// Message length (will update later)
// std.mem.writeInt(u16, buffer[2..4], 0, .big);
// Magic cookie
std.mem.writeInt(u32, buffer[4..8], STUN_MAGIC_COOKIE, .big);
// Transaction ID
@memcpy(buffer[8..20], transaction_id);
// Add XOR-MAPPED-ADDRESS attribute
var offset: usize = 20;
// Attribute type
std.mem.writeInt(u16, buffer[offset..][0..2], STUN_ATTR_XOR_MAPPED_ADDRESS, .big);
offset += 2;
// Attribute length (8 bytes for IPv4)
std.mem.writeInt(u16, buffer[offset..][0..2], 8, .big);
offset += 2;
// Reserved byte + family (IPv4 = 0x01)
buffer[offset] = 0;
buffer[offset + 1] = 0x01;
offset += 2;
// XOR'd port (port XOR upper 16 bits of magic cookie)
const magic_high: u16 = @truncate(STUN_MAGIC_COOKIE >> 16);
const addr_to_use = if (self.response_address.port != 0) self.response_address else client_addr;
const xor_port = addr_to_use.port ^ magic_high;
std.mem.writeInt(u16, buffer[offset..][0..2], xor_port, .big);
offset += 2;
// XOR'd address (address XOR magic cookie)
const magic_bytes = std.mem.toBytes(std.mem.nativeToBig(u32, STUN_MAGIC_COOKIE));
const addr_bytes = if (addr_to_use.family == .ipv4) addr_to_use.data.ipv4.bytes else [4]u8{ 127, 0, 0, 1 };
buffer[offset] = addr_bytes[0] ^ magic_bytes[0];
buffer[offset + 1] = addr_bytes[1] ^ magic_bytes[1];
buffer[offset + 2] = addr_bytes[2] ^ magic_bytes[2];
buffer[offset + 3] = addr_bytes[3] ^ magic_bytes[3];
offset += 4;
// Update message length (excluding header)
const attr_len: u16 = @intCast(offset - 20);
std.mem.writeInt(u16, buffer[2..4], attr_len, .big);
return offset;
}
};
/// Helper to build a raw STUN binding request for testing
pub fn buildStunBindingRequest(buffer: []u8, transaction_id: []const u8) usize {
// Message type: Binding Request
std.mem.writeInt(u16, buffer[0..2], STUN_BINDING_REQUEST, .big);
// Message length: 0 (no attributes)
std.mem.writeInt(u16, buffer[2..4], 0, .big);
// Magic cookie
std.mem.writeInt(u32, buffer[4..8], STUN_MAGIC_COOKIE, .big);
// Transaction ID
@memcpy(buffer[8..20], transaction_id);
return STUN_HEADER_SIZE;
}
/// Parse XOR-MAPPED-ADDRESS from a STUN response
pub fn parseXorMappedAddress(data: []const u8, transaction_id: []const u8) ?Address {
if (data.len < STUN_HEADER_SIZE) return null;
// Verify magic cookie
const magic = std.mem.readInt(u32, data[4..8], .big);
if (magic != STUN_MAGIC_COOKIE) return null;
// Verify transaction ID matches
if (!std.mem.eql(u8, data[8..20], transaction_id)) return null;
// Parse attributes
var offset: usize = STUN_HEADER_SIZE;
const msg_len = std.mem.readInt(u16, data[2..4], .big);
const end = STUN_HEADER_SIZE + msg_len;
while (offset + 4 <= end and offset + 4 <= data.len) {
const attr_type = std.mem.readInt(u16, data[offset..][0..2], .big);
const attr_len = std.mem.readInt(u16, data[offset + 2 ..][0..2], .big);
offset += 4;
if (attr_type == STUN_ATTR_XOR_MAPPED_ADDRESS and attr_len >= 8) {
const family = data[offset + 1];
if (family == 0x01) { // IPv4
const xor_port = std.mem.readInt(u16, data[offset + 2 ..][0..2], .big);
const magic_high: u16 = @truncate(STUN_MAGIC_COOKIE >> 16);
const port = xor_port ^ magic_high;
const magic_bytes = std.mem.toBytes(std.mem.nativeToBig(u32, STUN_MAGIC_COOKIE));
var addr_bytes: [4]u8 = undefined;
addr_bytes[0] = data[offset + 4] ^ magic_bytes[0];
addr_bytes[1] = data[offset + 5] ^ magic_bytes[1];
addr_bytes[2] = data[offset + 6] ^ magic_bytes[2];
addr_bytes[3] = data[offset + 7] ^ magic_bytes[3];
return Address.ipv4(addr_bytes, port);
}
}
// Move to next attribute (4-byte aligned)
offset += (attr_len + 3) & ~@as(usize, 3);
}
return null;
}
// ============================================================================
// Tests
// ============================================================================
test "MockStunServer: basic start and stop" {
var server = MockStunServer.init(std.testing.allocator);
defer server.deinit();
const port = try server.start();
try std.testing.expect(port > 0);
server.stop();
}
test "MockStunServer: responds to STUN request" {
var server = MockStunServer.init(std.testing.allocator);
defer server.deinit();
const port = try server.start();
// Create client socket
var client = Socket.init(.udp, std.testing.allocator) catch return error.SkipZigTest;
defer client.deinit();
const server_addr = Address.ipv4(.{ 127, 0, 0, 1 }, port);
// Build and send request
var request: [64]u8 = undefined;
var transaction_id: [12]u8 = undefined;
std.crypto.random.bytes(&transaction_id);
const req_len = buildStunBindingRequest(&request, &transaction_id);
_ = client.sendTo(request[0..req_len], server_addr) catch return error.SkipZigTest;
// Wait for response using poll
var fds = [1]posix.pollfd{
.{ .fd = client.fd, .events = posix.POLL.IN, .revents = 0 },
};
const poll_result = posix.poll(&fds, 1000) catch return error.SkipZigTest;
if (poll_result == 0) return error.SkipZigTest; // Timeout
var response: [512]u8 = undefined;
const recv = client.receiveFrom(&response) catch return error.SkipZigTest;
// Parse response
const addr = parseXorMappedAddress(response[0..recv.size], &transaction_id);
try std.testing.expect(addr != null);
}
test "MockStunServer: timeout when should_respond is false" {
var server = MockStunServer.init(std.testing.allocator);
defer server.deinit();
server.setShouldRespond(false);
const port = try server.start();
var client = Socket.init(.udp, std.testing.allocator) catch return error.SkipZigTest;
defer client.deinit();
const server_addr = Address.ipv4(.{ 127, 0, 0, 1 }, port);
var request: [64]u8 = undefined;
var transaction_id: [12]u8 = undefined;
std.crypto.random.bytes(&transaction_id);
const req_len = buildStunBindingRequest(&request, &transaction_id);
_ = client.sendTo(request[0..req_len], server_addr) catch return error.SkipZigTest;
// Should timeout - poll should return 0
var fds = [1]posix.pollfd{
.{ .fd = client.fd, .events = posix.POLL.IN, .revents = 0 },
};
const poll_result = posix.poll(&fds, 200) catch 0;
try std.testing.expectEqual(@as(usize, 0), poll_result);
}
test "buildStunBindingRequest: creates valid request" {
var buffer: [64]u8 = undefined;
const transaction_id = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
const len = buildStunBindingRequest(&buffer, &transaction_id);
try std.testing.expectEqual(@as(usize, 20), len);
try std.testing.expectEqual(@as(u16, STUN_BINDING_REQUEST), std.mem.readInt(u16, buffer[0..2], .big));
try std.testing.expectEqual(STUN_MAGIC_COOKIE, std.mem.readInt(u32, buffer[4..8], .big));
}

View File

@@ -0,0 +1,288 @@
//! Test Helper: P2P Pair for Connected Peer Testing
//!
//! This module provides a test harness for creating two P2P instances
//! that connect to each other via localhost TCP. This enables testing
//! of connection success paths, message exchange, and network I/O.
//!
//! Usage:
//! var pair = try TestP2PPair.init(testing.allocator);
//! defer pair.deinit();
//! const peer_id = try pair.connect();
//! // Now pair.server and pair.client are connected
const std = @import("std");
// Re-export mock servers for tests that need them
pub const mock_stun_server = @import("mock_stun_server.zig");
const testing = std.testing;
const mem = std.mem;
const p2p_lib = @import("p2p");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const P2PState = p2p_lib.P2PState;
const core = @import("core");
const Address = core.Address;
const Error = core.errors.Error;
const network = @import("network");
const PeerId = network.peer.PeerId;
const atomic = std.atomic;
/// Port range for coverage tests (19901-19999)
/// Each test pair uses 2 ports: base and base+1
var next_port = atomic.Value(u16).init(19901);
/// Get next available port pair for testing
fn getNextPortPair() struct { server: u16, client: u16 } {
const server = next_port.fetchAdd(2, .acq_rel);
return .{ .server = server, .client = server + 1 };
}
/// Reset port counter (for test isolation)
pub fn resetPortCounter() void {
next_port.store(19901, .release);
}
/// Test harness for two connected P2P instances
pub const TestP2PPair = struct {
allocator: mem.Allocator,
server: *P2P,
client: *P2P,
server_port: u16,
client_port: u16,
connected_peer_id: ?PeerId,
started: bool,
const Self = @This();
/// Initialize two P2P instances with minimal configuration
pub fn init(allocator: mem.Allocator) Error!Self {
return initWithConfig(allocator, .{}, .{});
}
/// Initialize with custom configuration overrides
pub fn initWithConfig(
allocator: mem.Allocator,
server_overrides: ConfigOverrides,
client_overrides: ConfigOverrides,
) Error!Self {
const ports = getNextPortPair();
// Create server P2P
var server_config = getMinimalConfig();
server_config.network.listen_port = ports.server;
applyOverrides(&server_config, server_overrides);
const server = allocator.create(P2P) catch return Error.OutOfMemory;
errdefer allocator.destroy(server);
server.* = P2P.init(allocator, server_config) catch return Error.InvalidState;
errdefer server.deinit();
// Create client P2P
var client_config = getMinimalConfig();
client_config.network.listen_port = ports.client;
applyOverrides(&client_config, client_overrides);
const client = allocator.create(P2P) catch return Error.OutOfMemory;
errdefer allocator.destroy(client);
client.* = P2P.init(allocator, client_config) catch return Error.InvalidState;
return Self{
.allocator = allocator,
.server = server,
.client = client,
.server_port = ports.server,
.client_port = ports.client,
.connected_peer_id = null,
.started = false,
};
}
/// Cleanup both P2P instances
pub fn deinit(self: *Self) void {
if (self.started) {
// Stop both instances first
self.client.stop() catch {};
self.server.stop() catch {};
}
self.client.deinit();
self.allocator.destroy(self.client);
self.server.deinit();
self.allocator.destroy(self.server);
}
/// Start both P2P instances, have server listen, and client connect
/// Returns the peer ID of the server as seen by the client
pub fn connect(self: *Self) Error!PeerId {
return self.connectWithTimeout(5000);
}
/// Connect with custom timeout
pub fn connectWithTimeout(self: *Self, timeout_ms: u32) Error!PeerId {
// Start both
self.server.start() catch return Error.InvalidState;
self.client.start() catch return Error.InvalidState;
self.started = true;
// Clear initialization events
_ = self.server.processAllEvents();
_ = self.client.processAllEvents();
// Server listens on localhost
var listen_addr = Address.init();
listen_addr.port = self.server_port;
listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } };
self.server.startListening(listen_addr) catch return Error.SocketBindingFailed;
// Give server time to start listening
std.Thread.sleep(50 * std.time.ns_per_ms);
// Client connects to server
var connect_addr = Address.init();
connect_addr.port = self.server_port;
connect_addr.data = .{ .ipv4 = .{ .bytes = .{ 127, 0, 0, 1 } } };
self.connected_peer_id = self.client.connectToPeer(connect_addr) catch |err| {
std.debug.print("TestP2PPair: Connection failed: {}\n", .{err});
return err;
};
// Wait for connection to be established
self.waitForConnection(timeout_ms) catch |err| {
std.debug.print("TestP2PPair: Connection timeout\n", .{});
return err;
};
return self.connected_peer_id.?;
}
/// Wait for connection to be fully established
pub fn waitForConnection(self: *Self, timeout_ms: u32) Error!void {
const start = std.time.milliTimestamp();
const timeout: i64 = @intCast(timeout_ms);
while (std.time.milliTimestamp() - start < timeout) {
self.server.update() catch {};
self.client.update() catch {};
// Check if server has accepted the connection
if (self.server.getStats().active_connections.load(.acquire) > 0) {
return;
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
return Error.ConnectionTimeout;
}
/// Run update() on both instances
pub fn updateBoth(self: *Self) Error!void {
self.server.update() catch {};
self.client.update() catch {};
}
/// Run multiple update cycles
pub fn updateBothN(self: *Self, n: usize) void {
for (0..n) |_| {
self.server.update() catch {};
self.client.update() catch {};
std.Thread.sleep(5 * std.time.ns_per_ms);
}
}
/// Get the connected peer ID (client's view of server)
pub fn getPeerId(self: *const Self) ?PeerId {
return self.connected_peer_id;
}
/// Check if both instances are connected
pub fn isConnected(self: *Self) bool {
return self.server.getStats().active_connections.load(.acquire) > 0 and
self.client.getStats().active_connections.load(.acquire) > 0;
}
/// Process all events on both sides
pub fn processAllEvents(self: *Self) void {
_ = self.server.processAllEvents();
_ = self.client.processAllEvents();
}
/// Configuration overrides for testing
pub const ConfigOverrides = struct {
enable_noise: ?bool = null,
enable_rate_limiting: ?bool = null,
enable_dos_protection: ?bool = null,
max_connections: ?u32 = null,
connection_timeout: ?u32 = null,
};
fn applyOverrides(config: *P2PConfig, overrides: ConfigOverrides) void {
if (overrides.enable_noise) |v| config.network.enable_noise_encryption = v;
if (overrides.enable_rate_limiting) |v| config.network.enable_rate_limiting = v;
if (overrides.enable_dos_protection) |v| config.network.enable_dos_protection = v;
if (overrides.max_connections) |v| config.network.max_connections = v;
if (overrides.connection_timeout) |v| config.network.connection_timeout = v;
}
/// Get minimal configuration for fast tests
fn getMinimalConfig() P2PConfig {
var config = P2PConfig.default();
// Disable features that slow down tests
config.network.enable_noise_encryption = false;
config.network.enable_rate_limiting = false;
config.network.enable_dos_protection = false;
config.network.enable_nat_traversal = false;
config.network.turn_enabled = false;
// Fast timeouts for tests
config.network.connection_timeout = 5000;
config.network.idle_timeout_ms = 120000;
config.network.health_check_interval_ms = 30000;
config.network.max_connections = 10;
// Minimal event queue
config.events.max_event_queue = 100;
// Disable auto-start for explicit control
config.library.auto_start = false;
config.library.enable_statistics = true;
// Allow sharing from test data directory
config.file_sharing.allowed_share_directories = &[_][]const u8{"tests/test_data"};
return config;
}
};
// Self-tests for the helper
test "TestP2PPair basic init and deinit" {
var pair = try TestP2PPair.init(testing.allocator);
defer pair.deinit();
// Verify instances were created (pointers are non-null after successful init)
try testing.expect(@intFromPtr(pair.server) != 0);
try testing.expect(@intFromPtr(pair.client) != 0);
try testing.expect(pair.connected_peer_id == null);
try testing.expect(!pair.started);
}
// Note: Connection tests are intentionally skipped here because:
// 1. The 41 tests in test_connected_coverage.zig thoroughly exercise connections
// 2. Blocking operations in a single-threaded test environment can cause hangs
// Connection functionality is validated by the integration test suite.
test "TestP2PPair with noise config (no connection)" {
// Just verify we can create a pair with Noise enabled
var pair = try TestP2PPair.initWithConfig(
testing.allocator,
.{ .enable_noise = true },
.{ .enable_noise = true },
);
defer pair.deinit();
// Verify Noise keys were generated
const server_key = pair.server.getNoisePublicKey();
const client_key = pair.client.getNoisePublicKey();
try testing.expect(server_key != null);
try testing.expect(client_key != null);
}