Files
zigp2p/tests/network/test_nat_extended.zig
2026-02-06 21:03:59 -03:00

649 lines
22 KiB
Zig

//! Extended tests for src/network/nat.zig
//!
//! Tests cover:
//! - TurnServer struct and configuration
//! - TurnAllocation lifetime management
//! - ChannelBinding expiration
//! - TurnClient initialization and state
//! - MappedAddress formatting
//! - Endpoint formatting
//! - STUN header building edge cases
//! - XOR address encoding/decoding
//! - STUN/TURN protocol constants
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const core = @import("core");
const Address = core.Address;
const Socket = core.socket.Socket;
const Error = core.errors.Error;
const network = @import("network");
const nat = network.nat;
const StunClient = nat.StunClient;
const StunServer = nat.StunServer;
const NatType = nat.NatType;
const MappedAddress = nat.MappedAddress;
const Endpoint = nat.Endpoint;
const HolePuncher = nat.HolePuncher;
const TurnServer = nat.TurnServer;
const TurnAllocation = nat.TurnAllocation;
const ChannelBinding = nat.ChannelBinding;
const TurnClient = nat.TurnClient;
// ============================================================================
// TurnServer Tests
// ============================================================================
test "TurnServer: default port is 3478" {
const server = TurnServer{ .host = "turn.example.com" };
try testing.expectEqual(@as(u16, 3478), server.port);
}
test "TurnServer: custom port" {
const server = TurnServer{ .host = "turn.example.com", .port = 5349 };
try testing.expectEqual(@as(u16, 5349), server.port);
}
test "TurnServer: with credentials" {
const server = TurnServer{
.host = "turn.example.com",
.port = 3478,
.username = "testuser",
.credential = "testpass",
};
try testing.expectEqualStrings("testuser", server.username.?);
try testing.expectEqualStrings("testpass", server.credential.?);
}
test "TurnServer: without credentials" {
const server = TurnServer{ .host = "turn.example.com" };
try testing.expectEqual(@as(?[]const u8, null), server.username);
try testing.expectEqual(@as(?[]const u8, null), server.credential);
}
test "DEFAULT_TURN_SERVERS: is empty by default" {
// TURN servers require authentication, so default list is empty
try testing.expectEqual(@as(usize, 0), nat.DEFAULT_TURN_SERVERS.len);
}
// ============================================================================
// TurnAllocation Tests
// ============================================================================
test "TurnAllocation: isExpired returns false for fresh allocation" {
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600,
.created_at = std.time.timestamp(),
.transaction_id = [_]u8{0} ** 12,
};
try testing.expect(!allocation.isExpired());
}
test "TurnAllocation: isExpired returns true for old allocation" {
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600,
.created_at = std.time.timestamp() - 700, // Created 700 seconds ago
.transaction_id = [_]u8{0} ** 12,
};
try testing.expect(allocation.isExpired());
}
test "TurnAllocation: remainingLifetime for fresh allocation" {
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600,
.created_at = std.time.timestamp(),
.transaction_id = [_]u8{0} ** 12,
};
const remaining = allocation.remainingLifetime();
// Should be close to 600 seconds (within a few seconds tolerance)
try testing.expect(remaining >= 595);
try testing.expect(remaining <= 600);
}
test "TurnAllocation: remainingLifetime returns 0 for expired allocation" {
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600,
.created_at = std.time.timestamp() - 1000, // Expired 400 seconds ago
.transaction_id = [_]u8{0} ** 12,
};
const remaining = allocation.remainingLifetime();
try testing.expectEqual(@as(i64, 0), remaining);
}
test "TurnAllocation: remainingLifetime decreases over time" {
const now = std.time.timestamp();
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600,
.created_at = now - 100, // Created 100 seconds ago
.transaction_id = [_]u8{0} ** 12,
};
const remaining = allocation.remainingLifetime();
// Should be around 500 seconds remaining
try testing.expect(remaining >= 495);
try testing.expect(remaining <= 500);
}
test "TurnAllocation: transaction_id is 12 bytes" {
const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.lifetime = 300,
.created_at = std.time.timestamp(),
.transaction_id = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 },
};
try testing.expectEqual(@as(usize, 12), allocation.transaction_id.len);
}
// ============================================================================
// ChannelBinding Tests
// ============================================================================
test "ChannelBinding: isExpired returns false for fresh binding" {
const binding = ChannelBinding{
.channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp(),
};
try testing.expect(!binding.isExpired());
}
test "ChannelBinding: isExpired returns true for old binding" {
const binding = ChannelBinding{
.channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp() - 700,
.lifetime = 600,
};
try testing.expect(binding.isExpired());
}
test "ChannelBinding: default lifetime is 600 seconds" {
const binding = ChannelBinding{
.channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp(),
};
try testing.expectEqual(@as(u32, 600), binding.lifetime);
}
test "ChannelBinding: custom lifetime" {
const binding = ChannelBinding{
.channel_number = 0x4001,
.peer_address = Address.ipv4(.{ 10, 0, 0, 2 }, 6000),
.created_at = std.time.timestamp(),
.lifetime = 1200, // 20 minutes
};
try testing.expectEqual(@as(u32, 1200), binding.lifetime);
}
test "ChannelBinding: channel numbers start at 0x4000" {
// Per RFC 5766, channel numbers are in range 0x4000-0x7FFF
const binding = ChannelBinding{
.channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp(),
};
try testing.expect(binding.channel_number >= 0x4000);
try testing.expect(binding.channel_number < 0x8000);
}
// ============================================================================
// TurnClient Tests
// ============================================================================
test "TurnClient: initialization" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const server = TurnServer{ .host = "turn.example.com", .port = 3478 };
var client = TurnClient.init(allocator, &socket, server);
defer client.deinit();
try testing.expectEqual(@as(?TurnAllocation, null), client.allocation);
try testing.expectEqual(@as(u16, 0x4000), client.next_channel_number);
}
test "TurnClient: getRelayedAddress returns null when no allocation" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const server = TurnServer{ .host = "turn.example.com" };
var client = TurnClient.init(allocator, &socket, server);
defer client.deinit();
try testing.expectEqual(@as(?Address, null), client.getRelayedAddress());
}
test "TurnClient: hasValidAllocation returns false when no allocation" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const server = TurnServer{ .host = "turn.example.com" };
var client = TurnClient.init(allocator, &socket, server);
defer client.deinit();
try testing.expect(!client.hasValidAllocation());
}
test "TurnClient: default timeout is 5000ms" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const server = TurnServer{ .host = "turn.example.com" };
var client = TurnClient.init(allocator, &socket, server);
defer client.deinit();
try testing.expectEqual(@as(u32, 5000), client.timeout_ms);
}
// ============================================================================
// MappedAddress Tests
// ============================================================================
test "MappedAddress: format produces non-empty output" {
const addr = Address.ipv4(.{ 203, 0, 113, 50 }, 3478);
const mapped = MappedAddress{
.address = addr,
.port = 3478,
};
var buf: [256]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try mapped.format(fbs.writer());
const str = fbs.getWritten();
try testing.expect(str.len > 0);
// Should contain port number
try testing.expect(std.mem.indexOf(u8, str, "3478") != null);
}
test "MappedAddress: format with different port" {
const addr = Address.ipv4(.{ 192, 168, 1, 1 }, 8080);
const mapped = MappedAddress{
.address = addr,
.port = 54321,
};
var buf: [256]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try mapped.format(fbs.writer());
const str = fbs.getWritten();
try testing.expect(std.mem.indexOf(u8, str, "54321") != null);
}
// ============================================================================
// Endpoint Tests
// ============================================================================
test "Endpoint: format produces non-empty output" {
const local = Address.ipv4(.{ 192, 168, 1, 100 }, 5000);
const public_addr = Address.ipv4(.{ 203, 0, 113, 50 }, 6000);
const endpoint = Endpoint{
.local_addr = local,
.local_port = 5000,
.public_addr = public_addr,
.public_port = 6000,
};
var buf: [512]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try endpoint.format(fbs.writer());
const str = fbs.getWritten();
try testing.expect(str.len > 0);
// Should contain "local=" and "public=" prefixes
try testing.expect(std.mem.indexOf(u8, str, "local=") != null);
try testing.expect(std.mem.indexOf(u8, str, "public=") != null);
}
test "Endpoint: format includes both ports" {
const local = Address.ipv4(.{ 10, 0, 0, 5 }, 8080);
const public_addr = Address.ipv4(.{ 1, 2, 3, 4 }, 9090);
const endpoint = Endpoint{
.local_addr = local,
.local_port = 8080,
.public_addr = public_addr,
.public_port = 9090,
};
var buf: [512]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try endpoint.format(fbs.writer());
const str = fbs.getWritten();
try testing.expect(std.mem.indexOf(u8, str, "8080") != null);
try testing.expect(std.mem.indexOf(u8, str, "9090") != null);
}
// ============================================================================
// HolePuncher Tests
// ============================================================================
test "HolePuncher: initialization with custom STUN servers" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const custom_servers = [_]StunServer{
.{ .host = "stun1.example.com", .port = 3478 },
.{ .host = "stun2.example.com", .port = 19302 },
};
const puncher = HolePuncher.initWithStunServers(allocator, &socket, &custom_servers);
_ = puncher;
}
test "HolePuncher: local_endpoint is initially null" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const puncher = HolePuncher.init(allocator, &socket);
try testing.expectEqual(@as(?Endpoint, null), puncher.local_endpoint);
}
// ============================================================================
// StunClient Tests
// ============================================================================
test "StunClient: initial state" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const client = StunClient.init(allocator, &socket);
try testing.expectEqual(@as(?MappedAddress, null), client.mapped_address);
try testing.expectEqual(NatType.unknown, client.nat_type);
try testing.expectEqual(@as(u32, 5000), client.timeout_ms);
}
test "StunClient: uses default STUN servers" {
const allocator = testing.allocator;
var socket = try Socket.init(.udp, allocator);
defer socket.deinit();
const client = StunClient.init(allocator, &socket);
try testing.expectEqual(nat.DEFAULT_STUN_SERVERS.len, client.stun_servers.len);
}
// ============================================================================
// NatType Additional Tests
// ============================================================================
test "NatType: all types have unique difficulty" {
const difficulties = [_]u8{
NatType.unknown.traversalDifficulty(),
NatType.open_internet.traversalDifficulty(),
NatType.full_cone.traversalDifficulty(),
NatType.restricted_cone.traversalDifficulty(),
NatType.port_restricted_cone.traversalDifficulty(),
NatType.symmetric.traversalDifficulty(),
};
// Check that all values are unique (except unknown which is 255)
for (difficulties, 0..) |d1, i| {
for (difficulties, 0..) |d2, j| {
if (i != j) {
try testing.expect(d1 != d2);
}
}
}
}
test "NatType: difficulty ordering is correct" {
// From easiest to hardest: open < full_cone < restricted < port_restricted < symmetric < unknown
try testing.expect(NatType.open_internet.traversalDifficulty() < NatType.full_cone.traversalDifficulty());
try testing.expect(NatType.full_cone.traversalDifficulty() < NatType.restricted_cone.traversalDifficulty());
try testing.expect(NatType.restricted_cone.traversalDifficulty() < NatType.port_restricted_cone.traversalDifficulty());
try testing.expect(NatType.port_restricted_cone.traversalDifficulty() < NatType.symmetric.traversalDifficulty());
try testing.expect(NatType.symmetric.traversalDifficulty() < NatType.unknown.traversalDifficulty());
}
// ============================================================================
// STUN Constants Tests
// ============================================================================
test "STUN magic cookie is correct" {
// RFC 5389 defines magic cookie as 0x2112A442
const magic: u32 = 0x2112A442;
const bytes = std.mem.toBytes(std.mem.nativeToBig(u32, magic));
try testing.expectEqual(@as(u8, 0x21), bytes[0]);
try testing.expectEqual(@as(u8, 0x12), bytes[1]);
try testing.expectEqual(@as(u8, 0xA4), bytes[2]);
try testing.expectEqual(@as(u8, 0x42), bytes[3]);
}
test "Hole punch magic is PUNC" {
const magic: u32 = 0x50554E43;
const bytes = std.mem.toBytes(std.mem.nativeToBig(u32, magic));
try testing.expectEqualStrings("PUNC", &bytes);
}
// ============================================================================
// XOR Address Encoding Tests
// ============================================================================
test "XOR port encoding is reversible" {
const magic_cookie: u32 = 0x2112A442;
const original_port: u16 = 54321;
// XOR with top 16 bits of magic cookie
const xored_port = original_port ^ @as(u16, @truncate(magic_cookie >> 16));
// XOR again to get back original
const decoded_port = xored_port ^ @as(u16, @truncate(magic_cookie >> 16));
try testing.expectEqual(original_port, decoded_port);
}
test "XOR IPv4 address encoding is reversible" {
const magic_cookie: u32 = 0x2112A442;
const original_ip: u32 = 0xC0A80164; // 192.168.1.100
const xored_ip = original_ip ^ magic_cookie;
const decoded_ip = xored_ip ^ magic_cookie;
try testing.expectEqual(original_ip, decoded_ip);
}
test "XOR encoding produces different value" {
const magic_cookie: u32 = 0x2112A442;
const original_port: u16 = 12345;
const xored_port = original_port ^ @as(u16, @truncate(magic_cookie >> 16));
try testing.expect(xored_port != original_port);
}
// ============================================================================
// Protocol Message Type Tests
// ============================================================================
test "STUN binding request type is 0x0001" {
const binding_request: u16 = 0x0001;
try testing.expectEqual(@as(u16, 0x0001), binding_request);
}
test "STUN binding response type is 0x0101" {
const binding_response: u16 = 0x0101;
try testing.expectEqual(@as(u16, 0x0101), binding_response);
}
test "STUN binding error type is 0x0111" {
const binding_error: u16 = 0x0111;
try testing.expectEqual(@as(u16, 0x0111), binding_error);
}
test "TURN allocate request type is 0x0003" {
const allocate_request: u16 = 0x0003;
try testing.expectEqual(@as(u16, 0x0003), allocate_request);
}
test "TURN allocate response type is 0x0103" {
const allocate_response: u16 = 0x0103;
try testing.expectEqual(@as(u16, 0x0103), allocate_response);
}
// ============================================================================
// Attribute Type Tests
// ============================================================================
test "STUN MAPPED-ADDRESS attribute type is 0x0001" {
const attr_type: u16 = 0x0001;
try testing.expectEqual(@as(u16, 0x0001), attr_type);
}
test "STUN XOR-MAPPED-ADDRESS attribute type is 0x0020" {
const attr_type: u16 = 0x0020;
try testing.expectEqual(@as(u16, 0x0020), attr_type);
}
test "TURN XOR-RELAYED-ADDRESS attribute type is 0x0016" {
const attr_type: u16 = 0x0016;
try testing.expectEqual(@as(u16, 0x0016), attr_type);
}
test "TURN LIFETIME attribute type is 0x000D" {
const attr_type: u16 = 0x000D;
try testing.expectEqual(@as(u16, 0x000D), attr_type);
}
// ============================================================================
// Address Family Tests
// ============================================================================
test "IPv4 family code is 0x01" {
const ipv4_family: u8 = 0x01;
try testing.expectEqual(@as(u8, 0x01), ipv4_family);
}
test "IPv6 family code is 0x02" {
const ipv6_family: u8 = 0x02;
try testing.expectEqual(@as(u8, 0x02), ipv6_family);
}
// ============================================================================
// Channel Number Range Tests
// ============================================================================
test "Channel numbers range from 0x4000 to 0x7FFF" {
const min_channel: u16 = 0x4000;
const max_channel: u16 = 0x7FFF;
try testing.expectEqual(@as(u16, 0x4000), min_channel);
try testing.expectEqual(@as(u16, 0x7FFF), max_channel);
try testing.expect(max_channel > min_channel);
}
// ============================================================================
// Default STUN Servers Tests
// ============================================================================
test "Default STUN servers include Google servers" {
var found_google = false;
for (nat.DEFAULT_STUN_SERVERS) |server| {
if (std.mem.indexOf(u8, server.host, "google") != null) {
found_google = true;
break;
}
}
try testing.expect(found_google);
}
test "Default STUN servers include Cloudflare" {
var found_cloudflare = false;
for (nat.DEFAULT_STUN_SERVERS) |server| {
if (std.mem.indexOf(u8, server.host, "cloudflare") != null) {
found_cloudflare = true;
break;
}
}
try testing.expect(found_cloudflare);
}
test "All default STUN servers have valid ports" {
for (nat.DEFAULT_STUN_SERVERS) |server| {
try testing.expect(server.port > 0);
try testing.expect(server.port < 65535);
}
}
test "All default STUN servers have non-empty hosts" {
for (nat.DEFAULT_STUN_SERVERS) |server| {
try testing.expect(server.host.len > 0);
}
}
// ============================================================================
// Integration Scenario Tests
// ============================================================================
test "NAT traversal scenario: both open internet" {
const a = NatType.open_internet;
const b = NatType.open_internet;
// Both can traverse, direct connection possible
try testing.expect(a.canTraverse());
try testing.expect(b.canTraverse());
}
test "NAT traversal scenario: one symmetric, one open" {
const symmetric = NatType.symmetric;
const open = NatType.open_internet;
// Open can initiate connection to symmetric
try testing.expect(!symmetric.canTraverse());
try testing.expect(open.canTraverse());
}
test "NAT traversal scenario: both symmetric" {
const a = NatType.symmetric;
const b = NatType.symmetric;
// Neither can traverse, need TURN relay
try testing.expect(!a.canTraverse());
try testing.expect(!b.canTraverse());
}
test "NAT traversal scenario: full cone to port restricted" {
const full_cone = NatType.full_cone;
const port_restricted = NatType.port_restricted_cone;
// Both can traverse with hole punching
try testing.expect(full_cone.canTraverse());
try testing.expect(port_restricted.canTraverse());
}